aboutsummaryrefslogtreecommitdiff
path: root/unittests
diff options
context:
space:
mode:
authorPirama Arumuga Nainar <pirama@google.com>2016-09-19 22:19:55 -0700
committerPirama Arumuga Nainar <pirama@google.com>2016-10-06 21:01:10 -0700
commit4967a710c84587c654b56c828382219c3937dacb (patch)
treeae0d585998e15fc175ca3e9146b21e53f290624b /unittests
parentd27d7495bf70da4faffda3d8083396e0e07f2931 (diff)
downloadclang-4967a710c84587c654b56c828382219c3937dacb.tar.gz
Update aosp/master Clang for rebase to r275480
Bug: http://b/31320715 This merges commit ac9cc4764cf47a6c3f031687d8592e080c9f5001 from aosp/dev. Test: Build AOSP and run RenderScript tests (host tests for slang and libbcc, RsTest, CTS) Change-Id: Ic2875e5c3673c83448cd7d1013861e42947b1b55
Diffstat (limited to 'unittests')
-rw-r--r--unittests/AST/ASTContextParentMapTest.cpp4
-rw-r--r--unittests/AST/ASTImporterTest.cpp460
-rw-r--r--unittests/AST/ASTTypeTraitsTest.cpp17
-rw-r--r--unittests/AST/CMakeLists.txt2
-rw-r--r--unittests/AST/Makefile19
-rw-r--r--unittests/AST/MatchVerifier.h19
-rw-r--r--unittests/AST/PostOrderASTVisitor.cpp123
-rw-r--r--unittests/AST/SourceLocationTest.cpp38
-rw-r--r--unittests/ASTMatchers/ASTMatchersInternalTest.cpp240
-rw-r--r--unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp1935
-rw-r--r--unittests/ASTMatchers/ASTMatchersNodeTest.cpp1539
-rw-r--r--unittests/ASTMatchers/ASTMatchersTest.cpp5070
-rw-r--r--unittests/ASTMatchers/ASTMatchersTest.h144
-rw-r--r--unittests/ASTMatchers/ASTMatchersTraversalTest.cpp2055
-rw-r--r--unittests/ASTMatchers/CMakeLists.txt14
-rw-r--r--unittests/ASTMatchers/Dynamic/Makefile22
-rw-r--r--unittests/ASTMatchers/Dynamic/ParserTest.cpp4
-rw-r--r--unittests/ASTMatchers/Dynamic/RegistryTest.cpp25
-rw-r--r--unittests/ASTMatchers/Dynamic/VariantValueTest.cpp3
-rw-r--r--unittests/ASTMatchers/Makefile22
-rw-r--r--unittests/Analysis/CFGTest.cpp58
-rw-r--r--unittests/Analysis/CMakeLists.txt16
-rw-r--r--unittests/Basic/DiagnosticTest.cpp23
-rw-r--r--unittests/Basic/Makefile15
-rw-r--r--unittests/Basic/SourceManagerTest.cpp19
-rw-r--r--unittests/Basic/VirtualFileSystemTest.cpp201
-rw-r--r--unittests/CMakeLists.txt1
-rw-r--r--unittests/CodeGen/BufferSourceTest.cpp3
-rw-r--r--unittests/CodeGen/Makefile20
-rw-r--r--unittests/Driver/Makefile16
-rw-r--r--unittests/Format/CMakeLists.txt5
-rw-r--r--unittests/Format/CleanupTest.cpp726
-rw-r--r--unittests/Format/FormatTest.cpp629
-rw-r--r--unittests/Format/FormatTestJS.cpp532
-rw-r--r--unittests/Format/FormatTestJava.cpp12
-rw-r--r--unittests/Format/FormatTestProto.cpp73
-rw-r--r--unittests/Format/FormatTestSelective.cpp44
-rw-r--r--unittests/Format/Makefile19
-rw-r--r--unittests/Format/SortImportsTestJS.cpp269
-rw-r--r--unittests/Format/SortIncludesTest.cpp52
-rw-r--r--unittests/Frontend/CMakeLists.txt2
-rw-r--r--unittests/Frontend/CodeGenActionTest.cpp61
-rw-r--r--unittests/Frontend/Makefile21
-rw-r--r--unittests/Lex/CMakeLists.txt1
-rw-r--r--unittests/Lex/HeaderMapTest.cpp258
-rw-r--r--unittests/Lex/LexerTest.cpp30
-rw-r--r--unittests/Lex/Makefile16
-rw-r--r--unittests/Lex/PPConditionalDirectiveRecordTest.cpp4
-rw-r--r--unittests/Makefile35
-rw-r--r--unittests/Rewrite/Makefile16
-rw-r--r--unittests/Sema/ExternalSemaSourceTest.cpp101
-rw-r--r--unittests/Sema/Makefile19
-rw-r--r--unittests/StaticAnalyzer/Makefile15
-rw-r--r--unittests/Tooling/CMakeLists.txt15
-rw-r--r--unittests/Tooling/FixItTest.cpp232
-rw-r--r--unittests/Tooling/Makefile20
-rw-r--r--unittests/Tooling/QualTypeNamesTest.cpp222
-rw-r--r--unittests/Tooling/RecursiveASTVisitorTest.cpp26
-rw-r--r--unittests/Tooling/RefactoringTest.cpp165
-rw-r--r--unittests/Tooling/RewriterTest.cpp5
-rw-r--r--unittests/Tooling/ToolingTest.cpp57
-rw-r--r--unittests/libclang/LibclangTest.cpp2
-rw-r--r--unittests/libclang/Makefile37
63 files changed, 10161 insertions, 5687 deletions
diff --git a/unittests/AST/ASTContextParentMapTest.cpp b/unittests/AST/ASTContextParentMapTest.cpp
index b1d7db4164..a39189620b 100644
--- a/unittests/AST/ASTContextParentMapTest.cpp
+++ b/unittests/AST/ASTContextParentMapTest.cpp
@@ -21,10 +21,6 @@
namespace clang {
namespace ast_matchers {
-using clang::tooling::newFrontendActionFactory;
-using clang::tooling::runToolOnCodeWithArgs;
-using clang::tooling::FrontendActionFactory;
-
TEST(GetParents, ReturnsParentForDecl) {
MatchVerifier<Decl> Verifier;
EXPECT_TRUE(
diff --git a/unittests/AST/ASTImporterTest.cpp b/unittests/AST/ASTImporterTest.cpp
new file mode 100644
index 0000000000..3cc38fb55b
--- /dev/null
+++ b/unittests/AST/ASTImporterTest.cpp
@@ -0,0 +1,460 @@
+//===- unittest/AST/ASTImporterTest.cpp - AST node import test ------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for the correct import of AST nodes from one AST context to another.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTImporter.h"
+#include "MatchVerifier.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace ast_matchers {
+
+typedef std::vector<std::string> StringVector;
+
+void getLangArgs(Language Lang, StringVector &Args) {
+ switch (Lang) {
+ case Lang_C:
+ Args.insert(Args.end(), { "-x", "c", "-std=c99" });
+ break;
+ case Lang_C89:
+ Args.insert(Args.end(), { "-x", "c", "-std=c89" });
+ break;
+ case Lang_CXX:
+ Args.push_back("-std=c++98");
+ break;
+ case Lang_CXX11:
+ Args.push_back("-std=c++11");
+ break;
+ case Lang_OpenCL:
+ case Lang_OBJCXX:
+ break;
+ }
+}
+
+template<typename NodeType, typename MatcherType>
+testing::AssertionResult
+testImport(const std::string &FromCode, Language FromLang,
+ const std::string &ToCode, Language ToLang,
+ MatchVerifier<NodeType> &Verifier,
+ const MatcherType &AMatcher) {
+ StringVector FromArgs, ToArgs;
+ getLangArgs(FromLang, FromArgs);
+ getLangArgs(ToLang, ToArgs);
+
+ const char *const InputFileName = "input.cc";
+ const char *const OutputFileName = "output.cc";
+
+ std::unique_ptr<ASTUnit>
+ FromAST = tooling::buildASTFromCodeWithArgs(
+ FromCode, FromArgs, InputFileName),
+ ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName);
+
+ ASTContext &FromCtx = FromAST->getASTContext(),
+ &ToCtx = ToAST->getASTContext();
+
+ // Add input.cc to virtual file system so importer can 'find' it
+ // while importing SourceLocations.
+ vfs::OverlayFileSystem *OFS = static_cast<vfs::OverlayFileSystem *>(
+ ToCtx.getSourceManager().getFileManager().getVirtualFileSystem().get());
+ vfs::InMemoryFileSystem *MFS = static_cast<vfs::InMemoryFileSystem *>(
+ OFS->overlays_begin()->get());
+ MFS->addFile(InputFileName, 0,
+ llvm::MemoryBuffer::getMemBuffer(FromCode.c_str()));
+
+ ASTImporter Importer(ToCtx, ToAST->getFileManager(),
+ FromCtx, FromAST->getFileManager(), false);
+
+ IdentifierInfo *ImportedII = &FromCtx.Idents.get("declToImport");
+ assert(ImportedII && "Declaration with 'declToImport' name"
+ "should be specified in test!");
+ DeclarationName ImportDeclName(ImportedII);
+ SmallVector<NamedDecl *, 4> FoundDecls;
+ FromCtx.getTranslationUnitDecl()->localUncachedLookup(
+ ImportDeclName, FoundDecls);
+
+ if (FoundDecls.size() != 1)
+ return testing::AssertionFailure() << "Multiple declarations were found!";
+
+ auto Imported = Importer.Import(*FoundDecls.begin());
+ if (!Imported)
+ return testing::AssertionFailure() << "Import failed, nullptr returned!";
+
+ // This should dump source locations and assert if some source locations
+ // were not imported
+ SmallString<1024> ImportChecker;
+ llvm::raw_svector_ostream ToNothing(ImportChecker);
+ ToCtx.getTranslationUnitDecl()->print(ToNothing);
+
+ return Verifier.match(Imported, AMatcher);
+}
+
+TEST(ImportExpr, ImportStringLiteral) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(testImport("void declToImport() { \"foo\"; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ stringLiteral(
+ hasType(
+ asString("const char [4]")))))))));
+ EXPECT_TRUE(testImport("void declToImport() { L\"foo\"; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ stringLiteral(
+ hasType(
+ asString("const wchar_t [4]")))))))));
+ EXPECT_TRUE(testImport("void declToImport() { \"foo\" \"bar\"; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ stringLiteral(
+ hasType(
+ asString("const char [7]")))))))));
+}
+
+TEST(ImportExpr, ImportGNUNullExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(testImport("void declToImport() { __null; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ gnuNullExpr(
+ hasType(isInteger()))))))));
+}
+
+TEST(ImportExpr, ImportCXXNullPtrLiteralExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(testImport("void declToImport() { nullptr; }",
+ Lang_CXX11, "", Lang_CXX11, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ cxxNullPtrLiteralExpr()))))));
+}
+
+
+TEST(ImportExpr, ImportFloatinglLiteralExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(testImport("void declToImport() { 1.0; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ floatLiteral(
+ equals(1.0),
+ hasType(asString("double")))))))));
+ EXPECT_TRUE(testImport("void declToImport() { 1.0e-5f; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ floatLiteral(
+ equals(1.0e-5f),
+ hasType(asString("float")))))))));
+}
+
+TEST(ImportExpr, ImportCompoundLiteralExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(
+ testImport(
+ "void declToImport() {"
+ " struct s { int x; long y; unsigned z; }; "
+ " (struct s){ 42, 0L, 1U }; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ compoundLiteralExpr(
+ hasType(asString("struct s")),
+ has(initListExpr(
+ hasType(asString("struct s")),
+ has(integerLiteral(
+ equals(42), hasType(asString("int")))),
+ has(integerLiteral(
+ equals(0), hasType(asString("long")))),
+ has(integerLiteral(
+ equals(1),
+ hasType(asString("unsigned int"))))
+ )))))))));
+}
+
+TEST(ImportExpr, ImportCXXThisExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(
+ testImport("class declToImport { void f() { this; } };",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ cxxRecordDecl(
+ hasMethod(
+ hasBody(
+ compoundStmt(
+ has(
+ cxxThisExpr(
+ hasType(
+ asString("class declToImport *"))))))))));
+}
+
+TEST(ImportExpr, ImportAtomicExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(testImport(
+ "void declToImport() { int *ptr; __atomic_load_n(ptr, 1); }", Lang_CXX,
+ "", Lang_CXX, Verifier,
+ functionDecl(hasBody(compoundStmt(has(atomicExpr(
+ has(ignoringParenImpCasts(
+ declRefExpr(hasDeclaration(varDecl(hasName("ptr"))),
+ hasType(asString("int *"))))),
+ has(integerLiteral(equals(1), hasType(asString("int")))))))))));
+}
+
+TEST(ImportExpr, ImportLabelDeclAndAddrLabelExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(
+ testImport(
+ "void declToImport() { loop: goto loop; &&loop; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(labelStmt(hasDeclaration(labelDecl(hasName("loop"))))),
+ has(addrLabelExpr(hasDeclaration(labelDecl(hasName("loop")))))
+ )))));
+}
+
+AST_MATCHER_P(TemplateDecl, hasTemplateDecl,
+ internal::Matcher<NamedDecl>, InnerMatcher) {
+ const NamedDecl *Template = Node.getTemplatedDecl();
+ return Template && InnerMatcher.matches(*Template, Finder, Builder);
+}
+
+TEST(ImportExpr, ImportParenListExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(
+ testImport(
+ "template<typename T> class dummy { void f() { dummy X(*this); } };"
+ "typedef dummy<int> declToImport;"
+ "template class dummy<int>;",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ typedefDecl(
+ hasType(
+ templateSpecializationType(
+ hasDeclaration(
+ classTemplateDecl(
+ hasTemplateDecl(
+ cxxRecordDecl(
+ hasMethod(
+ allOf(
+ hasName("f"),
+ hasBody(
+ compoundStmt(
+ has(
+ declStmt(
+ hasSingleDecl(
+ varDecl(
+ hasInitializer(
+ parenListExpr(
+ has(
+ unaryOperator(
+ hasOperatorName("*"),
+ hasUnaryOperand(cxxThisExpr())
+ )))))))))))))))))))));
+}
+
+TEST(ImportExpr, ImportStmtExpr) {
+ MatchVerifier<Decl> Verifier;
+ // NOTE: has() ignores implicit casts, using hasDescendant() to match it
+ EXPECT_TRUE(
+ testImport(
+ "void declToImport() { int b; int a = b ?: 1; int C = ({int X=4; X;}); }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ declStmt(
+ hasSingleDecl(
+ varDecl(
+ hasName("C"),
+ hasType(asString("int")),
+ hasInitializer(
+ stmtExpr(
+ hasAnySubstatement(
+ declStmt(
+ hasSingleDecl(
+ varDecl(
+ hasName("X"),
+ hasType(asString("int")),
+ hasInitializer(
+ integerLiteral(equals(4))))))),
+ hasDescendant(
+ implicitCastExpr()
+ ))))))))))));
+}
+
+TEST(ImportExpr, ImportConditionalOperator) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(
+ testImport(
+ "void declToImport() { true ? 1 : -5; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ conditionalOperator(
+ hasCondition(cxxBoolLiteral(equals(true))),
+ hasTrueExpression(integerLiteral(equals(1))),
+ hasFalseExpression(
+ unaryOperator(hasUnaryOperand(integerLiteral(equals(5))))
+ ))))))));
+}
+
+TEST(ImportExpr, ImportBinaryConditionalOperator) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(
+ testImport(
+ "void declToImport() { 1 ?: -5; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ binaryConditionalOperator(
+ hasCondition(
+ implicitCastExpr(
+ hasSourceExpression(
+ opaqueValueExpr(
+ hasSourceExpression(integerLiteral(equals(1))))),
+ hasType(booleanType()))),
+ hasTrueExpression(
+ opaqueValueExpr(hasSourceExpression(
+ integerLiteral(equals(1))))),
+ hasFalseExpression(
+ unaryOperator(hasOperatorName("-"),
+ hasUnaryOperand(integerLiteral(equals(5)))))
+ )))))));
+}
+
+TEST(ImportExpr, ImportDesignatedInitExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(testImport("void declToImport() {"
+ " struct point { double x; double y; };"
+ " struct point ptarray[10] = "
+ "{ [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
+ Lang_C, "", Lang_C, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ declStmt(
+ hasSingleDecl(
+ varDecl(
+ hasInitializer(
+ initListExpr(
+ hasSyntacticForm(
+ initListExpr(
+ has(
+ designatedInitExpr(
+ designatorCountIs(2),
+ has(floatLiteral(
+ equals(1.0))),
+ has(integerLiteral(
+ equals(2))))),
+ has(
+ designatedInitExpr(
+ designatorCountIs(2),
+ has(floatLiteral(
+ equals(2.0))),
+ has(integerLiteral(
+ equals(2))))),
+ has(
+ designatedInitExpr(
+ designatorCountIs(2),
+ has(floatLiteral(
+ equals(1.0))),
+ has(integerLiteral(
+ equals(0)))))
+ )))))))))))));
+}
+
+
+TEST(ImportExpr, ImportPredefinedExpr) {
+ MatchVerifier<Decl> Verifier;
+ // __func__ expands as StringLiteral("declToImport")
+ EXPECT_TRUE(testImport("void declToImport() { __func__; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ predefinedExpr(
+ hasType(
+ asString("const char [13]")),
+ has(
+ stringLiteral(
+ hasType(
+ asString("const char [13]")))))))))));
+}
+
+TEST(ImportExpr, ImportInitListExpr) {
+ MatchVerifier<Decl> Verifier;
+ EXPECT_TRUE(
+ testImport(
+ "void declToImport() {"
+ " struct point { double x; double y; };"
+ " point ptarray[10] = { [2].y = 1.0, [2].x = 2.0,"
+ " [0].x = 1.0 }; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+ hasBody(
+ compoundStmt(
+ has(
+ declStmt(
+ hasSingleDecl(
+ varDecl(
+ hasInitializer(
+ initListExpr(
+ has(
+ cxxConstructExpr(
+ requiresZeroInitialization())),
+ has(
+ initListExpr(
+ hasType(asString("struct point")),
+ has(floatLiteral(equals(1.0))),
+ has(implicitValueInitExpr(
+ hasType(asString("double")))))),
+ has(
+ initListExpr(
+ hasType(asString("struct point")),
+ has(floatLiteral(equals(2.0))),
+ has(floatLiteral(equals(1.0)))))
+ )))))))))));
+}
+
+
+} // end namespace ast_matchers
+} // end namespace clang
diff --git a/unittests/AST/ASTTypeTraitsTest.cpp b/unittests/AST/ASTTypeTraitsTest.cpp
index b6356538a1..436cd77514 100644
--- a/unittests/AST/ASTTypeTraitsTest.cpp
+++ b/unittests/AST/ASTTypeTraitsTest.cpp
@@ -107,10 +107,21 @@ TEST(ASTNodeKind, UnknownKind) {
}
TEST(ASTNodeKind, Name) {
- EXPECT_EQ("Decl", DNT<Decl>().asStringRef());
- EXPECT_EQ("CallExpr", DNT<CallExpr>().asStringRef());
- EXPECT_EQ("ConstantArrayType", DNT<ConstantArrayType>().asStringRef());
EXPECT_EQ("<None>", ASTNodeKind().asStringRef());
+#define VERIFY_NAME(Node) EXPECT_EQ(#Node, DNT<Node>().asStringRef());
+ VERIFY_NAME(TemplateArgument);
+ VERIFY_NAME(NestedNameSpecifierLoc);
+ VERIFY_NAME(QualType);
+ VERIFY_NAME(TypeLoc);
+ VERIFY_NAME(CXXCtorInitializer);
+ VERIFY_NAME(NestedNameSpecifier);
+ VERIFY_NAME(Decl);
+ VERIFY_NAME(CXXRecordDecl);
+ VERIFY_NAME(Stmt);
+ VERIFY_NAME(CallExpr);
+ VERIFY_NAME(Type);
+ VERIFY_NAME(ConstantArrayType);
+#undef VERIFY_NAME
}
TEST(DynTypedNode, DeclSourceRange) {
diff --git a/unittests/AST/CMakeLists.txt b/unittests/AST/CMakeLists.txt
index 2fa1078a5e..a7008f3e7e 100644
--- a/unittests/AST/CMakeLists.txt
+++ b/unittests/AST/CMakeLists.txt
@@ -4,6 +4,7 @@ set(LLVM_LINK_COMPONENTS
add_clang_unittest(ASTTests
ASTContextParentMapTest.cpp
+ ASTImporterTest.cpp
ASTTypeTraitsTest.cpp
ASTVectorTest.cpp
CommentLexer.cpp
@@ -13,6 +14,7 @@ add_clang_unittest(ASTTests
EvaluateAsRValueTest.cpp
ExternalASTSourceTest.cpp
NamedDeclPrinterTest.cpp
+ PostOrderASTVisitor.cpp
SourceLocationTest.cpp
StmtPrinterTest.cpp
)
diff --git a/unittests/AST/Makefile b/unittests/AST/Makefile
deleted file mode 100644
index e3b3d7dc33..0000000000
--- a/unittests/AST/Makefile
+++ /dev/null
@@ -1,19 +0,0 @@
-##===- unittests/AST/Makefile ------------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = AST
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc option
-USEDLIBS = clangTooling.a clangFrontend.a clangSerialization.a clangDriver.a \
- clangRewrite.a clangRewriteFrontend.a \
- clangParse.a clangSema.a clangAnalysis.a \
- clangEdit.a clangAST.a clangASTMatchers.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/AST/MatchVerifier.h b/unittests/AST/MatchVerifier.h
index 31932479ef..74b9bdfbe7 100644
--- a/unittests/AST/MatchVerifier.h
+++ b/unittests/AST/MatchVerifier.h
@@ -62,6 +62,9 @@ public:
std::vector<std::string>& Args,
Language L);
+ template <typename MatcherType>
+ testing::AssertionResult match(const Decl *D, const MatcherType &AMatcher);
+
protected:
void run(const MatchFinder::MatchResult &Result) override;
virtual void verify(const MatchFinder::MatchResult &Result,
@@ -127,6 +130,22 @@ testing::AssertionResult MatchVerifier<NodeType>::match(
return testing::AssertionSuccess();
}
+/// \brief Runs a matcher over some AST, and returns the result of the
+/// verifier for the matched node.
+template <typename NodeType> template <typename MatcherType>
+testing::AssertionResult MatchVerifier<NodeType>::match(
+ const Decl *D, const MatcherType &AMatcher) {
+ MatchFinder Finder;
+ Finder.addMatcher(AMatcher.bind(""), this);
+
+ setFailure("Could not find match");
+ Finder.match(*D, D->getASTContext());
+
+ if (!Verified)
+ return testing::AssertionFailure() << VerifyResult;
+ return testing::AssertionSuccess();
+}
+
template <typename NodeType>
void MatchVerifier<NodeType>::run(const MatchFinder::MatchResult &Result) {
const NodeType *Node = Result.Nodes.getNodeAs<NodeType>("");
diff --git a/unittests/AST/PostOrderASTVisitor.cpp b/unittests/AST/PostOrderASTVisitor.cpp
new file mode 100644
index 0000000000..012f63a48a
--- /dev/null
+++ b/unittests/AST/PostOrderASTVisitor.cpp
@@ -0,0 +1,123 @@
+//===- unittests/AST/PostOrderASTVisitor.cpp - Declaration printer tests --===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file contains tests for the post-order traversing functionality
+// of RecursiveASTVisitor.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+namespace {
+
+ class RecordingVisitor
+ : public RecursiveASTVisitor<RecordingVisitor> {
+
+ bool VisitPostOrder;
+ public:
+ explicit RecordingVisitor(bool VisitPostOrder)
+ : VisitPostOrder(VisitPostOrder) {
+ }
+
+ // List of visited nodes during traversal.
+ std::vector<std::string> VisitedNodes;
+
+ bool shouldTraversePostOrder() const { return VisitPostOrder; }
+
+ bool VisitBinaryOperator(BinaryOperator *Op) {
+ VisitedNodes.push_back(Op->getOpcodeStr());
+ return true;
+ }
+
+ bool VisitIntegerLiteral(IntegerLiteral *Lit) {
+ VisitedNodes.push_back(Lit->getValue().toString(10, false));
+ return true;
+ }
+
+ bool VisitVarDecl(VarDecl* D) {
+ VisitedNodes.push_back(D->getNameAsString());
+ return true;
+ }
+
+ bool VisitCXXMethodDecl(CXXMethodDecl *D) {
+ VisitedNodes.push_back(D->getQualifiedNameAsString());
+ return true;
+ }
+
+ bool VisitReturnStmt(ReturnStmt *S) {
+ VisitedNodes.push_back("return");
+ return true;
+ }
+
+ bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
+ VisitedNodes.push_back(Declaration->getQualifiedNameAsString());
+ return true;
+ }
+
+ bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
+ VisitedNodes.push_back(T->getDecl()->getQualifiedNameAsString());
+ return true;
+ }
+ };
+
+}
+
+TEST(RecursiveASTVisitor, PostOrderTraversal) {
+ auto ASTUnit = tooling::buildASTFromCode(
+ "class A {"
+ " class B {"
+ " int foo() { while(4) { int i = 9; } return (1 + 3) + 2; }"
+ " };"
+ "};"
+ );
+ auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();
+ // We traverse the translation unit and store all
+ // visited nodes.
+ RecordingVisitor Visitor(true);
+ Visitor.TraverseTranslationUnitDecl(TU);
+
+ std::vector<std::string> expected = {
+ "4", "9", "i", "1", "3", "+", "2", "+", "return", "A::B::foo", "A::B", "A"
+ };
+ // Compare the list of actually visited nodes
+ // with the expected list of visited nodes.
+ ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
+ for (std::size_t I = 0; I < expected.size(); I++) {
+ ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
+ }
+}
+
+TEST(RecursiveASTVisitor, NoPostOrderTraversal) {
+ auto ASTUnit = tooling::buildASTFromCode(
+ "class A {"
+ " class B {"
+ " int foo() { return 1 + 2; }"
+ " };"
+ "};"
+ );
+ auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();
+ // We traverse the translation unit and store all
+ // visited nodes.
+ RecordingVisitor Visitor(false);
+ Visitor.TraverseTranslationUnitDecl(TU);
+
+ std::vector<std::string> expected = {
+ "A", "A::B", "A::B::foo", "return", "+", "1", "2"
+ };
+ // Compare the list of actually visited nodes
+ // with the expected list of visited nodes.
+ ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
+ for (std::size_t I = 0; I < expected.size(); I++) {
+ ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
+ }
+}
diff --git a/unittests/AST/SourceLocationTest.cpp b/unittests/AST/SourceLocationTest.cpp
index 4c77def61b..9fae8d862a 100644
--- a/unittests/AST/SourceLocationTest.cpp
+++ b/unittests/AST/SourceLocationTest.cpp
@@ -542,5 +542,43 @@ TEST(ObjCMessageExpr, CXXConstructExprRange) {
cxxConstructExpr(), Lang_OBJCXX));
}
+TEST(FunctionDecl, FunctionDeclWithThrowSpecification) {
+ RangeVerifier<FunctionDecl> Verifier;
+ Verifier.expectRange(1, 1, 1, 16);
+ EXPECT_TRUE(Verifier.match(
+ "void f() throw();\n",
+ functionDecl()));
+}
+
+TEST(FunctionDecl, FunctionDeclWithNoExceptSpecification) {
+ RangeVerifier<FunctionDecl> Verifier;
+ Verifier.expectRange(1, 1, 1, 24);
+ EXPECT_TRUE(Verifier.match(
+ "void f() noexcept(false);\n",
+ functionDecl(),
+ Language::Lang_CXX11));
+}
+
+TEST(CXXMethodDecl, CXXMethodDeclWithThrowSpecification) {
+ RangeVerifier<FunctionDecl> Verifier;
+ Verifier.expectRange(2, 1, 2, 16);
+ EXPECT_TRUE(Verifier.match(
+ "class A {\n"
+ "void f() throw();\n"
+ "};\n",
+ functionDecl()));
+}
+
+TEST(CXXMethodDecl, CXXMethodDeclWithNoExceptSpecification) {
+ RangeVerifier<FunctionDecl> Verifier;
+ Verifier.expectRange(2, 1, 2, 24);
+ EXPECT_TRUE(Verifier.match(
+ "class A {\n"
+ "void f() noexcept(false);\n"
+ "};\n",
+ functionDecl(),
+ Language::Lang_CXX11));
+}
+
} // end namespace ast_matchers
} // end namespace clang
diff --git a/unittests/ASTMatchers/ASTMatchersInternalTest.cpp b/unittests/ASTMatchers/ASTMatchersInternalTest.cpp
new file mode 100644
index 0000000000..c12056f444
--- /dev/null
+++ b/unittests/ASTMatchers/ASTMatchersInternalTest.cpp
@@ -0,0 +1,240 @@
+// unittests/ASTMatchers/ASTMatchersInternalTest.cpp - AST matcher unit tests //
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ASTMatchersTest.h"
+#include "clang/AST/PrettyPrinter.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/Host.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace ast_matchers {
+
+#if GTEST_HAS_DEATH_TEST
+TEST(HasNameDeathTest, DiesOnEmptyName) {
+ ASSERT_DEBUG_DEATH({
+ DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
+ EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
+ }, "");
+}
+
+TEST(HasNameDeathTest, DiesOnEmptyPattern) {
+ ASSERT_DEBUG_DEATH({
+ DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
+ EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
+ }, "");
+}
+
+TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
+ ASSERT_DEBUG_DEATH({
+ DeclarationMatcher IsDerivedFromEmpty = cxxRecordDecl(isDerivedFrom(""));
+ EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
+ }, "");
+}
+#endif
+
+TEST(ConstructVariadic, MismatchedTypes_Regression) {
+ EXPECT_TRUE(
+ matches("const int a = 0;",
+ internal::DynTypedMatcher::constructVariadic(
+ internal::DynTypedMatcher::VO_AnyOf,
+ ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>(),
+ {isConstQualified(), arrayType()})
+ .convertTo<QualType>()));
+}
+
+// For testing AST_MATCHER_P().
+AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
+ // Make sure all special variables are used: node, match_finder,
+ // bound_nodes_builder, and the parameter named 'AMatcher'.
+ return AMatcher.matches(Node, Finder, Builder);
+}
+
+TEST(AstMatcherPMacro, Works) {
+ DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
+ HasClassB, llvm::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
+
+ EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
+ HasClassB, llvm::make_unique<VerifyIdIsBoundTo<Decl>>("a")));
+
+ EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
+ HasClassB, llvm::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
+}
+
+AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
+ AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
+ internal::Matcher<Decl>, AMatcher) {
+ return Finder->matchesChildOf(
+ Node, AMatcher, Builder,
+ ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
+ ASTMatchFinder::BK_First);
+}
+
+TEST(AstPolymorphicMatcherPMacro, Works) {
+ DeclarationMatcher HasClassB =
+ polymorphicHas(recordDecl(hasName("B")).bind("b"));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
+ HasClassB, llvm::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
+
+ EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
+ HasClassB, llvm::make_unique<VerifyIdIsBoundTo<Decl>>("a")));
+
+ EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
+ HasClassB, llvm::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
+
+ StatementMatcher StatementHasClassB =
+ polymorphicHas(recordDecl(hasName("B")));
+
+ EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
+}
+
+TEST(MatchFinder, CheckProfiling) {
+ MatchFinder::MatchFinderOptions Options;
+ llvm::StringMap<llvm::TimeRecord> Records;
+ Options.CheckProfiling.emplace(Records);
+ MatchFinder Finder(std::move(Options));
+
+ struct NamedCallback : public MatchFinder::MatchCallback {
+ void run(const MatchFinder::MatchResult &Result) override {}
+ StringRef getID() const override { return "MyID"; }
+ } Callback;
+ Finder.addMatcher(decl(), &Callback);
+ std::unique_ptr<FrontendActionFactory> Factory(
+ newFrontendActionFactory(&Finder));
+ ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
+
+ EXPECT_EQ(1u, Records.size());
+ EXPECT_EQ("MyID", Records.begin()->getKey());
+}
+
+class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
+public:
+ VerifyStartOfTranslationUnit() : Called(false) {}
+ void run(const MatchFinder::MatchResult &Result) override {
+ EXPECT_TRUE(Called);
+ }
+ void onStartOfTranslationUnit() override { Called = true; }
+ bool Called;
+};
+
+TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
+ MatchFinder Finder;
+ VerifyStartOfTranslationUnit VerifyCallback;
+ Finder.addMatcher(decl(), &VerifyCallback);
+ std::unique_ptr<FrontendActionFactory> Factory(
+ newFrontendActionFactory(&Finder));
+ ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
+ EXPECT_TRUE(VerifyCallback.Called);
+
+ VerifyCallback.Called = false;
+ std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
+ ASSERT_TRUE(AST.get());
+ Finder.matchAST(AST->getASTContext());
+ EXPECT_TRUE(VerifyCallback.Called);
+}
+
+class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
+public:
+ VerifyEndOfTranslationUnit() : Called(false) {}
+ void run(const MatchFinder::MatchResult &Result) override {
+ EXPECT_FALSE(Called);
+ }
+ void onEndOfTranslationUnit() override { Called = true; }
+ bool Called;
+};
+
+TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
+ MatchFinder Finder;
+ VerifyEndOfTranslationUnit VerifyCallback;
+ Finder.addMatcher(decl(), &VerifyCallback);
+ std::unique_ptr<FrontendActionFactory> Factory(
+ newFrontendActionFactory(&Finder));
+ ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
+ EXPECT_TRUE(VerifyCallback.Called);
+
+ VerifyCallback.Called = false;
+ std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
+ ASSERT_TRUE(AST.get());
+ Finder.matchAST(AST->getASTContext());
+ EXPECT_TRUE(VerifyCallback.Called);
+}
+
+TEST(Matcher, matchOverEntireASTContext) {
+ std::unique_ptr<ASTUnit> AST =
+ clang::tooling::buildASTFromCode("struct { int *foo; };");
+ ASSERT_TRUE(AST.get());
+ auto PT = selectFirst<PointerType>(
+ "x", match(pointerType().bind("x"), AST->getASTContext()));
+ EXPECT_NE(nullptr, PT);
+}
+
+TEST(IsInlineMatcher, IsInline) {
+ EXPECT_TRUE(matches("void g(); inline void f();",
+ functionDecl(isInline(), hasName("f"))));
+ EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
+ namespaceDecl(isInline(), hasName("m"))));
+}
+
+// FIXME: Figure out how to specify paths so the following tests pass on
+// Windows.
+#ifndef LLVM_ON_WIN32
+
+TEST(Matcher, IsExpansionInMainFileMatcher) {
+ EXPECT_TRUE(matches("class X {};",
+ recordDecl(hasName("X"), isExpansionInMainFile())));
+ EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
+ FileContentMappings M;
+ M.push_back(std::make_pair("/other", "class X {};"));
+ EXPECT_TRUE(matchesConditionally("#include <other>\n",
+ recordDecl(isExpansionInMainFile()), false,
+ "-isystem/", M));
+}
+
+TEST(Matcher, IsExpansionInSystemHeader) {
+ FileContentMappings M;
+ M.push_back(std::make_pair("/other", "class X {};"));
+ EXPECT_TRUE(matchesConditionally(
+ "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
+ "-isystem/", M));
+ EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
+ recordDecl(isExpansionInSystemHeader()),
+ false, "-I/", M));
+ EXPECT_TRUE(notMatches("class X {};",
+ recordDecl(isExpansionInSystemHeader())));
+ EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
+}
+
+TEST(Matcher, IsExpansionInFileMatching) {
+ FileContentMappings M;
+ M.push_back(std::make_pair("/foo", "class A {};"));
+ M.push_back(std::make_pair("/bar", "class B {};"));
+ EXPECT_TRUE(matchesConditionally(
+ "#include <foo>\n"
+ "#include <bar>\n"
+ "class X {};",
+ recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
+ "-isystem/", M));
+ EXPECT_TRUE(matchesConditionally(
+ "#include <foo>\n"
+ "#include <bar>\n"
+ "class X {};",
+ recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
+ "-isystem/", M));
+}
+
+#endif // LLVM_ON_WIN32
+
+} // end namespace ast_matchers
+} // end namespace clang
diff --git a/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp b/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
new file mode 100644
index 0000000000..82c5139a78
--- /dev/null
+++ b/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -0,0 +1,1935 @@
+// unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp - AST matcher unit tests//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ASTMatchersTest.h"
+#include "clang/AST/PrettyPrinter.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/Host.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace ast_matchers {
+
+
+TEST(AllOf, AllOverloadsWork) {
+ const char Program[] =
+ "struct T { };"
+ "int f(int, T*, int, int);"
+ "void g(int x) { T t; f(x, &t, 3, 4); }";
+ EXPECT_TRUE(matches(Program,
+ callExpr(allOf(callee(functionDecl(hasName("f"))),
+ hasArgument(0, declRefExpr(to(varDecl())))))));
+ EXPECT_TRUE(matches(Program,
+ callExpr(allOf(callee(functionDecl(hasName("f"))),
+ hasArgument(0, declRefExpr(to(varDecl()))),
+ hasArgument(1, hasType(pointsTo(
+ recordDecl(hasName("T")))))))));
+ EXPECT_TRUE(matches(Program,
+ callExpr(allOf(callee(functionDecl(hasName("f"))),
+ hasArgument(0, declRefExpr(to(varDecl()))),
+ hasArgument(1, hasType(pointsTo(
+ recordDecl(hasName("T"))))),
+ hasArgument(2, integerLiteral(equals(3)))))));
+ EXPECT_TRUE(matches(Program,
+ callExpr(allOf(callee(functionDecl(hasName("f"))),
+ hasArgument(0, declRefExpr(to(varDecl()))),
+ hasArgument(1, hasType(pointsTo(
+ recordDecl(hasName("T"))))),
+ hasArgument(2, integerLiteral(equals(3))),
+ hasArgument(3, integerLiteral(equals(4)))))));
+}
+
+TEST(DeclarationMatcher, MatchHas) {
+ DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
+ EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
+ EXPECT_TRUE(matches("class X {};", HasClassX));
+
+ DeclarationMatcher YHasClassX =
+ recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
+ EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
+ EXPECT_TRUE(notMatches("class X {};", YHasClassX));
+ EXPECT_TRUE(
+ notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
+}
+
+TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
+ DeclarationMatcher Recursive =
+ recordDecl(
+ has(recordDecl(
+ has(recordDecl(hasName("X"))),
+ has(recordDecl(hasName("Y"))),
+ hasName("Z"))),
+ has(recordDecl(
+ has(recordDecl(hasName("A"))),
+ has(recordDecl(hasName("B"))),
+ hasName("C"))),
+ hasName("F"));
+
+ EXPECT_TRUE(matches(
+ "class F {"
+ " class Z {"
+ " class X {};"
+ " class Y {};"
+ " };"
+ " class C {"
+ " class A {};"
+ " class B {};"
+ " };"
+ "};", Recursive));
+
+ EXPECT_TRUE(matches(
+ "class F {"
+ " class Z {"
+ " class A {};"
+ " class X {};"
+ " class Y {};"
+ " };"
+ " class C {"
+ " class X {};"
+ " class A {};"
+ " class B {};"
+ " };"
+ "};", Recursive));
+
+ EXPECT_TRUE(matches(
+ "class O1 {"
+ " class O2 {"
+ " class F {"
+ " class Z {"
+ " class A {};"
+ " class X {};"
+ " class Y {};"
+ " };"
+ " class C {"
+ " class X {};"
+ " class A {};"
+ " class B {};"
+ " };"
+ " };"
+ " };"
+ "};", Recursive));
+}
+
+TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
+ DeclarationMatcher Recursive =
+ recordDecl(
+ anyOf(
+ has(recordDecl(
+ anyOf(
+ has(recordDecl(
+ hasName("X"))),
+ has(recordDecl(
+ hasName("Y"))),
+ hasName("Z")))),
+ has(recordDecl(
+ anyOf(
+ hasName("C"),
+ has(recordDecl(
+ hasName("A"))),
+ has(recordDecl(
+ hasName("B")))))),
+ hasName("F")));
+
+ EXPECT_TRUE(matches("class F {};", Recursive));
+ EXPECT_TRUE(matches("class Z {};", Recursive));
+ EXPECT_TRUE(matches("class C {};", Recursive));
+ EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
+ EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
+ EXPECT_TRUE(
+ matches("class O1 { class O2 {"
+ " class M { class N { class B {}; }; }; "
+ "}; };", Recursive));
+}
+
+TEST(DeclarationMatcher, MatchNot) {
+ DeclarationMatcher NotClassX =
+ cxxRecordDecl(
+ isDerivedFrom("Y"),
+ unless(hasName("X")));
+ EXPECT_TRUE(notMatches("", NotClassX));
+ EXPECT_TRUE(notMatches("class Y {};", NotClassX));
+ EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
+ EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
+ EXPECT_TRUE(
+ notMatches("class Y {}; class Z {}; class X : public Y {};",
+ NotClassX));
+
+ DeclarationMatcher ClassXHasNotClassY =
+ recordDecl(
+ hasName("X"),
+ has(recordDecl(hasName("Z"))),
+ unless(
+ has(recordDecl(hasName("Y")))));
+ EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
+ EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
+ ClassXHasNotClassY));
+
+ DeclarationMatcher NamedNotRecord =
+ namedDecl(hasName("Foo"), unless(recordDecl()));
+ EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
+ EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
+}
+
+TEST(CastExpression, HasCastKind) {
+ EXPECT_TRUE(matches("char *p = 0;",
+ castExpr(hasCastKind(CK_NullToPointer))));
+ EXPECT_TRUE(notMatches("char *p = 0;",
+ castExpr(hasCastKind(CK_DerivedToBase))));
+ EXPECT_TRUE(matches("char *p = 0;",
+ implicitCastExpr(hasCastKind(CK_NullToPointer))));
+}
+
+TEST(DeclarationMatcher, HasDescendant) {
+ DeclarationMatcher ZDescendantClassX =
+ recordDecl(
+ hasDescendant(recordDecl(hasName("X"))),
+ hasName("Z"));
+ EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
+ EXPECT_TRUE(
+ matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
+ EXPECT_TRUE(
+ matches("class Z { class A { class Y { class X {}; }; }; };",
+ ZDescendantClassX));
+ EXPECT_TRUE(
+ matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
+ ZDescendantClassX));
+ EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
+
+ DeclarationMatcher ZDescendantClassXHasClassY =
+ recordDecl(
+ hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
+ hasName("X"))),
+ hasName("Z"));
+ EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
+ ZDescendantClassXHasClassY));
+ EXPECT_TRUE(
+ matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
+ ZDescendantClassXHasClassY));
+ EXPECT_TRUE(notMatches(
+ "class Z {"
+ " class A {"
+ " class B {"
+ " class X {"
+ " class C {"
+ " class Y {};"
+ " };"
+ " };"
+ " }; "
+ " };"
+ "};", ZDescendantClassXHasClassY));
+
+ DeclarationMatcher ZDescendantClassXDescendantClassY =
+ recordDecl(
+ hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
+ hasName("X"))),
+ hasName("Z"));
+ EXPECT_TRUE(
+ matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
+ ZDescendantClassXDescendantClassY));
+ EXPECT_TRUE(matches(
+ "class Z {"
+ " class A {"
+ " class X {"
+ " class B {"
+ " class Y {};"
+ " };"
+ " class Y {};"
+ " };"
+ " };"
+ "};", ZDescendantClassXDescendantClassY));
+}
+
+TEST(DeclarationMatcher, HasDescendantMemoization) {
+ DeclarationMatcher CannotMemoize =
+ decl(hasDescendant(typeLoc().bind("x")), has(decl()));
+ EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
+}
+
+TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
+ auto Name = hasName("i");
+ auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
+ auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
+ // Matching VD first should not make a cache hit for RD.
+ EXPECT_TRUE(notMatches("void f() { int i; }",
+ decl(hasDescendant(VD), hasDescendant(RD))));
+ EXPECT_TRUE(notMatches("void f() { int i; }",
+ decl(hasDescendant(RD), hasDescendant(VD))));
+ // Not matching RD first should not make a cache hit for VD either.
+ EXPECT_TRUE(matches("void f() { int i; }",
+ decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
+}
+
+TEST(DeclarationMatcher, HasAncestorMemoization) {
+ // This triggers an hasAncestor with a TemplateArgument in the bound nodes.
+ // That node can't be memoized so we have to check for it before trying to put
+ // it on the cache.
+ DeclarationMatcher CannotMemoize = classTemplateSpecializationDecl(
+ hasAnyTemplateArgument(templateArgument().bind("targ")),
+ forEach(fieldDecl(hasAncestor(forStmt()))));
+
+ EXPECT_TRUE(notMatches("template <typename T> struct S;"
+ "template <> struct S<int>{ int i; int j; };",
+ CannotMemoize));
+}
+
+TEST(DeclarationMatcher, HasAttr) {
+ EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
+ decl(hasAttr(clang::attr::WarnUnused))));
+ EXPECT_FALSE(matches("struct X {};",
+ decl(hasAttr(clang::attr::WarnUnused))));
+}
+
+
+TEST(DeclarationMatcher, MatchAnyOf) {
+ DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
+ anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
+ EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
+ EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
+ EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
+
+ DeclarationMatcher XOrYOrZOrU =
+ recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
+ EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
+ EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
+
+ DeclarationMatcher XOrYOrZOrUOrV =
+ recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
+ hasName("V")));
+ EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
+ EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
+ EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
+ EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
+ EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
+ EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
+
+ StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
+ EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
+ EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
+ EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
+
+ EXPECT_TRUE(
+ matches("void f() try { } catch (int) { } catch (...) { }",
+ cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
+}
+
+TEST(DeclarationMatcher, ClassIsDerived) {
+ DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
+
+ EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
+ EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
+ EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
+ EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
+ EXPECT_TRUE(notMatches("", IsDerivedFromX));
+
+ DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
+
+ EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
+ EXPECT_TRUE(matches("class X {};", IsAX));
+ EXPECT_TRUE(matches("class X;", IsAX));
+ EXPECT_TRUE(notMatches("class Y;", IsAX));
+ EXPECT_TRUE(notMatches("", IsAX));
+
+ DeclarationMatcher ZIsDerivedFromX =
+ cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
+ EXPECT_TRUE(
+ matches("class X {}; class Y : public X {}; class Z : public Y {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class X {};"
+ "template<class T> class Y : public X {};"
+ "class Z : public Y<int> {};", ZIsDerivedFromX));
+ EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template<class T> class X {}; "
+ "template<class T> class Z : public X<T> {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template<class T, class U=T> class X {}; "
+ "template<class T> class Z : public X<T> {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("template<class X> class A { class Z : public X {}; };",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template<class X> class A { public: class Z : public X {}; }; "
+ "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template <class T> class X {}; "
+ "template<class Y> class A { class Z : public X<Y> {}; };",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("template<template<class T> class X> class A { "
+ " class Z : public X<int> {}; };", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template<template<class T> class X> class A { "
+ " public: class Z : public X<int> {}; }; "
+ "template<class T> class X {}; void y() { A<X>::Z z; }",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("template<class X> class A { class Z : public X::D {}; };",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template<class X> class A { public: "
+ " class Z : public X::D {}; }; "
+ "class Y { public: class X {}; typedef X D; }; "
+ "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class X {}; typedef X Y; class Z : public Y {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template<class T> class Y { typedef typename T::U X; "
+ " class Z : public X {}; };", ZIsDerivedFromX));
+ EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("template<class T> class X {}; "
+ "template<class T> class A { class Z : public X<T>::D {}; };",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template<class T> class X { public: typedef X<T> D; }; "
+ "template<class T> class A { public: "
+ " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("template<class X> class A { class Z : public X::D::E {}; };",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class X {}; class Y : public X {}; "
+ "typedef Y V; typedef V W; class Z : public W {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template<class T, class U> class X {}; "
+ "template<class T> class A { class Z : public X<T, int> {}; };",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("template<class X> class D { typedef X A; typedef A B; "
+ " typedef B C; class Z : public C {}; };",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class X {}; typedef X A; typedef A B; "
+ "class Z : public B {};", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class X {}; typedef X A; typedef A B; typedef B C; "
+ "class Z : public C {};", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class U {}; typedef U X; typedef X V; "
+ "class Z : public V {};", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class Base {}; typedef Base X; "
+ "class Z : public Base {};", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class Base {}; typedef Base Base2; typedef Base2 X; "
+ "class Z : public Base {};", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
+ "class Z : public Base {};", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ matches("class A {}; typedef A X; typedef A Y; "
+ "class Z : public Y {};", ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("template <typename T> class Z;"
+ "template <> class Z<void> {};"
+ "template <typename T> class Z : public Z<void> {};",
+ IsDerivedFromX));
+ EXPECT_TRUE(
+ matches("template <typename T> class X;"
+ "template <> class X<void> {};"
+ "template <typename T> class X : public X<void> {};",
+ IsDerivedFromX));
+ EXPECT_TRUE(matches(
+ "class X {};"
+ "template <typename T> class Z;"
+ "template <> class Z<void> {};"
+ "template <typename T> class Z : public Z<void>, public X {};",
+ ZIsDerivedFromX));
+ EXPECT_TRUE(
+ notMatches("template<int> struct X;"
+ "template<int i> struct X : public X<i-1> {};",
+ cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
+ EXPECT_TRUE(matches(
+ "struct A {};"
+ "template<int> struct X;"
+ "template<int i> struct X : public X<i-1> {};"
+ "template<> struct X<0> : public A {};"
+ "struct B : public X<42> {};",
+ cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
+
+ // FIXME: Once we have better matchers for template type matching,
+ // get rid of the Variable(...) matching and match the right template
+ // declarations directly.
+ const char *RecursiveTemplateOneParameter =
+ "class Base1 {}; class Base2 {};"
+ "template <typename T> class Z;"
+ "template <> class Z<void> : public Base1 {};"
+ "template <> class Z<int> : public Base2 {};"
+ "template <> class Z<float> : public Z<void> {};"
+ "template <> class Z<double> : public Z<int> {};"
+ "template <typename T> class Z : public Z<float>, public Z<double> {};"
+ "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
+ EXPECT_TRUE(matches(
+ RecursiveTemplateOneParameter,
+ varDecl(hasName("z_float"),
+ hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
+ EXPECT_TRUE(notMatches(
+ RecursiveTemplateOneParameter,
+ varDecl(hasName("z_float"),
+ hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
+ EXPECT_TRUE(matches(
+ RecursiveTemplateOneParameter,
+ varDecl(hasName("z_char"),
+ hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
+ isDerivedFrom("Base2")))))));
+
+ const char *RecursiveTemplateTwoParameters =
+ "class Base1 {}; class Base2 {};"
+ "template <typename T1, typename T2> class Z;"
+ "template <typename T> class Z<void, T> : public Base1 {};"
+ "template <typename T> class Z<int, T> : public Base2 {};"
+ "template <typename T> class Z<float, T> : public Z<void, T> {};"
+ "template <typename T> class Z<double, T> : public Z<int, T> {};"
+ "template <typename T1, typename T2> class Z : "
+ " public Z<float, T2>, public Z<double, T2> {};"
+ "void f() { Z<float, void> z_float; Z<double, void> z_double; "
+ " Z<char, void> z_char; }";
+ EXPECT_TRUE(matches(
+ RecursiveTemplateTwoParameters,
+ varDecl(hasName("z_float"),
+ hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
+ EXPECT_TRUE(notMatches(
+ RecursiveTemplateTwoParameters,
+ varDecl(hasName("z_float"),
+ hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
+ EXPECT_TRUE(matches(
+ RecursiveTemplateTwoParameters,
+ varDecl(hasName("z_char"),
+ hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
+ isDerivedFrom("Base2")))))));
+ EXPECT_TRUE(matches(
+ "namespace ns { class X {}; class Y : public X {}; }",
+ cxxRecordDecl(isDerivedFrom("::ns::X"))));
+ EXPECT_TRUE(notMatches(
+ "class X {}; class Y : public X {};",
+ cxxRecordDecl(isDerivedFrom("::ns::X"))));
+
+ EXPECT_TRUE(matches(
+ "class X {}; class Y : public X {};",
+ cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
+
+ EXPECT_TRUE(matches(
+ "template<typename T> class X {};"
+ "template<typename T> using Z = X<T>;"
+ "template <typename T> class Y : Z<T> {};",
+ cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
+}
+
+TEST(DeclarationMatcher, IsLambda) {
+ const auto IsLambda = cxxMethodDecl(ofClass(cxxRecordDecl(isLambda())));
+ EXPECT_TRUE(matches("auto x = []{};", IsLambda));
+ EXPECT_TRUE(notMatches("struct S { void operator()() const; };", IsLambda));
+}
+
+TEST(Matcher, BindMatchedNodes) {
+ DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
+ ClassX, llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x")));
+
+ EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
+ ClassX, llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("other-id")));
+
+ TypeMatcher TypeAHasClassB = hasDeclaration(
+ recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
+ TypeAHasClassB,
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("b")));
+
+ StatementMatcher MethodX =
+ callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
+
+ EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
+ MethodX,
+ llvm::make_unique<VerifyIdIsBoundTo<CXXMemberCallExpr>>("x")));
+}
+
+TEST(Matcher, BindTheSameNameInAlternatives) {
+ StatementMatcher matcher = anyOf(
+ binaryOperator(hasOperatorName("+"),
+ hasLHS(expr().bind("x")),
+ hasRHS(integerLiteral(equals(0)))),
+ binaryOperator(hasOperatorName("+"),
+ hasLHS(integerLiteral(equals(0))),
+ hasRHS(expr().bind("x"))));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ // The first branch of the matcher binds x to 0 but then fails.
+ // The second branch binds x to f() and succeeds.
+ "int f() { return 0 + f(); }",
+ matcher,
+ llvm::make_unique<VerifyIdIsBoundTo<CallExpr>>("x")));
+}
+
+TEST(Matcher, BindsIDForMemoizedResults) {
+ // Using the same matcher in two match expressions will make memoization
+ // kick in.
+ DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { class B { class X {}; }; };",
+ DeclarationMatcher(anyOf(
+ recordDecl(hasName("A"), hasDescendant(ClassX)),
+ recordDecl(hasName("B"), hasDescendant(ClassX)))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 2)));
+}
+
+TEST(HasType, MatchesAsString) {
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
+ cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
+ EXPECT_TRUE(
+ matches("class X { void x(int x) {} };",
+ cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
+ EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
+ fieldDecl(hasType(asString("ns::A")))));
+ EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
+ fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
+}
+
+TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
+ StatementMatcher OpCallAndAnd =
+ cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
+ EXPECT_TRUE(matches("class Y { }; "
+ "bool operator&&(Y x, Y y) { return true; }; "
+ "Y a; Y b; bool c = a && b;", OpCallAndAnd));
+ StatementMatcher OpCallLessLess =
+ cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
+ EXPECT_TRUE(notMatches("class Y { }; "
+ "bool operator&&(Y x, Y y) { return true; }; "
+ "Y a; Y b; bool c = a && b;",
+ OpCallLessLess));
+ StatementMatcher OpStarCall =
+ cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
+ EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
+ OpStarCall));
+ DeclarationMatcher ClassWithOpStar =
+ cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
+ EXPECT_TRUE(matches("class Y { int operator*(); };",
+ ClassWithOpStar));
+ EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
+ ClassWithOpStar)) ;
+ DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
+ EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
+ EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
+}
+
+
+TEST(Matcher, NestedOverloadedOperatorCalls) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class Y { }; "
+ "Y& operator&&(Y& x, Y& y) { return x; }; "
+ "Y a; Y b; Y c; Y d = a && b && c;",
+ cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXOperatorCallExpr>>("x", 2)));
+ EXPECT_TRUE(matches("class Y { }; "
+ "Y& operator&&(Y& x, Y& y) { return x; }; "
+ "Y a; Y b; Y c; Y d = a && b && c;",
+ cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
+ EXPECT_TRUE(
+ matches("class Y { }; "
+ "Y& operator&&(Y& x, Y& y) { return x; }; "
+ "Y a; Y b; Y c; Y d = a && b && c;",
+ cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
+}
+
+TEST(Matcher, VarDecl_Storage) {
+ auto M = varDecl(hasName("X"), hasLocalStorage());
+ EXPECT_TRUE(matches("void f() { int X; }", M));
+ EXPECT_TRUE(notMatches("int X;", M));
+ EXPECT_TRUE(notMatches("void f() { static int X; }", M));
+
+ M = varDecl(hasName("X"), hasGlobalStorage());
+ EXPECT_TRUE(notMatches("void f() { int X; }", M));
+ EXPECT_TRUE(matches("int X;", M));
+ EXPECT_TRUE(matches("void f() { static int X; }", M));
+}
+
+TEST(Matcher, VarDecl_StorageDuration) {
+ std::string T =
+ "void f() { int x; static int y; } int a;";
+
+ EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
+ EXPECT_TRUE(
+ notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
+ EXPECT_TRUE(
+ notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
+
+ EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
+ EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
+ EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
+
+ // FIXME: It is really hard to test with thread_local itself because not all
+ // targets support TLS, which causes this to be an error depending on what
+ // platform the test is being run on. We do not have access to the TargetInfo
+ // object to be able to test whether the platform supports TLS or not.
+ EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
+ EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
+ EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
+}
+
+TEST(Matcher, FindsVarDeclInFunctionParameter) {
+ EXPECT_TRUE(matches(
+ "void f(int i) {}",
+ varDecl(hasName("i"))));
+}
+
+TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
+ EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
+ hasArgumentOfType(asString("int")))));
+ EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
+ hasArgumentOfType(asString("float")))));
+ EXPECT_TRUE(matches(
+ "struct A {}; void x() { A a; int b = sizeof(a); }",
+ sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
+ EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
+ hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
+}
+
+TEST(IsInteger, MatchesIntegers) {
+ EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
+ EXPECT_TRUE(matches(
+ "long long i = 0; void f(long long) { }; void g() {f(i);}",
+ callExpr(hasArgument(0, declRefExpr(
+ to(varDecl(hasType(isInteger()))))))));
+}
+
+TEST(IsInteger, ReportsNoFalsePositives) {
+ EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
+ EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
+ callExpr(hasArgument(0, declRefExpr(
+ to(varDecl(hasType(isInteger()))))))));
+}
+
+TEST(IsSignedInteger, MatchesSignedIntegers) {
+ EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isSignedInteger()))));
+ EXPECT_TRUE(notMatches("unsigned i = 0;",
+ varDecl(hasType(isSignedInteger()))));
+}
+
+TEST(IsUnsignedInteger, MatchesUnsignedIntegers) {
+ EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isUnsignedInteger()))));
+ EXPECT_TRUE(matches("unsigned i = 0;",
+ varDecl(hasType(isUnsignedInteger()))));
+}
+
+TEST(IsAnyPointer, MatchesPointers) {
+ EXPECT_TRUE(matches("int* i = nullptr;", varDecl(hasType(isAnyPointer()))));
+}
+
+TEST(IsAnyPointer, MatchesObjcPointer) {
+ EXPECT_TRUE(matchesObjC("@interface Foo @end Foo *f;",
+ varDecl(hasType(isAnyPointer()))));
+}
+
+TEST(IsAnyPointer, ReportsNoFalsePositives) {
+ EXPECT_TRUE(notMatches("int i = 0;", varDecl(hasType(isAnyPointer()))));
+}
+
+TEST(IsAnyCharacter, MatchesCharacters) {
+ EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
+}
+
+TEST(IsAnyCharacter, ReportsNoFalsePositives) {
+ EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
+}
+
+TEST(IsArrow, MatchesMemberVariablesViaArrow) {
+ EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
+ memberExpr(isArrow())));
+ EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
+ memberExpr(isArrow())));
+ EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
+ memberExpr(isArrow())));
+}
+
+TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
+ EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
+ memberExpr(isArrow())));
+ EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
+ memberExpr(isArrow())));
+ EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
+ memberExpr(isArrow())));
+}
+
+TEST(IsArrow, MatchesMemberCallsViaArrow) {
+ EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
+ memberExpr(isArrow())));
+ EXPECT_TRUE(matches("class Y { void x() { x(); } };",
+ memberExpr(isArrow())));
+ EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
+ memberExpr(isArrow())));
+}
+
+TEST(ConversionDeclaration, IsExplicit) {
+ EXPECT_TRUE(matches("struct S { explicit operator int(); };",
+ cxxConversionDecl(isExplicit())));
+ EXPECT_TRUE(notMatches("struct S { operator int(); };",
+ cxxConversionDecl(isExplicit())));
+}
+
+TEST(Matcher, ArgumentCount) {
+ StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
+
+ EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
+ EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
+ EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
+}
+
+TEST(Matcher, ParameterCount) {
+ DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
+ EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
+ EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
+ EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
+ EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
+ EXPECT_TRUE(matches("void f(int i, ...) {};", Function1Arg));
+}
+
+TEST(Matcher, References) {
+ DeclarationMatcher ReferenceClassX = varDecl(
+ hasType(references(recordDecl(hasName("X")))));
+ EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
+ ReferenceClassX));
+ EXPECT_TRUE(
+ matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
+ // The match here is on the implicit copy constructor code for
+ // class X, not on code 'X x = y'.
+ EXPECT_TRUE(
+ matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
+ EXPECT_TRUE(
+ notMatches("class X {}; extern X x;", ReferenceClassX));
+ EXPECT_TRUE(
+ notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
+}
+
+TEST(QualType, hasLocalQualifiers) {
+ EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
+ varDecl(hasType(hasLocalQualifiers()))));
+ EXPECT_TRUE(matches("int *const j = nullptr;",
+ varDecl(hasType(hasLocalQualifiers()))));
+ EXPECT_TRUE(matches("int *volatile k;",
+ varDecl(hasType(hasLocalQualifiers()))));
+ EXPECT_TRUE(notMatches("int m;",
+ varDecl(hasType(hasLocalQualifiers()))));
+}
+
+TEST(IsExternC, MatchesExternCFunctionDeclarations) {
+ EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
+ EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
+ functionDecl(isExternC())));
+ EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
+}
+
+TEST(IsDefaulted, MatchesDefaultedFunctionDeclarations) {
+ EXPECT_TRUE(notMatches("class A { ~A(); };",
+ functionDecl(hasName("~A"), isDefaulted())));
+ EXPECT_TRUE(matches("class B { ~B() = default; };",
+ functionDecl(hasName("~B"), isDefaulted())));
+}
+
+TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
+ EXPECT_TRUE(
+ notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
+ EXPECT_TRUE(matches("void Func() = delete;",
+ functionDecl(hasName("Func"), isDeleted())));
+}
+
+TEST(IsNoThrow, MatchesNoThrowFunctionDeclarations) {
+ EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
+ EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
+ EXPECT_TRUE(
+ notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
+ EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
+ EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
+
+ EXPECT_TRUE(notMatches("void f();", functionProtoType(isNoThrow())));
+ EXPECT_TRUE(notMatches("void f() throw(int);", functionProtoType(isNoThrow())));
+ EXPECT_TRUE(
+ notMatches("void f() noexcept(false);", functionProtoType(isNoThrow())));
+ EXPECT_TRUE(matches("void f() throw();", functionProtoType(isNoThrow())));
+ EXPECT_TRUE(matches("void f() noexcept;", functionProtoType(isNoThrow())));
+}
+
+TEST(isConstexpr, MatchesConstexprDeclarations) {
+ EXPECT_TRUE(matches("constexpr int foo = 42;",
+ varDecl(hasName("foo"), isConstexpr())));
+ EXPECT_TRUE(matches("constexpr int bar();",
+ functionDecl(hasName("bar"), isConstexpr())));
+}
+
+TEST(TemplateArgumentCountIs, Matches) {
+ EXPECT_TRUE(
+ matches("template<typename T> struct C {}; C<int> c;",
+ classTemplateSpecializationDecl(templateArgumentCountIs(1))));
+ EXPECT_TRUE(
+ notMatches("template<typename T> struct C {}; C<int> c;",
+ classTemplateSpecializationDecl(templateArgumentCountIs(2))));
+
+ EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
+ templateSpecializationType(templateArgumentCountIs(1))));
+ EXPECT_TRUE(
+ notMatches("template<typename T> struct C {}; C<int> c;",
+ templateSpecializationType(templateArgumentCountIs(2))));
+}
+
+TEST(IsIntegral, Matches) {
+ EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
+ classTemplateSpecializationDecl(
+ hasAnyTemplateArgument(isIntegral()))));
+ EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
+ classTemplateSpecializationDecl(hasAnyTemplateArgument(
+ templateArgument(isIntegral())))));
+}
+
+TEST(EqualsIntegralValue, Matches) {
+ EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
+ classTemplateSpecializationDecl(
+ hasAnyTemplateArgument(equalsIntegralValue("42")))));
+ EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
+ classTemplateSpecializationDecl(
+ hasAnyTemplateArgument(equalsIntegralValue("-42")))));
+ EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
+ classTemplateSpecializationDecl(
+ hasAnyTemplateArgument(equalsIntegralValue("-34")))));
+ EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
+ classTemplateSpecializationDecl(hasAnyTemplateArgument(
+ equalsIntegralValue("0042")))));
+}
+
+TEST(Matcher, MatchesAccessSpecDecls) {
+ EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
+ EXPECT_TRUE(
+ matches("class C { public: int i; };", accessSpecDecl(isPublic())));
+ EXPECT_TRUE(
+ notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
+ EXPECT_TRUE(
+ notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
+
+ EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
+}
+
+TEST(Matcher, MatchesFinal) {
+ EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
+ EXPECT_TRUE(matches("class X { virtual void f() final; };",
+ cxxMethodDecl(isFinal())));
+ EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
+ EXPECT_TRUE(
+ notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
+}
+
+TEST(Matcher, MatchesVirtualMethod) {
+ EXPECT_TRUE(matches("class X { virtual int f(); };",
+ cxxMethodDecl(isVirtual(), hasName("::X::f"))));
+ EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
+}
+
+TEST(Matcher, MatchesVirtualAsWrittenMethod) {
+ EXPECT_TRUE(matches("class A { virtual int f(); };"
+ "class B : public A { int f(); };",
+ cxxMethodDecl(isVirtualAsWritten(), hasName("::A::f"))));
+ EXPECT_TRUE(
+ notMatches("class A { virtual int f(); };"
+ "class B : public A { int f(); };",
+ cxxMethodDecl(isVirtualAsWritten(), hasName("::B::f"))));
+}
+
+TEST(Matcher, MatchesPureMethod) {
+ EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
+ cxxMethodDecl(isPure(), hasName("::X::f"))));
+ EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
+}
+
+TEST(Matcher, MatchesCopyAssignmentOperator) {
+ EXPECT_TRUE(matches("class X { X &operator=(X); };",
+ cxxMethodDecl(isCopyAssignmentOperator())));
+ EXPECT_TRUE(matches("class X { X &operator=(X &); };",
+ cxxMethodDecl(isCopyAssignmentOperator())));
+ EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
+ cxxMethodDecl(isCopyAssignmentOperator())));
+ EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
+ cxxMethodDecl(isCopyAssignmentOperator())));
+ EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
+ cxxMethodDecl(isCopyAssignmentOperator())));
+ EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
+ cxxMethodDecl(isCopyAssignmentOperator())));
+}
+
+TEST(Matcher, MatchesMoveAssignmentOperator) {
+ EXPECT_TRUE(notMatches("class X { X &operator=(X); };",
+ cxxMethodDecl(isMoveAssignmentOperator())));
+ EXPECT_TRUE(matches("class X { X &operator=(X &&); };",
+ cxxMethodDecl(isMoveAssignmentOperator())));
+ EXPECT_TRUE(matches("class X { X &operator=(const X &&); };",
+ cxxMethodDecl(isMoveAssignmentOperator())));
+ EXPECT_TRUE(matches("class X { X &operator=(volatile X &&); };",
+ cxxMethodDecl(isMoveAssignmentOperator())));
+ EXPECT_TRUE(matches("class X { X &operator=(const volatile X &&); };",
+ cxxMethodDecl(isMoveAssignmentOperator())));
+ EXPECT_TRUE(notMatches("class X { X &operator=(X &); };",
+ cxxMethodDecl(isMoveAssignmentOperator())));
+}
+
+TEST(Matcher, MatchesConstMethod) {
+ EXPECT_TRUE(
+ matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
+ EXPECT_TRUE(
+ notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
+}
+
+TEST(Matcher, MatchesOverridingMethod) {
+ EXPECT_TRUE(matches("class X { virtual int f(); }; "
+ "class Y : public X { int f(); };",
+ cxxMethodDecl(isOverride(), hasName("::Y::f"))));
+ EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
+ "class Y : public X { int f(); };",
+ cxxMethodDecl(isOverride(), hasName("::X::f"))));
+ EXPECT_TRUE(notMatches("class X { int f(); }; "
+ "class Y : public X { int f(); };",
+ cxxMethodDecl(isOverride())));
+ EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
+ cxxMethodDecl(isOverride())));
+ EXPECT_TRUE(
+ matches("template <typename Base> struct Y : Base { void f() override;};",
+ cxxMethodDecl(isOverride(), hasName("::Y::f"))));
+}
+
+TEST(Matcher, ConstructorArgument) {
+ StatementMatcher Constructor = cxxConstructExpr(
+ hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
+
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { int y; X x(y); }",
+ Constructor));
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
+ Constructor));
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { int y; X x = y; }",
+ Constructor));
+ EXPECT_TRUE(
+ notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
+ Constructor));
+
+ StatementMatcher WrongIndex = cxxConstructExpr(
+ hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
+ EXPECT_TRUE(
+ notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
+ WrongIndex));
+}
+
+TEST(Matcher, ConstructorArgumentCount) {
+ StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
+
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { X x(0); }",
+ Constructor1Arg));
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { X x = X(0); }",
+ Constructor1Arg));
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { X x = 0; }",
+ Constructor1Arg));
+ EXPECT_TRUE(
+ notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
+ Constructor1Arg));
+}
+
+TEST(Matcher, ConstructorListInitialization) {
+ StatementMatcher ConstructorListInit =
+ cxxConstructExpr(isListInitialization());
+
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { X x{0}; }",
+ ConstructorListInit));
+ EXPECT_FALSE(
+ matches("class X { public: X(int); }; void x() { X x(0); }",
+ ConstructorListInit));
+}
+
+TEST(ConstructorDeclaration, IsImplicit) {
+ // This one doesn't match because the constructor is not added by the
+ // compiler (it is not needed).
+ EXPECT_TRUE(notMatches("class Foo { };",
+ cxxConstructorDecl(isImplicit())));
+ // The compiler added the implicit default constructor.
+ EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
+ cxxConstructorDecl(isImplicit())));
+ EXPECT_TRUE(matches("class Foo { Foo(){} };",
+ cxxConstructorDecl(unless(isImplicit()))));
+ // The compiler added an implicit assignment operator.
+ EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
+ cxxMethodDecl(isImplicit(), hasName("operator="))));
+}
+
+TEST(ConstructorDeclaration, IsExplicit) {
+ EXPECT_TRUE(matches("struct S { explicit S(int); };",
+ cxxConstructorDecl(isExplicit())));
+ EXPECT_TRUE(notMatches("struct S { S(int); };",
+ cxxConstructorDecl(isExplicit())));
+}
+
+TEST(ConstructorDeclaration, Kinds) {
+ EXPECT_TRUE(matches("struct S { S(); };",
+ cxxConstructorDecl(isDefaultConstructor())));
+ EXPECT_TRUE(notMatches("struct S { S(); };",
+ cxxConstructorDecl(isCopyConstructor())));
+ EXPECT_TRUE(notMatches("struct S { S(); };",
+ cxxConstructorDecl(isMoveConstructor())));
+
+ EXPECT_TRUE(notMatches("struct S { S(const S&); };",
+ cxxConstructorDecl(isDefaultConstructor())));
+ EXPECT_TRUE(matches("struct S { S(const S&); };",
+ cxxConstructorDecl(isCopyConstructor())));
+ EXPECT_TRUE(notMatches("struct S { S(const S&); };",
+ cxxConstructorDecl(isMoveConstructor())));
+
+ EXPECT_TRUE(notMatches("struct S { S(S&&); };",
+ cxxConstructorDecl(isDefaultConstructor())));
+ EXPECT_TRUE(notMatches("struct S { S(S&&); };",
+ cxxConstructorDecl(isCopyConstructor())));
+ EXPECT_TRUE(matches("struct S { S(S&&); };",
+ cxxConstructorDecl(isMoveConstructor())));
+}
+
+TEST(ConstructorDeclaration, IsUserProvided) {
+ EXPECT_TRUE(notMatches("struct S { int X = 0; };",
+ cxxConstructorDecl(isUserProvided())));
+ EXPECT_TRUE(notMatches("struct S { S() = default; };",
+ cxxConstructorDecl(isUserProvided())));
+ EXPECT_TRUE(notMatches("struct S { S() = delete; };",
+ cxxConstructorDecl(isUserProvided())));
+ EXPECT_TRUE(
+ matches("struct S { S(); };", cxxConstructorDecl(isUserProvided())));
+ EXPECT_TRUE(matches("struct S { S(); }; S::S(){}",
+ cxxConstructorDecl(isUserProvided())));
+}
+
+TEST(ConstructorDeclaration, IsDelegatingConstructor) {
+ EXPECT_TRUE(notMatches("struct S { S(); S(int); int X; };",
+ cxxConstructorDecl(isDelegatingConstructor())));
+ EXPECT_TRUE(notMatches("struct S { S(){} S(int X) : X(X) {} int X; };",
+ cxxConstructorDecl(isDelegatingConstructor())));
+ EXPECT_TRUE(matches(
+ "struct S { S() : S(0) {} S(int X) : X(X) {} int X; };",
+ cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(0))));
+ EXPECT_TRUE(matches(
+ "struct S { S(); S(int X); int X; }; S::S(int X) : S() {}",
+ cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(1))));
+}
+
+TEST(StringLiteral, HasSize) {
+ StatementMatcher Literal = stringLiteral(hasSize(4));
+ EXPECT_TRUE(matches("const char *s = \"abcd\";", Literal));
+ // wide string
+ EXPECT_TRUE(matches("const wchar_t *s = L\"abcd\";", Literal));
+ // with escaped characters
+ EXPECT_TRUE(matches("const char *s = \"\x05\x06\x07\x08\";", Literal));
+ // no matching, too small
+ EXPECT_TRUE(notMatches("const char *s = \"ab\";", Literal));
+}
+
+TEST(Matcher, HasNameSupportsNamespaces) {
+ EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("a::b::C"))));
+ EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("::a::b::C"))));
+ EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("b::C"))));
+ EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("C"))));
+ EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("c::b::C"))));
+ EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("a::c::C"))));
+ EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("a::b::A"))));
+ EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("::C"))));
+ EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("::b::C"))));
+ EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("z::a::b::C"))));
+ EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
+ recordDecl(hasName("a+b::C"))));
+ EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
+ recordDecl(hasName("C"))));
+}
+
+TEST(Matcher, HasNameSupportsOuterClasses) {
+ EXPECT_TRUE(
+ matches("class A { class B { class C; }; };",
+ recordDecl(hasName("A::B::C"))));
+ EXPECT_TRUE(
+ matches("class A { class B { class C; }; };",
+ recordDecl(hasName("::A::B::C"))));
+ EXPECT_TRUE(
+ matches("class A { class B { class C; }; };",
+ recordDecl(hasName("B::C"))));
+ EXPECT_TRUE(
+ matches("class A { class B { class C; }; };",
+ recordDecl(hasName("C"))));
+ EXPECT_TRUE(
+ notMatches("class A { class B { class C; }; };",
+ recordDecl(hasName("c::B::C"))));
+ EXPECT_TRUE(
+ notMatches("class A { class B { class C; }; };",
+ recordDecl(hasName("A::c::C"))));
+ EXPECT_TRUE(
+ notMatches("class A { class B { class C; }; };",
+ recordDecl(hasName("A::B::A"))));
+ EXPECT_TRUE(
+ notMatches("class A { class B { class C; }; };",
+ recordDecl(hasName("::C"))));
+ EXPECT_TRUE(
+ notMatches("class A { class B { class C; }; };",
+ recordDecl(hasName("::B::C"))));
+ EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
+ recordDecl(hasName("z::A::B::C"))));
+ EXPECT_TRUE(
+ notMatches("class A { class B { class C; }; };",
+ recordDecl(hasName("A+B::C"))));
+}
+
+TEST(Matcher, HasNameSupportsInlinedNamespaces) {
+ std::string code = "namespace a { inline namespace b { class C; } }";
+ EXPECT_TRUE(matches(code, recordDecl(hasName("a::b::C"))));
+ EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
+ EXPECT_TRUE(matches(code, recordDecl(hasName("::a::b::C"))));
+ EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
+}
+
+TEST(Matcher, HasNameSupportsAnonymousNamespaces) {
+ std::string code = "namespace a { namespace { class C; } }";
+ EXPECT_TRUE(
+ matches(code, recordDecl(hasName("a::(anonymous namespace)::C"))));
+ EXPECT_TRUE(matches(code, recordDecl(hasName("a::C"))));
+ EXPECT_TRUE(
+ matches(code, recordDecl(hasName("::a::(anonymous namespace)::C"))));
+ EXPECT_TRUE(matches(code, recordDecl(hasName("::a::C"))));
+}
+
+TEST(Matcher, HasNameSupportsAnonymousOuterClasses) {
+ EXPECT_TRUE(matches("class A { class { class C; } x; };",
+ recordDecl(hasName("A::(anonymous class)::C"))));
+ EXPECT_TRUE(matches("class A { class { class C; } x; };",
+ recordDecl(hasName("::A::(anonymous class)::C"))));
+ EXPECT_FALSE(matches("class A { class { class C; } x; };",
+ recordDecl(hasName("::A::C"))));
+ EXPECT_TRUE(matches("class A { struct { class C; } x; };",
+ recordDecl(hasName("A::(anonymous struct)::C"))));
+ EXPECT_TRUE(matches("class A { struct { class C; } x; };",
+ recordDecl(hasName("::A::(anonymous struct)::C"))));
+ EXPECT_FALSE(matches("class A { struct { class C; } x; };",
+ recordDecl(hasName("::A::C"))));
+}
+
+TEST(Matcher, HasNameSupportsFunctionScope) {
+ std::string code =
+ "namespace a { void F(int a) { struct S { int m; }; int i; } }";
+ EXPECT_TRUE(matches(code, varDecl(hasName("i"))));
+ EXPECT_FALSE(matches(code, varDecl(hasName("F()::i"))));
+
+ EXPECT_TRUE(matches(code, fieldDecl(hasName("m"))));
+ EXPECT_TRUE(matches(code, fieldDecl(hasName("S::m"))));
+ EXPECT_TRUE(matches(code, fieldDecl(hasName("F(int)::S::m"))));
+ EXPECT_TRUE(matches(code, fieldDecl(hasName("a::F(int)::S::m"))));
+ EXPECT_TRUE(matches(code, fieldDecl(hasName("::a::F(int)::S::m"))));
+}
+
+TEST(Matcher, HasAnyName) {
+ const std::string Code = "namespace a { namespace b { class C; } }";
+
+ EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "a::b::C"))));
+ EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("a::b::C", "XX"))));
+ EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX::C", "a::b::C"))));
+ EXPECT_TRUE(matches(Code, recordDecl(hasAnyName("XX", "C"))));
+
+ EXPECT_TRUE(notMatches(Code, recordDecl(hasAnyName("::C", "::b::C"))));
+ EXPECT_TRUE(
+ matches(Code, recordDecl(hasAnyName("::C", "::b::C", "::a::b::C"))));
+
+ std::vector<StringRef> Names = {"::C", "::b::C", "::a::b::C"};
+ EXPECT_TRUE(matches(Code, recordDecl(hasAnyName(Names))));
+}
+
+TEST(Matcher, IsDefinition) {
+ DeclarationMatcher DefinitionOfClassA =
+ recordDecl(hasName("A"), isDefinition());
+ EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
+ EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
+
+ DeclarationMatcher DefinitionOfVariableA =
+ varDecl(hasName("a"), isDefinition());
+ EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
+ EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
+
+ DeclarationMatcher DefinitionOfMethodA =
+ cxxMethodDecl(hasName("a"), isDefinition());
+ EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
+ EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
+}
+
+TEST(Matcher, HandlesNullQualTypes) {
+ // FIXME: Add a Type matcher so we can replace uses of this
+ // variable with Type(True())
+ const TypeMatcher AnyType = anything();
+
+ // We don't really care whether this matcher succeeds; we're testing that
+ // it completes without crashing.
+ EXPECT_TRUE(matches(
+ "struct A { };"
+ "template <typename T>"
+ "void f(T t) {"
+ " T local_t(t /* this becomes a null QualType in the AST */);"
+ "}"
+ "void g() {"
+ " f(0);"
+ "}",
+ expr(hasType(TypeMatcher(
+ anyOf(
+ TypeMatcher(hasDeclaration(anything())),
+ pointsTo(AnyType),
+ references(AnyType)
+ // Other QualType matchers should go here.
+ ))))));
+}
+
+
+TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
+ EXPECT_TRUE(matches("void f() { }",
+ compoundStmt(statementCountIs(0))));
+ EXPECT_TRUE(notMatches("void f() {}",
+ compoundStmt(statementCountIs(1))));
+}
+
+TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
+ EXPECT_TRUE(matches("void f() { 1; }",
+ compoundStmt(statementCountIs(1))));
+ EXPECT_TRUE(notMatches("void f() { 1; }",
+ compoundStmt(statementCountIs(0))));
+ EXPECT_TRUE(notMatches("void f() { 1; }",
+ compoundStmt(statementCountIs(2))));
+}
+
+TEST(StatementCountIs, WorksWithMultipleStatements) {
+ EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
+ compoundStmt(statementCountIs(3))));
+}
+
+TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
+ EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
+ compoundStmt(statementCountIs(1))));
+ EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
+ compoundStmt(statementCountIs(2))));
+ EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
+ compoundStmt(statementCountIs(3))));
+ EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
+ compoundStmt(statementCountIs(4))));
+}
+
+TEST(Member, WorksInSimplestCase) {
+ EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
+ memberExpr(member(hasName("first")))));
+}
+
+TEST(Member, DoesNotMatchTheBaseExpression) {
+ // Don't pick out the wrong part of the member expression, this should
+ // be checking the member (name) only.
+ EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
+ memberExpr(member(hasName("first")))));
+}
+
+TEST(Member, MatchesInMemberFunctionCall) {
+ EXPECT_TRUE(matches("void f() {"
+ " struct { void first() {}; } s;"
+ " s.first();"
+ "};",
+ memberExpr(member(hasName("first")))));
+}
+
+TEST(Member, MatchesMember) {
+ EXPECT_TRUE(matches(
+ "struct A { int i; }; void f() { A a; a.i = 2; }",
+ memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
+ EXPECT_TRUE(notMatches(
+ "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
+ memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
+}
+
+TEST(Member, BitFields) {
+ EXPECT_TRUE(matches("class C { int a : 2; int b; };",
+ fieldDecl(isBitField(), hasName("a"))));
+ EXPECT_TRUE(notMatches("class C { int a : 2; int b; };",
+ fieldDecl(isBitField(), hasName("b"))));
+ EXPECT_TRUE(matches("class C { int a : 2; int b : 4; };",
+ fieldDecl(isBitField(), hasBitWidth(2), hasName("a"))));
+}
+
+TEST(Member, UnderstandsAccess) {
+ EXPECT_TRUE(matches(
+ "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
+ EXPECT_TRUE(notMatches(
+ "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
+ EXPECT_TRUE(notMatches(
+ "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
+
+ EXPECT_TRUE(notMatches(
+ "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
+ EXPECT_TRUE(notMatches(
+ "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
+ EXPECT_TRUE(matches(
+ "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
+
+ EXPECT_TRUE(notMatches(
+ "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
+ EXPECT_TRUE(matches("class A { protected: int i; };",
+ fieldDecl(isProtected(), hasName("i"))));
+ EXPECT_TRUE(notMatches(
+ "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
+
+ // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
+ EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
+ EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
+ EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
+}
+
+TEST(hasDynamicExceptionSpec, MatchesDynamicExceptionSpecifications) {
+ EXPECT_TRUE(notMatches("void f();", functionDecl(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(notMatches("void g() noexcept;",
+ functionDecl(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(notMatches("void h() noexcept(true);",
+ functionDecl(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(notMatches("void i() noexcept(false);",
+ functionDecl(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(
+ matches("void j() throw();", functionDecl(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(
+ matches("void k() throw(int);", functionDecl(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(
+ matches("void l() throw(...);", functionDecl(hasDynamicExceptionSpec())));
+
+ EXPECT_TRUE(notMatches("void f();", functionProtoType(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(notMatches("void g() noexcept;",
+ functionProtoType(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(notMatches("void h() noexcept(true);",
+ functionProtoType(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(notMatches("void i() noexcept(false);",
+ functionProtoType(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(
+ matches("void j() throw();", functionProtoType(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(
+ matches("void k() throw(int);", functionProtoType(hasDynamicExceptionSpec())));
+ EXPECT_TRUE(
+ matches("void l() throw(...);", functionProtoType(hasDynamicExceptionSpec())));
+}
+
+TEST(HasObjectExpression, DoesNotMatchMember) {
+ EXPECT_TRUE(notMatches(
+ "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
+ memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
+}
+
+TEST(HasObjectExpression, MatchesBaseOfVariable) {
+ EXPECT_TRUE(matches(
+ "struct X { int m; }; void f(X x) { x.m; }",
+ memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
+ EXPECT_TRUE(matches(
+ "struct X { int m; }; void f(X* x) { x->m; }",
+ memberExpr(hasObjectExpression(
+ hasType(pointsTo(recordDecl(hasName("X"))))))));
+}
+
+TEST(HasObjectExpression,
+ MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
+ EXPECT_TRUE(matches(
+ "class X {}; struct S { X m; void f() { this->m; } };",
+ memberExpr(hasObjectExpression(
+ hasType(pointsTo(recordDecl(hasName("S"))))))));
+ EXPECT_TRUE(matches(
+ "class X {}; struct S { X m; void f() { m; } };",
+ memberExpr(hasObjectExpression(
+ hasType(pointsTo(recordDecl(hasName("S"))))))));
+}
+
+TEST(Field, DoesNotMatchNonFieldMembers) {
+ EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
+ EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
+ EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
+ EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
+}
+
+TEST(Field, MatchesField) {
+ EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
+}
+
+TEST(IsVolatileQualified, QualifiersMatch) {
+ EXPECT_TRUE(matches("volatile int i = 42;",
+ varDecl(hasType(isVolatileQualified()))));
+ EXPECT_TRUE(notMatches("volatile int *i;",
+ varDecl(hasType(isVolatileQualified()))));
+ EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
+ varDecl(hasType(isVolatileQualified()))));
+}
+
+TEST(IsConstQualified, MatchesConstInt) {
+ EXPECT_TRUE(matches("const int i = 42;",
+ varDecl(hasType(isConstQualified()))));
+}
+
+TEST(IsConstQualified, MatchesConstPointer) {
+ EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
+ varDecl(hasType(isConstQualified()))));
+}
+
+TEST(IsConstQualified, MatchesThroughTypedef) {
+ EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
+ varDecl(hasType(isConstQualified()))));
+ EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
+ varDecl(hasType(isConstQualified()))));
+}
+
+TEST(IsConstQualified, DoesNotMatchInappropriately) {
+ EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
+ varDecl(hasType(isConstQualified()))));
+ EXPECT_TRUE(notMatches("int const* p;",
+ varDecl(hasType(isConstQualified()))));
+}
+
+TEST(DeclCount, DeclCountIsCorrect) {
+ EXPECT_TRUE(matches("void f() {int i,j;}",
+ declStmt(declCountIs(2))));
+ EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
+ declStmt(declCountIs(3))));
+ EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
+ declStmt(declCountIs(3))));
+}
+
+
+TEST(EachOf, TriggersForEachMatch) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { int a; int b; };",
+ recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
+ has(fieldDecl(hasName("b")).bind("v")))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 2)));
+}
+
+TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { int a; int c; };",
+ recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
+ has(fieldDecl(hasName("b")).bind("v")))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { int c; int b; };",
+ recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
+ has(fieldDecl(hasName("b")).bind("v")))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 1)));
+ EXPECT_TRUE(notMatches(
+ "class A { int c; int d; };",
+ recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
+ has(fieldDecl(hasName("b")).bind("v"))))));
+}
+
+TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
+ // Make sure that we can both match the class by name (::X) and by the type
+ // the template was instantiated with (via a field).
+
+ EXPECT_TRUE(matches(
+ "template <typename T> class X {}; class A {}; X<A> x;",
+ cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
+
+ EXPECT_TRUE(matches(
+ "template <typename T> class X { T t; }; class A {}; X<A> x;",
+ cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
+ fieldDecl(hasType(recordDecl(hasName("A"))))))));
+}
+
+TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
+ EXPECT_TRUE(matches(
+ "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
+ functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
+ isTemplateInstantiation())));
+}
+
+TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
+ EXPECT_TRUE(matches(
+ "template <typename T> class X { T t; }; class A {};"
+ "template class X<A>;",
+ cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
+ fieldDecl(hasType(recordDecl(hasName("A"))))))));
+}
+
+TEST(IsTemplateInstantiation,
+ MatchesInstantiationOfPartiallySpecializedClassTemplate) {
+ EXPECT_TRUE(matches(
+ "template <typename T> class X {};"
+ "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
+ cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
+}
+
+TEST(IsTemplateInstantiation,
+ MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
+ EXPECT_TRUE(matches(
+ "class A {};"
+ "class X {"
+ " template <typename U> class Y { U u; };"
+ " Y<A> y;"
+ "};",
+ cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
+}
+
+TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
+ // FIXME: Figure out whether this makes sense. It doesn't affect the
+ // normal use case as long as the uppermost instantiation always is marked
+ // as template instantiation, but it might be confusing as a predicate.
+ EXPECT_TRUE(matches(
+ "class A {};"
+ "template <typename T> class X {"
+ " template <typename U> class Y { U u; };"
+ " Y<T> y;"
+ "}; X<A> x;",
+ cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
+}
+
+TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
+ EXPECT_TRUE(notMatches(
+ "template <typename T> class X {}; class A {};"
+ "template <> class X<A> {}; X<A> x;",
+ cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
+}
+
+TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
+ EXPECT_TRUE(notMatches(
+ "class A {}; class Y { A a; };",
+ cxxRecordDecl(isTemplateInstantiation())));
+}
+
+TEST(IsInstantiated, MatchesInstantiation) {
+ EXPECT_TRUE(
+ matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
+ cxxRecordDecl(isInstantiated())));
+}
+
+TEST(IsInstantiated, NotMatchesDefinition) {
+ EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
+ cxxRecordDecl(isInstantiated())));
+}
+
+TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
+ EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
+ "class Y { A<int> a; }; Y y;",
+ declStmt(isInTemplateInstantiation())));
+}
+
+TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
+ EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
+ declStmt(isInTemplateInstantiation())));
+}
+
+TEST(IsInstantiated, MatchesFunctionInstantiation) {
+ EXPECT_TRUE(
+ matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
+ functionDecl(isInstantiated())));
+}
+
+TEST(IsInstantiated, NotMatchesFunctionDefinition) {
+ EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
+ varDecl(isInstantiated())));
+}
+
+TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
+ EXPECT_TRUE(
+ matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
+ declStmt(isInTemplateInstantiation())));
+}
+
+TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
+ EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
+ declStmt(isInTemplateInstantiation())));
+}
+
+TEST(IsInTemplateInstantiation, Sharing) {
+ auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
+ // FIXME: Node sharing is an implementation detail, exposing it is ugly
+ // and makes the matcher behave in non-obvious ways.
+ EXPECT_TRUE(notMatches(
+ "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
+ Matcher));
+ EXPECT_TRUE(matches(
+ "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
+ Matcher));
+}
+
+TEST(IsExplicitTemplateSpecialization,
+ DoesNotMatchPrimaryTemplate) {
+ EXPECT_TRUE(notMatches(
+ "template <typename T> class X {};",
+ cxxRecordDecl(isExplicitTemplateSpecialization())));
+ EXPECT_TRUE(notMatches(
+ "template <typename T> void f(T t);",
+ functionDecl(isExplicitTemplateSpecialization())));
+}
+
+TEST(IsExplicitTemplateSpecialization,
+ DoesNotMatchExplicitTemplateInstantiations) {
+ EXPECT_TRUE(notMatches(
+ "template <typename T> class X {};"
+ "template class X<int>; extern template class X<long>;",
+ cxxRecordDecl(isExplicitTemplateSpecialization())));
+ EXPECT_TRUE(notMatches(
+ "template <typename T> void f(T t) {}"
+ "template void f(int t); extern template void f(long t);",
+ functionDecl(isExplicitTemplateSpecialization())));
+}
+
+TEST(IsExplicitTemplateSpecialization,
+ DoesNotMatchImplicitTemplateInstantiations) {
+ EXPECT_TRUE(notMatches(
+ "template <typename T> class X {}; X<int> x;",
+ cxxRecordDecl(isExplicitTemplateSpecialization())));
+ EXPECT_TRUE(notMatches(
+ "template <typename T> void f(T t); void g() { f(10); }",
+ functionDecl(isExplicitTemplateSpecialization())));
+}
+
+TEST(IsExplicitTemplateSpecialization,
+ MatchesExplicitTemplateSpecializations) {
+ EXPECT_TRUE(matches(
+ "template <typename T> class X {};"
+ "template<> class X<int> {};",
+ cxxRecordDecl(isExplicitTemplateSpecialization())));
+ EXPECT_TRUE(matches(
+ "template <typename T> void f(T t) {}"
+ "template<> void f(int t) {}",
+ functionDecl(isExplicitTemplateSpecialization())));
+}
+
+TEST(TypeMatching, MatchesBool) {
+ EXPECT_TRUE(matches("struct S { bool func(); };",
+ cxxMethodDecl(returns(booleanType()))));
+ EXPECT_TRUE(notMatches("struct S { void func(); };",
+ cxxMethodDecl(returns(booleanType()))));
+}
+
+TEST(TypeMatching, MatchesVoid) {
+ EXPECT_TRUE(matches("struct S { void func(); };",
+ cxxMethodDecl(returns(voidType()))));
+}
+
+TEST(TypeMatching, MatchesRealFloats) {
+ EXPECT_TRUE(matches("struct S { float func(); };",
+ cxxMethodDecl(returns(realFloatingPointType()))));
+ EXPECT_TRUE(notMatches("struct S { int func(); };",
+ cxxMethodDecl(returns(realFloatingPointType()))));
+ EXPECT_TRUE(matches("struct S { long double func(); };",
+ cxxMethodDecl(returns(realFloatingPointType()))));
+}
+
+TEST(TypeMatching, MatchesArrayTypes) {
+ EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
+ EXPECT_TRUE(matches("int a[42];", arrayType()));
+ EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
+
+ EXPECT_TRUE(notMatches("struct A {}; A a[7];",
+ arrayType(hasElementType(builtinType()))));
+
+ EXPECT_TRUE(matches(
+ "int const a[] = { 2, 3 };",
+ qualType(arrayType(hasElementType(builtinType())))));
+ EXPECT_TRUE(matches(
+ "int const a[] = { 2, 3 };",
+ qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
+ EXPECT_TRUE(matches(
+ "typedef const int T; T x[] = { 1, 2 };",
+ qualType(isConstQualified(), arrayType())));
+
+ EXPECT_TRUE(notMatches(
+ "int a[] = { 2, 3 };",
+ qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
+ EXPECT_TRUE(notMatches(
+ "int a[] = { 2, 3 };",
+ qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
+ EXPECT_TRUE(notMatches(
+ "int const a[] = { 2, 3 };",
+ qualType(arrayType(hasElementType(builtinType())),
+ unless(isConstQualified()))));
+
+ EXPECT_TRUE(matches("int a[2];",
+ constantArrayType(hasElementType(builtinType()))));
+ EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
+}
+
+TEST(TypeMatching, DecayedType) {
+ EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
+ EXPECT_TRUE(notMatches("int i[7];", decayedType()));
+}
+
+TEST(TypeMatching, MatchesComplexTypes) {
+ EXPECT_TRUE(matches("_Complex float f;", complexType()));
+ EXPECT_TRUE(matches(
+ "_Complex float f;",
+ complexType(hasElementType(builtinType()))));
+ EXPECT_TRUE(notMatches(
+ "_Complex float f;",
+ complexType(hasElementType(isInteger()))));
+}
+
+TEST(NS, Anonymous) {
+ EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
+ EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
+}
+
+TEST(EqualsBoundNodeMatcher, QualType) {
+ EXPECT_TRUE(matches(
+ "int i = 1;", varDecl(hasType(qualType().bind("type")),
+ hasInitializer(ignoringParenImpCasts(
+ hasType(qualType(equalsBoundNode("type"))))))));
+ EXPECT_TRUE(notMatches("int i = 1.f;",
+ varDecl(hasType(qualType().bind("type")),
+ hasInitializer(ignoringParenImpCasts(hasType(
+ qualType(equalsBoundNode("type"))))))));
+}
+
+TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
+ EXPECT_TRUE(notMatches(
+ "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
+ hasInitializer(ignoringParenImpCasts(
+ hasType(qualType(equalsBoundNode("type"))))))));
+}
+
+TEST(EqualsBoundNodeMatcher, Stmt) {
+ EXPECT_TRUE(
+ matches("void f() { if(true) {} }",
+ stmt(allOf(ifStmt().bind("if"),
+ hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
+
+ EXPECT_TRUE(notMatches(
+ "void f() { if(true) { if (true) {} } }",
+ stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
+}
+
+TEST(EqualsBoundNodeMatcher, Decl) {
+ EXPECT_TRUE(matches(
+ "class X { class Y {}; };",
+ decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
+ hasParent(decl(has(decl(equalsBoundNode("record")))))))));
+
+ EXPECT_TRUE(notMatches("class X { class Y {}; };",
+ decl(allOf(recordDecl(hasName("::X")).bind("record"),
+ has(decl(equalsBoundNode("record")))))));
+}
+
+TEST(EqualsBoundNodeMatcher, Type) {
+ EXPECT_TRUE(matches(
+ "class X { int a; int b; };",
+ recordDecl(
+ has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
+ has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
+
+ EXPECT_TRUE(notMatches(
+ "class X { int a; double b; };",
+ recordDecl(
+ has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
+ has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
+}
+
+TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "int f() {"
+ " if (1) {"
+ " int i = 9;"
+ " }"
+ " int j = 10;"
+ " {"
+ " float k = 9.0;"
+ " }"
+ " return 0;"
+ "}",
+ // Look for variable declarations within functions whose type is the same
+ // as the function return type.
+ functionDecl(returns(qualType().bind("type")),
+ forEachDescendant(varDecl(hasType(
+ qualType(equalsBoundNode("type")))).bind("decl"))),
+ // Only i and j should match, not k.
+ llvm::make_unique<VerifyIdIsBoundTo<VarDecl>>("decl", 2)));
+}
+
+TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void f() {"
+ " int x;"
+ " double d;"
+ " x = d + x - d + x;"
+ "}",
+ functionDecl(
+ hasName("f"), forEachDescendant(varDecl().bind("d")),
+ forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
+ llvm::make_unique<VerifyIdIsBoundTo<VarDecl>>("d", 5)));
+}
+
+TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "struct StringRef { int size() const; const char* data() const; };"
+ "void f(StringRef v) {"
+ " v.data();"
+ "}",
+ cxxMemberCallExpr(
+ callee(cxxMethodDecl(hasName("data"))),
+ on(declRefExpr(to(
+ varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
+ unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
+ callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
+ on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
+ .bind("data"),
+ llvm::make_unique<VerifyIdIsBoundTo<Expr>>("data", 1)));
+
+ EXPECT_FALSE(matches(
+ "struct StringRef { int size() const; const char* data() const; };"
+ "void f(StringRef v) {"
+ " v.data();"
+ " v.size();"
+ "}",
+ cxxMemberCallExpr(
+ callee(cxxMethodDecl(hasName("data"))),
+ on(declRefExpr(to(
+ varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
+ unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
+ callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
+ on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
+ .bind("data")));
+}
+
+TEST(NullPointerConstants, Basic) {
+ EXPECT_TRUE(matches("#define NULL ((void *)0)\n"
+ "void *v1 = NULL;", expr(nullPointerConstant())));
+ EXPECT_TRUE(matches("void *v2 = nullptr;", expr(nullPointerConstant())));
+ EXPECT_TRUE(matches("void *v3 = __null;", expr(nullPointerConstant())));
+ EXPECT_TRUE(matches("char *cp = (char *)0;", expr(nullPointerConstant())));
+ EXPECT_TRUE(matches("int *ip = 0;", expr(nullPointerConstant())));
+ EXPECT_TRUE(notMatches("int i = 0;", expr(nullPointerConstant())));
+}
+
+} // namespace ast_matchers
+} // namespace clang
diff --git a/unittests/ASTMatchers/ASTMatchersNodeTest.cpp b/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
new file mode 100644
index 0000000000..6c8a5e000f
--- /dev/null
+++ b/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -0,0 +1,1539 @@
+//== unittests/ASTMatchers/ASTMatchersNodeTest.cpp - AST matcher unit tests ==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ASTMatchersTest.h"
+#include "clang/AST/PrettyPrinter.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/Host.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace ast_matchers {
+
+TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
+ MatchFinder Finder;
+ EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
+ EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
+ EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
+ nullptr));
+
+ // Do not accept non-toplevel matchers.
+ EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
+ EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
+}
+
+TEST(Decl, MatchesDeclarations) {
+ EXPECT_TRUE(notMatches("", decl(usingDecl())));
+ EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
+ decl(usingDecl())));
+}
+
+TEST(NameableDeclaration, MatchesVariousDecls) {
+ DeclarationMatcher NamedX = namedDecl(hasName("X"));
+ EXPECT_TRUE(matches("typedef int X;", NamedX));
+ EXPECT_TRUE(matches("int X;", NamedX));
+ EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
+ EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
+ EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
+ EXPECT_TRUE(matches("namespace X { }", NamedX));
+ EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
+
+ EXPECT_TRUE(notMatches("#define X 1", NamedX));
+}
+
+TEST(NameableDeclaration, REMatchesVariousDecls) {
+ DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
+ EXPECT_TRUE(matches("typedef int Xa;", NamedX));
+ EXPECT_TRUE(matches("int Xb;", NamedX));
+ EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
+ EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
+ EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
+ EXPECT_TRUE(matches("namespace Xij { }", NamedX));
+ EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
+
+ EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
+
+ DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
+ EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
+ EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
+
+ DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
+ EXPECT_TRUE(matches("int abc;", Abc));
+ EXPECT_TRUE(matches("int aFOObBARc;", Abc));
+ EXPECT_TRUE(notMatches("int cab;", Abc));
+ EXPECT_TRUE(matches("int cabc;", Abc));
+
+ DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
+ EXPECT_TRUE(matches("int k;", StartsWithK));
+ EXPECT_TRUE(matches("int kAbc;", StartsWithK));
+ EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
+ EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
+ EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
+}
+
+TEST(DeclarationMatcher, MatchClass) {
+ DeclarationMatcher ClassMatcher(recordDecl());
+
+ // This passes on Windows only because we explicitly pass -target
+ // i386-unknown-unknown. If we were to compile with the default target
+ // triple, we'd want to EXPECT_TRUE if it's Win32 or MSVC.
+ EXPECT_FALSE(matches("", ClassMatcher));
+
+ DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
+ EXPECT_TRUE(matches("class X;", ClassX));
+ EXPECT_TRUE(matches("class X {};", ClassX));
+ EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
+ EXPECT_TRUE(notMatches("", ClassX));
+}
+
+TEST(DeclarationMatcher, translationUnitDecl) {
+ const std::string Code = "int MyVar1;\n"
+ "namespace NameSpace {\n"
+ "int MyVar2;\n"
+ "} // namespace NameSpace\n";
+ EXPECT_TRUE(matches(
+ Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
+ EXPECT_FALSE(matches(
+ Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
+ EXPECT_TRUE(matches(
+ Code,
+ varDecl(hasName("MyVar2"),
+ hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
+}
+
+TEST(DeclarationMatcher, LinkageSpecification) {
+ EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
+ EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
+}
+
+TEST(ClassTemplate, DoesNotMatchClass) {
+ DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
+ EXPECT_TRUE(notMatches("class X;", ClassX));
+ EXPECT_TRUE(notMatches("class X {};", ClassX));
+}
+
+TEST(ClassTemplate, MatchesClassTemplate) {
+ DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
+ EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
+ EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
+}
+
+TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
+ EXPECT_TRUE(notMatches("template<typename T> class X { };"
+ "template<> class X<int> { int a; };",
+ classTemplateDecl(hasName("X"),
+ hasDescendant(fieldDecl(hasName("a"))))));
+}
+
+TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
+ EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
+ "template<typename T> class X<T, int> { int a; };",
+ classTemplateDecl(hasName("X"),
+ hasDescendant(fieldDecl(hasName("a"))))));
+}
+
+TEST(DeclarationMatcher, MatchCudaDecl) {
+ EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
+ "void g() { f<<<1, 2>>>(); }",
+ cudaKernelCallExpr()));
+ EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
+ hasAttr(clang::attr::CUDADevice)));
+ EXPECT_TRUE(notMatchesWithCuda("void f() {}",
+ cudaKernelCallExpr()));
+ EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
+ hasAttr(clang::attr::CUDAGlobal)));
+}
+
+TEST(ValueDecl, Matches) {
+ EXPECT_TRUE(matches("enum EnumType { EnumValue };",
+ valueDecl(hasType(asString("enum EnumType")))));
+ EXPECT_TRUE(matches("void FunctionDecl();",
+ valueDecl(hasType(asString("void (void)")))));
+}
+
+TEST(Enum, DoesNotMatchClasses) {
+ EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
+}
+
+TEST(Enum, MatchesEnums) {
+ EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
+}
+
+TEST(EnumConstant, Matches) {
+ DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
+ EXPECT_TRUE(matches("enum X{ A };", Matcher));
+ EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
+ EXPECT_TRUE(notMatches("enum X {};", Matcher));
+}
+
+TEST(Matcher, UnresolvedLookupExpr) {
+ // FIXME: The test is known to be broken on Windows with delayed template
+ // parsing.
+ EXPECT_TRUE(matchesConditionally("template<typename T>"
+ "T foo() { T a; return a; }"
+ "template<typename T>"
+ "void bar() {"
+ " foo<T>();"
+ "}",
+ unresolvedLookupExpr(),
+ /*ExpectMatch=*/true,
+ "-fno-delayed-template-parsing"));
+}
+
+TEST(Matcher, Call) {
+ // FIXME: Do we want to overload Call() to directly take
+ // Matcher<Decl>, too?
+ StatementMatcher MethodX =
+ callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
+
+ EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
+ EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
+
+ StatementMatcher MethodOnY =
+ cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
+
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
+ MethodOnY));
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
+ MethodOnY));
+ EXPECT_TRUE(
+ notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
+ MethodOnY));
+ EXPECT_TRUE(
+ notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
+ MethodOnY));
+ EXPECT_TRUE(
+ notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
+ MethodOnY));
+
+ StatementMatcher MethodOnYPointer =
+ cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
+
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
+ MethodOnYPointer));
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
+ MethodOnYPointer));
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
+ MethodOnYPointer));
+ EXPECT_TRUE(
+ notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
+ MethodOnYPointer));
+ EXPECT_TRUE(
+ notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
+ MethodOnYPointer));
+}
+TEST(Matcher, Lambda) {
+ EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
+ lambdaExpr()));
+}
+
+TEST(Matcher, ForRange) {
+ EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
+ "void f() { for (auto &a : as); }",
+ cxxForRangeStmt()));
+ EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
+ cxxForRangeStmt()));
+}
+
+TEST(Matcher, SubstNonTypeTemplateParm) {
+ EXPECT_FALSE(matches("template<int N>\n"
+ "struct A { static const int n = 0; };\n"
+ "struct B : public A<42> {};",
+ substNonTypeTemplateParmExpr()));
+ EXPECT_TRUE(matches("template<int N>\n"
+ "struct A { static const int n = N; };\n"
+ "struct B : public A<42> {};",
+ substNonTypeTemplateParmExpr()));
+}
+
+TEST(Matcher, NonTypeTemplateParmDecl) {
+ EXPECT_TRUE(matches("template <int N> void f();",
+ nonTypeTemplateParmDecl(hasName("N"))));
+ EXPECT_TRUE(
+ notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
+}
+
+TEST(Matcher, templateTypeParmDecl) {
+ EXPECT_TRUE(matches("template <typename T> void f();",
+ templateTypeParmDecl(hasName("T"))));
+ EXPECT_TRUE(
+ notMatches("template <int N> void f();", templateTypeParmDecl()));
+}
+
+TEST(Matcher, UserDefinedLiteral) {
+ EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
+ " return i + 1;"
+ "}"
+ "char c = 'a'_inc;",
+ userDefinedLiteral()));
+}
+
+TEST(Matcher, FlowControl) {
+ EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
+ EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
+ continueStmt()));
+ EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
+ EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}",
+ labelStmt(
+ hasDeclaration(
+ labelDecl(hasName("FOO"))))));
+ EXPECT_TRUE(matches("void f() { FOO: ; void *ptr = &&FOO; goto *ptr; }",
+ addrLabelExpr()));
+ EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
+}
+
+TEST(Matcher, OverloadedOperatorCall) {
+ StatementMatcher OpCall = cxxOperatorCallExpr();
+ // Unary operator
+ EXPECT_TRUE(matches("class Y { }; "
+ "bool operator!(Y x) { return false; }; "
+ "Y y; bool c = !y;", OpCall));
+ // No match -- special operators like "new", "delete"
+ // FIXME: operator new takes size_t, for which we need stddef.h, for which
+ // we need to figure out include paths in the test.
+ // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
+ // "class Y { }; "
+ // "void *operator new(size_t size) { return 0; } "
+ // "Y *y = new Y;", OpCall));
+ EXPECT_TRUE(notMatches("class Y { }; "
+ "void operator delete(void *p) { } "
+ "void a() {Y *y = new Y; delete y;}", OpCall));
+ // Binary operator
+ EXPECT_TRUE(matches("class Y { }; "
+ "bool operator&&(Y x, Y y) { return true; }; "
+ "Y a; Y b; bool c = a && b;",
+ OpCall));
+ // No match -- normal operator, not an overloaded one.
+ EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
+ EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
+}
+
+TEST(Matcher, ThisPointerType) {
+ StatementMatcher MethodOnY =
+ cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
+
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
+ MethodOnY));
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
+ MethodOnY));
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
+ MethodOnY));
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
+ MethodOnY));
+ EXPECT_TRUE(
+ matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
+ MethodOnY));
+
+ EXPECT_TRUE(matches(
+ "class Y {"
+ " public: virtual void x();"
+ "};"
+ "class X : public Y {"
+ " public: virtual void x();"
+ "};"
+ "void z() { X *x; x->Y::x(); }", MethodOnY));
+}
+
+TEST(Matcher, VariableUsage) {
+ StatementMatcher Reference =
+ declRefExpr(to(
+ varDecl(hasInitializer(
+ cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
+
+ EXPECT_TRUE(matches(
+ "class Y {"
+ " public:"
+ " bool x() const;"
+ "};"
+ "void z(const Y &y) {"
+ " bool b = y.x();"
+ " if (b) {}"
+ "}", Reference));
+
+ EXPECT_TRUE(notMatches(
+ "class Y {"
+ " public:"
+ " bool x() const;"
+ "};"
+ "void z(const Y &y) {"
+ " bool b = y.x();"
+ "}", Reference));
+}
+
+TEST(Matcher, CalledVariable) {
+ StatementMatcher CallOnVariableY =
+ cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
+
+ EXPECT_TRUE(matches(
+ "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
+ EXPECT_TRUE(matches(
+ "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
+ EXPECT_TRUE(matches(
+ "class Y { public: void x(); };"
+ "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
+ EXPECT_TRUE(matches(
+ "class Y { public: void x(); };"
+ "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
+ EXPECT_TRUE(notMatches(
+ "class Y { public: void x(); };"
+ "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
+ CallOnVariableY));
+}
+
+TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
+ EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
+ unaryExprOrTypeTraitExpr()));
+ EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
+ alignOfExpr(anything())));
+ // FIXME: Uncomment once alignof is enabled.
+ // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
+ // unaryExprOrTypeTraitExpr()));
+ // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
+ // sizeOfExpr()));
+}
+
+TEST(MemberExpression, DoesNotMatchClasses) {
+ EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
+}
+
+TEST(MemberExpression, MatchesMemberFunctionCall) {
+ EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
+}
+
+TEST(MemberExpression, MatchesVariable) {
+ EXPECT_TRUE(
+ matches("class Y { void x() { this->y; } int y; };", memberExpr()));
+ EXPECT_TRUE(
+ matches("class Y { void x() { y; } int y; };", memberExpr()));
+ EXPECT_TRUE(
+ matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
+}
+
+TEST(MemberExpression, MatchesStaticVariable) {
+ EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
+ memberExpr()));
+ EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
+ memberExpr()));
+ EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
+ memberExpr()));
+}
+
+TEST(Function, MatchesFunctionDeclarations) {
+ StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
+
+ EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
+ EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
+
+ if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
+ llvm::Triple::Win32) {
+ // FIXME: Make this work for MSVC.
+ // Dependent contexts, but a non-dependent call.
+ EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
+ CallFunctionF));
+ EXPECT_TRUE(
+ matches("void f(); template <int N> struct S { void g() { f(); } };",
+ CallFunctionF));
+ }
+
+ // Depedent calls don't match.
+ EXPECT_TRUE(
+ notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
+ CallFunctionF));
+ EXPECT_TRUE(
+ notMatches("void f(int);"
+ "template <typename T> struct S { void g(T t) { f(t); } };",
+ CallFunctionF));
+
+ EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
+ EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
+ EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
+ functionDecl(isVariadic())));
+ EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
+ EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
+ EXPECT_TRUE(matches("void f(...);", functionDecl(parameterCountIs(0))));
+ EXPECT_TRUE(matchesC("void f();", functionDecl(parameterCountIs(0))));
+ EXPECT_TRUE(matches("void f(int, ...);", functionDecl(parameterCountIs(1))));
+}
+
+TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
+ EXPECT_TRUE(
+ matches("template <typename T> void f(T t) {}",
+ functionTemplateDecl(hasName("f"))));
+}
+
+TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
+ EXPECT_TRUE(
+ notMatches("void f(double d); void f(int t) {}",
+ functionTemplateDecl(hasName("f"))));
+}
+
+TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
+ EXPECT_TRUE(
+ notMatches("void g(); template <typename T> void f(T t) {}"
+ "template <> void f(int t) { g(); }",
+ functionTemplateDecl(hasName("f"),
+ hasDescendant(declRefExpr(to(
+ functionDecl(hasName("g"))))))));
+}
+
+TEST(Matcher, MatchesClassTemplateSpecialization) {
+ EXPECT_TRUE(matches("template<typename T> struct A {};"
+ "template<> struct A<int> {};",
+ classTemplateSpecializationDecl()));
+ EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
+ classTemplateSpecializationDecl()));
+ EXPECT_TRUE(notMatches("template<typename T> struct A {};",
+ classTemplateSpecializationDecl()));
+}
+
+TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
+ EXPECT_TRUE(matches("int x;", declaratorDecl()));
+ EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
+}
+
+TEST(ParmVarDecl, MatchesParmVars) {
+ EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
+ EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
+}
+
+TEST(Matcher, ConstructorCall) {
+ StatementMatcher Constructor = cxxConstructExpr();
+
+ EXPECT_TRUE(
+ matches("class X { public: X(); }; void x() { X x; }", Constructor));
+ EXPECT_TRUE(
+ matches("class X { public: X(); }; void x() { X x = X(); }",
+ Constructor));
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { X x = 0; }",
+ Constructor));
+ EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
+}
+
+TEST(Matcher, ThisExpr) {
+ EXPECT_TRUE(
+ matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
+ EXPECT_TRUE(
+ notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
+}
+
+TEST(Matcher, BindTemporaryExpression) {
+ StatementMatcher TempExpression = cxxBindTemporaryExpr();
+
+ std::string ClassString = "class string { public: string(); ~string(); }; ";
+
+ EXPECT_TRUE(
+ matches(ClassString +
+ "string GetStringByValue();"
+ "void FunctionTakesString(string s);"
+ "void run() { FunctionTakesString(GetStringByValue()); }",
+ TempExpression));
+
+ EXPECT_TRUE(
+ notMatches(ClassString +
+ "string* GetStringPointer(); "
+ "void FunctionTakesStringPtr(string* s);"
+ "void run() {"
+ " string* s = GetStringPointer();"
+ " FunctionTakesStringPtr(GetStringPointer());"
+ " FunctionTakesStringPtr(s);"
+ "}",
+ TempExpression));
+
+ EXPECT_TRUE(
+ notMatches("class no_dtor {};"
+ "no_dtor GetObjByValue();"
+ "void ConsumeObj(no_dtor param);"
+ "void run() { ConsumeObj(GetObjByValue()); }",
+ TempExpression));
+}
+
+TEST(MaterializeTemporaryExpr, MatchesTemporary) {
+ std::string ClassString =
+ "class string { public: string(); int length(); }; ";
+
+ EXPECT_TRUE(
+ matches(ClassString +
+ "string GetStringByValue();"
+ "void FunctionTakesString(string s);"
+ "void run() { FunctionTakesString(GetStringByValue()); }",
+ materializeTemporaryExpr()));
+
+ EXPECT_TRUE(
+ notMatches(ClassString +
+ "string* GetStringPointer(); "
+ "void FunctionTakesStringPtr(string* s);"
+ "void run() {"
+ " string* s = GetStringPointer();"
+ " FunctionTakesStringPtr(GetStringPointer());"
+ " FunctionTakesStringPtr(s);"
+ "}",
+ materializeTemporaryExpr()));
+
+ EXPECT_TRUE(
+ notMatches(ClassString +
+ "string GetStringByValue();"
+ "void run() { int k = GetStringByValue().length(); }",
+ materializeTemporaryExpr()));
+
+ EXPECT_TRUE(
+ notMatches(ClassString +
+ "string GetStringByValue();"
+ "void run() { GetStringByValue(); }",
+ materializeTemporaryExpr()));
+}
+
+TEST(Matcher, NewExpression) {
+ StatementMatcher New = cxxNewExpr();
+
+ EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
+ EXPECT_TRUE(
+ matches("class X { public: X(); }; void x() { new X(); }", New));
+ EXPECT_TRUE(
+ matches("class X { public: X(int); }; void x() { new X(0); }", New));
+ EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
+}
+
+TEST(Matcher, DeleteExpression) {
+ EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
+ cxxDeleteExpr()));
+}
+
+TEST(Matcher, DefaultArgument) {
+ StatementMatcher Arg = cxxDefaultArgExpr();
+
+ EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
+ EXPECT_TRUE(
+ matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
+ EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
+}
+
+TEST(Matcher, StringLiterals) {
+ StatementMatcher Literal = stringLiteral();
+ EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
+ // wide string
+ EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
+ // with escaped characters
+ EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
+ // no matching -- though the data type is the same, there is no string literal
+ EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
+}
+
+TEST(Matcher, CharacterLiterals) {
+ StatementMatcher CharLiteral = characterLiteral();
+ EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
+ // wide character
+ EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
+ // wide character, Hex encoded, NOT MATCHED!
+ EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
+ EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
+}
+
+TEST(Matcher, IntegerLiterals) {
+ StatementMatcher HasIntLiteral = integerLiteral();
+ EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
+ EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
+ EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
+ EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
+
+ // Non-matching cases (character literals, float and double)
+ EXPECT_TRUE(notMatches("int i = L'a';",
+ HasIntLiteral)); // this is actually a character
+ // literal cast to int
+ EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
+ EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
+ EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
+}
+
+TEST(Matcher, FloatLiterals) {
+ StatementMatcher HasFloatLiteral = floatLiteral();
+ EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
+ EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
+ EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
+ EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
+ EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
+ EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
+ EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
+ EXPECT_TRUE(
+ matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
+
+ EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
+ EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
+ EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
+ EXPECT_TRUE(
+ notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
+}
+
+TEST(Matcher, NullPtrLiteral) {
+ EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
+}
+
+TEST(Matcher, GNUNullExpr) {
+ EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
+}
+
+TEST(Matcher, AtomicExpr) {
+ EXPECT_TRUE(matches("void foo() { int *ptr; __atomic_load_n(ptr, 1); }",
+ atomicExpr()));
+}
+
+TEST(Matcher, Initializers) {
+ const char *ToMatch = "void foo() { struct point { double x; double y; };"
+ " struct point ptarray[10] = "
+ " { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }";
+ EXPECT_TRUE(matchesConditionally(
+ ToMatch,
+ initListExpr(
+ has(
+ cxxConstructExpr(
+ requiresZeroInitialization())),
+ has(
+ initListExpr(
+ hasType(asString("struct point")),
+ has(floatLiteral(equals(1.0))),
+ has(implicitValueInitExpr(
+ hasType(asString("double")))))),
+ has(
+ initListExpr(
+ hasType(asString("struct point")),
+ has(floatLiteral(equals(2.0))),
+ has(floatLiteral(equals(1.0)))))
+ ), true, "-std=gnu++98"));
+
+ EXPECT_TRUE(matchesC99(ToMatch,
+ initListExpr(
+ hasSyntacticForm(
+ initListExpr(
+ has(
+ designatedInitExpr(
+ designatorCountIs(2),
+ has(floatLiteral(
+ equals(1.0))),
+ has(integerLiteral(
+ equals(2))))),
+ has(
+ designatedInitExpr(
+ designatorCountIs(2),
+ has(floatLiteral(
+ equals(2.0))),
+ has(integerLiteral(
+ equals(2))))),
+ has(
+ designatedInitExpr(
+ designatorCountIs(2),
+ has(floatLiteral(
+ equals(1.0))),
+ has(integerLiteral(
+ equals(0)))))
+ )))));
+}
+
+TEST(Matcher, ParenListExpr) {
+ EXPECT_TRUE(
+ matches("template<typename T> class foo { void bar() { foo X(*this); } };"
+ "template class foo<int>;",
+ varDecl(hasInitializer(parenListExpr(has(unaryOperator()))))));
+}
+
+TEST(Matcher, StmtExpr) {
+ EXPECT_TRUE(matches("void declToImport() { int C = ({int X=4; X;}); }",
+ varDecl(hasInitializer(stmtExpr()))));
+}
+
+TEST(Matcher, ImportPredefinedExpr) {
+ // __func__ expands as StringLiteral("foo")
+ EXPECT_TRUE(matches("void foo() { __func__; }",
+ predefinedExpr(
+ hasType(asString("const char [4]")),
+ has(stringLiteral()))));
+}
+
+TEST(Matcher, AsmStatement) {
+ EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
+}
+
+TEST(Matcher, Conditions) {
+ StatementMatcher Condition =
+ ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
+
+ EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
+ EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
+ EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
+ EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
+ EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
+}
+
+TEST(Matcher, ConditionalOperator) {
+ StatementMatcher Conditional = conditionalOperator(
+ hasCondition(cxxBoolLiteral(equals(true))),
+ hasTrueExpression(cxxBoolLiteral(equals(false))));
+
+ EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
+ EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
+ EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
+
+ StatementMatcher ConditionalFalse = conditionalOperator(
+ hasFalseExpression(cxxBoolLiteral(equals(false))));
+
+ EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
+ EXPECT_TRUE(
+ notMatches("void x() { true ? false : true; }", ConditionalFalse));
+
+ EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
+ EXPECT_TRUE(
+ notMatches("void x() { true ? false : true; }", ConditionalFalse));
+}
+
+TEST(Matcher, BinaryConditionalOperator) {
+ StatementMatcher AlwaysOne = binaryConditionalOperator(
+ hasCondition(implicitCastExpr(
+ has(
+ opaqueValueExpr(
+ hasSourceExpression((integerLiteral(equals(1)))))))),
+ hasFalseExpression(integerLiteral(equals(0))));
+
+ EXPECT_TRUE(matches("void x() { 1 ?: 0; }", AlwaysOne));
+
+ StatementMatcher FourNotFive = binaryConditionalOperator(
+ hasTrueExpression(opaqueValueExpr(
+ hasSourceExpression((integerLiteral(equals(4)))))),
+ hasFalseExpression(integerLiteral(equals(5))));
+
+ EXPECT_TRUE(matches("void x() { 4 ?: 5; }", FourNotFive));
+}
+
+TEST(ArraySubscriptMatchers, ArraySubscripts) {
+ EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
+ arraySubscriptExpr()));
+ EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
+ arraySubscriptExpr()));
+}
+
+TEST(For, FindsForLoops) {
+ EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
+ EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
+ EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
+ "void f() { for (auto &a : as); }",
+ forStmt()));
+}
+
+TEST(For, ReportsNoFalsePositives) {
+ EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
+ EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
+}
+
+TEST(CompoundStatement, HandlesSimpleCases) {
+ EXPECT_TRUE(notMatches("void f();", compoundStmt()));
+ EXPECT_TRUE(matches("void f() {}", compoundStmt()));
+ EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
+}
+
+TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
+ // It's not a compound statement just because there's "{}" in the source
+ // text. This is an AST search, not grep.
+ EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
+ compoundStmt()));
+ EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
+ compoundStmt()));
+}
+
+TEST(CastExpression, MatchesExplicitCasts) {
+ EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
+ EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
+ EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
+ EXPECT_TRUE(matches("char c = char(0);", castExpr()));
+}
+TEST(CastExpression, MatchesImplicitCasts) {
+ // This test creates an implicit cast from int to char.
+ EXPECT_TRUE(matches("char c = 0;", castExpr()));
+ // This test creates an implicit cast from lvalue to rvalue.
+ EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
+}
+
+TEST(CastExpression, DoesNotMatchNonCasts) {
+ EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
+ EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
+ EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
+ EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
+}
+
+TEST(ReinterpretCast, MatchesSimpleCase) {
+ EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
+ cxxReinterpretCastExpr()));
+}
+
+TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
+ EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
+ EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
+ cxxReinterpretCastExpr()));
+ EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
+ cxxReinterpretCastExpr()));
+ EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
+ "B b;"
+ "D* p = dynamic_cast<D*>(&b);",
+ cxxReinterpretCastExpr()));
+}
+
+TEST(FunctionalCast, MatchesSimpleCase) {
+ std::string foo_class = "class Foo { public: Foo(const char*); };";
+ EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
+ cxxFunctionalCastExpr()));
+}
+
+TEST(FunctionalCast, DoesNotMatchOtherCasts) {
+ std::string FooClass = "class Foo { public: Foo(const char*); };";
+ EXPECT_TRUE(
+ notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
+ cxxFunctionalCastExpr()));
+ EXPECT_TRUE(
+ notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
+ cxxFunctionalCastExpr()));
+}
+
+TEST(DynamicCast, MatchesSimpleCase) {
+ EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
+ "B b;"
+ "D* p = dynamic_cast<D*>(&b);",
+ cxxDynamicCastExpr()));
+}
+
+TEST(StaticCast, MatchesSimpleCase) {
+ EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
+ cxxStaticCastExpr()));
+}
+
+TEST(StaticCast, DoesNotMatchOtherCasts) {
+ EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
+ EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
+ cxxStaticCastExpr()));
+ EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
+ cxxStaticCastExpr()));
+ EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
+ "B b;"
+ "D* p = dynamic_cast<D*>(&b);",
+ cxxStaticCastExpr()));
+}
+
+TEST(CStyleCast, MatchesSimpleCase) {
+ EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
+}
+
+TEST(CStyleCast, DoesNotMatchOtherCasts) {
+ EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
+ "char q, *r = const_cast<char*>(&q);"
+ "void* s = reinterpret_cast<char*>(&s);"
+ "struct B { virtual ~B() {} }; struct D : B {};"
+ "B b;"
+ "D* t = dynamic_cast<D*>(&b);",
+ cStyleCastExpr()));
+}
+
+TEST(ImplicitCast, MatchesSimpleCase) {
+ // This test creates an implicit const cast.
+ EXPECT_TRUE(matches("int x = 0; const int y = x;",
+ varDecl(hasInitializer(implicitCastExpr()))));
+ // This test creates an implicit cast from int to char.
+ EXPECT_TRUE(matches("char c = 0;",
+ varDecl(hasInitializer(implicitCastExpr()))));
+ // This test creates an implicit array-to-pointer cast.
+ EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
+ varDecl(hasInitializer(implicitCastExpr()))));
+}
+
+TEST(ImplicitCast, DoesNotMatchIncorrectly) {
+ // This test verifies that implicitCastExpr() matches exactly when implicit casts
+ // are present, and that it ignores explicit and paren casts.
+
+ // These two test cases have no casts.
+ EXPECT_TRUE(notMatches("int x = 0;",
+ varDecl(hasInitializer(implicitCastExpr()))));
+ EXPECT_TRUE(notMatches("int x = 0, &y = x;",
+ varDecl(hasInitializer(implicitCastExpr()))));
+
+ EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
+ varDecl(hasInitializer(implicitCastExpr()))));
+ EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
+ varDecl(hasInitializer(implicitCastExpr()))));
+
+ EXPECT_TRUE(notMatches("int x = (0);",
+ varDecl(hasInitializer(implicitCastExpr()))));
+}
+
+TEST(Statement, DoesNotMatchDeclarations) {
+ EXPECT_TRUE(notMatches("class X {};", stmt()));
+}
+
+TEST(Statement, MatchesCompoundStatments) {
+ EXPECT_TRUE(matches("void x() {}", stmt()));
+}
+
+TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
+ EXPECT_TRUE(notMatches("void x() {}", declStmt()));
+}
+
+TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
+ EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
+}
+
+TEST(ExprWithCleanups, MatchesExprWithCleanups) {
+ EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
+ "const Foo f = Foo();",
+ varDecl(hasInitializer(exprWithCleanups()))));
+ EXPECT_FALSE(matches("struct Foo { }; Foo a;"
+ "const Foo f = a;",
+ varDecl(hasInitializer(exprWithCleanups()))));
+}
+
+TEST(InitListExpression, MatchesInitListExpression) {
+ EXPECT_TRUE(matches("int a[] = { 1, 2 };",
+ initListExpr(hasType(asString("int [2]")))));
+ EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
+ initListExpr(hasType(recordDecl(hasName("B"))))));
+ EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
+ "void f();"
+ "S s[1] = { &f };",
+ declRefExpr(to(functionDecl(hasName("f"))))));
+ EXPECT_TRUE(
+ matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
+}
+
+TEST(UsingDeclaration, MatchesUsingDeclarations) {
+ EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
+ usingDecl()));
+}
+
+TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
+ EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
+ usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
+}
+
+TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
+ EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
+ usingDirectiveDecl()));
+ EXPECT_FALSE(
+ matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
+}
+
+
+TEST(While, MatchesWhileLoops) {
+ EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
+ EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
+ EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
+}
+
+TEST(Do, MatchesDoLoops) {
+ EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
+ EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
+}
+
+TEST(Do, DoesNotMatchWhileLoops) {
+ EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
+}
+
+TEST(SwitchCase, MatchesCase) {
+ EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
+ EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
+ EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
+ EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
+}
+
+TEST(SwitchCase, MatchesSwitch) {
+ EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
+ EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
+ EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
+ EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
+}
+
+TEST(ExceptionHandling, SimpleCases) {
+ EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
+ EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
+ EXPECT_TRUE(
+ notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
+ EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
+ cxxThrowExpr()));
+ EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
+ cxxThrowExpr()));
+ EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
+ cxxCatchStmt(isCatchAll())));
+ EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
+ cxxCatchStmt(isCatchAll())));
+ EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
+ varDecl(isExceptionVariable())));
+ EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
+ varDecl(isExceptionVariable())));
+}
+
+TEST(ParenExpression, SimpleCases) {
+ EXPECT_TRUE(matches("int i = (3);", parenExpr()));
+ EXPECT_TRUE(matches("int i = (3 + 7);", parenExpr()));
+ EXPECT_TRUE(notMatches("int i = 3;", parenExpr()));
+ EXPECT_TRUE(notMatches("int foo() { return 1; }; int a = foo();",
+ parenExpr()));
+}
+
+TEST(TypeMatching, MatchesTypes) {
+ EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
+}
+
+TEST(TypeMatching, MatchesConstantArrayTypes) {
+ EXPECT_TRUE(matches("int a[2];", constantArrayType()));
+ EXPECT_TRUE(notMatches(
+ "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
+ constantArrayType(hasElementType(builtinType()))));
+
+ EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
+ EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
+ EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
+}
+
+TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
+ EXPECT_TRUE(matches(
+ "template <typename T, int Size> class array { T data[Size]; };",
+ dependentSizedArrayType()));
+ EXPECT_TRUE(notMatches(
+ "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
+ dependentSizedArrayType()));
+}
+
+TEST(TypeMatching, MatchesIncompleteArrayType) {
+ EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
+ EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
+
+ EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
+ incompleteArrayType()));
+}
+
+TEST(TypeMatching, MatchesVariableArrayType) {
+ EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
+ EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
+
+ EXPECT_TRUE(matches(
+ "void f(int b) { int a[b]; }",
+ variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
+ varDecl(hasName("b")))))))));
+}
+
+
+TEST(TypeMatching, MatchesAtomicTypes) {
+ if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
+ llvm::Triple::Win32) {
+ // FIXME: Make this work for MSVC.
+ EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
+
+ EXPECT_TRUE(matches("_Atomic(int) i;",
+ atomicType(hasValueType(isInteger()))));
+ EXPECT_TRUE(notMatches("_Atomic(float) f;",
+ atomicType(hasValueType(isInteger()))));
+ }
+}
+
+TEST(TypeMatching, MatchesAutoTypes) {
+ EXPECT_TRUE(matches("auto i = 2;", autoType()));
+ EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
+ autoType()));
+
+ // FIXME: Matching against the type-as-written can't work here, because the
+ // type as written was not deduced.
+ //EXPECT_TRUE(matches("auto a = 1;",
+ // autoType(hasDeducedType(isInteger()))));
+ //EXPECT_TRUE(notMatches("auto b = 2.0;",
+ // autoType(hasDeducedType(isInteger()))));
+}
+
+TEST(TypeMatching, MatchesFunctionTypes) {
+ EXPECT_TRUE(matches("int (*f)(int);", functionType()));
+ EXPECT_TRUE(matches("void f(int i) {}", functionType()));
+}
+
+TEST(TypeMatching, IgnoringParens) {
+ EXPECT_TRUE(
+ notMatches("void (*fp)(void);", pointerType(pointee(functionType()))));
+ EXPECT_TRUE(matches("void (*fp)(void);",
+ pointerType(pointee(ignoringParens(functionType())))));
+}
+
+TEST(TypeMatching, MatchesFunctionProtoTypes) {
+ EXPECT_TRUE(matches("int (*f)(int);", functionProtoType()));
+ EXPECT_TRUE(matches("void f(int i);", functionProtoType()));
+ EXPECT_TRUE(matches("void f();", functionProtoType(parameterCountIs(0))));
+ EXPECT_TRUE(notMatchesC("void f();", functionProtoType()));
+ EXPECT_TRUE(
+ matchesC("void f(void);", functionProtoType(parameterCountIs(0))));
+}
+
+TEST(TypeMatching, MatchesParenType) {
+ EXPECT_TRUE(
+ matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
+ EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
+
+ EXPECT_TRUE(matches(
+ "int (*ptr_to_func)(int);",
+ varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
+ EXPECT_TRUE(notMatches(
+ "int (*ptr_to_array)[4];",
+ varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
+}
+
+TEST(TypeMatching, PointerTypes) {
+ // FIXME: Reactive when these tests can be more specific (not matching
+ // implicit code on certain platforms), likely when we have hasDescendant for
+ // Types/TypeLocs.
+ //EXPECT_TRUE(matchAndVerifyResultTrue(
+ // "int* a;",
+ // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
+ // llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
+ //EXPECT_TRUE(matchAndVerifyResultTrue(
+ // "int* a;",
+ // pointerTypeLoc().bind("loc"),
+ // llvm::make_unique<VerifyIdIsBoundTo<TypeLoc>>("loc", 1)));
+ EXPECT_TRUE(matches(
+ "int** a;",
+ loc(pointerType(pointee(qualType())))));
+ EXPECT_TRUE(matches(
+ "int** a;",
+ loc(pointerType(pointee(pointerType())))));
+ EXPECT_TRUE(matches(
+ "int* b; int* * const a = &b;",
+ loc(qualType(isConstQualified(), pointerType()))));
+
+ std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
+ hasType(blockPointerType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
+ hasType(memberPointerType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
+ hasType(pointerType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
+ hasType(referenceType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
+ hasType(lValueReferenceType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
+ hasType(rValueReferenceType()))));
+
+ Fragment = "int *ptr;";
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
+ hasType(blockPointerType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
+ hasType(memberPointerType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
+ hasType(pointerType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
+ hasType(referenceType()))));
+
+ Fragment = "int a; int &ref = a;";
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
+ hasType(blockPointerType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
+ hasType(memberPointerType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
+ hasType(pointerType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
+ hasType(referenceType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
+ hasType(lValueReferenceType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
+ hasType(rValueReferenceType()))));
+
+ Fragment = "int &&ref = 2;";
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
+ hasType(blockPointerType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
+ hasType(memberPointerType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
+ hasType(pointerType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
+ hasType(referenceType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
+ hasType(lValueReferenceType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
+ hasType(rValueReferenceType()))));
+}
+
+TEST(TypeMatching, AutoRefTypes) {
+ std::string Fragment = "auto a = 1;"
+ "auto b = a;"
+ "auto &c = a;"
+ "auto &&d = c;"
+ "auto &&e = 2;";
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
+ hasType(referenceType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
+ hasType(referenceType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
+ hasType(referenceType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
+ hasType(lValueReferenceType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
+ hasType(rValueReferenceType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
+ hasType(referenceType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
+ hasType(lValueReferenceType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
+ hasType(rValueReferenceType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
+ hasType(referenceType()))));
+ EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
+ hasType(lValueReferenceType()))));
+ EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
+ hasType(rValueReferenceType()))));
+}
+
+TEST(TypeMatching, MatchesEnumTypes) {
+ EXPECT_TRUE(matches("enum Color { Green }; Color color;",
+ loc(enumType())));
+ EXPECT_TRUE(matches("enum class Color { Green }; Color color;",
+ loc(enumType())));
+}
+
+TEST(TypeMatching, MatchesPointersToConstTypes) {
+ EXPECT_TRUE(matches("int b; int * const a = &b;",
+ loc(pointerType())));
+ EXPECT_TRUE(matches("int b; int * const a = &b;",
+ loc(pointerType())));
+ EXPECT_TRUE(matches(
+ "int b; const int * a = &b;",
+ loc(pointerType(pointee(builtinType())))));
+ EXPECT_TRUE(matches(
+ "int b; const int * a = &b;",
+ pointerType(pointee(builtinType()))));
+}
+
+TEST(TypeMatching, MatchesTypedefTypes) {
+ EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
+ hasType(typedefType()))));
+}
+
+TEST(TypeMatching, MatchesTemplateSpecializationType) {
+ EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
+ templateSpecializationType()));
+}
+
+TEST(TypeMatching, MatchesRecordType) {
+ EXPECT_TRUE(matches("class C{}; C c;", recordType()));
+ EXPECT_TRUE(matches("struct S{}; S s;",
+ recordType(hasDeclaration(recordDecl(hasName("S"))))));
+ EXPECT_TRUE(notMatches("int i;",
+ recordType(hasDeclaration(recordDecl(hasName("S"))))));
+}
+
+TEST(TypeMatching, MatchesElaboratedType) {
+ EXPECT_TRUE(matches(
+ "namespace N {"
+ " namespace M {"
+ " class D {};"
+ " }"
+ "}"
+ "N::M::D d;", elaboratedType()));
+ EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
+ EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
+}
+
+TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
+ const std::string code = "template <typename T>"
+ "int F() {"
+ " return 1 + T();"
+ "}"
+ "int i = F<int>();";
+ EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
+ expr(hasType(substTemplateTypeParmType()))))));
+ EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
+ expr(hasType(substTemplateTypeParmType()))))));
+}
+
+TEST(NNS, MatchesNestedNameSpecifiers) {
+ EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
+ nestedNameSpecifier()));
+ EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
+ nestedNameSpecifier()));
+ EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
+ nestedNameSpecifier()));
+ EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
+ nestedNameSpecifier()));
+
+ EXPECT_TRUE(matches(
+ "struct A { static void f() {} }; void g() { A::f(); }",
+ nestedNameSpecifier()));
+ EXPECT_TRUE(notMatches(
+ "struct A { static void f() {} }; void g(A* a) { a->f(); }",
+ nestedNameSpecifier()));
+}
+
+TEST(NullStatement, SimpleCases) {
+ EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
+ EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
+}
+
+TEST(NS, Alias) {
+ EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
+ namespaceAliasDecl(hasName("alias"))));
+}
+
+TEST(NNS, MatchesTypes) {
+ NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
+ specifiesType(hasDeclaration(recordDecl(hasName("A")))));
+ EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
+ EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
+ Matcher));
+ EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
+}
+
+TEST(NNS, MatchesNamespaceDecls) {
+ NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
+ specifiesNamespace(hasName("ns")));
+ EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
+ EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
+ EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
+}
+
+TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
+ EXPECT_TRUE(matches(
+ "struct A { struct B { struct C {}; }; }; A::B::C c;",
+ nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
+ EXPECT_TRUE(matches(
+ "struct A { struct B { struct C {}; }; }; A::B::C c;",
+ nestedNameSpecifierLoc(hasPrefix(
+ specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
+}
+
+
+template <typename T>
+class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
+public:
+ bool run(const BoundNodes *Nodes) override { return false; }
+
+ bool run(const BoundNodes *Nodes, ASTContext *Context) override {
+ const T *Node = Nodes->getNodeAs<T>("");
+ return verify(*Nodes, *Context, Node);
+ }
+
+ bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
+ // Use the original typed pointer to verify we can pass pointers to subtypes
+ // to equalsNode.
+ const T *TypedNode = cast<T>(Node);
+ return selectFirst<T>(
+ "", match(stmt(hasParent(
+ stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
+ *Node, Context)) != nullptr;
+ }
+ bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
+ // Use the original typed pointer to verify we can pass pointers to subtypes
+ // to equalsNode.
+ const T *TypedNode = cast<T>(Node);
+ return selectFirst<T>(
+ "", match(decl(hasParent(
+ decl(has(decl(equalsNode(TypedNode)))).bind(""))),
+ *Node, Context)) != nullptr;
+ }
+ bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
+ // Use the original typed pointer to verify we can pass pointers to subtypes
+ // to equalsNode.
+ const T *TypedNode = cast<T>(Node);
+ const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
+ return selectFirst<T>(
+ "", match(fieldDecl(hasParent(decl(has(fieldDecl(
+ hasType(type(equalsNode(TypedNode)).bind(""))))))),
+ *Dec, Context)) != nullptr;
+ }
+};
+
+TEST(IsEqualTo, MatchesNodesByIdentity) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
+ llvm::make_unique<VerifyAncestorHasChildIsEqual<CXXRecordDecl>>()));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void f() { if (true) if(true) {} }", ifStmt().bind(""),
+ llvm::make_unique<VerifyAncestorHasChildIsEqual<IfStmt>>()));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X { class Y {} y; };",
+ fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
+ llvm::make_unique<VerifyAncestorHasChildIsEqual<Type>>()));
+}
+
+TEST(TypedefDeclMatcher, Match) {
+ EXPECT_TRUE(matches("typedef int typedefDeclTest;",
+ typedefDecl(hasName("typedefDeclTest"))));
+ EXPECT_TRUE(notMatches("using typedefDeclTest2 = int;",
+ typedefDecl(hasName("typedefDeclTest2"))));
+}
+
+TEST(TypeAliasDeclMatcher, Match) {
+ EXPECT_TRUE(matches("using typeAliasTest2 = int;",
+ typeAliasDecl(hasName("typeAliasTest2"))));
+ EXPECT_TRUE(notMatches("typedef int typeAliasTest;",
+ typeAliasDecl(hasName("typeAliasTest"))));
+}
+
+TEST(TypedefNameDeclMatcher, Match) {
+ EXPECT_TRUE(matches("typedef int typedefNameDeclTest1;",
+ typedefNameDecl(hasName("typedefNameDeclTest1"))));
+ EXPECT_TRUE(matches("using typedefNameDeclTest2 = int;",
+ typedefNameDecl(hasName("typedefNameDeclTest2"))));
+}
+
+TEST(ObjCMessageExprMatcher, SimpleExprs) {
+ // don't find ObjCMessageExpr where none are present
+ EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
+
+ std::string Objc1String =
+ "@interface Str "
+ " - (Str *)uppercaseString:(Str *)str;"
+ "@end "
+ "@interface foo "
+ "- (void)meth:(Str *)text;"
+ "@end "
+ " "
+ "@implementation foo "
+ "- (void) meth:(Str *)text { "
+ " [self contents];"
+ " Str *up = [text uppercaseString];"
+ "} "
+ "@end ";
+ EXPECT_TRUE(matchesObjC(
+ Objc1String,
+ objcMessageExpr(anything())));
+ EXPECT_TRUE(matchesObjC(
+ Objc1String,
+ objcMessageExpr(hasSelector("contents"))));
+ EXPECT_TRUE(matchesObjC(
+ Objc1String,
+ objcMessageExpr(matchesSelector("cont*"))));
+ EXPECT_FALSE(matchesObjC(
+ Objc1String,
+ objcMessageExpr(matchesSelector("?cont*"))));
+ EXPECT_TRUE(notMatchesObjC(
+ Objc1String,
+ objcMessageExpr(hasSelector("contents"), hasNullSelector())));
+ EXPECT_TRUE(matchesObjC(
+ Objc1String,
+ objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
+ EXPECT_TRUE(matchesObjC(
+ Objc1String,
+ objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
+ EXPECT_TRUE(matchesObjC(
+ Objc1String,
+ objcMessageExpr(matchesSelector("uppercase*"),
+ argumentCountIs(0)
+ )));
+}
+
+} // namespace ast_matchers
+} // namespace clang
diff --git a/unittests/ASTMatchers/ASTMatchersTest.cpp b/unittests/ASTMatchers/ASTMatchersTest.cpp
deleted file mode 100644
index 80f234338a..0000000000
--- a/unittests/ASTMatchers/ASTMatchersTest.cpp
+++ /dev/null
@@ -1,5070 +0,0 @@
-//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher unit tests ------===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "ASTMatchersTest.h"
-#include "clang/AST/PrettyPrinter.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/ASTMatchers/ASTMatchers.h"
-#include "clang/Tooling/Tooling.h"
-#include "llvm/ADT/Triple.h"
-#include "llvm/Support/Host.h"
-#include "gtest/gtest.h"
-
-namespace clang {
-namespace ast_matchers {
-
-#if GTEST_HAS_DEATH_TEST
-TEST(HasNameDeathTest, DiesOnEmptyName) {
- ASSERT_DEBUG_DEATH({
- DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
- EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
- }, "");
-}
-
-TEST(HasNameDeathTest, DiesOnEmptyPattern) {
- ASSERT_DEBUG_DEATH({
- DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
- EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
- }, "");
-}
-
-TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
- ASSERT_DEBUG_DEATH({
- DeclarationMatcher IsDerivedFromEmpty = cxxRecordDecl(isDerivedFrom(""));
- EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
- }, "");
-}
-#endif
-
-TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
- MatchFinder Finder;
- EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
- EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
- EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
- nullptr));
-
- // Do not accept non-toplevel matchers.
- EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
- EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
- EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
-}
-
-TEST(Decl, MatchesDeclarations) {
- EXPECT_TRUE(notMatches("", decl(usingDecl())));
- EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
- decl(usingDecl())));
-}
-
-TEST(NameableDeclaration, MatchesVariousDecls) {
- DeclarationMatcher NamedX = namedDecl(hasName("X"));
- EXPECT_TRUE(matches("typedef int X;", NamedX));
- EXPECT_TRUE(matches("int X;", NamedX));
- EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
- EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
- EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
- EXPECT_TRUE(matches("namespace X { }", NamedX));
- EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
-
- EXPECT_TRUE(notMatches("#define X 1", NamedX));
-}
-
-TEST(NameableDeclaration, REMatchesVariousDecls) {
- DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
- EXPECT_TRUE(matches("typedef int Xa;", NamedX));
- EXPECT_TRUE(matches("int Xb;", NamedX));
- EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
- EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
- EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
- EXPECT_TRUE(matches("namespace Xij { }", NamedX));
- EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
-
- EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
-
- DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
- EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
- EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
-
- DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
- EXPECT_TRUE(matches("int abc;", Abc));
- EXPECT_TRUE(matches("int aFOObBARc;", Abc));
- EXPECT_TRUE(notMatches("int cab;", Abc));
- EXPECT_TRUE(matches("int cabc;", Abc));
-
- DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
- EXPECT_TRUE(matches("int k;", StartsWithK));
- EXPECT_TRUE(matches("int kAbc;", StartsWithK));
- EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
- EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
- EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
-}
-
-TEST(DeclarationMatcher, MatchClass) {
- DeclarationMatcher ClassMatcher(recordDecl());
- llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
- if (Triple.getOS() != llvm::Triple::Win32 ||
- Triple.getEnvironment() != llvm::Triple::MSVC)
- EXPECT_FALSE(matches("", ClassMatcher));
- else
- // Matches class type_info.
- EXPECT_TRUE(matches("", ClassMatcher));
-
- DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
- EXPECT_TRUE(matches("class X;", ClassX));
- EXPECT_TRUE(matches("class X {};", ClassX));
- EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
- EXPECT_TRUE(notMatches("", ClassX));
-}
-
-TEST(DeclarationMatcher, ClassIsDerived) {
- DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
-
- EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
- EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
- EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
- EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
- EXPECT_TRUE(notMatches("", IsDerivedFromX));
-
- DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
-
- EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
- EXPECT_TRUE(matches("class X {};", IsAX));
- EXPECT_TRUE(matches("class X;", IsAX));
- EXPECT_TRUE(notMatches("class Y;", IsAX));
- EXPECT_TRUE(notMatches("", IsAX));
-
- DeclarationMatcher ZIsDerivedFromX =
- cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
- EXPECT_TRUE(
- matches("class X {}; class Y : public X {}; class Z : public Y {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class X {};"
- "template<class T> class Y : public X {};"
- "class Z : public Y<int> {};", ZIsDerivedFromX));
- EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template<class T> class X {}; "
- "template<class T> class Z : public X<T> {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template<class T, class U=T> class X {}; "
- "template<class T> class Z : public X<T> {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("template<class X> class A { class Z : public X {}; };",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template<class X> class A { public: class Z : public X {}; }; "
- "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template <class T> class X {}; "
- "template<class Y> class A { class Z : public X<Y> {}; };",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("template<template<class T> class X> class A { "
- " class Z : public X<int> {}; };", ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template<template<class T> class X> class A { "
- " public: class Z : public X<int> {}; }; "
- "template<class T> class X {}; void y() { A<X>::Z z; }",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("template<class X> class A { class Z : public X::D {}; };",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template<class X> class A { public: "
- " class Z : public X::D {}; }; "
- "class Y { public: class X {}; typedef X D; }; "
- "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class X {}; typedef X Y; class Z : public Y {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template<class T> class Y { typedef typename T::U X; "
- " class Z : public X {}; };", ZIsDerivedFromX));
- EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("template<class T> class X {}; "
- "template<class T> class A { class Z : public X<T>::D {}; };",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template<class T> class X { public: typedef X<T> D; }; "
- "template<class T> class A { public: "
- " class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("template<class X> class A { class Z : public X::D::E {}; };",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class X {}; class Y : public X {}; "
- "typedef Y V; typedef V W; class Z : public W {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("template<class T, class U> class X {}; "
- "template<class T> class A { class Z : public X<T, int> {}; };",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("template<class X> class D { typedef X A; typedef A B; "
- " typedef B C; class Z : public C {}; };",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class X {}; typedef X A; typedef A B; "
- "class Z : public B {};", ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class X {}; typedef X A; typedef A B; typedef B C; "
- "class Z : public C {};", ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class U {}; typedef U X; typedef X V; "
- "class Z : public V {};", ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class Base {}; typedef Base X; "
- "class Z : public Base {};", ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class Base {}; typedef Base Base2; typedef Base2 X; "
- "class Z : public Base {};", ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
- "class Z : public Base {};", ZIsDerivedFromX));
- EXPECT_TRUE(
- matches("class A {}; typedef A X; typedef A Y; "
- "class Z : public Y {};", ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("template <typename T> class Z;"
- "template <> class Z<void> {};"
- "template <typename T> class Z : public Z<void> {};",
- IsDerivedFromX));
- EXPECT_TRUE(
- matches("template <typename T> class X;"
- "template <> class X<void> {};"
- "template <typename T> class X : public X<void> {};",
- IsDerivedFromX));
- EXPECT_TRUE(matches(
- "class X {};"
- "template <typename T> class Z;"
- "template <> class Z<void> {};"
- "template <typename T> class Z : public Z<void>, public X {};",
- ZIsDerivedFromX));
- EXPECT_TRUE(
- notMatches("template<int> struct X;"
- "template<int i> struct X : public X<i-1> {};",
- cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
- EXPECT_TRUE(matches(
- "struct A {};"
- "template<int> struct X;"
- "template<int i> struct X : public X<i-1> {};"
- "template<> struct X<0> : public A {};"
- "struct B : public X<42> {};",
- cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
-
- // FIXME: Once we have better matchers for template type matching,
- // get rid of the Variable(...) matching and match the right template
- // declarations directly.
- const char *RecursiveTemplateOneParameter =
- "class Base1 {}; class Base2 {};"
- "template <typename T> class Z;"
- "template <> class Z<void> : public Base1 {};"
- "template <> class Z<int> : public Base2 {};"
- "template <> class Z<float> : public Z<void> {};"
- "template <> class Z<double> : public Z<int> {};"
- "template <typename T> class Z : public Z<float>, public Z<double> {};"
- "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
- EXPECT_TRUE(matches(
- RecursiveTemplateOneParameter,
- varDecl(hasName("z_float"),
- hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
- EXPECT_TRUE(notMatches(
- RecursiveTemplateOneParameter,
- varDecl(hasName("z_float"),
- hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
- EXPECT_TRUE(matches(
- RecursiveTemplateOneParameter,
- varDecl(hasName("z_char"),
- hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
- isDerivedFrom("Base2")))))));
-
- const char *RecursiveTemplateTwoParameters =
- "class Base1 {}; class Base2 {};"
- "template <typename T1, typename T2> class Z;"
- "template <typename T> class Z<void, T> : public Base1 {};"
- "template <typename T> class Z<int, T> : public Base2 {};"
- "template <typename T> class Z<float, T> : public Z<void, T> {};"
- "template <typename T> class Z<double, T> : public Z<int, T> {};"
- "template <typename T1, typename T2> class Z : "
- " public Z<float, T2>, public Z<double, T2> {};"
- "void f() { Z<float, void> z_float; Z<double, void> z_double; "
- " Z<char, void> z_char; }";
- EXPECT_TRUE(matches(
- RecursiveTemplateTwoParameters,
- varDecl(hasName("z_float"),
- hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
- EXPECT_TRUE(notMatches(
- RecursiveTemplateTwoParameters,
- varDecl(hasName("z_float"),
- hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
- EXPECT_TRUE(matches(
- RecursiveTemplateTwoParameters,
- varDecl(hasName("z_char"),
- hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
- isDerivedFrom("Base2")))))));
- EXPECT_TRUE(matches(
- "namespace ns { class X {}; class Y : public X {}; }",
- cxxRecordDecl(isDerivedFrom("::ns::X"))));
- EXPECT_TRUE(notMatches(
- "class X {}; class Y : public X {};",
- cxxRecordDecl(isDerivedFrom("::ns::X"))));
-
- EXPECT_TRUE(matches(
- "class X {}; class Y : public X {};",
- cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
-
- EXPECT_TRUE(matches(
- "template<typename T> class X {};"
- "template<typename T> using Z = X<T>;"
- "template <typename T> class Y : Z<T> {};",
- cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
-}
-
-TEST(DeclarationMatcher, hasMethod) {
- EXPECT_TRUE(matches("class A { void func(); };",
- cxxRecordDecl(hasMethod(hasName("func")))));
- EXPECT_TRUE(notMatches("class A { void func(); };",
- cxxRecordDecl(hasMethod(isPublic()))));
-}
-
-TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
- EXPECT_TRUE(matches(
- "template <typename T> struct A {"
- " template <typename T2> struct F {};"
- "};"
- "template <typename T> struct B : A<T>::template F<T> {};"
- "B<int> b;",
- cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
-}
-
-TEST(DeclarationMatcher, hasDeclContext) {
- EXPECT_TRUE(matches(
- "namespace N {"
- " namespace M {"
- " class D {};"
- " }"
- "}",
- recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
- EXPECT_TRUE(notMatches(
- "namespace N {"
- " namespace M {"
- " class D {};"
- " }"
- "}",
- recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
-
- EXPECT_TRUE(matches("namespace {"
- " namespace M {"
- " class D {};"
- " }"
- "}",
- recordDecl(hasDeclContext(namespaceDecl(
- hasName("M"), hasDeclContext(namespaceDecl()))))));
-
- EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
-}
-
-TEST(DeclarationMatcher, translationUnitDecl) {
- const std::string Code = "int MyVar1;\n"
- "namespace NameSpace {\n"
- "int MyVar2;\n"
- "} // namespace NameSpace\n";
- EXPECT_TRUE(matches(
- Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
- EXPECT_FALSE(matches(
- Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
- EXPECT_TRUE(matches(
- Code,
- varDecl(hasName("MyVar2"),
- hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
-}
-
-TEST(DeclarationMatcher, LinkageSpecification) {
- EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
- EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
-}
-
-TEST(ClassTemplate, DoesNotMatchClass) {
- DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
- EXPECT_TRUE(notMatches("class X;", ClassX));
- EXPECT_TRUE(notMatches("class X {};", ClassX));
-}
-
-TEST(ClassTemplate, MatchesClassTemplate) {
- DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
- EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
- EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
-}
-
-TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
- EXPECT_TRUE(notMatches("template<typename T> class X { };"
- "template<> class X<int> { int a; };",
- classTemplateDecl(hasName("X"),
- hasDescendant(fieldDecl(hasName("a"))))));
-}
-
-TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
- EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
- "template<typename T> class X<T, int> { int a; };",
- classTemplateDecl(hasName("X"),
- hasDescendant(fieldDecl(hasName("a"))))));
-}
-
-TEST(AllOf, AllOverloadsWork) {
- const char Program[] =
- "struct T { };"
- "int f(int, T*, int, int);"
- "void g(int x) { T t; f(x, &t, 3, 4); }";
- EXPECT_TRUE(matches(Program,
- callExpr(allOf(callee(functionDecl(hasName("f"))),
- hasArgument(0, declRefExpr(to(varDecl())))))));
- EXPECT_TRUE(matches(Program,
- callExpr(allOf(callee(functionDecl(hasName("f"))),
- hasArgument(0, declRefExpr(to(varDecl()))),
- hasArgument(1, hasType(pointsTo(
- recordDecl(hasName("T")))))))));
- EXPECT_TRUE(matches(Program,
- callExpr(allOf(callee(functionDecl(hasName("f"))),
- hasArgument(0, declRefExpr(to(varDecl()))),
- hasArgument(1, hasType(pointsTo(
- recordDecl(hasName("T"))))),
- hasArgument(2, integerLiteral(equals(3)))))));
- EXPECT_TRUE(matches(Program,
- callExpr(allOf(callee(functionDecl(hasName("f"))),
- hasArgument(0, declRefExpr(to(varDecl()))),
- hasArgument(1, hasType(pointsTo(
- recordDecl(hasName("T"))))),
- hasArgument(2, integerLiteral(equals(3))),
- hasArgument(3, integerLiteral(equals(4)))))));
-}
-
-TEST(ConstructVariadic, MismatchedTypes_Regression) {
- EXPECT_TRUE(
- matches("const int a = 0;",
- internal::DynTypedMatcher::constructVariadic(
- internal::DynTypedMatcher::VO_AnyOf,
- ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>(),
- {isConstQualified(), arrayType()})
- .convertTo<QualType>()));
-}
-
-TEST(DeclarationMatcher, MatchAnyOf) {
- DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
- anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
- EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
- EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
- EXPECT_TRUE(
- notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
- EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
-
- DeclarationMatcher XOrYOrZOrU =
- recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
- EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
- EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
-
- DeclarationMatcher XOrYOrZOrUOrV =
- recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
- hasName("V")));
- EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
- EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
- EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
- EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
- EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
- EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
-
- StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
- EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
- EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
- EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
-
- EXPECT_TRUE(
- matches("void f() try { } catch (int) { } catch (...) { }",
- cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
-}
-
-TEST(DeclarationMatcher, MatchHas) {
- DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
- EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
- EXPECT_TRUE(matches("class X {};", HasClassX));
-
- DeclarationMatcher YHasClassX =
- recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
- EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
- EXPECT_TRUE(notMatches("class X {};", YHasClassX));
- EXPECT_TRUE(
- notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
-}
-
-TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
- DeclarationMatcher Recursive =
- recordDecl(
- has(recordDecl(
- has(recordDecl(hasName("X"))),
- has(recordDecl(hasName("Y"))),
- hasName("Z"))),
- has(recordDecl(
- has(recordDecl(hasName("A"))),
- has(recordDecl(hasName("B"))),
- hasName("C"))),
- hasName("F"));
-
- EXPECT_TRUE(matches(
- "class F {"
- " class Z {"
- " class X {};"
- " class Y {};"
- " };"
- " class C {"
- " class A {};"
- " class B {};"
- " };"
- "};", Recursive));
-
- EXPECT_TRUE(matches(
- "class F {"
- " class Z {"
- " class A {};"
- " class X {};"
- " class Y {};"
- " };"
- " class C {"
- " class X {};"
- " class A {};"
- " class B {};"
- " };"
- "};", Recursive));
-
- EXPECT_TRUE(matches(
- "class O1 {"
- " class O2 {"
- " class F {"
- " class Z {"
- " class A {};"
- " class X {};"
- " class Y {};"
- " };"
- " class C {"
- " class X {};"
- " class A {};"
- " class B {};"
- " };"
- " };"
- " };"
- "};", Recursive));
-}
-
-TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
- DeclarationMatcher Recursive =
- recordDecl(
- anyOf(
- has(recordDecl(
- anyOf(
- has(recordDecl(
- hasName("X"))),
- has(recordDecl(
- hasName("Y"))),
- hasName("Z")))),
- has(recordDecl(
- anyOf(
- hasName("C"),
- has(recordDecl(
- hasName("A"))),
- has(recordDecl(
- hasName("B")))))),
- hasName("F")));
-
- EXPECT_TRUE(matches("class F {};", Recursive));
- EXPECT_TRUE(matches("class Z {};", Recursive));
- EXPECT_TRUE(matches("class C {};", Recursive));
- EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
- EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
- EXPECT_TRUE(
- matches("class O1 { class O2 {"
- " class M { class N { class B {}; }; }; "
- "}; };", Recursive));
-}
-
-TEST(DeclarationMatcher, MatchNot) {
- DeclarationMatcher NotClassX =
- cxxRecordDecl(
- isDerivedFrom("Y"),
- unless(hasName("X")));
- EXPECT_TRUE(notMatches("", NotClassX));
- EXPECT_TRUE(notMatches("class Y {};", NotClassX));
- EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
- EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
- EXPECT_TRUE(
- notMatches("class Y {}; class Z {}; class X : public Y {};",
- NotClassX));
-
- DeclarationMatcher ClassXHasNotClassY =
- recordDecl(
- hasName("X"),
- has(recordDecl(hasName("Z"))),
- unless(
- has(recordDecl(hasName("Y")))));
- EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
- EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
- ClassXHasNotClassY));
-
- DeclarationMatcher NamedNotRecord =
- namedDecl(hasName("Foo"), unless(recordDecl()));
- EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
- EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
-}
-
-TEST(DeclarationMatcher, HasDescendant) {
- DeclarationMatcher ZDescendantClassX =
- recordDecl(
- hasDescendant(recordDecl(hasName("X"))),
- hasName("Z"));
- EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
- EXPECT_TRUE(
- matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
- EXPECT_TRUE(
- matches("class Z { class A { class Y { class X {}; }; }; };",
- ZDescendantClassX));
- EXPECT_TRUE(
- matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
- ZDescendantClassX));
- EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
-
- DeclarationMatcher ZDescendantClassXHasClassY =
- recordDecl(
- hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
- hasName("X"))),
- hasName("Z"));
- EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
- ZDescendantClassXHasClassY));
- EXPECT_TRUE(
- matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
- ZDescendantClassXHasClassY));
- EXPECT_TRUE(notMatches(
- "class Z {"
- " class A {"
- " class B {"
- " class X {"
- " class C {"
- " class Y {};"
- " };"
- " };"
- " }; "
- " };"
- "};", ZDescendantClassXHasClassY));
-
- DeclarationMatcher ZDescendantClassXDescendantClassY =
- recordDecl(
- hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
- hasName("X"))),
- hasName("Z"));
- EXPECT_TRUE(
- matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
- ZDescendantClassXDescendantClassY));
- EXPECT_TRUE(matches(
- "class Z {"
- " class A {"
- " class X {"
- " class B {"
- " class Y {};"
- " };"
- " class Y {};"
- " };"
- " };"
- "};", ZDescendantClassXDescendantClassY));
-}
-
-TEST(DeclarationMatcher, HasDescendantMemoization) {
- DeclarationMatcher CannotMemoize =
- decl(hasDescendant(typeLoc().bind("x")), has(decl()));
- EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
-}
-
-TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
- auto Name = hasName("i");
- auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
- auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
- // Matching VD first should not make a cache hit for RD.
- EXPECT_TRUE(notMatches("void f() { int i; }",
- decl(hasDescendant(VD), hasDescendant(RD))));
- EXPECT_TRUE(notMatches("void f() { int i; }",
- decl(hasDescendant(RD), hasDescendant(VD))));
- // Not matching RD first should not make a cache hit for VD either.
- EXPECT_TRUE(matches("void f() { int i; }",
- decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
-}
-
-TEST(DeclarationMatcher, HasAttr) {
- EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
- decl(hasAttr(clang::attr::WarnUnused))));
- EXPECT_FALSE(matches("struct X {};",
- decl(hasAttr(clang::attr::WarnUnused))));
-}
-
-TEST(DeclarationMatcher, MatchCudaDecl) {
- EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
- "void g() { f<<<1, 2>>>(); }",
- cudaKernelCallExpr()));
- EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
- hasAttr(clang::attr::CUDADevice)));
- EXPECT_TRUE(notMatchesWithCuda("void f() {}",
- cudaKernelCallExpr()));
- EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
- hasAttr(clang::attr::CUDAGlobal)));
-}
-
-// Implements a run method that returns whether BoundNodes contains a
-// Decl bound to Id that can be dynamically cast to T.
-// Optionally checks that the check succeeded a specific number of times.
-template <typename T>
-class VerifyIdIsBoundTo : public BoundNodesCallback {
-public:
- // Create an object that checks that a node of type \c T was bound to \c Id.
- // Does not check for a certain number of matches.
- explicit VerifyIdIsBoundTo(llvm::StringRef Id)
- : Id(Id), ExpectedCount(-1), Count(0) {}
-
- // Create an object that checks that a node of type \c T was bound to \c Id.
- // Checks that there were exactly \c ExpectedCount matches.
- VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
- : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
-
- // Create an object that checks that a node of type \c T was bound to \c Id.
- // Checks that there was exactly one match with the name \c ExpectedName.
- // Note that \c T must be a NamedDecl for this to work.
- VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
- int ExpectedCount = 1)
- : Id(Id), ExpectedCount(ExpectedCount), Count(0),
- ExpectedName(ExpectedName) {}
-
- void onEndOfTranslationUnit() override {
- if (ExpectedCount != -1)
- EXPECT_EQ(ExpectedCount, Count);
- if (!ExpectedName.empty())
- EXPECT_EQ(ExpectedName, Name);
- Count = 0;
- Name.clear();
- }
-
- ~VerifyIdIsBoundTo() override {
- EXPECT_EQ(0, Count);
- EXPECT_EQ("", Name);
- }
-
- bool run(const BoundNodes *Nodes) override {
- const BoundNodes::IDToNodeMap &M = Nodes->getMap();
- if (Nodes->getNodeAs<T>(Id)) {
- ++Count;
- if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
- Name = Named->getNameAsString();
- } else if (const NestedNameSpecifier *NNS =
- Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
- llvm::raw_string_ostream OS(Name);
- NNS->print(OS, PrintingPolicy(LangOptions()));
- }
- BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
- EXPECT_NE(M.end(), I);
- if (I != M.end())
- EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
- return true;
- }
- EXPECT_TRUE(M.count(Id) == 0 ||
- M.find(Id)->second.template get<T>() == nullptr);
- return false;
- }
-
- bool run(const BoundNodes *Nodes, ASTContext *Context) override {
- return run(Nodes);
- }
-
-private:
- const std::string Id;
- const int ExpectedCount;
- int Count;
- const std::string ExpectedName;
- std::string Name;
-};
-
-TEST(HasDescendant, MatchesDescendantTypes) {
- EXPECT_TRUE(matches("void f() { int i = 3; }",
- decl(hasDescendant(loc(builtinType())))));
- EXPECT_TRUE(matches("void f() { int i = 3; }",
- stmt(hasDescendant(builtinType()))));
-
- EXPECT_TRUE(matches("void f() { int i = 3; }",
- stmt(hasDescendant(loc(builtinType())))));
- EXPECT_TRUE(matches("void f() { int i = 3; }",
- stmt(hasDescendant(qualType(builtinType())))));
-
- EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
- stmt(hasDescendant(isInteger()))));
-
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void f() { int a; float c; int d; int e; }",
- functionDecl(forEachDescendant(
- varDecl(hasDescendant(isInteger())).bind("x"))),
- new VerifyIdIsBoundTo<Decl>("x", 3)));
-}
-
-TEST(HasDescendant, MatchesDescendantsOfTypes) {
- EXPECT_TRUE(matches("void f() { int*** i; }",
- qualType(hasDescendant(builtinType()))));
- EXPECT_TRUE(matches("void f() { int*** i; }",
- qualType(hasDescendant(
- pointerType(pointee(builtinType()))))));
- EXPECT_TRUE(matches("void f() { int*** i; }",
- typeLoc(hasDescendant(loc(builtinType())))));
-
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void f() { int*** i; }",
- qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
- new VerifyIdIsBoundTo<Type>("x", 2)));
-}
-
-TEST(Has, MatchesChildrenOfTypes) {
- EXPECT_TRUE(matches("int i;",
- varDecl(hasName("i"), has(isInteger()))));
- EXPECT_TRUE(notMatches("int** i;",
- varDecl(hasName("i"), has(isInteger()))));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "int (*f)(float, int);",
- qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
- new VerifyIdIsBoundTo<QualType>("x", 2)));
-}
-
-TEST(Has, MatchesChildTypes) {
- EXPECT_TRUE(matches(
- "int* i;",
- varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
- EXPECT_TRUE(notMatches(
- "int* i;",
- varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
-}
-
-TEST(ValueDecl, Matches) {
- EXPECT_TRUE(matches("enum EnumType { EnumValue };",
- valueDecl(hasType(asString("enum EnumType")))));
- EXPECT_TRUE(matches("void FunctionDecl();",
- valueDecl(hasType(asString("void (void)")))));
-}
-
-TEST(Enum, DoesNotMatchClasses) {
- EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
-}
-
-TEST(Enum, MatchesEnums) {
- EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
-}
-
-TEST(EnumConstant, Matches) {
- DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
- EXPECT_TRUE(matches("enum X{ A };", Matcher));
- EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
- EXPECT_TRUE(notMatches("enum X {};", Matcher));
-}
-
-TEST(StatementMatcher, Has) {
- StatementMatcher HasVariableI =
- expr(hasType(pointsTo(recordDecl(hasName("X")))),
- has(declRefExpr(to(varDecl(hasName("i"))))));
-
- EXPECT_TRUE(matches(
- "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
- EXPECT_TRUE(notMatches(
- "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
-}
-
-TEST(StatementMatcher, HasDescendant) {
- StatementMatcher HasDescendantVariableI =
- expr(hasType(pointsTo(recordDecl(hasName("X")))),
- hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
-
- EXPECT_TRUE(matches(
- "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
- HasDescendantVariableI));
- EXPECT_TRUE(notMatches(
- "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
- HasDescendantVariableI));
-}
-
-TEST(TypeMatcher, MatchesClassType) {
- TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
-
- EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
- EXPECT_TRUE(notMatches("class A {};", TypeA));
-
- TypeMatcher TypeDerivedFromA =
- hasDeclaration(cxxRecordDecl(isDerivedFrom("A")));
-
- EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
- TypeDerivedFromA));
- EXPECT_TRUE(notMatches("class A {};", TypeA));
-
- TypeMatcher TypeAHasClassB = hasDeclaration(
- recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
-
- EXPECT_TRUE(
- matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
-
- EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }",
- varDecl(hasType(namedDecl(hasName("S"))))));
-}
-
-TEST(TypeMatcher, MatchesDeclTypes) {
- // TypedefType -> TypedefNameDecl
- EXPECT_TRUE(matches("typedef int I; void f(I i);",
- parmVarDecl(hasType(namedDecl(hasName("I"))))));
- // ObjCObjectPointerType
- EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);",
- parmVarDecl(hasType(objcObjectPointerType()))));
- // ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl
- EXPECT_TRUE(matchesObjC(
- "@interface Foo @end void f(Foo *f);",
- parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo")))))));
- // TemplateTypeParmType
- EXPECT_TRUE(matches("template <typename T> void f(T t);",
- parmVarDecl(hasType(templateTypeParmType()))));
- // TemplateTypeParmType -> TemplateTypeParmDecl
- EXPECT_TRUE(matches("template <typename T> void f(T t);",
- parmVarDecl(hasType(namedDecl(hasName("T"))))));
- // InjectedClassNameType
- EXPECT_TRUE(matches("template <typename T> struct S {"
- " void f(S s);"
- "};",
- parmVarDecl(hasType(injectedClassNameType()))));
- EXPECT_TRUE(notMatches("template <typename T> struct S {"
- " void g(S<T> s);"
- "};",
- parmVarDecl(hasType(injectedClassNameType()))));
- // InjectedClassNameType -> CXXRecordDecl
- EXPECT_TRUE(matches("template <typename T> struct S {"
- " void f(S s);"
- "};",
- parmVarDecl(hasType(namedDecl(hasName("S"))))));
-
- static const char Using[] = "template <typename T>"
- "struct Base {"
- " typedef T Foo;"
- "};"
- ""
- "template <typename T>"
- "struct S : private Base<T> {"
- " using typename Base<T>::Foo;"
- " void f(Foo);"
- "};";
- // UnresolvedUsingTypenameDecl
- EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo"))));
- // UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl
- EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo"))))));
-}
-
-TEST(Matcher, BindMatchedNodes) {
- DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
-
- EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
- ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
-
- EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
- ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
-
- TypeMatcher TypeAHasClassB = hasDeclaration(
- recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
-
- EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
- TypeAHasClassB,
- new VerifyIdIsBoundTo<Decl>("b")));
-
- StatementMatcher MethodX =
- callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
-
- EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
- MethodX,
- new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
-}
-
-TEST(Matcher, BindTheSameNameInAlternatives) {
- StatementMatcher matcher = anyOf(
- binaryOperator(hasOperatorName("+"),
- hasLHS(expr().bind("x")),
- hasRHS(integerLiteral(equals(0)))),
- binaryOperator(hasOperatorName("+"),
- hasLHS(integerLiteral(equals(0))),
- hasRHS(expr().bind("x"))));
-
- EXPECT_TRUE(matchAndVerifyResultTrue(
- // The first branch of the matcher binds x to 0 but then fails.
- // The second branch binds x to f() and succeeds.
- "int f() { return 0 + f(); }",
- matcher,
- new VerifyIdIsBoundTo<CallExpr>("x")));
-}
-
-TEST(Matcher, BindsIDForMemoizedResults) {
- // Using the same matcher in two match expressions will make memoization
- // kick in.
- DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { class B { class X {}; }; };",
- DeclarationMatcher(anyOf(
- recordDecl(hasName("A"), hasDescendant(ClassX)),
- recordDecl(hasName("B"), hasDescendant(ClassX)))),
- new VerifyIdIsBoundTo<Decl>("x", 2)));
-}
-
-TEST(HasDeclaration, HasDeclarationOfEnumType) {
- EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
- expr(hasType(pointsTo(
- qualType(hasDeclaration(enumDecl(hasName("X")))))))));
-}
-
-TEST(HasDeclaration, HasGetDeclTraitTest) {
- EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
- EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
- EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
-}
-
-TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
- EXPECT_TRUE(matches("typedef int X; X a;",
- varDecl(hasName("a"),
- hasType(typedefType(hasDeclaration(decl()))))));
-
- // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
-}
-
-TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
- EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
- varDecl(hasType(templateSpecializationType(
- hasDeclaration(namedDecl(hasName("A"))))))));
-}
-
-TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
- TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
- EXPECT_TRUE(
- matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
- EXPECT_TRUE(
- notMatches("class X {}; void y(X *x) { x; }",
- expr(hasType(ClassX))));
- EXPECT_TRUE(
- matches("class X {}; void y(X *x) { x; }",
- expr(hasType(pointsTo(ClassX)))));
-}
-
-TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
- TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
- EXPECT_TRUE(
- matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
- EXPECT_TRUE(
- notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
- EXPECT_TRUE(
- matches("class X {}; void y() { X *x; }",
- varDecl(hasType(pointsTo(ClassX)))));
-}
-
-TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
- DeclarationMatcher ClassX = recordDecl(hasName("X"));
- EXPECT_TRUE(
- matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
- EXPECT_TRUE(
- notMatches("class X {}; void y(X *x) { x; }",
- expr(hasType(ClassX))));
-}
-
-TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
- DeclarationMatcher ClassX = recordDecl(hasName("X"));
- EXPECT_TRUE(
- matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
- EXPECT_TRUE(
- notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
-}
-
-TEST(HasTypeLoc, MatchesDeclaratorDecls) {
- EXPECT_TRUE(matches("int x;",
- varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
-
- // Make sure we don't crash on implicit constructors.
- EXPECT_TRUE(notMatches("class X {}; X x;",
- declaratorDecl(hasTypeLoc(loc(asString("int"))))));
-}
-
-TEST(Matcher, Call) {
- // FIXME: Do we want to overload Call() to directly take
- // Matcher<Decl>, too?
- StatementMatcher MethodX =
- callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
-
- EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
- EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
-
- StatementMatcher MethodOnY =
- cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
-
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
- MethodOnY));
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
- MethodOnY));
- EXPECT_TRUE(
- notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
- MethodOnY));
- EXPECT_TRUE(
- notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
- MethodOnY));
- EXPECT_TRUE(
- notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
- MethodOnY));
-
- StatementMatcher MethodOnYPointer =
- cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
-
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
- MethodOnYPointer));
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
- MethodOnYPointer));
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
- MethodOnYPointer));
- EXPECT_TRUE(
- notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
- MethodOnYPointer));
- EXPECT_TRUE(
- notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
- MethodOnYPointer));
-}
-
-TEST(Matcher, Lambda) {
- EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
- lambdaExpr()));
-}
-
-TEST(Matcher, ForRange) {
- EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
- "void f() { for (auto &a : as); }",
- cxxForRangeStmt()));
- EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
- cxxForRangeStmt()));
-}
-
-TEST(Matcher, SubstNonTypeTemplateParm) {
- EXPECT_FALSE(matches("template<int N>\n"
- "struct A { static const int n = 0; };\n"
- "struct B : public A<42> {};",
- substNonTypeTemplateParmExpr()));
- EXPECT_TRUE(matches("template<int N>\n"
- "struct A { static const int n = N; };\n"
- "struct B : public A<42> {};",
- substNonTypeTemplateParmExpr()));
-}
-
-TEST(Matcher, NonTypeTemplateParmDecl) {
- EXPECT_TRUE(matches("template <int N> void f();",
- nonTypeTemplateParmDecl(hasName("N"))));
- EXPECT_TRUE(
- notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
-}
-
-TEST(Matcher, templateTypeParmDecl) {
- EXPECT_TRUE(matches("template <typename T> void f();",
- templateTypeParmDecl(hasName("T"))));
- EXPECT_TRUE(
- notMatches("template <int N> void f();", templateTypeParmDecl()));
-}
-
-TEST(Matcher, UserDefinedLiteral) {
- EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
- " return i + 1;"
- "}"
- "char c = 'a'_inc;",
- userDefinedLiteral()));
-}
-
-TEST(Matcher, FlowControl) {
- EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
- EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
- continueStmt()));
- EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
- EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
- EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
-}
-
-TEST(HasType, MatchesAsString) {
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
- cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
- EXPECT_TRUE(
- matches("class X { void x(int x) {} };",
- cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
- EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
- fieldDecl(hasType(asString("ns::A")))));
- EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
- fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
-}
-
-TEST(Matcher, OverloadedOperatorCall) {
- StatementMatcher OpCall = cxxOperatorCallExpr();
- // Unary operator
- EXPECT_TRUE(matches("class Y { }; "
- "bool operator!(Y x) { return false; }; "
- "Y y; bool c = !y;", OpCall));
- // No match -- special operators like "new", "delete"
- // FIXME: operator new takes size_t, for which we need stddef.h, for which
- // we need to figure out include paths in the test.
- // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
- // "class Y { }; "
- // "void *operator new(size_t size) { return 0; } "
- // "Y *y = new Y;", OpCall));
- EXPECT_TRUE(notMatches("class Y { }; "
- "void operator delete(void *p) { } "
- "void a() {Y *y = new Y; delete y;}", OpCall));
- // Binary operator
- EXPECT_TRUE(matches("class Y { }; "
- "bool operator&&(Y x, Y y) { return true; }; "
- "Y a; Y b; bool c = a && b;",
- OpCall));
- // No match -- normal operator, not an overloaded one.
- EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
- EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
-}
-
-TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
- StatementMatcher OpCallAndAnd =
- cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
- EXPECT_TRUE(matches("class Y { }; "
- "bool operator&&(Y x, Y y) { return true; }; "
- "Y a; Y b; bool c = a && b;", OpCallAndAnd));
- StatementMatcher OpCallLessLess =
- cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
- EXPECT_TRUE(notMatches("class Y { }; "
- "bool operator&&(Y x, Y y) { return true; }; "
- "Y a; Y b; bool c = a && b;",
- OpCallLessLess));
- StatementMatcher OpStarCall =
- cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
- EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
- OpStarCall));
- DeclarationMatcher ClassWithOpStar =
- cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
- EXPECT_TRUE(matches("class Y { int operator*(); };",
- ClassWithOpStar));
- EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
- ClassWithOpStar)) ;
- DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
- EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
- EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
-}
-
-TEST(Matcher, NestedOverloadedOperatorCalls) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class Y { }; "
- "Y& operator&&(Y& x, Y& y) { return x; }; "
- "Y a; Y b; Y c; Y d = a && b && c;",
- cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
- new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
- EXPECT_TRUE(matches("class Y { }; "
- "Y& operator&&(Y& x, Y& y) { return x; }; "
- "Y a; Y b; Y c; Y d = a && b && c;",
- cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
- EXPECT_TRUE(
- matches("class Y { }; "
- "Y& operator&&(Y& x, Y& y) { return x; }; "
- "Y a; Y b; Y c; Y d = a && b && c;",
- cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
-}
-
-TEST(Matcher, ThisPointerType) {
- StatementMatcher MethodOnY =
- cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
-
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
- MethodOnY));
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
- MethodOnY));
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
- MethodOnY));
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
- MethodOnY));
- EXPECT_TRUE(
- matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
- MethodOnY));
-
- EXPECT_TRUE(matches(
- "class Y {"
- " public: virtual void x();"
- "};"
- "class X : public Y {"
- " public: virtual void x();"
- "};"
- "void z() { X *x; x->Y::x(); }", MethodOnY));
-}
-
-TEST(Matcher, VariableUsage) {
- StatementMatcher Reference =
- declRefExpr(to(
- varDecl(hasInitializer(
- cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
-
- EXPECT_TRUE(matches(
- "class Y {"
- " public:"
- " bool x() const;"
- "};"
- "void z(const Y &y) {"
- " bool b = y.x();"
- " if (b) {}"
- "}", Reference));
-
- EXPECT_TRUE(notMatches(
- "class Y {"
- " public:"
- " bool x() const;"
- "};"
- "void z(const Y &y) {"
- " bool b = y.x();"
- "}", Reference));
-}
-
-TEST(Matcher, VarDecl_Storage) {
- auto M = varDecl(hasName("X"), hasLocalStorage());
- EXPECT_TRUE(matches("void f() { int X; }", M));
- EXPECT_TRUE(notMatches("int X;", M));
- EXPECT_TRUE(notMatches("void f() { static int X; }", M));
-
- M = varDecl(hasName("X"), hasGlobalStorage());
- EXPECT_TRUE(notMatches("void f() { int X; }", M));
- EXPECT_TRUE(matches("int X;", M));
- EXPECT_TRUE(matches("void f() { static int X; }", M));
-}
-
-TEST(Matcher, VarDecl_StorageDuration) {
- std::string T =
- "void f() { int x; static int y; } int a;";
-
- EXPECT_TRUE(matches(T, varDecl(hasName("x"), hasAutomaticStorageDuration())));
- EXPECT_TRUE(
- notMatches(T, varDecl(hasName("y"), hasAutomaticStorageDuration())));
- EXPECT_TRUE(
- notMatches(T, varDecl(hasName("a"), hasAutomaticStorageDuration())));
-
- EXPECT_TRUE(matches(T, varDecl(hasName("y"), hasStaticStorageDuration())));
- EXPECT_TRUE(matches(T, varDecl(hasName("a"), hasStaticStorageDuration())));
- EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasStaticStorageDuration())));
-
- // FIXME: It is really hard to test with thread_local itself because not all
- // targets support TLS, which causes this to be an error depending on what
- // platform the test is being run on. We do not have access to the TargetInfo
- // object to be able to test whether the platform supports TLS or not.
- EXPECT_TRUE(notMatches(T, varDecl(hasName("x"), hasThreadStorageDuration())));
- EXPECT_TRUE(notMatches(T, varDecl(hasName("y"), hasThreadStorageDuration())));
- EXPECT_TRUE(notMatches(T, varDecl(hasName("a"), hasThreadStorageDuration())));
-}
-
-TEST(Matcher, FindsVarDeclInFunctionParameter) {
- EXPECT_TRUE(matches(
- "void f(int i) {}",
- varDecl(hasName("i"))));
-}
-
-TEST(Matcher, CalledVariable) {
- StatementMatcher CallOnVariableY =
- cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
-
- EXPECT_TRUE(matches(
- "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
- EXPECT_TRUE(matches(
- "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
- EXPECT_TRUE(matches(
- "class Y { public: void x(); };"
- "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
- EXPECT_TRUE(matches(
- "class Y { public: void x(); };"
- "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
- EXPECT_TRUE(notMatches(
- "class Y { public: void x(); };"
- "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
- CallOnVariableY));
-}
-
-TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
- EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
- unaryExprOrTypeTraitExpr()));
- EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
- alignOfExpr(anything())));
- // FIXME: Uncomment once alignof is enabled.
- // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
- // unaryExprOrTypeTraitExpr()));
- // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
- // sizeOfExpr()));
-}
-
-TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
- EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
- hasArgumentOfType(asString("int")))));
- EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
- hasArgumentOfType(asString("float")))));
- EXPECT_TRUE(matches(
- "struct A {}; void x() { A a; int b = sizeof(a); }",
- sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
- EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
- hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
-}
-
-TEST(MemberExpression, DoesNotMatchClasses) {
- EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
-}
-
-TEST(MemberExpression, MatchesMemberFunctionCall) {
- EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
-}
-
-TEST(MemberExpression, MatchesVariable) {
- EXPECT_TRUE(
- matches("class Y { void x() { this->y; } int y; };", memberExpr()));
- EXPECT_TRUE(
- matches("class Y { void x() { y; } int y; };", memberExpr()));
- EXPECT_TRUE(
- matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
-}
-
-TEST(MemberExpression, MatchesStaticVariable) {
- EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
- memberExpr()));
- EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
- memberExpr()));
- EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
- memberExpr()));
-}
-
-TEST(IsInteger, MatchesIntegers) {
- EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
- EXPECT_TRUE(matches(
- "long long i = 0; void f(long long) { }; void g() {f(i);}",
- callExpr(hasArgument(0, declRefExpr(
- to(varDecl(hasType(isInteger()))))))));
-}
-
-TEST(IsInteger, ReportsNoFalsePositives) {
- EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
- EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
- callExpr(hasArgument(0, declRefExpr(
- to(varDecl(hasType(isInteger()))))))));
-}
-
-TEST(IsAnyCharacter, MatchesCharacters) {
- EXPECT_TRUE(matches("char i = 0;", varDecl(hasType(isAnyCharacter()))));
-}
-
-TEST(IsAnyCharacter, ReportsNoFalsePositives) {
- EXPECT_TRUE(notMatches("int i;", varDecl(hasType(isAnyCharacter()))));
-}
-
-TEST(IsArrow, MatchesMemberVariablesViaArrow) {
- EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
- memberExpr(isArrow())));
- EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
- memberExpr(isArrow())));
- EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
- memberExpr(isArrow())));
-}
-
-TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
- EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
- memberExpr(isArrow())));
- EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
- memberExpr(isArrow())));
- EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
- memberExpr(isArrow())));
-}
-
-TEST(IsArrow, MatchesMemberCallsViaArrow) {
- EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
- memberExpr(isArrow())));
- EXPECT_TRUE(matches("class Y { void x() { x(); } };",
- memberExpr(isArrow())));
- EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
- memberExpr(isArrow())));
-}
-
-TEST(Callee, MatchesDeclarations) {
- StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
-
- EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
- EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
-
- CallMethodX = callExpr(callee(cxxConversionDecl()));
- EXPECT_TRUE(
- matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
- EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
- CallMethodX));
-}
-
-TEST(ConversionDeclaration, IsExplicit) {
- EXPECT_TRUE(matches("struct S { explicit operator int(); };",
- cxxConversionDecl(isExplicit())));
- EXPECT_TRUE(notMatches("struct S { operator int(); };",
- cxxConversionDecl(isExplicit())));
-}
-
-TEST(Callee, MatchesMemberExpressions) {
- EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
- callExpr(callee(memberExpr()))));
- EXPECT_TRUE(
- notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
-}
-
-TEST(Function, MatchesFunctionDeclarations) {
- StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
-
- EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
- EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
-
- if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
- llvm::Triple::Win32) {
- // FIXME: Make this work for MSVC.
- // Dependent contexts, but a non-dependent call.
- EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
- CallFunctionF));
- EXPECT_TRUE(
- matches("void f(); template <int N> struct S { void g() { f(); } };",
- CallFunctionF));
- }
-
- // Depedent calls don't match.
- EXPECT_TRUE(
- notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
- CallFunctionF));
- EXPECT_TRUE(
- notMatches("void f(int);"
- "template <typename T> struct S { void g(T t) { f(t); } };",
- CallFunctionF));
-
- EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
- EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
- EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
- functionDecl(isVariadic())));
- EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
- EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
-}
-
-TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
- EXPECT_TRUE(
- matches("template <typename T> void f(T t) {}",
- functionTemplateDecl(hasName("f"))));
-}
-
-TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
- EXPECT_TRUE(
- notMatches("void f(double d); void f(int t) {}",
- functionTemplateDecl(hasName("f"))));
-}
-
-TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
- EXPECT_TRUE(
- notMatches("void g(); template <typename T> void f(T t) {}"
- "template <> void f(int t) { g(); }",
- functionTemplateDecl(hasName("f"),
- hasDescendant(declRefExpr(to(
- functionDecl(hasName("g"))))))));
-}
-
-TEST(Matcher, Argument) {
- StatementMatcher CallArgumentY = callExpr(
- hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
-
- EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
- EXPECT_TRUE(
- matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
- EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
-
- StatementMatcher WrongIndex = callExpr(
- hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
- EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
-}
-
-TEST(Matcher, AnyArgument) {
- StatementMatcher CallArgumentY = callExpr(
- hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
- EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
- EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
- EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
-}
-
-TEST(Matcher, ArgumentCount) {
- StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
-
- EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
- EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
- EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
-}
-
-TEST(Matcher, ParameterCount) {
- DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
- EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
- EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
- EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
- EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
-}
-
-TEST(Matcher, References) {
- DeclarationMatcher ReferenceClassX = varDecl(
- hasType(references(recordDecl(hasName("X")))));
- EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
- ReferenceClassX));
- EXPECT_TRUE(
- matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
- // The match here is on the implicit copy constructor code for
- // class X, not on code 'X x = y'.
- EXPECT_TRUE(
- matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
- EXPECT_TRUE(
- notMatches("class X {}; extern X x;", ReferenceClassX));
- EXPECT_TRUE(
- notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
-}
-
-TEST(QualType, hasCanonicalType) {
- EXPECT_TRUE(notMatches("typedef int &int_ref;"
- "int a;"
- "int_ref b = a;",
- varDecl(hasType(qualType(referenceType())))));
- EXPECT_TRUE(
- matches("typedef int &int_ref;"
- "int a;"
- "int_ref b = a;",
- varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
-}
-
-TEST(QualType, hasLocalQualifiers) {
- EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
- varDecl(hasType(hasLocalQualifiers()))));
- EXPECT_TRUE(matches("int *const j = nullptr;",
- varDecl(hasType(hasLocalQualifiers()))));
- EXPECT_TRUE(matches("int *volatile k;",
- varDecl(hasType(hasLocalQualifiers()))));
- EXPECT_TRUE(notMatches("int m;",
- varDecl(hasType(hasLocalQualifiers()))));
-}
-
-TEST(HasParameter, CallsInnerMatcher) {
- EXPECT_TRUE(matches("class X { void x(int) {} };",
- cxxMethodDecl(hasParameter(0, varDecl()))));
- EXPECT_TRUE(notMatches("class X { void x(int) {} };",
- cxxMethodDecl(hasParameter(0, hasName("x")))));
-}
-
-TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
- EXPECT_TRUE(notMatches("class X { void x(int) {} };",
- cxxMethodDecl(hasParameter(42, varDecl()))));
-}
-
-TEST(HasType, MatchesParameterVariableTypesStrictly) {
- EXPECT_TRUE(matches(
- "class X { void x(X x) {} };",
- cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
- EXPECT_TRUE(notMatches(
- "class X { void x(const X &x) {} };",
- cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
- EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
- cxxMethodDecl(hasParameter(
- 0, hasType(pointsTo(recordDecl(hasName("X"))))))));
- EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
- cxxMethodDecl(hasParameter(
- 0, hasType(references(recordDecl(hasName("X"))))))));
-}
-
-TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
- EXPECT_TRUE(matches(
- "class Y {}; class X { void x(X x, Y y) {} };",
- cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
- EXPECT_TRUE(matches(
- "class Y {}; class X { void x(Y y, X x) {} };",
- cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
-}
-
-TEST(Returns, MatchesReturnTypes) {
- EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
- functionDecl(returns(asString("int")))));
- EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
- functionDecl(returns(asString("float")))));
- EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
- functionDecl(returns(hasDeclaration(
- recordDecl(hasName("Y")))))));
-}
-
-TEST(IsExternC, MatchesExternCFunctionDeclarations) {
- EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
- EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
- functionDecl(isExternC())));
- EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
-}
-
-TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
- EXPECT_TRUE(
- notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
- EXPECT_TRUE(matches("void Func() = delete;",
- functionDecl(hasName("Func"), isDeleted())));
-}
-
-TEST(IsNoThrow, MatchesNoThrowFunctionDeclarations) {
- EXPECT_TRUE(notMatches("void f();", functionDecl(isNoThrow())));
- EXPECT_TRUE(notMatches("void f() throw(int);", functionDecl(isNoThrow())));
- EXPECT_TRUE(
- notMatches("void f() noexcept(false);", functionDecl(isNoThrow())));
- EXPECT_TRUE(matches("void f() throw();", functionDecl(isNoThrow())));
- EXPECT_TRUE(matches("void f() noexcept;", functionDecl(isNoThrow())));
-}
-
-TEST(isConstexpr, MatchesConstexprDeclarations) {
- EXPECT_TRUE(matches("constexpr int foo = 42;",
- varDecl(hasName("foo"), isConstexpr())));
- EXPECT_TRUE(matches("constexpr int bar();",
- functionDecl(hasName("bar"), isConstexpr())));
-}
-
-TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
- EXPECT_TRUE(notMatches(
- "class Y {}; class X { void x(int) {} };",
- cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
-}
-
-TEST(HasAnyParameter, DoesNotMatchThisPointer) {
- EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
- cxxMethodDecl(hasAnyParameter(
- hasType(pointsTo(recordDecl(hasName("X"))))))));
-}
-
-TEST(HasName, MatchesParameterVariableDeclarations) {
- EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
- cxxMethodDecl(hasAnyParameter(hasName("x")))));
- EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
- cxxMethodDecl(hasAnyParameter(hasName("x")))));
-}
-
-TEST(Matcher, MatchesClassTemplateSpecialization) {
- EXPECT_TRUE(matches("template<typename T> struct A {};"
- "template<> struct A<int> {};",
- classTemplateSpecializationDecl()));
- EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
- classTemplateSpecializationDecl()));
- EXPECT_TRUE(notMatches("template<typename T> struct A {};",
- classTemplateSpecializationDecl()));
-}
-
-TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
- EXPECT_TRUE(matches("int x;", declaratorDecl()));
- EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
-}
-
-TEST(ParmVarDecl, MatchesParmVars) {
- EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
- EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
-}
-
-TEST(Matcher, MatchesTypeTemplateArgument) {
- EXPECT_TRUE(matches(
- "template<typename T> struct B {};"
- "B<int> b;",
- classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
- asString("int"))))));
-}
-
-TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
- EXPECT_TRUE(matches(
- "struct B { int next; };"
- "template<int(B::*next_ptr)> struct A {};"
- "A<&B::next> a;",
- classTemplateSpecializationDecl(hasAnyTemplateArgument(
- refersToDeclaration(fieldDecl(hasName("next")))))));
-
- EXPECT_TRUE(notMatches(
- "template <typename T> struct A {};"
- "A<int> a;",
- classTemplateSpecializationDecl(hasAnyTemplateArgument(
- refersToDeclaration(decl())))));
-
- EXPECT_TRUE(matches(
- "struct B { int next; };"
- "template<int(B::*next_ptr)> struct A {};"
- "A<&B::next> a;",
- templateSpecializationType(hasAnyTemplateArgument(isExpr(
- hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
-
- EXPECT_TRUE(notMatches(
- "template <typename T> struct A {};"
- "A<int> a;",
- templateSpecializationType(hasAnyTemplateArgument(
- refersToDeclaration(decl())))));
-}
-
-TEST(Matcher, MatchesSpecificArgument) {
- EXPECT_TRUE(matches(
- "template<typename T, typename U> class A {};"
- "A<bool, int> a;",
- classTemplateSpecializationDecl(hasTemplateArgument(
- 1, refersToType(asString("int"))))));
- EXPECT_TRUE(notMatches(
- "template<typename T, typename U> class A {};"
- "A<int, bool> a;",
- classTemplateSpecializationDecl(hasTemplateArgument(
- 1, refersToType(asString("int"))))));
-
- EXPECT_TRUE(matches(
- "template<typename T, typename U> class A {};"
- "A<bool, int> a;",
- templateSpecializationType(hasTemplateArgument(
- 1, refersToType(asString("int"))))));
- EXPECT_TRUE(notMatches(
- "template<typename T, typename U> class A {};"
- "A<int, bool> a;",
- templateSpecializationType(hasTemplateArgument(
- 1, refersToType(asString("int"))))));
-}
-
-TEST(TemplateArgument, Matches) {
- EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
- classTemplateSpecializationDecl(
- hasAnyTemplateArgument(templateArgument()))));
- EXPECT_TRUE(matches(
- "template<typename T> struct C {}; C<int> c;",
- templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
-}
-
-TEST(TemplateArgumentCountIs, Matches) {
- EXPECT_TRUE(
- matches("template<typename T> struct C {}; C<int> c;",
- classTemplateSpecializationDecl(templateArgumentCountIs(1))));
- EXPECT_TRUE(
- notMatches("template<typename T> struct C {}; C<int> c;",
- classTemplateSpecializationDecl(templateArgumentCountIs(2))));
-
- EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
- templateSpecializationType(templateArgumentCountIs(1))));
- EXPECT_TRUE(
- notMatches("template<typename T> struct C {}; C<int> c;",
- templateSpecializationType(templateArgumentCountIs(2))));
-}
-
-TEST(IsIntegral, Matches) {
- EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
- classTemplateSpecializationDecl(
- hasAnyTemplateArgument(isIntegral()))));
- EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
- classTemplateSpecializationDecl(hasAnyTemplateArgument(
- templateArgument(isIntegral())))));
-}
-
-TEST(RefersToIntegralType, Matches) {
- EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
- classTemplateSpecializationDecl(
- hasAnyTemplateArgument(refersToIntegralType(
- asString("int"))))));
- EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
- classTemplateSpecializationDecl(hasAnyTemplateArgument(
- refersToIntegralType(asString("int"))))));
-}
-
-TEST(EqualsIntegralValue, Matches) {
- EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
- classTemplateSpecializationDecl(
- hasAnyTemplateArgument(equalsIntegralValue("42")))));
- EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
- classTemplateSpecializationDecl(
- hasAnyTemplateArgument(equalsIntegralValue("-42")))));
- EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
- classTemplateSpecializationDecl(
- hasAnyTemplateArgument(equalsIntegralValue("-34")))));
- EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
- classTemplateSpecializationDecl(hasAnyTemplateArgument(
- equalsIntegralValue("0042")))));
-}
-
-TEST(Matcher, MatchesAccessSpecDecls) {
- EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
- EXPECT_TRUE(
- matches("class C { public: int i; };", accessSpecDecl(isPublic())));
- EXPECT_TRUE(
- notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
- EXPECT_TRUE(
- notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
-
- EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
-}
-
-TEST(Matcher, MatchesFinal) {
- EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
- EXPECT_TRUE(matches("class X { virtual void f() final; };",
- cxxMethodDecl(isFinal())));
- EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
- EXPECT_TRUE(
- notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
-}
-
-TEST(Matcher, MatchesVirtualMethod) {
- EXPECT_TRUE(matches("class X { virtual int f(); };",
- cxxMethodDecl(isVirtual(), hasName("::X::f"))));
- EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
-}
-
-TEST(Matcher, MatchesPureMethod) {
- EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
- cxxMethodDecl(isPure(), hasName("::X::f"))));
- EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
-}
-
-TEST(Matcher, MatchesCopyAssignmentOperator) {
- EXPECT_TRUE(matches("class X { X &operator=(X); };",
- cxxMethodDecl(isCopyAssignmentOperator())));
- EXPECT_TRUE(matches("class X { X &operator=(X &); };",
- cxxMethodDecl(isCopyAssignmentOperator())));
- EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
- cxxMethodDecl(isCopyAssignmentOperator())));
- EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
- cxxMethodDecl(isCopyAssignmentOperator())));
- EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
- cxxMethodDecl(isCopyAssignmentOperator())));
- EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
- cxxMethodDecl(isCopyAssignmentOperator())));
-}
-
-TEST(Matcher, MatchesConstMethod) {
- EXPECT_TRUE(
- matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
- EXPECT_TRUE(
- notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
-}
-
-TEST(Matcher, MatchesOverridingMethod) {
- EXPECT_TRUE(matches("class X { virtual int f(); }; "
- "class Y : public X { int f(); };",
- cxxMethodDecl(isOverride(), hasName("::Y::f"))));
- EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
- "class Y : public X { int f(); };",
- cxxMethodDecl(isOverride(), hasName("::X::f"))));
- EXPECT_TRUE(notMatches("class X { int f(); }; "
- "class Y : public X { int f(); };",
- cxxMethodDecl(isOverride())));
- EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
- cxxMethodDecl(isOverride())));
- EXPECT_TRUE(
- matches("template <typename Base> struct Y : Base { void f() override;};",
- cxxMethodDecl(isOverride(), hasName("::Y::f"))));
-}
-
-TEST(Matcher, ConstructorCall) {
- StatementMatcher Constructor = cxxConstructExpr();
-
- EXPECT_TRUE(
- matches("class X { public: X(); }; void x() { X x; }", Constructor));
- EXPECT_TRUE(
- matches("class X { public: X(); }; void x() { X x = X(); }",
- Constructor));
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { X x = 0; }",
- Constructor));
- EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
-}
-
-TEST(Matcher, ConstructorArgument) {
- StatementMatcher Constructor = cxxConstructExpr(
- hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
-
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { int y; X x(y); }",
- Constructor));
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
- Constructor));
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { int y; X x = y; }",
- Constructor));
- EXPECT_TRUE(
- notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
- Constructor));
-
- StatementMatcher WrongIndex = cxxConstructExpr(
- hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
- EXPECT_TRUE(
- notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
- WrongIndex));
-}
-
-TEST(Matcher, ConstructorArgumentCount) {
- StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
-
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { X x(0); }",
- Constructor1Arg));
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { X x = X(0); }",
- Constructor1Arg));
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { X x = 0; }",
- Constructor1Arg));
- EXPECT_TRUE(
- notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
- Constructor1Arg));
-}
-
-TEST(Matcher, ConstructorListInitialization) {
- StatementMatcher ConstructorListInit =
- cxxConstructExpr(isListInitialization());
-
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { X x{0}; }",
- ConstructorListInit));
- EXPECT_FALSE(
- matches("class X { public: X(int); }; void x() { X x(0); }",
- ConstructorListInit));
-}
-
-TEST(Matcher,ThisExpr) {
- EXPECT_TRUE(
- matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
- EXPECT_TRUE(
- notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
-}
-
-TEST(Matcher, BindTemporaryExpression) {
- StatementMatcher TempExpression = cxxBindTemporaryExpr();
-
- std::string ClassString = "class string { public: string(); ~string(); }; ";
-
- EXPECT_TRUE(
- matches(ClassString +
- "string GetStringByValue();"
- "void FunctionTakesString(string s);"
- "void run() { FunctionTakesString(GetStringByValue()); }",
- TempExpression));
-
- EXPECT_TRUE(
- notMatches(ClassString +
- "string* GetStringPointer(); "
- "void FunctionTakesStringPtr(string* s);"
- "void run() {"
- " string* s = GetStringPointer();"
- " FunctionTakesStringPtr(GetStringPointer());"
- " FunctionTakesStringPtr(s);"
- "}",
- TempExpression));
-
- EXPECT_TRUE(
- notMatches("class no_dtor {};"
- "no_dtor GetObjByValue();"
- "void ConsumeObj(no_dtor param);"
- "void run() { ConsumeObj(GetObjByValue()); }",
- TempExpression));
-}
-
-TEST(MaterializeTemporaryExpr, MatchesTemporary) {
- std::string ClassString =
- "class string { public: string(); int length(); }; ";
-
- EXPECT_TRUE(
- matches(ClassString +
- "string GetStringByValue();"
- "void FunctionTakesString(string s);"
- "void run() { FunctionTakesString(GetStringByValue()); }",
- materializeTemporaryExpr()));
-
- EXPECT_TRUE(
- notMatches(ClassString +
- "string* GetStringPointer(); "
- "void FunctionTakesStringPtr(string* s);"
- "void run() {"
- " string* s = GetStringPointer();"
- " FunctionTakesStringPtr(GetStringPointer());"
- " FunctionTakesStringPtr(s);"
- "}",
- materializeTemporaryExpr()));
-
- EXPECT_TRUE(
- notMatches(ClassString +
- "string GetStringByValue();"
- "void run() { int k = GetStringByValue().length(); }",
- materializeTemporaryExpr()));
-
- EXPECT_TRUE(
- notMatches(ClassString +
- "string GetStringByValue();"
- "void run() { GetStringByValue(); }",
- materializeTemporaryExpr()));
-}
-
-TEST(ConstructorDeclaration, SimpleCase) {
- EXPECT_TRUE(matches("class Foo { Foo(int i); };",
- cxxConstructorDecl(ofClass(hasName("Foo")))));
- EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
- cxxConstructorDecl(ofClass(hasName("Bar")))));
-}
-
-TEST(ConstructorDeclaration, IsImplicit) {
- // This one doesn't match because the constructor is not added by the
- // compiler (it is not needed).
- EXPECT_TRUE(notMatches("class Foo { };",
- cxxConstructorDecl(isImplicit())));
- // The compiler added the implicit default constructor.
- EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
- cxxConstructorDecl(isImplicit())));
- EXPECT_TRUE(matches("class Foo { Foo(){} };",
- cxxConstructorDecl(unless(isImplicit()))));
- // The compiler added an implicit assignment operator.
- EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
- cxxMethodDecl(isImplicit(), hasName("operator="))));
-}
-
-TEST(ConstructorDeclaration, IsExplicit) {
- EXPECT_TRUE(matches("struct S { explicit S(int); };",
- cxxConstructorDecl(isExplicit())));
- EXPECT_TRUE(notMatches("struct S { S(int); };",
- cxxConstructorDecl(isExplicit())));
-}
-
-TEST(ConstructorDeclaration, Kinds) {
- EXPECT_TRUE(matches("struct S { S(); };",
- cxxConstructorDecl(isDefaultConstructor())));
- EXPECT_TRUE(notMatches("struct S { S(); };",
- cxxConstructorDecl(isCopyConstructor())));
- EXPECT_TRUE(notMatches("struct S { S(); };",
- cxxConstructorDecl(isMoveConstructor())));
-
- EXPECT_TRUE(notMatches("struct S { S(const S&); };",
- cxxConstructorDecl(isDefaultConstructor())));
- EXPECT_TRUE(matches("struct S { S(const S&); };",
- cxxConstructorDecl(isCopyConstructor())));
- EXPECT_TRUE(notMatches("struct S { S(const S&); };",
- cxxConstructorDecl(isMoveConstructor())));
-
- EXPECT_TRUE(notMatches("struct S { S(S&&); };",
- cxxConstructorDecl(isDefaultConstructor())));
- EXPECT_TRUE(notMatches("struct S { S(S&&); };",
- cxxConstructorDecl(isCopyConstructor())));
- EXPECT_TRUE(matches("struct S { S(S&&); };",
- cxxConstructorDecl(isMoveConstructor())));
-}
-
-TEST(DestructorDeclaration, MatchesVirtualDestructor) {
- EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
- cxxDestructorDecl(ofClass(hasName("Foo")))));
-}
-
-TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
- EXPECT_TRUE(notMatches("class Foo {};",
- cxxDestructorDecl(ofClass(hasName("Foo")))));
-}
-
-TEST(HasAnyConstructorInitializer, SimpleCase) {
- EXPECT_TRUE(
- notMatches("class Foo { Foo() { } };",
- cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
- EXPECT_TRUE(
- matches("class Foo {"
- " Foo() : foo_() { }"
- " int foo_;"
- "};",
- cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
-}
-
-TEST(HasAnyConstructorInitializer, ForField) {
- static const char Code[] =
- "class Baz { };"
- "class Foo {"
- " Foo() : foo_() { }"
- " Baz foo_;"
- " Baz bar_;"
- "};";
- EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
- forField(hasType(recordDecl(hasName("Baz"))))))));
- EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
- forField(hasName("foo_"))))));
- EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
- forField(hasType(recordDecl(hasName("Bar"))))))));
-}
-
-TEST(HasAnyConstructorInitializer, WithInitializer) {
- static const char Code[] =
- "class Foo {"
- " Foo() : foo_(0) { }"
- " int foo_;"
- "};";
- EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
- withInitializer(integerLiteral(equals(0)))))));
- EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
- withInitializer(integerLiteral(equals(1)))))));
-}
-
-TEST(HasAnyConstructorInitializer, IsWritten) {
- static const char Code[] =
- "struct Bar { Bar(){} };"
- "class Foo {"
- " Foo() : foo_() { }"
- " Bar foo_;"
- " Bar bar_;"
- "};";
- EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
- allOf(forField(hasName("foo_")), isWritten())))));
- EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
- allOf(forField(hasName("bar_")), isWritten())))));
- EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
- allOf(forField(hasName("bar_")), unless(isWritten()))))));
-}
-
-TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
- static const char Code[] =
- "struct B {};"
- "struct D : B {"
- " int I;"
- " D(int i) : I(i) {}"
- "};"
- "struct E : B {"
- " E() : B() {}"
- "};";
- EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
- hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
- hasName("E")))));
- EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
- hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
- hasName("D")))));
- EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
- hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
- hasName("D")))));
- EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
- hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
- hasName("E")))));
-}
-
-TEST(Matcher, NewExpression) {
- StatementMatcher New = cxxNewExpr();
-
- EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
- EXPECT_TRUE(
- matches("class X { public: X(); }; void x() { new X(); }", New));
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { new X(0); }", New));
- EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
-}
-
-TEST(Matcher, NewExpressionArgument) {
- StatementMatcher New = cxxConstructExpr(
- hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
-
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { int y; new X(y); }",
- New));
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { int y; new X(y); }",
- New));
- EXPECT_TRUE(
- notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
- New));
-
- StatementMatcher WrongIndex = cxxConstructExpr(
- hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
- EXPECT_TRUE(
- notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
- WrongIndex));
-}
-
-TEST(Matcher, NewExpressionArgumentCount) {
- StatementMatcher New = cxxConstructExpr(argumentCountIs(1));
-
- EXPECT_TRUE(
- matches("class X { public: X(int); }; void x() { new X(0); }", New));
- EXPECT_TRUE(
- notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
- New));
-}
-
-TEST(Matcher, DeleteExpression) {
- EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
- cxxDeleteExpr()));
-}
-
-TEST(Matcher, DefaultArgument) {
- StatementMatcher Arg = cxxDefaultArgExpr();
-
- EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
- EXPECT_TRUE(
- matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
- EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
-}
-
-TEST(Matcher, StringLiterals) {
- StatementMatcher Literal = stringLiteral();
- EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
- // wide string
- EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
- // with escaped characters
- EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
- // no matching -- though the data type is the same, there is no string literal
- EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
-}
-
-TEST(Matcher, CharacterLiterals) {
- StatementMatcher CharLiteral = characterLiteral();
- EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
- // wide character
- EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
- // wide character, Hex encoded, NOT MATCHED!
- EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
- EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
-}
-
-TEST(Matcher, IntegerLiterals) {
- StatementMatcher HasIntLiteral = integerLiteral();
- EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
- EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
- EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
- EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
-
- // Non-matching cases (character literals, float and double)
- EXPECT_TRUE(notMatches("int i = L'a';",
- HasIntLiteral)); // this is actually a character
- // literal cast to int
- EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
- EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
- EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
-}
-
-TEST(Matcher, FloatLiterals) {
- StatementMatcher HasFloatLiteral = floatLiteral();
- EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
- EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
- EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
- EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
- EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
- EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
- EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
- EXPECT_TRUE(
- matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
-
- EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
- EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
- EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
- EXPECT_TRUE(
- notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
-}
-
-TEST(Matcher, NullPtrLiteral) {
- EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
-}
-
-TEST(Matcher, GNUNullExpr) {
- EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
-}
-
-TEST(Matcher, AsmStatement) {
- EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
-}
-
-TEST(Matcher, Conditions) {
- StatementMatcher Condition =
- ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
-
- EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
- EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
- EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
- EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
- EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
-}
-
-TEST(IfStmt, ChildTraversalMatchers) {
- EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
- ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
- EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
- ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
- EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
- ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
- EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
- ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
-}
-
-TEST(MatchBinaryOperator, HasOperatorName) {
- StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
-
- EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
- EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
-}
-
-TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
- StatementMatcher OperatorTrueFalse =
- binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
- hasRHS(cxxBoolLiteral(equals(false))));
-
- EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
- EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
- EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
-
- StatementMatcher OperatorIntPointer = arraySubscriptExpr(
- hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
- EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
- EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
-}
-
-TEST(MatchBinaryOperator, HasEitherOperand) {
- StatementMatcher HasOperand =
- binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
-
- EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
- EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
- EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
-}
-
-TEST(Matcher, BinaryOperatorTypes) {
- // Integration test that verifies the AST provides all binary operators in
- // a way we expect.
- // FIXME: Operator ','
- EXPECT_TRUE(
- matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
- EXPECT_TRUE(
- matches("bool b; bool c = (b = true);",
- binaryOperator(hasOperatorName("="))));
- EXPECT_TRUE(
- matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
- EXPECT_TRUE(
- matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
- EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
- EXPECT_TRUE(
- matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
- EXPECT_TRUE(
- matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
- EXPECT_TRUE(
- matches("int i = 1; int j = (i <<= 2);",
- binaryOperator(hasOperatorName("<<="))));
- EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
- EXPECT_TRUE(
- matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
- EXPECT_TRUE(
- matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
- EXPECT_TRUE(
- matches("int i = 1; int j = (i >>= 2);",
- binaryOperator(hasOperatorName(">>="))));
- EXPECT_TRUE(
- matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
- EXPECT_TRUE(
- matches("int i = 42; int j = (i ^= 42);",
- binaryOperator(hasOperatorName("^="))));
- EXPECT_TRUE(
- matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
- EXPECT_TRUE(
- matches("int i = 42; int j = (i %= 42);",
- binaryOperator(hasOperatorName("%="))));
- EXPECT_TRUE(
- matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
- EXPECT_TRUE(
- matches("bool b = true && false;",
- binaryOperator(hasOperatorName("&&"))));
- EXPECT_TRUE(
- matches("bool b = true; bool c = (b &= false);",
- binaryOperator(hasOperatorName("&="))));
- EXPECT_TRUE(
- matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
- EXPECT_TRUE(
- matches("bool b = true || false;",
- binaryOperator(hasOperatorName("||"))));
- EXPECT_TRUE(
- matches("bool b = true; bool c = (b |= false);",
- binaryOperator(hasOperatorName("|="))));
- EXPECT_TRUE(
- matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
- EXPECT_TRUE(
- matches("int i = 42; int j = (i *= 23);",
- binaryOperator(hasOperatorName("*="))));
- EXPECT_TRUE(
- matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
- EXPECT_TRUE(
- matches("int i = 42; int j = (i /= 23);",
- binaryOperator(hasOperatorName("/="))));
- EXPECT_TRUE(
- matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
- EXPECT_TRUE(
- matches("int i = 42; int j = (i += 23);",
- binaryOperator(hasOperatorName("+="))));
- EXPECT_TRUE(
- matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
- EXPECT_TRUE(
- matches("int i = 42; int j = (i -= 23);",
- binaryOperator(hasOperatorName("-="))));
- EXPECT_TRUE(
- matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
- binaryOperator(hasOperatorName("->*"))));
- EXPECT_TRUE(
- matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
- binaryOperator(hasOperatorName(".*"))));
-
- // Member expressions as operators are not supported in matches.
- EXPECT_TRUE(
- notMatches("struct A { void x(A *a) { a->x(this); } };",
- binaryOperator(hasOperatorName("->"))));
-
- // Initializer assignments are not represented as operator equals.
- EXPECT_TRUE(
- notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
-
- // Array indexing is not represented as operator.
- EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
-
- // Overloaded operators do not match at all.
- EXPECT_TRUE(notMatches(
- "struct A { bool operator&&(const A &a) const { return false; } };"
- "void x() { A a, b; a && b; }",
- binaryOperator()));
-}
-
-TEST(MatchUnaryOperator, HasOperatorName) {
- StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
-
- EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
- EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
-}
-
-TEST(MatchUnaryOperator, HasUnaryOperand) {
- StatementMatcher OperatorOnFalse =
- unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
-
- EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
- EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
-}
-
-TEST(Matcher, UnaryOperatorTypes) {
- // Integration test that verifies the AST provides all unary operators in
- // a way we expect.
- EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
- EXPECT_TRUE(
- matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
- EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
- EXPECT_TRUE(
- matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
- EXPECT_TRUE(
- matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
- EXPECT_TRUE(
- matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
- EXPECT_TRUE(
- matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
- EXPECT_TRUE(
- matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
- EXPECT_TRUE(
- matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
- EXPECT_TRUE(
- matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
-
- // We don't match conversion operators.
- EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
-
- // Function calls are not represented as operator.
- EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
-
- // Overloaded operators do not match at all.
- // FIXME: We probably want to add that.
- EXPECT_TRUE(notMatches(
- "struct A { bool operator!() const { return false; } };"
- "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
-}
-
-TEST(Matcher, ConditionalOperator) {
- StatementMatcher Conditional = conditionalOperator(
- hasCondition(cxxBoolLiteral(equals(true))),
- hasTrueExpression(cxxBoolLiteral(equals(false))));
-
- EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
- EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
- EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
-
- StatementMatcher ConditionalFalse = conditionalOperator(
- hasFalseExpression(cxxBoolLiteral(equals(false))));
-
- EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
- EXPECT_TRUE(
- notMatches("void x() { true ? false : true; }", ConditionalFalse));
-}
-
-TEST(ArraySubscriptMatchers, ArraySubscripts) {
- EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
- arraySubscriptExpr()));
- EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
- arraySubscriptExpr()));
-}
-
-TEST(ArraySubscriptMatchers, ArrayIndex) {
- EXPECT_TRUE(matches(
- "int i[2]; void f() { i[1] = 1; }",
- arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
- EXPECT_TRUE(matches(
- "int i[2]; void f() { 1[i] = 1; }",
- arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
- EXPECT_TRUE(notMatches(
- "int i[2]; void f() { i[1] = 1; }",
- arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
-}
-
-TEST(ArraySubscriptMatchers, MatchesArrayBase) {
- EXPECT_TRUE(matches(
- "int i[2]; void f() { i[1] = 2; }",
- arraySubscriptExpr(hasBase(implicitCastExpr(
- hasSourceExpression(declRefExpr()))))));
-}
-
-TEST(Matcher, HasNameSupportsNamespaces) {
- EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("a::b::C"))));
- EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("::a::b::C"))));
- EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("b::C"))));
- EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("C"))));
- EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("c::b::C"))));
- EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("a::c::C"))));
- EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("a::b::A"))));
- EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("::C"))));
- EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("::b::C"))));
- EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("z::a::b::C"))));
- EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
- recordDecl(hasName("a+b::C"))));
- EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
- recordDecl(hasName("C"))));
-}
-
-TEST(Matcher, HasNameSupportsOuterClasses) {
- EXPECT_TRUE(
- matches("class A { class B { class C; }; };",
- recordDecl(hasName("A::B::C"))));
- EXPECT_TRUE(
- matches("class A { class B { class C; }; };",
- recordDecl(hasName("::A::B::C"))));
- EXPECT_TRUE(
- matches("class A { class B { class C; }; };",
- recordDecl(hasName("B::C"))));
- EXPECT_TRUE(
- matches("class A { class B { class C; }; };",
- recordDecl(hasName("C"))));
- EXPECT_TRUE(
- notMatches("class A { class B { class C; }; };",
- recordDecl(hasName("c::B::C"))));
- EXPECT_TRUE(
- notMatches("class A { class B { class C; }; };",
- recordDecl(hasName("A::c::C"))));
- EXPECT_TRUE(
- notMatches("class A { class B { class C; }; };",
- recordDecl(hasName("A::B::A"))));
- EXPECT_TRUE(
- notMatches("class A { class B { class C; }; };",
- recordDecl(hasName("::C"))));
- EXPECT_TRUE(
- notMatches("class A { class B { class C; }; };",
- recordDecl(hasName("::B::C"))));
- EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
- recordDecl(hasName("z::A::B::C"))));
- EXPECT_TRUE(
- notMatches("class A { class B { class C; }; };",
- recordDecl(hasName("A+B::C"))));
-}
-
-TEST(Matcher, IsDefinition) {
- DeclarationMatcher DefinitionOfClassA =
- recordDecl(hasName("A"), isDefinition());
- EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
- EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
-
- DeclarationMatcher DefinitionOfVariableA =
- varDecl(hasName("a"), isDefinition());
- EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
- EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
-
- DeclarationMatcher DefinitionOfMethodA =
- cxxMethodDecl(hasName("a"), isDefinition());
- EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
- EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
-}
-
-TEST(Matcher, OfClass) {
- StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
- ofClass(hasName("X")))));
-
- EXPECT_TRUE(
- matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
- EXPECT_TRUE(
- matches("class X { public: X(); }; void x(int) { X x = X(); }",
- Constructor));
- EXPECT_TRUE(
- notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
- Constructor));
-}
-
-TEST(Matcher, VisitsTemplateInstantiations) {
- EXPECT_TRUE(matches(
- "class A { public: void x(); };"
- "template <typename T> class B { public: void y() { T t; t.x(); } };"
- "void f() { B<A> b; b.y(); }",
- callExpr(callee(cxxMethodDecl(hasName("x"))))));
-
- EXPECT_TRUE(matches(
- "class A { public: void x(); };"
- "class C {"
- " public:"
- " template <typename T> class B { public: void y() { T t; t.x(); } };"
- "};"
- "void f() {"
- " C::B<A> b; b.y();"
- "}",
- recordDecl(hasName("C"), hasDescendant(callExpr(
- callee(cxxMethodDecl(hasName("x"))))))));
-}
-
-TEST(Matcher, HandlesNullQualTypes) {
- // FIXME: Add a Type matcher so we can replace uses of this
- // variable with Type(True())
- const TypeMatcher AnyType = anything();
-
- // We don't really care whether this matcher succeeds; we're testing that
- // it completes without crashing.
- EXPECT_TRUE(matches(
- "struct A { };"
- "template <typename T>"
- "void f(T t) {"
- " T local_t(t /* this becomes a null QualType in the AST */);"
- "}"
- "void g() {"
- " f(0);"
- "}",
- expr(hasType(TypeMatcher(
- anyOf(
- TypeMatcher(hasDeclaration(anything())),
- pointsTo(AnyType),
- references(AnyType)
- // Other QualType matchers should go here.
- ))))));
-}
-
-// For testing AST_MATCHER_P().
-AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
- // Make sure all special variables are used: node, match_finder,
- // bound_nodes_builder, and the parameter named 'AMatcher'.
- return AMatcher.matches(Node, Finder, Builder);
-}
-
-TEST(AstMatcherPMacro, Works) {
- DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
-
- EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
- HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
-
- EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
- HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
-
- EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
- HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
-}
-
-AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
- AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
- internal::Matcher<Decl>, AMatcher) {
- return Finder->matchesChildOf(
- Node, AMatcher, Builder,
- ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
- ASTMatchFinder::BK_First);
-}
-
-TEST(AstPolymorphicMatcherPMacro, Works) {
- DeclarationMatcher HasClassB =
- polymorphicHas(recordDecl(hasName("B")).bind("b"));
-
- EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
- HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
-
- EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
- HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
-
- EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
- HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
-
- StatementMatcher StatementHasClassB =
- polymorphicHas(recordDecl(hasName("B")));
-
- EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
-}
-
-TEST(For, FindsForLoops) {
- EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
- EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
- EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
- "void f() { for (auto &a : as); }",
- forStmt()));
-}
-
-TEST(For, ForLoopInternals) {
- EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
- forStmt(hasCondition(anything()))));
- EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
- forStmt(hasLoopInit(anything()))));
-}
-
-TEST(For, ForRangeLoopInternals) {
- EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
- cxxForRangeStmt(hasLoopVariable(anything()))));
- EXPECT_TRUE(matches(
- "void f(){ int a[] {1, 2}; for (int i : a); }",
- cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
-}
-
-TEST(For, NegativeForLoopInternals) {
- EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
- forStmt(hasCondition(expr()))));
- EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
- forStmt(hasLoopInit(anything()))));
-}
-
-TEST(For, ReportsNoFalsePositives) {
- EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
- EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
-}
-
-TEST(CompoundStatement, HandlesSimpleCases) {
- EXPECT_TRUE(notMatches("void f();", compoundStmt()));
- EXPECT_TRUE(matches("void f() {}", compoundStmt()));
- EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
-}
-
-TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
- // It's not a compound statement just because there's "{}" in the source
- // text. This is an AST search, not grep.
- EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
- compoundStmt()));
- EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
- compoundStmt()));
-}
-
-TEST(HasBody, FindsBodyOfForWhileDoLoops) {
- EXPECT_TRUE(matches("void f() { for(;;) {} }",
- forStmt(hasBody(compoundStmt()))));
- EXPECT_TRUE(notMatches("void f() { for(;;); }",
- forStmt(hasBody(compoundStmt()))));
- EXPECT_TRUE(matches("void f() { while(true) {} }",
- whileStmt(hasBody(compoundStmt()))));
- EXPECT_TRUE(matches("void f() { do {} while(true); }",
- doStmt(hasBody(compoundStmt()))));
- EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
- cxxForRangeStmt(hasBody(compoundStmt()))));
-}
-
-TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
- // The simplest case: every compound statement is in a function
- // definition, and the function body itself must be a compound
- // statement.
- EXPECT_TRUE(matches("void f() { for (;;); }",
- compoundStmt(hasAnySubstatement(forStmt()))));
-}
-
-TEST(HasAnySubstatement, IsNotRecursive) {
- // It's really "has any immediate substatement".
- EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
- compoundStmt(hasAnySubstatement(forStmt()))));
-}
-
-TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
- EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
- compoundStmt(hasAnySubstatement(forStmt()))));
-}
-
-TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
- EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
- compoundStmt(hasAnySubstatement(forStmt()))));
-}
-
-TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
- EXPECT_TRUE(matches("void f() { }",
- compoundStmt(statementCountIs(0))));
- EXPECT_TRUE(notMatches("void f() {}",
- compoundStmt(statementCountIs(1))));
-}
-
-TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
- EXPECT_TRUE(matches("void f() { 1; }",
- compoundStmt(statementCountIs(1))));
- EXPECT_TRUE(notMatches("void f() { 1; }",
- compoundStmt(statementCountIs(0))));
- EXPECT_TRUE(notMatches("void f() { 1; }",
- compoundStmt(statementCountIs(2))));
-}
-
-TEST(StatementCountIs, WorksWithMultipleStatements) {
- EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
- compoundStmt(statementCountIs(3))));
-}
-
-TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
- EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
- compoundStmt(statementCountIs(1))));
- EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
- compoundStmt(statementCountIs(2))));
- EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
- compoundStmt(statementCountIs(3))));
- EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
- compoundStmt(statementCountIs(4))));
-}
-
-TEST(Member, WorksInSimplestCase) {
- EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
- memberExpr(member(hasName("first")))));
-}
-
-TEST(Member, DoesNotMatchTheBaseExpression) {
- // Don't pick out the wrong part of the member expression, this should
- // be checking the member (name) only.
- EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
- memberExpr(member(hasName("first")))));
-}
-
-TEST(Member, MatchesInMemberFunctionCall) {
- EXPECT_TRUE(matches("void f() {"
- " struct { void first() {}; } s;"
- " s.first();"
- "};",
- memberExpr(member(hasName("first")))));
-}
-
-TEST(Member, MatchesMember) {
- EXPECT_TRUE(matches(
- "struct A { int i; }; void f() { A a; a.i = 2; }",
- memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
- EXPECT_TRUE(notMatches(
- "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
- memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
-}
-
-TEST(Member, UnderstandsAccess) {
- EXPECT_TRUE(matches(
- "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
- EXPECT_TRUE(notMatches(
- "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
- EXPECT_TRUE(notMatches(
- "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
-
- EXPECT_TRUE(notMatches(
- "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
- EXPECT_TRUE(notMatches(
- "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
- EXPECT_TRUE(matches(
- "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
-
- EXPECT_TRUE(notMatches(
- "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
- EXPECT_TRUE(matches("class A { protected: int i; };",
- fieldDecl(isProtected(), hasName("i"))));
- EXPECT_TRUE(notMatches(
- "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
-
- // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
- EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
- EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
- EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
-}
-
-TEST(Member, MatchesMemberAllocationFunction) {
- // Fails in C++11 mode
- EXPECT_TRUE(matchesConditionally(
- "namespace std { typedef typeof(sizeof(int)) size_t; }"
- "class X { void *operator new(std::size_t); };",
- cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
-
- EXPECT_TRUE(matches("class X { void operator delete(void*); };",
- cxxMethodDecl(ofClass(hasName("X")))));
-
- // Fails in C++11 mode
- EXPECT_TRUE(matchesConditionally(
- "namespace std { typedef typeof(sizeof(int)) size_t; }"
- "class X { void operator delete[](void*, std::size_t); };",
- cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
-}
-
-TEST(HasObjectExpression, DoesNotMatchMember) {
- EXPECT_TRUE(notMatches(
- "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
- memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
-}
-
-TEST(HasObjectExpression, MatchesBaseOfVariable) {
- EXPECT_TRUE(matches(
- "struct X { int m; }; void f(X x) { x.m; }",
- memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
- EXPECT_TRUE(matches(
- "struct X { int m; }; void f(X* x) { x->m; }",
- memberExpr(hasObjectExpression(
- hasType(pointsTo(recordDecl(hasName("X"))))))));
-}
-
-TEST(HasObjectExpression,
- MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
- EXPECT_TRUE(matches(
- "class X {}; struct S { X m; void f() { this->m; } };",
- memberExpr(hasObjectExpression(
- hasType(pointsTo(recordDecl(hasName("S"))))))));
- EXPECT_TRUE(matches(
- "class X {}; struct S { X m; void f() { m; } };",
- memberExpr(hasObjectExpression(
- hasType(pointsTo(recordDecl(hasName("S"))))))));
-}
-
-TEST(Field, DoesNotMatchNonFieldMembers) {
- EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
- EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
- EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
- EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
-}
-
-TEST(Field, MatchesField) {
- EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
-}
-
-TEST(IsVolatileQualified, QualifiersMatch) {
- EXPECT_TRUE(matches("volatile int i = 42;",
- varDecl(hasType(isVolatileQualified()))));
- EXPECT_TRUE(notMatches("volatile int *i;",
- varDecl(hasType(isVolatileQualified()))));
- EXPECT_TRUE(matches("typedef volatile int v_int; v_int i = 42;",
- varDecl(hasType(isVolatileQualified()))));
-}
-
-TEST(IsConstQualified, MatchesConstInt) {
- EXPECT_TRUE(matches("const int i = 42;",
- varDecl(hasType(isConstQualified()))));
-}
-
-TEST(IsConstQualified, MatchesConstPointer) {
- EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
- varDecl(hasType(isConstQualified()))));
-}
-
-TEST(IsConstQualified, MatchesThroughTypedef) {
- EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
- varDecl(hasType(isConstQualified()))));
- EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
- varDecl(hasType(isConstQualified()))));
-}
-
-TEST(IsConstQualified, DoesNotMatchInappropriately) {
- EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
- varDecl(hasType(isConstQualified()))));
- EXPECT_TRUE(notMatches("int const* p;",
- varDecl(hasType(isConstQualified()))));
-}
-
-TEST(CastExpression, MatchesExplicitCasts) {
- EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
- EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
- EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
- EXPECT_TRUE(matches("char c = char(0);", castExpr()));
-}
-TEST(CastExpression, MatchesImplicitCasts) {
- // This test creates an implicit cast from int to char.
- EXPECT_TRUE(matches("char c = 0;", castExpr()));
- // This test creates an implicit cast from lvalue to rvalue.
- EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
-}
-
-TEST(CastExpression, DoesNotMatchNonCasts) {
- EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
- EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
- EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
- EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
-}
-
-TEST(ReinterpretCast, MatchesSimpleCase) {
- EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
- cxxReinterpretCastExpr()));
-}
-
-TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
- EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxReinterpretCastExpr()));
- EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
- cxxReinterpretCastExpr()));
- EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
- cxxReinterpretCastExpr()));
- EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
- "B b;"
- "D* p = dynamic_cast<D*>(&b);",
- cxxReinterpretCastExpr()));
-}
-
-TEST(FunctionalCast, MatchesSimpleCase) {
- std::string foo_class = "class Foo { public: Foo(const char*); };";
- EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
- cxxFunctionalCastExpr()));
-}
-
-TEST(FunctionalCast, DoesNotMatchOtherCasts) {
- std::string FooClass = "class Foo { public: Foo(const char*); };";
- EXPECT_TRUE(
- notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
- cxxFunctionalCastExpr()));
- EXPECT_TRUE(
- notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
- cxxFunctionalCastExpr()));
-}
-
-TEST(DynamicCast, MatchesSimpleCase) {
- EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
- "B b;"
- "D* p = dynamic_cast<D*>(&b);",
- cxxDynamicCastExpr()));
-}
-
-TEST(StaticCast, MatchesSimpleCase) {
- EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
- cxxStaticCastExpr()));
-}
-
-TEST(StaticCast, DoesNotMatchOtherCasts) {
- EXPECT_TRUE(notMatches("char* p = (char*)(&p);", cxxStaticCastExpr()));
- EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
- cxxStaticCastExpr()));
- EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
- cxxStaticCastExpr()));
- EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
- "B b;"
- "D* p = dynamic_cast<D*>(&b);",
- cxxStaticCastExpr()));
-}
-
-TEST(CStyleCast, MatchesSimpleCase) {
- EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
-}
-
-TEST(CStyleCast, DoesNotMatchOtherCasts) {
- EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
- "char q, *r = const_cast<char*>(&q);"
- "void* s = reinterpret_cast<char*>(&s);"
- "struct B { virtual ~B() {} }; struct D : B {};"
- "B b;"
- "D* t = dynamic_cast<D*>(&b);",
- cStyleCastExpr()));
-}
-
-TEST(HasDestinationType, MatchesSimpleCase) {
- EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
- cxxStaticCastExpr(hasDestinationType(
- pointsTo(TypeMatcher(anything()))))));
-}
-
-TEST(HasImplicitDestinationType, MatchesSimpleCase) {
- // This test creates an implicit const cast.
- EXPECT_TRUE(matches("int x; const int i = x;",
- implicitCastExpr(
- hasImplicitDestinationType(isInteger()))));
- // This test creates an implicit array-to-pointer cast.
- EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
- implicitCastExpr(hasImplicitDestinationType(
- pointsTo(TypeMatcher(anything()))))));
-}
-
-TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
- // This test creates an implicit cast from int to char.
- EXPECT_TRUE(notMatches("char c = 0;",
- implicitCastExpr(hasImplicitDestinationType(
- unless(anything())))));
- // This test creates an implicit array-to-pointer cast.
- EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
- implicitCastExpr(hasImplicitDestinationType(
- unless(anything())))));
-}
-
-TEST(ImplicitCast, MatchesSimpleCase) {
- // This test creates an implicit const cast.
- EXPECT_TRUE(matches("int x = 0; const int y = x;",
- varDecl(hasInitializer(implicitCastExpr()))));
- // This test creates an implicit cast from int to char.
- EXPECT_TRUE(matches("char c = 0;",
- varDecl(hasInitializer(implicitCastExpr()))));
- // This test creates an implicit array-to-pointer cast.
- EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
- varDecl(hasInitializer(implicitCastExpr()))));
-}
-
-TEST(ImplicitCast, DoesNotMatchIncorrectly) {
- // This test verifies that implicitCastExpr() matches exactly when implicit casts
- // are present, and that it ignores explicit and paren casts.
-
- // These two test cases have no casts.
- EXPECT_TRUE(notMatches("int x = 0;",
- varDecl(hasInitializer(implicitCastExpr()))));
- EXPECT_TRUE(notMatches("int x = 0, &y = x;",
- varDecl(hasInitializer(implicitCastExpr()))));
-
- EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
- varDecl(hasInitializer(implicitCastExpr()))));
- EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
- varDecl(hasInitializer(implicitCastExpr()))));
-
- EXPECT_TRUE(notMatches("int x = (0);",
- varDecl(hasInitializer(implicitCastExpr()))));
-}
-
-TEST(IgnoringImpCasts, MatchesImpCasts) {
- // This test checks that ignoringImpCasts matches when implicit casts are
- // present and its inner matcher alone does not match.
- // Note that this test creates an implicit const cast.
- EXPECT_TRUE(matches("int x = 0; const int y = x;",
- varDecl(hasInitializer(ignoringImpCasts(
- declRefExpr(to(varDecl(hasName("x")))))))));
- // This test creates an implict cast from int to char.
- EXPECT_TRUE(matches("char x = 0;",
- varDecl(hasInitializer(ignoringImpCasts(
- integerLiteral(equals(0)))))));
-}
-
-TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
- // These tests verify that ignoringImpCasts does not match if the inner
- // matcher does not match.
- // Note that the first test creates an implicit const cast.
- EXPECT_TRUE(notMatches("int x; const int y = x;",
- varDecl(hasInitializer(ignoringImpCasts(
- unless(anything()))))));
- EXPECT_TRUE(notMatches("int x; int y = x;",
- varDecl(hasInitializer(ignoringImpCasts(
- unless(anything()))))));
-
- // These tests verify that ignoringImplictCasts does not look through explicit
- // casts or parentheses.
- EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
- varDecl(hasInitializer(ignoringImpCasts(
- integerLiteral())))));
- EXPECT_TRUE(notMatches("int i = (0);",
- varDecl(hasInitializer(ignoringImpCasts(
- integerLiteral())))));
- EXPECT_TRUE(notMatches("float i = (float)0;",
- varDecl(hasInitializer(ignoringImpCasts(
- integerLiteral())))));
- EXPECT_TRUE(notMatches("float i = float(0);",
- varDecl(hasInitializer(ignoringImpCasts(
- integerLiteral())))));
-}
-
-TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
- // This test verifies that expressions that do not have implicit casts
- // still match the inner matcher.
- EXPECT_TRUE(matches("int x = 0; int &y = x;",
- varDecl(hasInitializer(ignoringImpCasts(
- declRefExpr(to(varDecl(hasName("x")))))))));
-}
-
-TEST(IgnoringParenCasts, MatchesParenCasts) {
- // This test checks that ignoringParenCasts matches when parentheses and/or
- // casts are present and its inner matcher alone does not match.
- EXPECT_TRUE(matches("int x = (0);",
- varDecl(hasInitializer(ignoringParenCasts(
- integerLiteral(equals(0)))))));
- EXPECT_TRUE(matches("int x = (((((0)))));",
- varDecl(hasInitializer(ignoringParenCasts(
- integerLiteral(equals(0)))))));
-
- // This test creates an implict cast from int to char in addition to the
- // parentheses.
- EXPECT_TRUE(matches("char x = (0);",
- varDecl(hasInitializer(ignoringParenCasts(
- integerLiteral(equals(0)))))));
-
- EXPECT_TRUE(matches("char x = (char)0;",
- varDecl(hasInitializer(ignoringParenCasts(
- integerLiteral(equals(0)))))));
- EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
- varDecl(hasInitializer(ignoringParenCasts(
- integerLiteral(equals(0)))))));
-}
-
-TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
- // This test verifies that expressions that do not have any casts still match.
- EXPECT_TRUE(matches("int x = 0;",
- varDecl(hasInitializer(ignoringParenCasts(
- integerLiteral(equals(0)))))));
-}
-
-TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
- // These tests verify that ignoringImpCasts does not match if the inner
- // matcher does not match.
- EXPECT_TRUE(notMatches("int x = ((0));",
- varDecl(hasInitializer(ignoringParenCasts(
- unless(anything()))))));
-
- // This test creates an implicit cast from int to char in addition to the
- // parentheses.
- EXPECT_TRUE(notMatches("char x = ((0));",
- varDecl(hasInitializer(ignoringParenCasts(
- unless(anything()))))));
-
- EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
- varDecl(hasInitializer(ignoringParenCasts(
- unless(anything()))))));
-}
-
-TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
- // This test checks that ignoringParenAndImpCasts matches when
- // parentheses and/or implicit casts are present and its inner matcher alone
- // does not match.
- // Note that this test creates an implicit const cast.
- EXPECT_TRUE(matches("int x = 0; const int y = x;",
- varDecl(hasInitializer(ignoringParenImpCasts(
- declRefExpr(to(varDecl(hasName("x")))))))));
- // This test creates an implicit cast from int to char.
- EXPECT_TRUE(matches("const char x = (0);",
- varDecl(hasInitializer(ignoringParenImpCasts(
- integerLiteral(equals(0)))))));
-}
-
-TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
- // This test verifies that expressions that do not have parentheses or
- // implicit casts still match.
- EXPECT_TRUE(matches("int x = 0; int &y = x;",
- varDecl(hasInitializer(ignoringParenImpCasts(
- declRefExpr(to(varDecl(hasName("x")))))))));
- EXPECT_TRUE(matches("int x = 0;",
- varDecl(hasInitializer(ignoringParenImpCasts(
- integerLiteral(equals(0)))))));
-}
-
-TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
- // These tests verify that ignoringParenImpCasts does not match if
- // the inner matcher does not match.
- // This test creates an implicit cast.
- EXPECT_TRUE(notMatches("char c = ((3));",
- varDecl(hasInitializer(ignoringParenImpCasts(
- unless(anything()))))));
- // These tests verify that ignoringParenAndImplictCasts does not look
- // through explicit casts.
- EXPECT_TRUE(notMatches("float y = (float(0));",
- varDecl(hasInitializer(ignoringParenImpCasts(
- integerLiteral())))));
- EXPECT_TRUE(notMatches("float y = (float)0;",
- varDecl(hasInitializer(ignoringParenImpCasts(
- integerLiteral())))));
- EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
- varDecl(hasInitializer(ignoringParenImpCasts(
- integerLiteral())))));
-}
-
-TEST(HasSourceExpression, MatchesImplicitCasts) {
- EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
- "void r() {string a_string; URL url = a_string; }",
- implicitCastExpr(
- hasSourceExpression(cxxConstructExpr()))));
-}
-
-TEST(HasSourceExpression, MatchesExplicitCasts) {
- EXPECT_TRUE(matches("float x = static_cast<float>(42);",
- explicitCastExpr(
- hasSourceExpression(hasDescendant(
- expr(integerLiteral()))))));
-}
-
-TEST(Statement, DoesNotMatchDeclarations) {
- EXPECT_TRUE(notMatches("class X {};", stmt()));
-}
-
-TEST(Statement, MatchesCompoundStatments) {
- EXPECT_TRUE(matches("void x() {}", stmt()));
-}
-
-TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
- EXPECT_TRUE(notMatches("void x() {}", declStmt()));
-}
-
-TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
- EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
-}
-
-TEST(ExprWithCleanups, MatchesExprWithCleanups) {
- EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
- "const Foo f = Foo();",
- varDecl(hasInitializer(exprWithCleanups()))));
- EXPECT_FALSE(matches("struct Foo { };"
- "const Foo f = Foo();",
- varDecl(hasInitializer(exprWithCleanups()))));
-}
-
-TEST(InitListExpression, MatchesInitListExpression) {
- EXPECT_TRUE(matches("int a[] = { 1, 2 };",
- initListExpr(hasType(asString("int [2]")))));
- EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
- initListExpr(hasType(recordDecl(hasName("B"))))));
- EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
- "void f();"
- "S s[1] = { &f };",
- declRefExpr(to(functionDecl(hasName("f"))))));
- EXPECT_TRUE(
- matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
-}
-
-TEST(UsingDeclaration, MatchesUsingDeclarations) {
- EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
- usingDecl()));
-}
-
-TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
- EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
- usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
-}
-
-TEST(UsingDeclaration, MatchesSpecificTarget) {
- EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
- usingDecl(hasAnyUsingShadowDecl(
- hasTargetDecl(functionDecl())))));
- EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
- usingDecl(hasAnyUsingShadowDecl(
- hasTargetDecl(functionDecl())))));
-}
-
-TEST(UsingDeclaration, ThroughUsingDeclaration) {
- EXPECT_TRUE(matches(
- "namespace a { void f(); } using a::f; void g() { f(); }",
- declRefExpr(throughUsingDecl(anything()))));
- EXPECT_TRUE(notMatches(
- "namespace a { void f(); } using a::f; void g() { a::f(); }",
- declRefExpr(throughUsingDecl(anything()))));
-}
-
-TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
- EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
- usingDirectiveDecl()));
- EXPECT_FALSE(
- matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
-}
-
-TEST(SingleDecl, IsSingleDecl) {
- StatementMatcher SingleDeclStmt =
- declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
- EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
- EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
- EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
- SingleDeclStmt));
-}
-
-TEST(DeclStmt, ContainsDeclaration) {
- DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
-
- EXPECT_TRUE(matches("void f() {int a = 4;}",
- declStmt(containsDeclaration(0, MatchesInit))));
- EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
- declStmt(containsDeclaration(0, MatchesInit),
- containsDeclaration(1, MatchesInit))));
- unsigned WrongIndex = 42;
- EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
- declStmt(containsDeclaration(WrongIndex,
- MatchesInit))));
-}
-
-TEST(DeclCount, DeclCountIsCorrect) {
- EXPECT_TRUE(matches("void f() {int i,j;}",
- declStmt(declCountIs(2))));
- EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
- declStmt(declCountIs(3))));
- EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
- declStmt(declCountIs(3))));
-}
-
-TEST(While, MatchesWhileLoops) {
- EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
- EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
- EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
-}
-
-TEST(Do, MatchesDoLoops) {
- EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
- EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
-}
-
-TEST(Do, DoesNotMatchWhileLoops) {
- EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
-}
-
-TEST(SwitchCase, MatchesCase) {
- EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
- EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
- EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
- EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
-}
-
-TEST(SwitchCase, MatchesSwitch) {
- EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
- EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
- EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
- EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
-}
-
-TEST(SwitchCase, MatchesEachCase) {
- EXPECT_TRUE(notMatches("void x() { switch(42); }",
- switchStmt(forEachSwitchCase(caseStmt()))));
- EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
- switchStmt(forEachSwitchCase(caseStmt()))));
- EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
- switchStmt(forEachSwitchCase(caseStmt()))));
- EXPECT_TRUE(notMatches(
- "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
- ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
- EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
- switchStmt(forEachSwitchCase(
- caseStmt(hasCaseConstant(integerLiteral()))))));
- EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
- switchStmt(forEachSwitchCase(
- caseStmt(hasCaseConstant(integerLiteral()))))));
- EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
- switchStmt(forEachSwitchCase(
- caseStmt(hasCaseConstant(integerLiteral()))))));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
- switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
- new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
-}
-
-TEST(ForEachConstructorInitializer, MatchesInitializers) {
- EXPECT_TRUE(matches(
- "struct X { X() : i(42), j(42) {} int i, j; };",
- cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer()))));
-}
-
-TEST(ExceptionHandling, SimpleCases) {
- EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxCatchStmt()));
- EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", cxxTryStmt()));
- EXPECT_TRUE(
- notMatches("void foo() try { } catch(int X) { }", cxxThrowExpr()));
- EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
- cxxThrowExpr()));
- EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
- cxxThrowExpr()));
- EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
- cxxCatchStmt(isCatchAll())));
- EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
- cxxCatchStmt(isCatchAll())));
- EXPECT_TRUE(matches("void foo() try {} catch(int X) { }",
- varDecl(isExceptionVariable())));
- EXPECT_TRUE(notMatches("void foo() try { int X; } catch (...) { }",
- varDecl(isExceptionVariable())));
-}
-
-TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
- EXPECT_TRUE(notMatches(
- "void x() { if(true) {} }",
- ifStmt(hasConditionVariableStatement(declStmt()))));
- EXPECT_TRUE(notMatches(
- "void x() { int x; if((x = 42)) {} }",
- ifStmt(hasConditionVariableStatement(declStmt()))));
-}
-
-TEST(HasConditionVariableStatement, MatchesConditionVariables) {
- EXPECT_TRUE(matches(
- "void x() { if(int* a = 0) {} }",
- ifStmt(hasConditionVariableStatement(declStmt()))));
-}
-
-TEST(ForEach, BindsOneNode) {
- EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
- recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
- new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
-}
-
-TEST(ForEach, BindsMultipleNodes) {
- EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
- recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
- new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
-}
-
-TEST(ForEach, BindsRecursiveCombinations) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class C { class D { int x; int y; }; class E { int y; int z; }; };",
- recordDecl(hasName("C"),
- forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
- new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
-}
-
-TEST(ForEachDescendant, BindsOneNode) {
- EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
- recordDecl(hasName("C"),
- forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
- new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
-}
-
-TEST(ForEachDescendant, NestedForEachDescendant) {
- DeclarationMatcher m = recordDecl(
- isDefinition(), decl().bind("x"), hasName("C"));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { class B { class C {}; }; };",
- recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
- new VerifyIdIsBoundTo<Decl>("x", "C")));
-
- // Check that a partial match of 'm' that binds 'x' in the
- // first part of anyOf(m, anything()) will not overwrite the
- // binding created by the earlier binding in the hasDescendant.
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { class B { class C {}; }; };",
- recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
- new VerifyIdIsBoundTo<Decl>("x", "C")));
-}
-
-TEST(ForEachDescendant, BindsMultipleNodes) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class C { class D { int x; int y; }; "
- " class E { class F { int y; int z; }; }; };",
- recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
- new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
-}
-
-TEST(ForEachDescendant, BindsRecursiveCombinations) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class C { class D { "
- " class E { class F { class G { int y; int z; }; }; }; }; };",
- recordDecl(hasName("C"), forEachDescendant(recordDecl(
- forEachDescendant(fieldDecl().bind("f"))))),
- new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
-}
-
-TEST(ForEachDescendant, BindsCombinations) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
- "(true) {} }",
- compoundStmt(forEachDescendant(ifStmt().bind("if")),
- forEachDescendant(whileStmt().bind("while"))),
- new VerifyIdIsBoundTo<IfStmt>("if", 6)));
-}
-
-TEST(Has, DoesNotDeleteBindings) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
-}
-
-TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
- // Those matchers cover all the cases where an inner matcher is called
- // and there is not a 1:1 relationship between the match of the outer
- // matcher and the match of the inner matcher.
- // The pattern to look for is:
- // ... return InnerMatcher.matches(...); ...
- // In which case no special handling is needed.
- //
- // On the other hand, if there are multiple alternative matches
- // (for example forEach*) or matches might be discarded (for example has*)
- // the implementation must make sure that the discarded matches do not
- // affect the bindings.
- // When new such matchers are added, add a test here that:
- // - matches a simple node, and binds it as the first thing in the matcher:
- // recordDecl(decl().bind("x"), hasName("X")))
- // - uses the matcher under test afterwards in a way that not the first
- // alternative is matched; for anyOf, that means the first branch
- // would need to return false; for hasAncestor, it means that not
- // the direct parent matches the inner matcher.
-
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X { int y; };",
- recordDecl(
- recordDecl().bind("x"), hasName("::X"),
- anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
- new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
- anyOf(unless(anything()), anything())),
- new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "template<typename T1, typename T2> class X {}; X<float, int> x;",
- classTemplateSpecializationDecl(
- decl().bind("x"),
- hasAnyTemplateArgument(refersToType(asString("int")))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X { void f(); void g(); };",
- cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X { X() : a(1), b(2) {} double a; int b; };",
- recordDecl(decl().bind("x"),
- has(cxxConstructorDecl(
- hasAnyConstructorInitializer(forField(hasName("b")))))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void x(int, int) { x(0, 42); }",
- callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
- new VerifyIdIsBoundTo<Expr>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void x(int, int y) {}",
- functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void x() { return; if (true) {} }",
- functionDecl(decl().bind("x"),
- has(compoundStmt(hasAnySubstatement(ifStmt())))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "namespace X { void b(int); void b(); }"
- "using X::b;",
- usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
- functionDecl(parameterCountIs(1))))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A{}; class B{}; class C : B, A {};",
- cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A{}; typedef A B; typedef A C; typedef A D;"
- "class E : A {};",
- cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { class B { void f() {} }; };",
- functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "template <typename T> struct A { struct B {"
- " void f() { if(true) {} }"
- "}; };"
- "void t() { A<int>::B b; b.f(); }",
- ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
- new VerifyIdIsBoundTo<Stmt>("x", 2)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A {};",
- recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { A() : s(), i(42) {} const char *s; int i; };",
- cxxConstructorDecl(hasName("::A::A"), decl().bind("x"),
- forEachConstructorInitializer(forField(hasName("i")))),
- new VerifyIdIsBoundTo<Decl>("x", 1)));
-}
-
-TEST(ForEachDescendant, BindsCorrectNodes) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class C { void f(); int i; };",
- recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
- new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class C { void f() {} int i; };",
- recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
- new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
-}
-
-TEST(FindAll, BindsNodeOnMatch) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A {};",
- recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
- new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
-}
-
-TEST(FindAll, BindsDescendantNodeOnMatch) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { int a; int b; };",
- recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
- new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
-}
-
-TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { int a; int b; };",
- recordDecl(hasName("::A"),
- findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
- fieldDecl().bind("v"))))),
- new VerifyIdIsBoundTo<Decl>("v", 3)));
-
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { class B {}; class C {}; };",
- recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
- new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
-}
-
-TEST(EachOf, TriggersForEachMatch) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { int a; int b; };",
- recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
- has(fieldDecl(hasName("b")).bind("v")))),
- new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
-}
-
-TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { int a; int c; };",
- recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
- has(fieldDecl(hasName("b")).bind("v")))),
- new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class A { int c; int b; };",
- recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
- has(fieldDecl(hasName("b")).bind("v")))),
- new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
- EXPECT_TRUE(notMatches(
- "class A { int c; int d; };",
- recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
- has(fieldDecl(hasName("b")).bind("v"))))));
-}
-
-TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
- // Make sure that we can both match the class by name (::X) and by the type
- // the template was instantiated with (via a field).
-
- EXPECT_TRUE(matches(
- "template <typename T> class X {}; class A {}; X<A> x;",
- cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
-
- EXPECT_TRUE(matches(
- "template <typename T> class X { T t; }; class A {}; X<A> x;",
- cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
- fieldDecl(hasType(recordDecl(hasName("A"))))))));
-}
-
-TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
- EXPECT_TRUE(matches(
- "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
- functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
- isTemplateInstantiation())));
-}
-
-TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
- EXPECT_TRUE(matches(
- "template <typename T> class X { T t; }; class A {};"
- "template class X<A>;",
- cxxRecordDecl(isTemplateInstantiation(), hasDescendant(
- fieldDecl(hasType(recordDecl(hasName("A"))))))));
-}
-
-TEST(IsTemplateInstantiation,
- MatchesInstantiationOfPartiallySpecializedClassTemplate) {
- EXPECT_TRUE(matches(
- "template <typename T> class X {};"
- "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
- cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
-}
-
-TEST(IsTemplateInstantiation,
- MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
- EXPECT_TRUE(matches(
- "class A {};"
- "class X {"
- " template <typename U> class Y { U u; };"
- " Y<A> y;"
- "};",
- cxxRecordDecl(hasName("::X::Y"), isTemplateInstantiation())));
-}
-
-TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
- // FIXME: Figure out whether this makes sense. It doesn't affect the
- // normal use case as long as the uppermost instantiation always is marked
- // as template instantiation, but it might be confusing as a predicate.
- EXPECT_TRUE(matches(
- "class A {};"
- "template <typename T> class X {"
- " template <typename U> class Y { U u; };"
- " Y<T> y;"
- "}; X<A> x;",
- cxxRecordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
-}
-
-TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
- EXPECT_TRUE(notMatches(
- "template <typename T> class X {}; class A {};"
- "template <> class X<A> {}; X<A> x;",
- cxxRecordDecl(hasName("::X"), isTemplateInstantiation())));
-}
-
-TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
- EXPECT_TRUE(notMatches(
- "class A {}; class Y { A a; };",
- cxxRecordDecl(isTemplateInstantiation())));
-}
-
-TEST(IsInstantiated, MatchesInstantiation) {
- EXPECT_TRUE(
- matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
- cxxRecordDecl(isInstantiated())));
-}
-
-TEST(IsInstantiated, NotMatchesDefinition) {
- EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
- cxxRecordDecl(isInstantiated())));
-}
-
-TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
- EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
- "class Y { A<int> a; }; Y y;",
- declStmt(isInTemplateInstantiation())));
-}
-
-TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
- EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
- declStmt(isInTemplateInstantiation())));
-}
-
-TEST(IsInstantiated, MatchesFunctionInstantiation) {
- EXPECT_TRUE(
- matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
- functionDecl(isInstantiated())));
-}
-
-TEST(IsInstantiated, NotMatchesFunctionDefinition) {
- EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
- varDecl(isInstantiated())));
-}
-
-TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
- EXPECT_TRUE(
- matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
- declStmt(isInTemplateInstantiation())));
-}
-
-TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
- EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
- declStmt(isInTemplateInstantiation())));
-}
-
-TEST(IsInTemplateInstantiation, Sharing) {
- auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
- // FIXME: Node sharing is an implementation detail, exposing it is ugly
- // and makes the matcher behave in non-obvious ways.
- EXPECT_TRUE(notMatches(
- "int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
- Matcher));
- EXPECT_TRUE(matches(
- "int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
- Matcher));
-}
-
-TEST(IsExplicitTemplateSpecialization,
- DoesNotMatchPrimaryTemplate) {
- EXPECT_TRUE(notMatches(
- "template <typename T> class X {};",
- cxxRecordDecl(isExplicitTemplateSpecialization())));
- EXPECT_TRUE(notMatches(
- "template <typename T> void f(T t);",
- functionDecl(isExplicitTemplateSpecialization())));
-}
-
-TEST(IsExplicitTemplateSpecialization,
- DoesNotMatchExplicitTemplateInstantiations) {
- EXPECT_TRUE(notMatches(
- "template <typename T> class X {};"
- "template class X<int>; extern template class X<long>;",
- cxxRecordDecl(isExplicitTemplateSpecialization())));
- EXPECT_TRUE(notMatches(
- "template <typename T> void f(T t) {}"
- "template void f(int t); extern template void f(long t);",
- functionDecl(isExplicitTemplateSpecialization())));
-}
-
-TEST(IsExplicitTemplateSpecialization,
- DoesNotMatchImplicitTemplateInstantiations) {
- EXPECT_TRUE(notMatches(
- "template <typename T> class X {}; X<int> x;",
- cxxRecordDecl(isExplicitTemplateSpecialization())));
- EXPECT_TRUE(notMatches(
- "template <typename T> void f(T t); void g() { f(10); }",
- functionDecl(isExplicitTemplateSpecialization())));
-}
-
-TEST(IsExplicitTemplateSpecialization,
- MatchesExplicitTemplateSpecializations) {
- EXPECT_TRUE(matches(
- "template <typename T> class X {};"
- "template<> class X<int> {};",
- cxxRecordDecl(isExplicitTemplateSpecialization())));
- EXPECT_TRUE(matches(
- "template <typename T> void f(T t) {}"
- "template<> void f(int t) {}",
- functionDecl(isExplicitTemplateSpecialization())));
-}
-
-TEST(HasAncenstor, MatchesDeclarationAncestors) {
- EXPECT_TRUE(matches(
- "class A { class B { class C {}; }; };",
- recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
-}
-
-TEST(HasAncenstor, FailsIfNoAncestorMatches) {
- EXPECT_TRUE(notMatches(
- "class A { class B { class C {}; }; };",
- recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
-}
-
-TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
- EXPECT_TRUE(matches(
- "class A { class B { void f() { C c; } class C {}; }; };",
- varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
- hasAncestor(recordDecl(hasName("A"))))))));
-}
-
-TEST(HasAncenstor, MatchesStatementAncestors) {
- EXPECT_TRUE(matches(
- "void f() { if (true) { while (false) { 42; } } }",
- integerLiteral(equals(42), hasAncestor(ifStmt()))));
-}
-
-TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
- EXPECT_TRUE(matches(
- "void f() { if (true) { int x = 42; } }",
- integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
-}
-
-TEST(HasAncestor, BindsRecursiveCombinations) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class C { class D { class E { class F { int y; }; }; }; };",
- fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
- new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
-}
-
-TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class C { class D { class E { class F { int y; }; }; }; };",
- fieldDecl(hasAncestor(
- decl(
- hasDescendant(recordDecl(isDefinition(),
- hasAncestor(recordDecl())))
- ).bind("d")
- )),
- new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
-}
-
-TEST(HasAncestor, MatchesClosestAncestor) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "template <typename T> struct C {"
- " void f(int) {"
- " struct I { void g(T) { int x; } } i; i.g(42);"
- " }"
- "};"
- "template struct C<int>;",
- varDecl(hasName("x"),
- hasAncestor(functionDecl(hasParameter(
- 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
- new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
-}
-
-TEST(HasAncestor, MatchesInTemplateInstantiations) {
- EXPECT_TRUE(matches(
- "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
- "A<int>::B::C a;",
- fieldDecl(hasType(asString("int")),
- hasAncestor(recordDecl(hasName("A"))))));
-}
-
-TEST(HasAncestor, MatchesInImplicitCode) {
- EXPECT_TRUE(matches(
- "struct X {}; struct A { A() {} X x; };",
- cxxConstructorDecl(
- hasAnyConstructorInitializer(withInitializer(expr(
- hasAncestor(recordDecl(hasName("A")))))))));
-}
-
-TEST(HasParent, MatchesOnlyParent) {
- EXPECT_TRUE(matches(
- "void f() { if (true) { int x = 42; } }",
- compoundStmt(hasParent(ifStmt()))));
- EXPECT_TRUE(notMatches(
- "void f() { for (;;) { int x = 42; } }",
- compoundStmt(hasParent(ifStmt()))));
- EXPECT_TRUE(notMatches(
- "void f() { if (true) for (;;) { int x = 42; } }",
- compoundStmt(hasParent(ifStmt()))));
-}
-
-TEST(HasAncestor, MatchesAllAncestors) {
- EXPECT_TRUE(matches(
- "template <typename T> struct C { static void f() { 42; } };"
- "void t() { C<int>::f(); }",
- integerLiteral(
- equals(42),
- allOf(
- hasAncestor(cxxRecordDecl(isTemplateInstantiation())),
- hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation())))))));
-}
-
-TEST(HasParent, MatchesAllParents) {
- EXPECT_TRUE(matches(
- "template <typename T> struct C { static void f() { 42; } };"
- "void t() { C<int>::f(); }",
- integerLiteral(
- equals(42),
- hasParent(compoundStmt(hasParent(functionDecl(
- hasParent(cxxRecordDecl(isTemplateInstantiation())))))))));
- EXPECT_TRUE(
- matches("template <typename T> struct C { static void f() { 42; } };"
- "void t() { C<int>::f(); }",
- integerLiteral(
- equals(42),
- hasParent(compoundStmt(hasParent(functionDecl(hasParent(
- cxxRecordDecl(unless(isTemplateInstantiation()))))))))));
- EXPECT_TRUE(matches(
- "template <typename T> struct C { static void f() { 42; } };"
- "void t() { C<int>::f(); }",
- integerLiteral(equals(42),
- hasParent(compoundStmt(
- allOf(hasParent(functionDecl(hasParent(
- cxxRecordDecl(isTemplateInstantiation())))),
- hasParent(functionDecl(hasParent(cxxRecordDecl(
- unless(isTemplateInstantiation())))))))))));
- EXPECT_TRUE(
- notMatches("template <typename T> struct C { static void f() {} };"
- "void t() { C<int>::f(); }",
- compoundStmt(hasParent(recordDecl()))));
-}
-
-TEST(HasParent, NoDuplicateParents) {
- class HasDuplicateParents : public BoundNodesCallback {
- public:
- bool run(const BoundNodes *Nodes) override { return false; }
- bool run(const BoundNodes *Nodes, ASTContext *Context) override {
- const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
- std::set<const void *> Parents;
- for (const auto &Parent : Context->getParents(*Node)) {
- if (!Parents.insert(Parent.getMemoizationData()).second) {
- return true;
- }
- }
- return false;
- }
- };
- EXPECT_FALSE(matchAndVerifyResultTrue(
- "template <typename T> int Foo() { return 1 + 2; }\n"
- "int x = Foo<int>() + Foo<unsigned>();",
- stmt().bind("node"), new HasDuplicateParents()));
-}
-
-TEST(TypeMatching, MatchesTypes) {
- EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
-}
-
-TEST(TypeMatching, MatchesVoid) {
- EXPECT_TRUE(matches("struct S { void func(); };",
- cxxMethodDecl(returns(voidType()))));
-}
-
-TEST(TypeMatching, MatchesArrayTypes) {
- EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
- EXPECT_TRUE(matches("int a[42];", arrayType()));
- EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
-
- EXPECT_TRUE(notMatches("struct A {}; A a[7];",
- arrayType(hasElementType(builtinType()))));
-
- EXPECT_TRUE(matches(
- "int const a[] = { 2, 3 };",
- qualType(arrayType(hasElementType(builtinType())))));
- EXPECT_TRUE(matches(
- "int const a[] = { 2, 3 };",
- qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
- EXPECT_TRUE(matches(
- "typedef const int T; T x[] = { 1, 2 };",
- qualType(isConstQualified(), arrayType())));
-
- EXPECT_TRUE(notMatches(
- "int a[] = { 2, 3 };",
- qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
- EXPECT_TRUE(notMatches(
- "int a[] = { 2, 3 };",
- qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
- EXPECT_TRUE(notMatches(
- "int const a[] = { 2, 3 };",
- qualType(arrayType(hasElementType(builtinType())),
- unless(isConstQualified()))));
-
- EXPECT_TRUE(matches("int a[2];",
- constantArrayType(hasElementType(builtinType()))));
- EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
-}
-
-TEST(TypeMatching, DecayedType) {
- EXPECT_TRUE(matches("void f(int i[]);", valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))));
- EXPECT_TRUE(notMatches("int i[7];", decayedType()));
-}
-
-TEST(TypeMatching, MatchesComplexTypes) {
- EXPECT_TRUE(matches("_Complex float f;", complexType()));
- EXPECT_TRUE(matches(
- "_Complex float f;",
- complexType(hasElementType(builtinType()))));
- EXPECT_TRUE(notMatches(
- "_Complex float f;",
- complexType(hasElementType(isInteger()))));
-}
-
-TEST(TypeMatching, MatchesConstantArrayTypes) {
- EXPECT_TRUE(matches("int a[2];", constantArrayType()));
- EXPECT_TRUE(notMatches(
- "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
- constantArrayType(hasElementType(builtinType()))));
-
- EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
- EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
- EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
-}
-
-TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
- EXPECT_TRUE(matches(
- "template <typename T, int Size> class array { T data[Size]; };",
- dependentSizedArrayType()));
- EXPECT_TRUE(notMatches(
- "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
- dependentSizedArrayType()));
-}
-
-TEST(TypeMatching, MatchesIncompleteArrayType) {
- EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
- EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
-
- EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
- incompleteArrayType()));
-}
-
-TEST(TypeMatching, MatchesVariableArrayType) {
- EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
- EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
-
- EXPECT_TRUE(matches(
- "void f(int b) { int a[b]; }",
- variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
- varDecl(hasName("b")))))))));
-}
-
-TEST(TypeMatching, MatchesAtomicTypes) {
- if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
- llvm::Triple::Win32) {
- // FIXME: Make this work for MSVC.
- EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
-
- EXPECT_TRUE(matches("_Atomic(int) i;",
- atomicType(hasValueType(isInteger()))));
- EXPECT_TRUE(notMatches("_Atomic(float) f;",
- atomicType(hasValueType(isInteger()))));
- }
-}
-
-TEST(TypeMatching, MatchesAutoTypes) {
- EXPECT_TRUE(matches("auto i = 2;", autoType()));
- EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
- autoType()));
-
- // FIXME: Matching against the type-as-written can't work here, because the
- // type as written was not deduced.
- //EXPECT_TRUE(matches("auto a = 1;",
- // autoType(hasDeducedType(isInteger()))));
- //EXPECT_TRUE(notMatches("auto b = 2.0;",
- // autoType(hasDeducedType(isInteger()))));
-}
-
-TEST(TypeMatching, MatchesFunctionTypes) {
- EXPECT_TRUE(matches("int (*f)(int);", functionType()));
- EXPECT_TRUE(matches("void f(int i) {}", functionType()));
-}
-
-TEST(TypeMatching, MatchesParenType) {
- EXPECT_TRUE(
- matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
- EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
-
- EXPECT_TRUE(matches(
- "int (*ptr_to_func)(int);",
- varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
- EXPECT_TRUE(notMatches(
- "int (*ptr_to_array)[4];",
- varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
-}
-
-TEST(TypeMatching, PointerTypes) {
- // FIXME: Reactive when these tests can be more specific (not matching
- // implicit code on certain platforms), likely when we have hasDescendant for
- // Types/TypeLocs.
- //EXPECT_TRUE(matchAndVerifyResultTrue(
- // "int* a;",
- // pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
- // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
- //EXPECT_TRUE(matchAndVerifyResultTrue(
- // "int* a;",
- // pointerTypeLoc().bind("loc"),
- // new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
- EXPECT_TRUE(matches(
- "int** a;",
- loc(pointerType(pointee(qualType())))));
- EXPECT_TRUE(matches(
- "int** a;",
- loc(pointerType(pointee(pointerType())))));
- EXPECT_TRUE(matches(
- "int* b; int* * const a = &b;",
- loc(qualType(isConstQualified(), pointerType()))));
-
- std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
- hasType(blockPointerType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
- hasType(memberPointerType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
- hasType(pointerType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
- hasType(referenceType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
- hasType(lValueReferenceType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
- hasType(rValueReferenceType()))));
-
- Fragment = "int *ptr;";
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
- hasType(blockPointerType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
- hasType(memberPointerType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
- hasType(pointerType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
- hasType(referenceType()))));
-
- Fragment = "int a; int &ref = a;";
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
- hasType(blockPointerType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
- hasType(memberPointerType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
- hasType(pointerType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
- hasType(referenceType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
- hasType(lValueReferenceType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
- hasType(rValueReferenceType()))));
-
- Fragment = "int &&ref = 2;";
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
- hasType(blockPointerType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
- hasType(memberPointerType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
- hasType(pointerType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
- hasType(referenceType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
- hasType(lValueReferenceType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
- hasType(rValueReferenceType()))));
-}
-
-TEST(TypeMatching, AutoRefTypes) {
- std::string Fragment = "auto a = 1;"
- "auto b = a;"
- "auto &c = a;"
- "auto &&d = c;"
- "auto &&e = 2;";
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
- hasType(referenceType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
- hasType(referenceType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
- hasType(referenceType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
- hasType(lValueReferenceType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
- hasType(rValueReferenceType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
- hasType(referenceType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
- hasType(lValueReferenceType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
- hasType(rValueReferenceType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
- hasType(referenceType()))));
- EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
- hasType(lValueReferenceType()))));
- EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
- hasType(rValueReferenceType()))));
-}
-
-TEST(TypeMatching, PointeeTypes) {
- EXPECT_TRUE(matches("int b; int &a = b;",
- referenceType(pointee(builtinType()))));
- EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
-
- EXPECT_TRUE(matches("int *a;",
- loc(pointerType(pointee(builtinType())))));
-
- EXPECT_TRUE(matches(
- "int const *A;",
- pointerType(pointee(isConstQualified(), builtinType()))));
- EXPECT_TRUE(notMatches(
- "int *A;",
- pointerType(pointee(isConstQualified(), builtinType()))));
-}
-
-TEST(TypeMatching, MatchesPointersToConstTypes) {
- EXPECT_TRUE(matches("int b; int * const a = &b;",
- loc(pointerType())));
- EXPECT_TRUE(matches("int b; int * const a = &b;",
- loc(pointerType())));
- EXPECT_TRUE(matches(
- "int b; const int * a = &b;",
- loc(pointerType(pointee(builtinType())))));
- EXPECT_TRUE(matches(
- "int b; const int * a = &b;",
- pointerType(pointee(builtinType()))));
-}
-
-TEST(TypeMatching, MatchesTypedefTypes) {
- EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
- hasType(typedefType()))));
-}
-
-TEST(TypeMatching, MatchesTemplateSpecializationType) {
- EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
- templateSpecializationType()));
-}
-
-TEST(TypeMatching, MatchesRecordType) {
- EXPECT_TRUE(matches("class C{}; C c;", recordType()));
- EXPECT_TRUE(matches("struct S{}; S s;",
- recordType(hasDeclaration(recordDecl(hasName("S"))))));
- EXPECT_TRUE(notMatches("int i;",
- recordType(hasDeclaration(recordDecl(hasName("S"))))));
-}
-
-TEST(TypeMatching, MatchesElaboratedType) {
- EXPECT_TRUE(matches(
- "namespace N {"
- " namespace M {"
- " class D {};"
- " }"
- "}"
- "N::M::D d;", elaboratedType()));
- EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
- EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
-}
-
-TEST(ElaboratedTypeNarrowing, hasQualifier) {
- EXPECT_TRUE(matches(
- "namespace N {"
- " namespace M {"
- " class D {};"
- " }"
- "}"
- "N::M::D d;",
- elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
- EXPECT_TRUE(notMatches(
- "namespace M {"
- " class D {};"
- "}"
- "M::D d;",
- elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
- EXPECT_TRUE(notMatches(
- "struct D {"
- "} d;",
- elaboratedType(hasQualifier(nestedNameSpecifier()))));
-}
-
-TEST(ElaboratedTypeNarrowing, namesType) {
- EXPECT_TRUE(matches(
- "namespace N {"
- " namespace M {"
- " class D {};"
- " }"
- "}"
- "N::M::D d;",
- elaboratedType(elaboratedType(namesType(recordType(
- hasDeclaration(namedDecl(hasName("D")))))))));
- EXPECT_TRUE(notMatches(
- "namespace M {"
- " class D {};"
- "}"
- "M::D d;",
- elaboratedType(elaboratedType(namesType(typedefType())))));
-}
-
-TEST(TypeMatching, MatchesSubstTemplateTypeParmType) {
- const std::string code = "template <typename T>"
- "int F() {"
- " return 1 + T();"
- "}"
- "int i = F<int>();";
- EXPECT_FALSE(matches(code, binaryOperator(hasLHS(
- expr(hasType(substTemplateTypeParmType()))))));
- EXPECT_TRUE(matches(code, binaryOperator(hasRHS(
- expr(hasType(substTemplateTypeParmType()))))));
-}
-
-TEST(NNS, MatchesNestedNameSpecifiers) {
- EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
- nestedNameSpecifier()));
- EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
- nestedNameSpecifier()));
- EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
- nestedNameSpecifier()));
- EXPECT_TRUE(matches("namespace a { namespace b {} } namespace ab = a::b;",
- nestedNameSpecifier()));
-
- EXPECT_TRUE(matches(
- "struct A { static void f() {} }; void g() { A::f(); }",
- nestedNameSpecifier()));
- EXPECT_TRUE(notMatches(
- "struct A { static void f() {} }; void g(A* a) { a->f(); }",
- nestedNameSpecifier()));
-}
-
-TEST(NullStatement, SimpleCases) {
- EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
- EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
-}
-
-TEST(NS, Anonymous) {
- EXPECT_TRUE(notMatches("namespace N {}", namespaceDecl(isAnonymous())));
- EXPECT_TRUE(matches("namespace {}", namespaceDecl(isAnonymous())));
-}
-
-TEST(NS, Alias) {
- EXPECT_TRUE(matches("namespace test {} namespace alias = ::test;",
- namespaceAliasDecl(hasName("alias"))));
-}
-
-TEST(NNS, MatchesTypes) {
- NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
- specifiesType(hasDeclaration(recordDecl(hasName("A")))));
- EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
- EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
- Matcher));
- EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
-}
-
-TEST(NNS, MatchesNamespaceDecls) {
- NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
- specifiesNamespace(hasName("ns")));
- EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
- EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
- EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
-}
-
-TEST(NNS, BindsNestedNameSpecifiers) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
- nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
- new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
-}
-
-TEST(NNS, BindsNestedNameSpecifierLocs) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "namespace ns { struct B {}; } ns::B b;",
- loc(nestedNameSpecifier()).bind("loc"),
- new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
-}
-
-TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
- EXPECT_TRUE(matches(
- "struct A { struct B { struct C {}; }; }; A::B::C c;",
- nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
- EXPECT_TRUE(matches(
- "struct A { struct B { struct C {}; }; }; A::B::C c;",
- nestedNameSpecifierLoc(hasPrefix(
- specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
-}
-
-TEST(NNS, DescendantsOfNestedNameSpecifiers) {
- std::string Fragment =
- "namespace a { struct A { struct B { struct C {}; }; }; };"
- "void f() { a::A::B::C c; }";
- EXPECT_TRUE(matches(
- Fragment,
- nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
- hasDescendant(nestedNameSpecifier(
- specifiesNamespace(hasName("a")))))));
- EXPECT_TRUE(notMatches(
- Fragment,
- nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
- has(nestedNameSpecifier(
- specifiesNamespace(hasName("a")))))));
- EXPECT_TRUE(matches(
- Fragment,
- nestedNameSpecifier(specifiesType(asString("struct a::A")),
- has(nestedNameSpecifier(
- specifiesNamespace(hasName("a")))))));
-
- // Not really useful because a NestedNameSpecifier can af at most one child,
- // but to complete the interface.
- EXPECT_TRUE(matchAndVerifyResultTrue(
- Fragment,
- nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
- forEach(nestedNameSpecifier().bind("x"))),
- new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
-}
-
-TEST(NNS, NestedNameSpecifiersAsDescendants) {
- std::string Fragment =
- "namespace a { struct A { struct B { struct C {}; }; }; };"
- "void f() { a::A::B::C c; }";
- EXPECT_TRUE(matches(
- Fragment,
- decl(hasDescendant(nestedNameSpecifier(specifiesType(
- asString("struct a::A")))))));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- Fragment,
- functionDecl(hasName("f"),
- forEachDescendant(nestedNameSpecifier().bind("x"))),
- // Nested names: a, a::A and a::A::B.
- new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
-}
-
-TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
- std::string Fragment =
- "namespace a { struct A { struct B { struct C {}; }; }; };"
- "void f() { a::A::B::C c; }";
- EXPECT_TRUE(matches(
- Fragment,
- nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
- hasDescendant(loc(nestedNameSpecifier(
- specifiesNamespace(hasName("a"))))))));
- EXPECT_TRUE(notMatches(
- Fragment,
- nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
- has(loc(nestedNameSpecifier(
- specifiesNamespace(hasName("a"))))))));
- EXPECT_TRUE(matches(
- Fragment,
- nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
- has(loc(nestedNameSpecifier(
- specifiesNamespace(hasName("a"))))))));
-
- EXPECT_TRUE(matchAndVerifyResultTrue(
- Fragment,
- nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
- forEach(nestedNameSpecifierLoc().bind("x"))),
- new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
-}
-
-TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
- std::string Fragment =
- "namespace a { struct A { struct B { struct C {}; }; }; };"
- "void f() { a::A::B::C c; }";
- EXPECT_TRUE(matches(
- Fragment,
- decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
- asString("struct a::A"))))))));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- Fragment,
- functionDecl(hasName("f"),
- forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
- // Nested names: a, a::A and a::A::B.
- new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
-}
-
-template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
-public:
- VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
- StringRef InnerId)
- : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
- }
-
- bool run(const BoundNodes *Nodes) override { return false; }
-
- bool run(const BoundNodes *Nodes, ASTContext *Context) override {
- const T *Node = Nodes->getNodeAs<T>(Id);
- return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
- nullptr;
- }
-private:
- std::string Id;
- internal::Matcher<T> InnerMatcher;
- std::string InnerId;
-};
-
-TEST(MatchFinder, CanMatchDeclarationsRecursively) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
- new VerifyMatchOnNode<clang::Decl>(
- "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
- "Y")));
- EXPECT_TRUE(matchAndVerifyResultFalse(
- "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
- new VerifyMatchOnNode<clang::Decl>(
- "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
- "Z")));
-}
-
-TEST(MatchFinder, CanMatchStatementsRecursively) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
- new VerifyMatchOnNode<clang::Stmt>(
- "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
- EXPECT_TRUE(matchAndVerifyResultFalse(
- "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
- new VerifyMatchOnNode<clang::Stmt>(
- "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
-}
-
-TEST(MatchFinder, CanMatchSingleNodesRecursively) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
- new VerifyMatchOnNode<clang::Decl>(
- "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
- EXPECT_TRUE(matchAndVerifyResultFalse(
- "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
- new VerifyMatchOnNode<clang::Decl>(
- "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
-}
-
-template <typename T>
-class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
-public:
- bool run(const BoundNodes *Nodes) override { return false; }
-
- bool run(const BoundNodes *Nodes, ASTContext *Context) override {
- const T *Node = Nodes->getNodeAs<T>("");
- return verify(*Nodes, *Context, Node);
- }
-
- bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
- // Use the original typed pointer to verify we can pass pointers to subtypes
- // to equalsNode.
- const T *TypedNode = cast<T>(Node);
- return selectFirst<T>(
- "", match(stmt(hasParent(
- stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
- *Node, Context)) != nullptr;
- }
- bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
- // Use the original typed pointer to verify we can pass pointers to subtypes
- // to equalsNode.
- const T *TypedNode = cast<T>(Node);
- return selectFirst<T>(
- "", match(decl(hasParent(
- decl(has(decl(equalsNode(TypedNode)))).bind(""))),
- *Node, Context)) != nullptr;
- }
- bool verify(const BoundNodes &Nodes, ASTContext &Context, const Type *Node) {
- // Use the original typed pointer to verify we can pass pointers to subtypes
- // to equalsNode.
- const T *TypedNode = cast<T>(Node);
- const auto *Dec = Nodes.getNodeAs<FieldDecl>("decl");
- return selectFirst<T>(
- "", match(fieldDecl(hasParent(decl(has(fieldDecl(
- hasType(type(equalsNode(TypedNode)).bind(""))))))),
- *Dec, Context)) != nullptr;
- }
-};
-
-TEST(IsEqualTo, MatchesNodesByIdentity) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
- new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void f() { if (true) if(true) {} }", ifStmt().bind(""),
- new VerifyAncestorHasChildIsEqual<IfStmt>()));
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "class X { class Y {} y; };",
- fieldDecl(hasName("y"), hasType(type().bind(""))).bind("decl"),
- new VerifyAncestorHasChildIsEqual<Type>()));
-}
-
-TEST(MatchFinder, CheckProfiling) {
- MatchFinder::MatchFinderOptions Options;
- llvm::StringMap<llvm::TimeRecord> Records;
- Options.CheckProfiling.emplace(Records);
- MatchFinder Finder(std::move(Options));
-
- struct NamedCallback : public MatchFinder::MatchCallback {
- void run(const MatchFinder::MatchResult &Result) override {}
- StringRef getID() const override { return "MyID"; }
- } Callback;
- Finder.addMatcher(decl(), &Callback);
- std::unique_ptr<FrontendActionFactory> Factory(
- newFrontendActionFactory(&Finder));
- ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
-
- EXPECT_EQ(1u, Records.size());
- EXPECT_EQ("MyID", Records.begin()->getKey());
-}
-
-class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
-public:
- VerifyStartOfTranslationUnit() : Called(false) {}
- void run(const MatchFinder::MatchResult &Result) override {
- EXPECT_TRUE(Called);
- }
- void onStartOfTranslationUnit() override { Called = true; }
- bool Called;
-};
-
-TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
- MatchFinder Finder;
- VerifyStartOfTranslationUnit VerifyCallback;
- Finder.addMatcher(decl(), &VerifyCallback);
- std::unique_ptr<FrontendActionFactory> Factory(
- newFrontendActionFactory(&Finder));
- ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
- EXPECT_TRUE(VerifyCallback.Called);
-
- VerifyCallback.Called = false;
- std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
- ASSERT_TRUE(AST.get());
- Finder.matchAST(AST->getASTContext());
- EXPECT_TRUE(VerifyCallback.Called);
-}
-
-class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
-public:
- VerifyEndOfTranslationUnit() : Called(false) {}
- void run(const MatchFinder::MatchResult &Result) override {
- EXPECT_FALSE(Called);
- }
- void onEndOfTranslationUnit() override { Called = true; }
- bool Called;
-};
-
-TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
- MatchFinder Finder;
- VerifyEndOfTranslationUnit VerifyCallback;
- Finder.addMatcher(decl(), &VerifyCallback);
- std::unique_ptr<FrontendActionFactory> Factory(
- newFrontendActionFactory(&Finder));
- ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
- EXPECT_TRUE(VerifyCallback.Called);
-
- VerifyCallback.Called = false;
- std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
- ASSERT_TRUE(AST.get());
- Finder.matchAST(AST->getASTContext());
- EXPECT_TRUE(VerifyCallback.Called);
-}
-
-TEST(EqualsBoundNodeMatcher, QualType) {
- EXPECT_TRUE(matches(
- "int i = 1;", varDecl(hasType(qualType().bind("type")),
- hasInitializer(ignoringParenImpCasts(
- hasType(qualType(equalsBoundNode("type"))))))));
- EXPECT_TRUE(notMatches("int i = 1.f;",
- varDecl(hasType(qualType().bind("type")),
- hasInitializer(ignoringParenImpCasts(hasType(
- qualType(equalsBoundNode("type"))))))));
-}
-
-TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
- EXPECT_TRUE(notMatches(
- "int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
- hasInitializer(ignoringParenImpCasts(
- hasType(qualType(equalsBoundNode("type"))))))));
-}
-
-TEST(EqualsBoundNodeMatcher, Stmt) {
- EXPECT_TRUE(
- matches("void f() { if(true) {} }",
- stmt(allOf(ifStmt().bind("if"),
- hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
-
- EXPECT_TRUE(notMatches(
- "void f() { if(true) { if (true) {} } }",
- stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
-}
-
-TEST(EqualsBoundNodeMatcher, Decl) {
- EXPECT_TRUE(matches(
- "class X { class Y {}; };",
- decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
- hasParent(decl(has(decl(equalsBoundNode("record")))))))));
-
- EXPECT_TRUE(notMatches("class X { class Y {}; };",
- decl(allOf(recordDecl(hasName("::X")).bind("record"),
- has(decl(equalsBoundNode("record")))))));
-}
-
-TEST(EqualsBoundNodeMatcher, Type) {
- EXPECT_TRUE(matches(
- "class X { int a; int b; };",
- recordDecl(
- has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
- has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
-
- EXPECT_TRUE(notMatches(
- "class X { int a; double b; };",
- recordDecl(
- has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
- has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
-}
-
-TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "int f() {"
- " if (1) {"
- " int i = 9;"
- " }"
- " int j = 10;"
- " {"
- " float k = 9.0;"
- " }"
- " return 0;"
- "}",
- // Look for variable declarations within functions whose type is the same
- // as the function return type.
- functionDecl(returns(qualType().bind("type")),
- forEachDescendant(varDecl(hasType(
- qualType(equalsBoundNode("type")))).bind("decl"))),
- // Only i and j should match, not k.
- new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
-}
-
-TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "void f() {"
- " int x;"
- " double d;"
- " x = d + x - d + x;"
- "}",
- functionDecl(
- hasName("f"), forEachDescendant(varDecl().bind("d")),
- forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
- new VerifyIdIsBoundTo<VarDecl>("d", 5)));
-}
-
-TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
- EXPECT_TRUE(matchAndVerifyResultTrue(
- "struct StringRef { int size() const; const char* data() const; };"
- "void f(StringRef v) {"
- " v.data();"
- "}",
- cxxMemberCallExpr(
- callee(cxxMethodDecl(hasName("data"))),
- on(declRefExpr(to(
- varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
- unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
- callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
- on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
- .bind("data"),
- new VerifyIdIsBoundTo<Expr>("data", 1)));
-
- EXPECT_FALSE(matches(
- "struct StringRef { int size() const; const char* data() const; };"
- "void f(StringRef v) {"
- " v.data();"
- " v.size();"
- "}",
- cxxMemberCallExpr(
- callee(cxxMethodDecl(hasName("data"))),
- on(declRefExpr(to(
- varDecl(hasType(recordDecl(hasName("StringRef")))).bind("var")))),
- unless(hasAncestor(stmt(hasDescendant(cxxMemberCallExpr(
- callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))),
- on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
- .bind("data")));
-}
-
-TEST(TypeDefDeclMatcher, Match) {
- EXPECT_TRUE(matches("typedef int typedefDeclTest;",
- typedefDecl(hasName("typedefDeclTest"))));
-}
-
-TEST(IsInlineMatcher, IsInline) {
- EXPECT_TRUE(matches("void g(); inline void f();",
- functionDecl(isInline(), hasName("f"))));
- EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
- namespaceDecl(isInline(), hasName("m"))));
-}
-
-// FIXME: Figure out how to specify paths so the following tests pass on Windows.
-#ifndef LLVM_ON_WIN32
-
-TEST(Matcher, IsExpansionInMainFileMatcher) {
- EXPECT_TRUE(matches("class X {};",
- recordDecl(hasName("X"), isExpansionInMainFile())));
- EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
- FileContentMappings M;
- M.push_back(std::make_pair("/other", "class X {};"));
- EXPECT_TRUE(matchesConditionally("#include <other>\n",
- recordDecl(isExpansionInMainFile()), false,
- "-isystem/", M));
-}
-
-TEST(Matcher, IsExpansionInSystemHeader) {
- FileContentMappings M;
- M.push_back(std::make_pair("/other", "class X {};"));
- EXPECT_TRUE(matchesConditionally(
- "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
- "-isystem/", M));
- EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
- recordDecl(isExpansionInSystemHeader()),
- false, "-I/", M));
- EXPECT_TRUE(notMatches("class X {};",
- recordDecl(isExpansionInSystemHeader())));
- EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
-}
-
-TEST(Matcher, IsExpansionInFileMatching) {
- FileContentMappings M;
- M.push_back(std::make_pair("/foo", "class A {};"));
- M.push_back(std::make_pair("/bar", "class B {};"));
- EXPECT_TRUE(matchesConditionally(
- "#include <foo>\n"
- "#include <bar>\n"
- "class X {};",
- recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
- "-isystem/", M));
- EXPECT_TRUE(matchesConditionally(
- "#include <foo>\n"
- "#include <bar>\n"
- "class X {};",
- recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
- "-isystem/", M));
-}
-
-#endif // LLVM_ON_WIN32
-
-
-TEST(ObjCMessageExprMatcher, SimpleExprs) {
- // don't find ObjCMessageExpr where none are present
- EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
-
- std::string Objc1String =
- "@interface Str "
- " - (Str *)uppercaseString:(Str *)str;"
- "@end "
- "@interface foo "
- "- (void)meth:(Str *)text;"
- "@end "
- " "
- "@implementation foo "
- "- (void) meth:(Str *)text { "
- " [self contents];"
- " Str *up = [text uppercaseString];"
- "} "
- "@end ";
- EXPECT_TRUE(matchesObjC(
- Objc1String,
- objcMessageExpr(anything())));
- EXPECT_TRUE(matchesObjC(
- Objc1String,
- objcMessageExpr(hasSelector("contents"))));
- EXPECT_TRUE(matchesObjC(
- Objc1String,
- objcMessageExpr(matchesSelector("cont*"))));
- EXPECT_FALSE(matchesObjC(
- Objc1String,
- objcMessageExpr(matchesSelector("?cont*"))));
- EXPECT_TRUE(notMatchesObjC(
- Objc1String,
- objcMessageExpr(hasSelector("contents"), hasNullSelector())));
- EXPECT_TRUE(matchesObjC(
- Objc1String,
- objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
- EXPECT_TRUE(matchesObjC(
- Objc1String,
- objcMessageExpr(hasSelector("contents"), numSelectorArgs(0))));
- EXPECT_TRUE(matchesObjC(
- Objc1String,
- objcMessageExpr(matchesSelector("uppercase*"),
- argumentCountIs(0)
- )));
-
-}
-
-} // end namespace ast_matchers
-} // end namespace clang
diff --git a/unittests/ASTMatchers/ASTMatchersTest.h b/unittests/ASTMatchers/ASTMatchersTest.h
index 68824e61ac..4b3387c0ba 100644
--- a/unittests/ASTMatchers/ASTMatchersTest.h
+++ b/unittests/ASTMatchers/ASTMatchersTest.h
@@ -37,8 +37,8 @@ public:
// If 'FindResultVerifier' is NULL, sets *Verified to true when Run is called.
class VerifyMatch : public MatchFinder::MatchCallback {
public:
- VerifyMatch(BoundNodesCallback *FindResultVerifier, bool *Verified)
- : Verified(Verified), FindResultReviewer(FindResultVerifier) {}
+ VerifyMatch(std::unique_ptr<BoundNodesCallback> FindResultVerifier, bool *Verified)
+ : Verified(Verified), FindResultReviewer(std::move(FindResultVerifier)) {}
void run(const MatchFinder::MatchResult &Result) override {
if (FindResultReviewer != nullptr) {
@@ -55,7 +55,7 @@ public:
private:
bool *const Verified;
- BoundNodesCallback *const FindResultReviewer;
+ const std::unique_ptr<BoundNodesCallback> FindResultReviewer;
};
template <typename T>
@@ -73,15 +73,19 @@ testing::AssertionResult matchesConditionally(
return testing::AssertionFailure() << "Could not add dynamic matcher";
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
- // Some tests use typeof, which is a gnu extension.
- std::vector<std::string> Args;
- Args.push_back(CompileArg);
- // Some tests need rtti/exceptions on
- Args.push_back("-frtti");
- Args.push_back("-fexceptions");
- if (!runToolOnCodeWithArgs(Factory->create(), Code, Args, Filename,
- std::make_shared<PCHContainerOperations>(),
- VirtualMappedFiles)) {
+ // Some tests need rtti/exceptions on. Use an unknown-unknown triple so we
+ // don't instantiate the full system toolchain. On Linux, instantiating the
+ // toolchain involves stat'ing large portions of /usr/lib, and this slows down
+ // not only this test, but all other tests, via contention in the kernel.
+ //
+ // FIXME: This is a hack to work around the fact that there's no way to do the
+ // equivalent of runToolOnCodeWithArgs without instantiating a full Driver.
+ // We should consider having a function, at least for tests, that invokes cc1.
+ std::vector<std::string> Args = {CompileArg, "-frtti", "-fexceptions",
+ "-target", "i386-unknown-unknown"};
+ if (!runToolOnCodeWithArgs(
+ Factory->create(), Code, Args, Filename, "clang-tool",
+ std::make_shared<PCHContainerOperations>(), VirtualMappedFiles)) {
return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
}
if (Found != DynamicFound) {
@@ -126,6 +130,13 @@ testing::AssertionResult matchesC(const std::string &Code, const T &AMatcher) {
}
template <typename T>
+testing::AssertionResult matchesC99(const std::string &Code,
+ const T &AMatcher) {
+ return matchesConditionally(Code, AMatcher, true, "-std=c99",
+ FileContentMappings(), "input.c");
+}
+
+template <typename T>
testing::AssertionResult notMatchesC(const std::string &Code,
const T &AMatcher) {
return matchesConditionally(Code, AMatcher, false, "", FileContentMappings(),
@@ -173,13 +184,12 @@ testing::AssertionResult matchesConditionallyWithCuda(
return testing::AssertionFailure() << "Could not add dynamic matcher";
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
- // Some tests use typeof, which is a gnu extension.
- std::vector<std::string> Args;
- Args.push_back("-xcuda");
- Args.push_back("-fno-ms-extensions");
- Args.push_back("--cuda-host-only");
- Args.push_back("-nocudainc");
- Args.push_back(CompileArg);
+ // Some tests use typeof, which is a gnu extension. Using an explicit
+ // unknown-unknown triple is good for a large speedup, because it lets us
+ // avoid constructing a full system triple.
+ std::vector<std::string> Args = {
+ "-xcuda", "-fno-ms-extensions", "--cuda-host-only", "-nocudainc",
+ "-target", "nvptx64-unknown-unknown", CompileArg};
if (!runToolOnCodeWithArgs(Factory->create(),
CudaHeader + Code, Args)) {
return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
@@ -215,17 +225,19 @@ testing::AssertionResult notMatchesWithCuda(const std::string &Code,
template <typename T>
testing::AssertionResult
matchAndVerifyResultConditionally(const std::string &Code, const T &AMatcher,
- BoundNodesCallback *FindResultVerifier,
+ std::unique_ptr<BoundNodesCallback> FindResultVerifier,
bool ExpectResult) {
- std::unique_ptr<BoundNodesCallback> ScopedVerifier(FindResultVerifier);
bool VerifiedResult = false;
MatchFinder Finder;
- VerifyMatch VerifyVerifiedResult(FindResultVerifier, &VerifiedResult);
+ VerifyMatch VerifyVerifiedResult(std::move(FindResultVerifier), &VerifiedResult);
Finder.addMatcher(AMatcher, &VerifyVerifiedResult);
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
- // Some tests use typeof, which is a gnu extension.
- std::vector<std::string> Args(1, "-std=gnu++98");
+ // Some tests use typeof, which is a gnu extension. Using an explicit
+ // unknown-unknown triple is good for a large speedup, because it lets us
+ // avoid constructing a full system triple.
+ std::vector<std::string> Args = {"-std=gnu++98", "-target",
+ "i386-unknown-unknown"};
if (!runToolOnCodeWithArgs(Factory->create(), Code, Args)) {
return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
}
@@ -259,20 +271,92 @@ matchAndVerifyResultConditionally(const std::string &Code, const T &AMatcher,
template <typename T>
testing::AssertionResult
matchAndVerifyResultTrue(const std::string &Code, const T &AMatcher,
- BoundNodesCallback *FindResultVerifier) {
+ std::unique_ptr<BoundNodesCallback> FindResultVerifier) {
return matchAndVerifyResultConditionally(
- Code, AMatcher, FindResultVerifier, true);
+ Code, AMatcher, std::move(FindResultVerifier), true);
}
template <typename T>
testing::AssertionResult
matchAndVerifyResultFalse(const std::string &Code, const T &AMatcher,
- BoundNodesCallback *FindResultVerifier) {
+ std::unique_ptr<BoundNodesCallback> FindResultVerifier) {
return matchAndVerifyResultConditionally(
- Code, AMatcher, FindResultVerifier, false);
+ Code, AMatcher, std::move(FindResultVerifier), false);
}
-} // end namespace ast_matchers
-} // end namespace clang
+// Implements a run method that returns whether BoundNodes contains a
+// Decl bound to Id that can be dynamically cast to T.
+// Optionally checks that the check succeeded a specific number of times.
+template <typename T>
+class VerifyIdIsBoundTo : public BoundNodesCallback {
+public:
+ // Create an object that checks that a node of type \c T was bound to \c Id.
+ // Does not check for a certain number of matches.
+ explicit VerifyIdIsBoundTo(llvm::StringRef Id)
+ : Id(Id), ExpectedCount(-1), Count(0) {}
+
+ // Create an object that checks that a node of type \c T was bound to \c Id.
+ // Checks that there were exactly \c ExpectedCount matches.
+ VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
+ : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
+
+ // Create an object that checks that a node of type \c T was bound to \c Id.
+ // Checks that there was exactly one match with the name \c ExpectedName.
+ // Note that \c T must be a NamedDecl for this to work.
+ VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
+ int ExpectedCount = 1)
+ : Id(Id), ExpectedCount(ExpectedCount), Count(0),
+ ExpectedName(ExpectedName) {}
+
+ void onEndOfTranslationUnit() override {
+ if (ExpectedCount != -1)
+ EXPECT_EQ(ExpectedCount, Count);
+ if (!ExpectedName.empty())
+ EXPECT_EQ(ExpectedName, Name);
+ Count = 0;
+ Name.clear();
+ }
+
+ ~VerifyIdIsBoundTo() override {
+ EXPECT_EQ(0, Count);
+ EXPECT_EQ("", Name);
+ }
+
+ bool run(const BoundNodes *Nodes) override {
+ const BoundNodes::IDToNodeMap &M = Nodes->getMap();
+ if (Nodes->getNodeAs<T>(Id)) {
+ ++Count;
+ if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
+ Name = Named->getNameAsString();
+ } else if (const NestedNameSpecifier *NNS =
+ Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
+ llvm::raw_string_ostream OS(Name);
+ NNS->print(OS, PrintingPolicy(LangOptions()));
+ }
+ BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
+ EXPECT_NE(M.end(), I);
+ if (I != M.end())
+ EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
+ return true;
+ }
+ EXPECT_TRUE(M.count(Id) == 0 ||
+ M.find(Id)->second.template get<T>() == nullptr);
+ return false;
+ }
+
+ bool run(const BoundNodes *Nodes, ASTContext *Context) override {
+ return run(Nodes);
+ }
+
+private:
+ const std::string Id;
+ const int ExpectedCount;
+ int Count;
+ const std::string ExpectedName;
+ std::string Name;
+};
+
+} // namespace ast_matchers
+} // namespace clang
#endif // LLVM_CLANG_UNITTESTS_AST_MATCHERS_AST_MATCHERS_TEST_H
diff --git a/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp b/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
new file mode 100644
index 0000000000..4149d4fd0b
--- /dev/null
+++ b/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -0,0 +1,2055 @@
+//= unittests/ASTMatchers/ASTMatchersTraversalTest.cpp - matchers unit tests =//
+//
+// The LLVM Compiler Infrastructure
+//`
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ASTMatchersTest.h"
+#include "clang/AST/PrettyPrinter.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/Host.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace ast_matchers {
+
+TEST(DeclarationMatcher, hasMethod) {
+ EXPECT_TRUE(matches("class A { void func(); };",
+ cxxRecordDecl(hasMethod(hasName("func")))));
+ EXPECT_TRUE(notMatches("class A { void func(); };",
+ cxxRecordDecl(hasMethod(isPublic()))));
+}
+
+TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
+ EXPECT_TRUE(matches(
+ "template <typename T> struct A {"
+ " template <typename T2> struct F {};"
+ "};"
+ "template <typename T> struct B : A<T>::template F<T> {};"
+ "B<int> b;",
+ cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
+}
+
+TEST(DeclarationMatcher, hasDeclContext) {
+ EXPECT_TRUE(matches(
+ "namespace N {"
+ " namespace M {"
+ " class D {};"
+ " }"
+ "}",
+ recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
+ EXPECT_TRUE(notMatches(
+ "namespace N {"
+ " namespace M {"
+ " class D {};"
+ " }"
+ "}",
+ recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
+
+ EXPECT_TRUE(matches("namespace {"
+ " namespace M {"
+ " class D {};"
+ " }"
+ "}",
+ recordDecl(hasDeclContext(namespaceDecl(
+ hasName("M"), hasDeclContext(namespaceDecl()))))));
+
+ EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
+}
+
+TEST(HasDescendant, MatchesDescendantTypes) {
+ EXPECT_TRUE(matches("void f() { int i = 3; }",
+ decl(hasDescendant(loc(builtinType())))));
+ EXPECT_TRUE(matches("void f() { int i = 3; }",
+ stmt(hasDescendant(builtinType()))));
+
+ EXPECT_TRUE(matches("void f() { int i = 3; }",
+ stmt(hasDescendant(loc(builtinType())))));
+ EXPECT_TRUE(matches("void f() { int i = 3; }",
+ stmt(hasDescendant(qualType(builtinType())))));
+
+ EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
+ stmt(hasDescendant(isInteger()))));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void f() { int a; float c; int d; int e; }",
+ functionDecl(forEachDescendant(
+ varDecl(hasDescendant(isInteger())).bind("x"))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 3)));
+}
+
+TEST(HasDescendant, MatchesDescendantsOfTypes) {
+ EXPECT_TRUE(matches("void f() { int*** i; }",
+ qualType(hasDescendant(builtinType()))));
+ EXPECT_TRUE(matches("void f() { int*** i; }",
+ qualType(hasDescendant(
+ pointerType(pointee(builtinType()))))));
+ EXPECT_TRUE(matches("void f() { int*** i; }",
+ typeLoc(hasDescendant(loc(builtinType())))));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void f() { int*** i; }",
+ qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
+ llvm::make_unique<VerifyIdIsBoundTo<Type>>("x", 2)));
+}
+
+
+TEST(Has, MatchesChildrenOfTypes) {
+ EXPECT_TRUE(matches("int i;",
+ varDecl(hasName("i"), has(isInteger()))));
+ EXPECT_TRUE(notMatches("int** i;",
+ varDecl(hasName("i"), has(isInteger()))));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "int (*f)(float, int);",
+ qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
+ llvm::make_unique<VerifyIdIsBoundTo<QualType>>("x", 2)));
+}
+
+TEST(Has, MatchesChildTypes) {
+ EXPECT_TRUE(matches(
+ "int* i;",
+ varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
+ EXPECT_TRUE(notMatches(
+ "int* i;",
+ varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
+}
+
+TEST(StatementMatcher, Has) {
+ StatementMatcher HasVariableI =
+ expr(hasType(pointsTo(recordDecl(hasName("X")))),
+ has(ignoringParenImpCasts(declRefExpr(to(varDecl(hasName("i")))))));
+
+ EXPECT_TRUE(matches(
+ "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
+ EXPECT_TRUE(notMatches(
+ "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
+}
+
+TEST(StatementMatcher, HasDescendant) {
+ StatementMatcher HasDescendantVariableI =
+ expr(hasType(pointsTo(recordDecl(hasName("X")))),
+ hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
+
+ EXPECT_TRUE(matches(
+ "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
+ HasDescendantVariableI));
+ EXPECT_TRUE(notMatches(
+ "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
+ HasDescendantVariableI));
+}
+
+TEST(TypeMatcher, MatchesClassType) {
+ TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
+
+ EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
+ EXPECT_TRUE(notMatches("class A {};", TypeA));
+
+ TypeMatcher TypeDerivedFromA =
+ hasDeclaration(cxxRecordDecl(isDerivedFrom("A")));
+
+ EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
+ TypeDerivedFromA));
+ EXPECT_TRUE(notMatches("class A {};", TypeA));
+
+ TypeMatcher TypeAHasClassB = hasDeclaration(
+ recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
+
+ EXPECT_TRUE(
+ matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
+
+ EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }",
+ varDecl(hasType(namedDecl(hasName("S"))))));
+}
+
+TEST(TypeMatcher, MatchesDeclTypes) {
+ // TypedefType -> TypedefNameDecl
+ EXPECT_TRUE(matches("typedef int I; void f(I i);",
+ parmVarDecl(hasType(namedDecl(hasName("I"))))));
+ // ObjCObjectPointerType
+ EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);",
+ parmVarDecl(hasType(objcObjectPointerType()))));
+ // ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl
+ EXPECT_TRUE(matchesObjC(
+ "@interface Foo @end void f(Foo *f);",
+ parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo")))))));
+ // TemplateTypeParmType
+ EXPECT_TRUE(matches("template <typename T> void f(T t);",
+ parmVarDecl(hasType(templateTypeParmType()))));
+ // TemplateTypeParmType -> TemplateTypeParmDecl
+ EXPECT_TRUE(matches("template <typename T> void f(T t);",
+ parmVarDecl(hasType(namedDecl(hasName("T"))))));
+ // InjectedClassNameType
+ EXPECT_TRUE(matches("template <typename T> struct S {"
+ " void f(S s);"
+ "};",
+ parmVarDecl(hasType(injectedClassNameType()))));
+ EXPECT_TRUE(notMatches("template <typename T> struct S {"
+ " void g(S<T> s);"
+ "};",
+ parmVarDecl(hasType(injectedClassNameType()))));
+ // InjectedClassNameType -> CXXRecordDecl
+ EXPECT_TRUE(matches("template <typename T> struct S {"
+ " void f(S s);"
+ "};",
+ parmVarDecl(hasType(namedDecl(hasName("S"))))));
+
+ static const char Using[] = "template <typename T>"
+ "struct Base {"
+ " typedef T Foo;"
+ "};"
+ ""
+ "template <typename T>"
+ "struct S : private Base<T> {"
+ " using typename Base<T>::Foo;"
+ " void f(Foo);"
+ "};";
+ // UnresolvedUsingTypenameDecl
+ EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo"))));
+ // UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl
+ EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo"))))));
+}
+
+TEST(HasDeclaration, HasDeclarationOfEnumType) {
+ EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
+ expr(hasType(pointsTo(
+ qualType(hasDeclaration(enumDecl(hasName("X")))))))));
+}
+
+TEST(HasDeclaration, HasGetDeclTraitTest) {
+ EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
+ EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
+ EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
+}
+
+TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
+ EXPECT_TRUE(matches("typedef int X; X a;",
+ varDecl(hasName("a"),
+ hasType(typedefType(hasDeclaration(decl()))))));
+
+ // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
+}
+
+TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
+ EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
+ varDecl(hasType(templateSpecializationType(
+ hasDeclaration(namedDecl(hasName("A"))))))));
+}
+
+TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
+ TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
+ EXPECT_TRUE(
+ matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
+ EXPECT_TRUE(
+ notMatches("class X {}; void y(X *x) { x; }",
+ expr(hasType(ClassX))));
+ EXPECT_TRUE(
+ matches("class X {}; void y(X *x) { x; }",
+ expr(hasType(pointsTo(ClassX)))));
+}
+
+TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
+ TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
+ EXPECT_TRUE(
+ matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
+ EXPECT_TRUE(
+ notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
+ EXPECT_TRUE(
+ matches("class X {}; void y() { X *x; }",
+ varDecl(hasType(pointsTo(ClassX)))));
+}
+
+TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
+ DeclarationMatcher ClassX = recordDecl(hasName("X"));
+ EXPECT_TRUE(
+ matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
+ EXPECT_TRUE(
+ notMatches("class X {}; void y(X *x) { x; }",
+ expr(hasType(ClassX))));
+}
+
+TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
+ DeclarationMatcher ClassX = recordDecl(hasName("X"));
+ EXPECT_TRUE(
+ matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
+ EXPECT_TRUE(
+ notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
+}
+
+TEST(HasType, MatchesTypedefDecl) {
+ EXPECT_TRUE(matches("typedef int X;", typedefDecl(hasType(asString("int")))));
+ EXPECT_TRUE(matches("typedef const int T;",
+ typedefDecl(hasType(asString("const int")))));
+ EXPECT_TRUE(notMatches("typedef const int T;",
+ typedefDecl(hasType(asString("int")))));
+ EXPECT_TRUE(matches("typedef int foo; typedef foo bar;",
+ typedefDecl(hasType(asString("foo")), hasName("bar"))));
+}
+
+TEST(HasType, MatchesTypedefNameDecl) {
+ EXPECT_TRUE(matches("using X = int;", typedefNameDecl(hasType(asString("int")))));
+ EXPECT_TRUE(matches("using T = const int;",
+ typedefNameDecl(hasType(asString("const int")))));
+ EXPECT_TRUE(notMatches("using T = const int;",
+ typedefNameDecl(hasType(asString("int")))));
+ EXPECT_TRUE(matches("using foo = int; using bar = foo;",
+ typedefNameDecl(hasType(asString("foo")), hasName("bar"))));
+}
+
+TEST(HasTypeLoc, MatchesDeclaratorDecls) {
+ EXPECT_TRUE(matches("int x;",
+ varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
+
+ // Make sure we don't crash on implicit constructors.
+ EXPECT_TRUE(notMatches("class X {}; X x;",
+ declaratorDecl(hasTypeLoc(loc(asString("int"))))));
+}
+
+
+TEST(Callee, MatchesDeclarations) {
+ StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
+
+ EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
+ EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
+
+ CallMethodX = callExpr(callee(cxxConversionDecl()));
+ EXPECT_TRUE(
+ matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
+ EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
+ CallMethodX));
+}
+
+TEST(Callee, MatchesMemberExpressions) {
+ EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
+ callExpr(callee(memberExpr()))));
+ EXPECT_TRUE(
+ notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
+}
+
+TEST(Matcher, Argument) {
+ StatementMatcher CallArgumentY = callExpr(
+ hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
+
+ EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
+ EXPECT_TRUE(
+ matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
+ EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
+
+ StatementMatcher WrongIndex = callExpr(
+ hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
+ EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
+}
+
+TEST(Matcher, AnyArgument) {
+ StatementMatcher CallArgumentY = callExpr(
+ hasAnyArgument(
+ ignoringParenImpCasts(declRefExpr(to(varDecl(hasName("y")))))));
+ EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
+ EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
+ EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
+
+ StatementMatcher ImplicitCastedArgument = callExpr(
+ hasAnyArgument(implicitCastExpr()));
+ EXPECT_TRUE(matches("void x(long) { int y; x(y); }", ImplicitCastedArgument));
+}
+
+TEST(ForEachArgumentWithParam, ReportsNoFalsePositives) {
+ StatementMatcher ArgumentY =
+ declRefExpr(to(varDecl(hasName("y")))).bind("arg");
+ DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
+ StatementMatcher CallExpr =
+ callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
+
+ // IntParam does not match.
+ EXPECT_TRUE(notMatches("void f(int* i) { int* y; f(y); }", CallExpr));
+ // ArgumentY does not match.
+ EXPECT_TRUE(notMatches("void f(int i) { int x; f(x); }", CallExpr));
+}
+
+TEST(ForEachArgumentWithParam, MatchesCXXMemberCallExpr) {
+ StatementMatcher ArgumentY =
+ declRefExpr(to(varDecl(hasName("y")))).bind("arg");
+ DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
+ StatementMatcher CallExpr =
+ callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "struct S {"
+ " const S& operator[](int i) { return *this; }"
+ "};"
+ "void f(S S1) {"
+ " int y = 1;"
+ " S1[y];"
+ "}",
+ CallExpr, llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param", 1)));
+
+ StatementMatcher CallExpr2 =
+ callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "struct S {"
+ " static void g(int i);"
+ "};"
+ "void f() {"
+ " int y = 1;"
+ " S::g(y);"
+ "}",
+ CallExpr2, llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param", 1)));
+}
+
+TEST(ForEachArgumentWithParam, MatchesCallExpr) {
+ StatementMatcher ArgumentY =
+ declRefExpr(to(varDecl(hasName("y")))).bind("arg");
+ DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
+ StatementMatcher CallExpr =
+ callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
+
+ EXPECT_TRUE(
+ matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr,
+ llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>(
+ "param")));
+ EXPECT_TRUE(
+ matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr,
+ llvm::make_unique<VerifyIdIsBoundTo<DeclRefExpr>>(
+ "arg")));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void f(int i, int j) { int y; f(y, y); }", CallExpr,
+ llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param", 2)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void f(int i, int j) { int y; f(y, y); }", CallExpr,
+ llvm::make_unique<VerifyIdIsBoundTo<DeclRefExpr>>("arg", 2)));
+}
+
+TEST(ForEachArgumentWithParam, MatchesConstructExpr) {
+ StatementMatcher ArgumentY =
+ declRefExpr(to(varDecl(hasName("y")))).bind("arg");
+ DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
+ StatementMatcher ConstructExpr =
+ cxxConstructExpr(forEachArgumentWithParam(ArgumentY, IntParam));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "struct C {"
+ " C(int i) {}"
+ "};"
+ "int y = 0;"
+ "C Obj(y);",
+ ConstructExpr,
+ llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param")));
+}
+
+TEST(ForEachArgumentWithParam, HandlesBoundNodesForNonMatches) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void g(int i, int j) {"
+ " int a;"
+ " int b;"
+ " int c;"
+ " g(a, 0);"
+ " g(a, b);"
+ " g(0, b);"
+ "}",
+ functionDecl(
+ forEachDescendant(varDecl().bind("v")),
+ forEachDescendant(callExpr(forEachArgumentWithParam(
+ declRefExpr(to(decl(equalsBoundNode("v")))), parmVarDecl())))),
+ llvm::make_unique<VerifyIdIsBoundTo<VarDecl>>("v", 4)));
+}
+
+TEST(QualType, hasCanonicalType) {
+ EXPECT_TRUE(notMatches("typedef int &int_ref;"
+ "int a;"
+ "int_ref b = a;",
+ varDecl(hasType(qualType(referenceType())))));
+ EXPECT_TRUE(
+ matches("typedef int &int_ref;"
+ "int a;"
+ "int_ref b = a;",
+ varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
+}
+
+TEST(HasParameter, CallsInnerMatcher) {
+ EXPECT_TRUE(matches("class X { void x(int) {} };",
+ cxxMethodDecl(hasParameter(0, varDecl()))));
+ EXPECT_TRUE(notMatches("class X { void x(int) {} };",
+ cxxMethodDecl(hasParameter(0, hasName("x")))));
+}
+
+TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
+ EXPECT_TRUE(notMatches("class X { void x(int) {} };",
+ cxxMethodDecl(hasParameter(42, varDecl()))));
+}
+
+TEST(HasType, MatchesParameterVariableTypesStrictly) {
+ EXPECT_TRUE(matches(
+ "class X { void x(X x) {} };",
+ cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
+ EXPECT_TRUE(notMatches(
+ "class X { void x(const X &x) {} };",
+ cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
+ EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
+ cxxMethodDecl(hasParameter(
+ 0, hasType(pointsTo(recordDecl(hasName("X"))))))));
+ EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
+ cxxMethodDecl(hasParameter(
+ 0, hasType(references(recordDecl(hasName("X"))))))));
+}
+
+TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
+ EXPECT_TRUE(matches(
+ "class Y {}; class X { void x(X x, Y y) {} };",
+ cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
+ EXPECT_TRUE(matches(
+ "class Y {}; class X { void x(Y y, X x) {} };",
+ cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
+}
+
+TEST(Returns, MatchesReturnTypes) {
+ EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
+ functionDecl(returns(asString("int")))));
+ EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
+ functionDecl(returns(asString("float")))));
+ EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
+ functionDecl(returns(hasDeclaration(
+ recordDecl(hasName("Y")))))));
+}
+
+TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
+ EXPECT_TRUE(notMatches(
+ "class Y {}; class X { void x(int) {} };",
+ cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
+}
+
+TEST(HasAnyParameter, DoesNotMatchThisPointer) {
+ EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
+ cxxMethodDecl(hasAnyParameter(
+ hasType(pointsTo(recordDecl(hasName("X"))))))));
+}
+
+TEST(HasName, MatchesParameterVariableDeclarations) {
+ EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
+ cxxMethodDecl(hasAnyParameter(hasName("x")))));
+ EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
+ cxxMethodDecl(hasAnyParameter(hasName("x")))));
+}
+
+TEST(Matcher, MatchesTypeTemplateArgument) {
+ EXPECT_TRUE(matches(
+ "template<typename T> struct B {};"
+ "B<int> b;",
+ classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
+ asString("int"))))));
+}
+
+TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
+ EXPECT_TRUE(matches(
+ "struct B { int next; };"
+ "template<int(B::*next_ptr)> struct A {};"
+ "A<&B::next> a;",
+ classTemplateSpecializationDecl(hasAnyTemplateArgument(
+ refersToDeclaration(fieldDecl(hasName("next")))))));
+
+ EXPECT_TRUE(notMatches(
+ "template <typename T> struct A {};"
+ "A<int> a;",
+ classTemplateSpecializationDecl(hasAnyTemplateArgument(
+ refersToDeclaration(decl())))));
+
+ EXPECT_TRUE(matches(
+ "struct B { int next; };"
+ "template<int(B::*next_ptr)> struct A {};"
+ "A<&B::next> a;",
+ templateSpecializationType(hasAnyTemplateArgument(isExpr(
+ hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
+
+ EXPECT_TRUE(notMatches(
+ "template <typename T> struct A {};"
+ "A<int> a;",
+ templateSpecializationType(hasAnyTemplateArgument(
+ refersToDeclaration(decl())))));
+}
+
+
+TEST(Matcher, MatchesSpecificArgument) {
+ EXPECT_TRUE(matches(
+ "template<typename T, typename U> class A {};"
+ "A<bool, int> a;",
+ classTemplateSpecializationDecl(hasTemplateArgument(
+ 1, refersToType(asString("int"))))));
+ EXPECT_TRUE(notMatches(
+ "template<typename T, typename U> class A {};"
+ "A<int, bool> a;",
+ classTemplateSpecializationDecl(hasTemplateArgument(
+ 1, refersToType(asString("int"))))));
+
+ EXPECT_TRUE(matches(
+ "template<typename T, typename U> class A {};"
+ "A<bool, int> a;",
+ templateSpecializationType(hasTemplateArgument(
+ 1, refersToType(asString("int"))))));
+ EXPECT_TRUE(notMatches(
+ "template<typename T, typename U> class A {};"
+ "A<int, bool> a;",
+ templateSpecializationType(hasTemplateArgument(
+ 1, refersToType(asString("int"))))));
+}
+
+TEST(TemplateArgument, Matches) {
+ EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
+ classTemplateSpecializationDecl(
+ hasAnyTemplateArgument(templateArgument()))));
+ EXPECT_TRUE(matches(
+ "template<typename T> struct C {}; C<int> c;",
+ templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
+}
+
+TEST(RefersToIntegralType, Matches) {
+ EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
+ classTemplateSpecializationDecl(
+ hasAnyTemplateArgument(refersToIntegralType(
+ asString("int"))))));
+ EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
+ classTemplateSpecializationDecl(hasAnyTemplateArgument(
+ refersToIntegralType(asString("int"))))));
+}
+
+TEST(ConstructorDeclaration, SimpleCase) {
+ EXPECT_TRUE(matches("class Foo { Foo(int i); };",
+ cxxConstructorDecl(ofClass(hasName("Foo")))));
+ EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
+ cxxConstructorDecl(ofClass(hasName("Bar")))));
+}
+
+TEST(DestructorDeclaration, MatchesVirtualDestructor) {
+ EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
+ cxxDestructorDecl(ofClass(hasName("Foo")))));
+}
+
+TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
+ EXPECT_TRUE(notMatches("class Foo {};",
+ cxxDestructorDecl(ofClass(hasName("Foo")))));
+}
+
+TEST(HasAnyConstructorInitializer, SimpleCase) {
+ EXPECT_TRUE(
+ notMatches("class Foo { Foo() { } };",
+ cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
+ EXPECT_TRUE(
+ matches("class Foo {"
+ " Foo() : foo_() { }"
+ " int foo_;"
+ "};",
+ cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
+}
+
+TEST(HasAnyConstructorInitializer, ForField) {
+ static const char Code[] =
+ "class Baz { };"
+ "class Foo {"
+ " Foo() : foo_() { }"
+ " Baz foo_;"
+ " Baz bar_;"
+ "};";
+ EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
+ forField(hasType(recordDecl(hasName("Baz"))))))));
+ EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
+ forField(hasName("foo_"))))));
+ EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
+ forField(hasType(recordDecl(hasName("Bar"))))))));
+}
+
+TEST(HasAnyConstructorInitializer, WithInitializer) {
+ static const char Code[] =
+ "class Foo {"
+ " Foo() : foo_(0) { }"
+ " int foo_;"
+ "};";
+ EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
+ withInitializer(integerLiteral(equals(0)))))));
+ EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
+ withInitializer(integerLiteral(equals(1)))))));
+}
+
+TEST(HasAnyConstructorInitializer, IsWritten) {
+ static const char Code[] =
+ "struct Bar { Bar(){} };"
+ "class Foo {"
+ " Foo() : foo_() { }"
+ " Bar foo_;"
+ " Bar bar_;"
+ "};";
+ EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
+ allOf(forField(hasName("foo_")), isWritten())))));
+ EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
+ allOf(forField(hasName("bar_")), isWritten())))));
+ EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
+ allOf(forField(hasName("bar_")), unless(isWritten()))))));
+}
+
+TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
+ static const char Code[] =
+ "struct B {};"
+ "struct D : B {"
+ " int I;"
+ " D(int i) : I(i) {}"
+ "};"
+ "struct E : B {"
+ " E() : B() {}"
+ "};";
+ EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
+ hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
+ hasName("E")))));
+ EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
+ hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
+ hasName("D")))));
+ EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
+ hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
+ hasName("D")))));
+ EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
+ hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
+ hasName("E")))));
+}
+
+TEST(IfStmt, ChildTraversalMatchers) {
+ EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
+ ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
+ EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
+ ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
+ EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
+ ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
+ EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
+ ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
+}
+
+TEST(MatchBinaryOperator, HasOperatorName) {
+ StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
+
+ EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
+ EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
+}
+
+TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
+ StatementMatcher OperatorTrueFalse =
+ binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
+ hasRHS(cxxBoolLiteral(equals(false))));
+
+ EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
+ EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
+ EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
+
+ StatementMatcher OperatorIntPointer = arraySubscriptExpr(
+ hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
+ EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
+ EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
+}
+
+TEST(MatchBinaryOperator, HasEitherOperand) {
+ StatementMatcher HasOperand =
+ binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
+
+ EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
+ EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
+ EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
+}
+
+TEST(Matcher, BinaryOperatorTypes) {
+ // Integration test that verifies the AST provides all binary operators in
+ // a way we expect.
+ // FIXME: Operator ','
+ EXPECT_TRUE(
+ matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
+ EXPECT_TRUE(
+ matches("bool b; bool c = (b = true);",
+ binaryOperator(hasOperatorName("="))));
+ EXPECT_TRUE(
+ matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
+ EXPECT_TRUE(
+ matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
+ EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
+ EXPECT_TRUE(
+ matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
+ EXPECT_TRUE(
+ matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
+ EXPECT_TRUE(
+ matches("int i = 1; int j = (i <<= 2);",
+ binaryOperator(hasOperatorName("<<="))));
+ EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
+ EXPECT_TRUE(
+ matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
+ EXPECT_TRUE(
+ matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
+ EXPECT_TRUE(
+ matches("int i = 1; int j = (i >>= 2);",
+ binaryOperator(hasOperatorName(">>="))));
+ EXPECT_TRUE(
+ matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
+ EXPECT_TRUE(
+ matches("int i = 42; int j = (i ^= 42);",
+ binaryOperator(hasOperatorName("^="))));
+ EXPECT_TRUE(
+ matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
+ EXPECT_TRUE(
+ matches("int i = 42; int j = (i %= 42);",
+ binaryOperator(hasOperatorName("%="))));
+ EXPECT_TRUE(
+ matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
+ EXPECT_TRUE(
+ matches("bool b = true && false;",
+ binaryOperator(hasOperatorName("&&"))));
+ EXPECT_TRUE(
+ matches("bool b = true; bool c = (b &= false);",
+ binaryOperator(hasOperatorName("&="))));
+ EXPECT_TRUE(
+ matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
+ EXPECT_TRUE(
+ matches("bool b = true || false;",
+ binaryOperator(hasOperatorName("||"))));
+ EXPECT_TRUE(
+ matches("bool b = true; bool c = (b |= false);",
+ binaryOperator(hasOperatorName("|="))));
+ EXPECT_TRUE(
+ matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
+ EXPECT_TRUE(
+ matches("int i = 42; int j = (i *= 23);",
+ binaryOperator(hasOperatorName("*="))));
+ EXPECT_TRUE(
+ matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
+ EXPECT_TRUE(
+ matches("int i = 42; int j = (i /= 23);",
+ binaryOperator(hasOperatorName("/="))));
+ EXPECT_TRUE(
+ matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
+ EXPECT_TRUE(
+ matches("int i = 42; int j = (i += 23);",
+ binaryOperator(hasOperatorName("+="))));
+ EXPECT_TRUE(
+ matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
+ EXPECT_TRUE(
+ matches("int i = 42; int j = (i -= 23);",
+ binaryOperator(hasOperatorName("-="))));
+ EXPECT_TRUE(
+ matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
+ binaryOperator(hasOperatorName("->*"))));
+ EXPECT_TRUE(
+ matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
+ binaryOperator(hasOperatorName(".*"))));
+
+ // Member expressions as operators are not supported in matches.
+ EXPECT_TRUE(
+ notMatches("struct A { void x(A *a) { a->x(this); } };",
+ binaryOperator(hasOperatorName("->"))));
+
+ // Initializer assignments are not represented as operator equals.
+ EXPECT_TRUE(
+ notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
+
+ // Array indexing is not represented as operator.
+ EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
+
+ // Overloaded operators do not match at all.
+ EXPECT_TRUE(notMatches(
+ "struct A { bool operator&&(const A &a) const { return false; } };"
+ "void x() { A a, b; a && b; }",
+ binaryOperator()));
+}
+
+TEST(MatchUnaryOperator, HasOperatorName) {
+ StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
+
+ EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
+ EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
+}
+
+TEST(MatchUnaryOperator, HasUnaryOperand) {
+ StatementMatcher OperatorOnFalse =
+ unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
+
+ EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
+ EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
+}
+
+TEST(Matcher, UnaryOperatorTypes) {
+ // Integration test that verifies the AST provides all unary operators in
+ // a way we expect.
+ EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
+ EXPECT_TRUE(
+ matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
+ EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
+ EXPECT_TRUE(
+ matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
+ EXPECT_TRUE(
+ matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
+ EXPECT_TRUE(
+ matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
+ EXPECT_TRUE(
+ matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
+ EXPECT_TRUE(
+ matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
+ EXPECT_TRUE(
+ matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
+ EXPECT_TRUE(
+ matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
+
+ // We don't match conversion operators.
+ EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
+
+ // Function calls are not represented as operator.
+ EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
+
+ // Overloaded operators do not match at all.
+ // FIXME: We probably want to add that.
+ EXPECT_TRUE(notMatches(
+ "struct A { bool operator!() const { return false; } };"
+ "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
+}
+
+TEST(ArraySubscriptMatchers, ArrayIndex) {
+ EXPECT_TRUE(matches(
+ "int i[2]; void f() { i[1] = 1; }",
+ arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
+ EXPECT_TRUE(matches(
+ "int i[2]; void f() { 1[i] = 1; }",
+ arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
+ EXPECT_TRUE(notMatches(
+ "int i[2]; void f() { i[1] = 1; }",
+ arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
+}
+
+TEST(ArraySubscriptMatchers, MatchesArrayBase) {
+ EXPECT_TRUE(matches(
+ "int i[2]; void f() { i[1] = 2; }",
+ arraySubscriptExpr(hasBase(implicitCastExpr(
+ hasSourceExpression(declRefExpr()))))));
+}
+
+TEST(Matcher, OfClass) {
+ StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
+ ofClass(hasName("X")))));
+
+ EXPECT_TRUE(
+ matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
+ EXPECT_TRUE(
+ matches("class X { public: X(); }; void x(int) { X x = X(); }",
+ Constructor));
+ EXPECT_TRUE(
+ notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
+ Constructor));
+}
+
+TEST(Matcher, VisitsTemplateInstantiations) {
+ EXPECT_TRUE(matches(
+ "class A { public: void x(); };"
+ "template <typename T> class B { public: void y() { T t; t.x(); } };"
+ "void f() { B<A> b; b.y(); }",
+ callExpr(callee(cxxMethodDecl(hasName("x"))))));
+
+ EXPECT_TRUE(matches(
+ "class A { public: void x(); };"
+ "class C {"
+ " public:"
+ " template <typename T> class B { public: void y() { T t; t.x(); } };"
+ "};"
+ "void f() {"
+ " C::B<A> b; b.y();"
+ "}",
+ recordDecl(hasName("C"), hasDescendant(callExpr(
+ callee(cxxMethodDecl(hasName("x"))))))));
+}
+
+TEST(Matcher, HasCondition) {
+ StatementMatcher IfStmt =
+ ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
+ EXPECT_TRUE(matches("void x() { if (true) {} }", IfStmt));
+ EXPECT_TRUE(notMatches("void x() { if (false) {} }", IfStmt));
+
+ StatementMatcher ForStmt =
+ forStmt(hasCondition(cxxBoolLiteral(equals(true))));
+ EXPECT_TRUE(matches("void x() { for (;true;) {} }", ForStmt));
+ EXPECT_TRUE(notMatches("void x() { for (;false;) {} }", ForStmt));
+
+ StatementMatcher WhileStmt =
+ whileStmt(hasCondition(cxxBoolLiteral(equals(true))));
+ EXPECT_TRUE(matches("void x() { while (true) {} }", WhileStmt));
+ EXPECT_TRUE(notMatches("void x() { while (false) {} }", WhileStmt));
+
+ StatementMatcher SwitchStmt =
+ switchStmt(hasCondition(integerLiteral(equals(42))));
+ EXPECT_TRUE(matches("void x() { switch (42) {case 42:;} }", SwitchStmt));
+ EXPECT_TRUE(notMatches("void x() { switch (43) {case 43:;} }", SwitchStmt));
+}
+
+TEST(For, ForLoopInternals) {
+ EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
+ forStmt(hasCondition(anything()))));
+ EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
+ forStmt(hasLoopInit(anything()))));
+}
+
+TEST(For, ForRangeLoopInternals) {
+ EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
+ cxxForRangeStmt(hasLoopVariable(anything()))));
+ EXPECT_TRUE(matches(
+ "void f(){ int a[] {1, 2}; for (int i : a); }",
+ cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
+}
+
+TEST(For, NegativeForLoopInternals) {
+ EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
+ forStmt(hasCondition(expr()))));
+ EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
+ forStmt(hasLoopInit(anything()))));
+}
+
+TEST(HasBody, FindsBodyOfForWhileDoLoops) {
+ EXPECT_TRUE(matches("void f() { for(;;) {} }",
+ forStmt(hasBody(compoundStmt()))));
+ EXPECT_TRUE(notMatches("void f() { for(;;); }",
+ forStmt(hasBody(compoundStmt()))));
+ EXPECT_TRUE(matches("void f() { while(true) {} }",
+ whileStmt(hasBody(compoundStmt()))));
+ EXPECT_TRUE(matches("void f() { do {} while(true); }",
+ doStmt(hasBody(compoundStmt()))));
+ EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
+ cxxForRangeStmt(hasBody(compoundStmt()))));
+ EXPECT_TRUE(matches("void f() {}", functionDecl(hasBody(compoundStmt()))));
+ EXPECT_TRUE(notMatches("void f();", functionDecl(hasBody(compoundStmt()))));
+ EXPECT_TRUE(matches("void f(); void f() {}",
+ functionDecl(hasBody(compoundStmt()))));
+}
+
+TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
+ // The simplest case: every compound statement is in a function
+ // definition, and the function body itself must be a compound
+ // statement.
+ EXPECT_TRUE(matches("void f() { for (;;); }",
+ compoundStmt(hasAnySubstatement(forStmt()))));
+}
+
+TEST(HasAnySubstatement, IsNotRecursive) {
+ // It's really "has any immediate substatement".
+ EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
+ compoundStmt(hasAnySubstatement(forStmt()))));
+}
+
+TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
+ EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
+ compoundStmt(hasAnySubstatement(forStmt()))));
+}
+
+TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
+ EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
+ compoundStmt(hasAnySubstatement(forStmt()))));
+}
+
+TEST(Member, MatchesMemberAllocationFunction) {
+ // Fails in C++11 mode
+ EXPECT_TRUE(matchesConditionally(
+ "namespace std { typedef typeof(sizeof(int)) size_t; }"
+ "class X { void *operator new(std::size_t); };",
+ cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
+
+ EXPECT_TRUE(matches("class X { void operator delete(void*); };",
+ cxxMethodDecl(ofClass(hasName("X")))));
+
+ // Fails in C++11 mode
+ EXPECT_TRUE(matchesConditionally(
+ "namespace std { typedef typeof(sizeof(int)) size_t; }"
+ "class X { void operator delete[](void*, std::size_t); };",
+ cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
+}
+
+TEST(HasDestinationType, MatchesSimpleCase) {
+ EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
+ cxxStaticCastExpr(hasDestinationType(
+ pointsTo(TypeMatcher(anything()))))));
+}
+
+TEST(HasImplicitDestinationType, MatchesSimpleCase) {
+ // This test creates an implicit const cast.
+ EXPECT_TRUE(matches("int x; const int i = x;",
+ implicitCastExpr(
+ hasImplicitDestinationType(isInteger()))));
+ // This test creates an implicit array-to-pointer cast.
+ EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
+ implicitCastExpr(hasImplicitDestinationType(
+ pointsTo(TypeMatcher(anything()))))));
+}
+
+TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
+ // This test creates an implicit cast from int to char.
+ EXPECT_TRUE(notMatches("char c = 0;",
+ implicitCastExpr(hasImplicitDestinationType(
+ unless(anything())))));
+ // This test creates an implicit array-to-pointer cast.
+ EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
+ implicitCastExpr(hasImplicitDestinationType(
+ unless(anything())))));
+}
+
+TEST(IgnoringImplicit, MatchesImplicit) {
+ EXPECT_TRUE(matches("class C {}; C a = C();",
+ varDecl(has(ignoringImplicit(cxxConstructExpr())))));
+}
+
+TEST(IgnoringImplicit, DoesNotMatchIncorrectly) {
+ EXPECT_TRUE(
+ notMatches("class C {}; C a = C();", varDecl(has(cxxConstructExpr()))));
+}
+
+TEST(IgnoringImpCasts, MatchesImpCasts) {
+ // This test checks that ignoringImpCasts matches when implicit casts are
+ // present and its inner matcher alone does not match.
+ // Note that this test creates an implicit const cast.
+ EXPECT_TRUE(matches("int x = 0; const int y = x;",
+ varDecl(hasInitializer(ignoringImpCasts(
+ declRefExpr(to(varDecl(hasName("x")))))))));
+ // This test creates an implict cast from int to char.
+ EXPECT_TRUE(matches("char x = 0;",
+ varDecl(hasInitializer(ignoringImpCasts(
+ integerLiteral(equals(0)))))));
+}
+
+TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
+ // These tests verify that ignoringImpCasts does not match if the inner
+ // matcher does not match.
+ // Note that the first test creates an implicit const cast.
+ EXPECT_TRUE(notMatches("int x; const int y = x;",
+ varDecl(hasInitializer(ignoringImpCasts(
+ unless(anything()))))));
+ EXPECT_TRUE(notMatches("int x; int y = x;",
+ varDecl(hasInitializer(ignoringImpCasts(
+ unless(anything()))))));
+
+ // These tests verify that ignoringImplictCasts does not look through explicit
+ // casts or parentheses.
+ EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
+ varDecl(hasInitializer(ignoringImpCasts(
+ integerLiteral())))));
+ EXPECT_TRUE(notMatches("int i = (0);",
+ varDecl(hasInitializer(ignoringImpCasts(
+ integerLiteral())))));
+ EXPECT_TRUE(notMatches("float i = (float)0;",
+ varDecl(hasInitializer(ignoringImpCasts(
+ integerLiteral())))));
+ EXPECT_TRUE(notMatches("float i = float(0);",
+ varDecl(hasInitializer(ignoringImpCasts(
+ integerLiteral())))));
+}
+
+TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
+ // This test verifies that expressions that do not have implicit casts
+ // still match the inner matcher.
+ EXPECT_TRUE(matches("int x = 0; int &y = x;",
+ varDecl(hasInitializer(ignoringImpCasts(
+ declRefExpr(to(varDecl(hasName("x")))))))));
+}
+
+TEST(IgnoringParenCasts, MatchesParenCasts) {
+ // This test checks that ignoringParenCasts matches when parentheses and/or
+ // casts are present and its inner matcher alone does not match.
+ EXPECT_TRUE(matches("int x = (0);",
+ varDecl(hasInitializer(ignoringParenCasts(
+ integerLiteral(equals(0)))))));
+ EXPECT_TRUE(matches("int x = (((((0)))));",
+ varDecl(hasInitializer(ignoringParenCasts(
+ integerLiteral(equals(0)))))));
+
+ // This test creates an implict cast from int to char in addition to the
+ // parentheses.
+ EXPECT_TRUE(matches("char x = (0);",
+ varDecl(hasInitializer(ignoringParenCasts(
+ integerLiteral(equals(0)))))));
+
+ EXPECT_TRUE(matches("char x = (char)0;",
+ varDecl(hasInitializer(ignoringParenCasts(
+ integerLiteral(equals(0)))))));
+ EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
+ varDecl(hasInitializer(ignoringParenCasts(
+ integerLiteral(equals(0)))))));
+}
+
+TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
+ // This test verifies that expressions that do not have any casts still match.
+ EXPECT_TRUE(matches("int x = 0;",
+ varDecl(hasInitializer(ignoringParenCasts(
+ integerLiteral(equals(0)))))));
+}
+
+TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
+ // These tests verify that ignoringImpCasts does not match if the inner
+ // matcher does not match.
+ EXPECT_TRUE(notMatches("int x = ((0));",
+ varDecl(hasInitializer(ignoringParenCasts(
+ unless(anything()))))));
+
+ // This test creates an implicit cast from int to char in addition to the
+ // parentheses.
+ EXPECT_TRUE(notMatches("char x = ((0));",
+ varDecl(hasInitializer(ignoringParenCasts(
+ unless(anything()))))));
+
+ EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
+ varDecl(hasInitializer(ignoringParenCasts(
+ unless(anything()))))));
+}
+
+TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
+ // This test checks that ignoringParenAndImpCasts matches when
+ // parentheses and/or implicit casts are present and its inner matcher alone
+ // does not match.
+ // Note that this test creates an implicit const cast.
+ EXPECT_TRUE(matches("int x = 0; const int y = x;",
+ varDecl(hasInitializer(ignoringParenImpCasts(
+ declRefExpr(to(varDecl(hasName("x")))))))));
+ // This test creates an implicit cast from int to char.
+ EXPECT_TRUE(matches("const char x = (0);",
+ varDecl(hasInitializer(ignoringParenImpCasts(
+ integerLiteral(equals(0)))))));
+}
+
+TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
+ // This test verifies that expressions that do not have parentheses or
+ // implicit casts still match.
+ EXPECT_TRUE(matches("int x = 0; int &y = x;",
+ varDecl(hasInitializer(ignoringParenImpCasts(
+ declRefExpr(to(varDecl(hasName("x")))))))));
+ EXPECT_TRUE(matches("int x = 0;",
+ varDecl(hasInitializer(ignoringParenImpCasts(
+ integerLiteral(equals(0)))))));
+}
+
+TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
+ // These tests verify that ignoringParenImpCasts does not match if
+ // the inner matcher does not match.
+ // This test creates an implicit cast.
+ EXPECT_TRUE(notMatches("char c = ((3));",
+ varDecl(hasInitializer(ignoringParenImpCasts(
+ unless(anything()))))));
+ // These tests verify that ignoringParenAndImplictCasts does not look
+ // through explicit casts.
+ EXPECT_TRUE(notMatches("float y = (float(0));",
+ varDecl(hasInitializer(ignoringParenImpCasts(
+ integerLiteral())))));
+ EXPECT_TRUE(notMatches("float y = (float)0;",
+ varDecl(hasInitializer(ignoringParenImpCasts(
+ integerLiteral())))));
+ EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
+ varDecl(hasInitializer(ignoringParenImpCasts(
+ integerLiteral())))));
+}
+
+TEST(HasSourceExpression, MatchesImplicitCasts) {
+ EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
+ "void r() {string a_string; URL url = a_string; }",
+ implicitCastExpr(
+ hasSourceExpression(cxxConstructExpr()))));
+}
+
+TEST(HasSourceExpression, MatchesExplicitCasts) {
+ EXPECT_TRUE(matches("float x = static_cast<float>(42);",
+ explicitCastExpr(
+ hasSourceExpression(hasDescendant(
+ expr(integerLiteral()))))));
+}
+
+TEST(UsingDeclaration, MatchesSpecificTarget) {
+ EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
+ usingDecl(hasAnyUsingShadowDecl(
+ hasTargetDecl(functionDecl())))));
+ EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
+ usingDecl(hasAnyUsingShadowDecl(
+ hasTargetDecl(functionDecl())))));
+}
+
+TEST(UsingDeclaration, ThroughUsingDeclaration) {
+ EXPECT_TRUE(matches(
+ "namespace a { void f(); } using a::f; void g() { f(); }",
+ declRefExpr(throughUsingDecl(anything()))));
+ EXPECT_TRUE(notMatches(
+ "namespace a { void f(); } using a::f; void g() { a::f(); }",
+ declRefExpr(throughUsingDecl(anything()))));
+}
+
+TEST(SingleDecl, IsSingleDecl) {
+ StatementMatcher SingleDeclStmt =
+ declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
+ EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
+ EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
+ EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
+ SingleDeclStmt));
+}
+
+TEST(DeclStmt, ContainsDeclaration) {
+ DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
+
+ EXPECT_TRUE(matches("void f() {int a = 4;}",
+ declStmt(containsDeclaration(0, MatchesInit))));
+ EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
+ declStmt(containsDeclaration(0, MatchesInit),
+ containsDeclaration(1, MatchesInit))));
+ unsigned WrongIndex = 42;
+ EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
+ declStmt(containsDeclaration(WrongIndex,
+ MatchesInit))));
+}
+
+TEST(SwitchCase, MatchesEachCase) {
+ EXPECT_TRUE(notMatches("void x() { switch(42); }",
+ switchStmt(forEachSwitchCase(caseStmt()))));
+ EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
+ switchStmt(forEachSwitchCase(caseStmt()))));
+ EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
+ switchStmt(forEachSwitchCase(caseStmt()))));
+ EXPECT_TRUE(notMatches(
+ "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
+ ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
+ EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
+ switchStmt(forEachSwitchCase(
+ caseStmt(hasCaseConstant(integerLiteral()))))));
+ EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
+ switchStmt(forEachSwitchCase(
+ caseStmt(hasCaseConstant(integerLiteral()))))));
+ EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
+ switchStmt(forEachSwitchCase(
+ caseStmt(hasCaseConstant(integerLiteral()))))));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
+ switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
+ llvm::make_unique<VerifyIdIsBoundTo<CaseStmt>>("x", 3)));
+}
+
+TEST(ForEachConstructorInitializer, MatchesInitializers) {
+ EXPECT_TRUE(matches(
+ "struct X { X() : i(42), j(42) {} int i, j; };",
+ cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer()))));
+}
+
+TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
+ EXPECT_TRUE(notMatches(
+ "void x() { if(true) {} }",
+ ifStmt(hasConditionVariableStatement(declStmt()))));
+ EXPECT_TRUE(notMatches(
+ "void x() { int x; if((x = 42)) {} }",
+ ifStmt(hasConditionVariableStatement(declStmt()))));
+}
+
+TEST(HasConditionVariableStatement, MatchesConditionVariables) {
+ EXPECT_TRUE(matches(
+ "void x() { if(int* a = 0) {} }",
+ ifStmt(hasConditionVariableStatement(declStmt()))));
+}
+
+TEST(ForEach, BindsOneNode) {
+ EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
+ recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("x", 1)));
+}
+
+TEST(ForEach, BindsMultipleNodes) {
+ EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
+ recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f", 3)));
+}
+
+TEST(ForEach, BindsRecursiveCombinations) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class C { class D { int x; int y; }; class E { int y; int z; }; };",
+ recordDecl(hasName("C"),
+ forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f", 4)));
+}
+
+TEST(ForEachDescendant, BindsOneNode) {
+ EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
+ recordDecl(hasName("C"),
+ forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("x", 1)));
+}
+
+TEST(ForEachDescendant, NestedForEachDescendant) {
+ DeclarationMatcher m = recordDecl(
+ isDefinition(), decl().bind("x"), hasName("C"));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { class B { class C {}; }; };",
+ recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", "C")));
+
+ // Check that a partial match of 'm' that binds 'x' in the
+ // first part of anyOf(m, anything()) will not overwrite the
+ // binding created by the earlier binding in the hasDescendant.
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { class B { class C {}; }; };",
+ recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", "C")));
+}
+
+TEST(ForEachDescendant, BindsMultipleNodes) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class C { class D { int x; int y; }; "
+ " class E { class F { int y; int z; }; }; };",
+ recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f", 4)));
+}
+
+TEST(ForEachDescendant, BindsRecursiveCombinations) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class C { class D { "
+ " class E { class F { class G { int y; int z; }; }; }; }; };",
+ recordDecl(hasName("C"), forEachDescendant(recordDecl(
+ forEachDescendant(fieldDecl().bind("f"))))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f", 8)));
+}
+
+TEST(ForEachDescendant, BindsCombinations) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
+ "(true) {} }",
+ compoundStmt(forEachDescendant(ifStmt().bind("if")),
+ forEachDescendant(whileStmt().bind("while"))),
+ llvm::make_unique<VerifyIdIsBoundTo<IfStmt>>("if", 6)));
+}
+
+TEST(Has, DoesNotDeleteBindings) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+}
+
+TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
+ // Those matchers cover all the cases where an inner matcher is called
+ // and there is not a 1:1 relationship between the match of the outer
+ // matcher and the match of the inner matcher.
+ // The pattern to look for is:
+ // ... return InnerMatcher.matches(...); ...
+ // In which case no special handling is needed.
+ //
+ // On the other hand, if there are multiple alternative matches
+ // (for example forEach*) or matches might be discarded (for example has*)
+ // the implementation must make sure that the discarded matches do not
+ // affect the bindings.
+ // When new such matchers are added, add a test here that:
+ // - matches a simple node, and binds it as the first thing in the matcher:
+ // recordDecl(decl().bind("x"), hasName("X")))
+ // - uses the matcher under test afterwards in a way that not the first
+ // alternative is matched; for anyOf, that means the first branch
+ // would need to return false; for hasAncestor, it means that not
+ // the direct parent matches the inner matcher.
+
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X { int y; };",
+ recordDecl(
+ recordDecl().bind("x"), hasName("::X"),
+ anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
+ anyOf(unless(anything()), anything())),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "template<typename T1, typename T2> class X {}; X<float, int> x;",
+ classTemplateSpecializationDecl(
+ decl().bind("x"),
+ hasAnyTemplateArgument(refersToType(asString("int")))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X { void f(); void g(); };",
+ cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X { X() : a(1), b(2) {} double a; int b; };",
+ recordDecl(decl().bind("x"),
+ has(cxxConstructorDecl(
+ hasAnyConstructorInitializer(forField(hasName("b")))))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void x(int, int) { x(0, 42); }",
+ callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
+ llvm::make_unique<VerifyIdIsBoundTo<Expr>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void x(int, int y) {}",
+ functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void x() { return; if (true) {} }",
+ functionDecl(decl().bind("x"),
+ has(compoundStmt(hasAnySubstatement(ifStmt())))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "namespace X { void b(int); void b(); }"
+ "using X::b;",
+ usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
+ functionDecl(parameterCountIs(1))))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A{}; class B{}; class C : B, A {};",
+ cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A{}; typedef A B; typedef A C; typedef A D;"
+ "class E : A {};",
+ cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { class B { void f() {} }; };",
+ functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "template <typename T> struct A { struct B {"
+ " void f() { if(true) {} }"
+ "}; };"
+ "void t() { A<int>::B b; b.f(); }",
+ ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
+ llvm::make_unique<VerifyIdIsBoundTo<Stmt>>("x", 2)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A {};",
+ recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { A() : s(), i(42) {} const char *s; int i; };",
+ cxxConstructorDecl(hasName("::A::A"), decl().bind("x"),
+ forEachConstructorInitializer(forField(hasName("i")))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1)));
+}
+
+TEST(ForEachDescendant, BindsCorrectNodes) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class C { void f(); int i; };",
+ recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("decl", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class C { void f() {} int i; };",
+ recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
+ llvm::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("decl", 1)));
+}
+
+TEST(FindAll, BindsNodeOnMatch) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A {};",
+ recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("v", 1)));
+}
+
+TEST(FindAll, BindsDescendantNodeOnMatch) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { int a; int b; };",
+ recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
+ llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 2)));
+}
+
+TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { int a; int b; };",
+ recordDecl(hasName("::A"),
+ findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
+ fieldDecl().bind("v"))))),
+ llvm::make_unique<VerifyIdIsBoundTo<Decl>>("v", 3)));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class A { class B {}; class C {}; };",
+ recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("v", 3)));
+}
+
+TEST(HasAncenstor, MatchesDeclarationAncestors) {
+ EXPECT_TRUE(matches(
+ "class A { class B { class C {}; }; };",
+ recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
+}
+
+TEST(HasAncenstor, FailsIfNoAncestorMatches) {
+ EXPECT_TRUE(notMatches(
+ "class A { class B { class C {}; }; };",
+ recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
+}
+
+TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
+ EXPECT_TRUE(matches(
+ "class A { class B { void f() { C c; } class C {}; }; };",
+ varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
+ hasAncestor(recordDecl(hasName("A"))))))));
+}
+
+TEST(HasAncenstor, MatchesStatementAncestors) {
+ EXPECT_TRUE(matches(
+ "void f() { if (true) { while (false) { 42; } } }",
+ integerLiteral(equals(42), hasAncestor(ifStmt()))));
+}
+
+TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
+ EXPECT_TRUE(matches(
+ "void f() { if (true) { int x = 42; } }",
+ integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
+}
+
+TEST(HasAncestor, BindsRecursiveCombinations) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class C { class D { class E { class F { int y; }; }; }; };",
+ fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("r", 1)));
+}
+
+TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class C { class D { class E { class F { int y; }; }; }; };",
+ fieldDecl(hasAncestor(
+ decl(
+ hasDescendant(recordDecl(isDefinition(),
+ hasAncestor(recordDecl())))
+ ).bind("d")
+ )),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("d", "E")));
+}
+
+TEST(HasAncestor, MatchesClosestAncestor) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "template <typename T> struct C {"
+ " void f(int) {"
+ " struct I { void g(T) { int x; } } i; i.g(42);"
+ " }"
+ "};"
+ "template struct C<int>;",
+ varDecl(hasName("x"),
+ hasAncestor(functionDecl(hasParameter(
+ 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
+ llvm::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("f", "g", 2)));
+}
+
+TEST(HasAncestor, MatchesInTemplateInstantiations) {
+ EXPECT_TRUE(matches(
+ "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
+ "A<int>::B::C a;",
+ fieldDecl(hasType(asString("int")),
+ hasAncestor(recordDecl(hasName("A"))))));
+}
+
+TEST(HasAncestor, MatchesInImplicitCode) {
+ EXPECT_TRUE(matches(
+ "struct X {}; struct A { A() {} X x; };",
+ cxxConstructorDecl(
+ hasAnyConstructorInitializer(withInitializer(expr(
+ hasAncestor(recordDecl(hasName("A")))))))));
+}
+
+TEST(HasParent, MatchesOnlyParent) {
+ EXPECT_TRUE(matches(
+ "void f() { if (true) { int x = 42; } }",
+ compoundStmt(hasParent(ifStmt()))));
+ EXPECT_TRUE(notMatches(
+ "void f() { for (;;) { int x = 42; } }",
+ compoundStmt(hasParent(ifStmt()))));
+ EXPECT_TRUE(notMatches(
+ "void f() { if (true) for (;;) { int x = 42; } }",
+ compoundStmt(hasParent(ifStmt()))));
+}
+
+TEST(HasAncestor, MatchesAllAncestors) {
+ EXPECT_TRUE(matches(
+ "template <typename T> struct C { static void f() { 42; } };"
+ "void t() { C<int>::f(); }",
+ integerLiteral(
+ equals(42),
+ allOf(
+ hasAncestor(cxxRecordDecl(isTemplateInstantiation())),
+ hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation())))))));
+}
+
+TEST(HasAncestor, ImplicitArrayCopyCtorDeclRefExpr) {
+ EXPECT_TRUE(matches("struct MyClass {\n"
+ " int c[1];\n"
+ " static MyClass Create() { return MyClass(); }\n"
+ "};",
+ declRefExpr(to(decl(hasAncestor(decl()))))));
+}
+
+TEST(HasAncestor, AnonymousUnionMemberExpr) {
+ EXPECT_TRUE(matches("int F() {\n"
+ " union { int i; };\n"
+ " return i;\n"
+ "}\n",
+ memberExpr(member(hasAncestor(decl())))));
+ EXPECT_TRUE(matches("void f() {\n"
+ " struct {\n"
+ " struct { int a; int b; };\n"
+ " } s;\n"
+ " s.a = 4;\n"
+ "}\n",
+ memberExpr(member(hasAncestor(decl())))));
+ EXPECT_TRUE(matches("void f() {\n"
+ " struct {\n"
+ " struct { int a; int b; };\n"
+ " } s;\n"
+ " s.a = 4;\n"
+ "}\n",
+ declRefExpr(to(decl(hasAncestor(decl()))))));
+}
+TEST(HasAncestor, NonParmDependentTemplateParmVarDeclRefExpr) {
+ EXPECT_TRUE(matches("struct PartitionAllocator {\n"
+ " template<typename T>\n"
+ " static int quantizedSize(int count) {\n"
+ " return count;\n"
+ " }\n"
+ " void f() { quantizedSize<int>(10); }\n"
+ "};",
+ declRefExpr(to(decl(hasAncestor(decl()))))));
+}
+
+TEST(HasAncestor, AddressOfExplicitSpecializationFunction) {
+ EXPECT_TRUE(matches("template <class T> void f();\n"
+ "template <> void f<int>();\n"
+ "void (*get_f())() { return f<int>; }\n",
+ declRefExpr(to(decl(hasAncestor(decl()))))));
+}
+
+TEST(HasParent, MatchesAllParents) {
+ EXPECT_TRUE(matches(
+ "template <typename T> struct C { static void f() { 42; } };"
+ "void t() { C<int>::f(); }",
+ integerLiteral(
+ equals(42),
+ hasParent(compoundStmt(hasParent(functionDecl(
+ hasParent(cxxRecordDecl(isTemplateInstantiation())))))))));
+ EXPECT_TRUE(
+ matches("template <typename T> struct C { static void f() { 42; } };"
+ "void t() { C<int>::f(); }",
+ integerLiteral(
+ equals(42),
+ hasParent(compoundStmt(hasParent(functionDecl(hasParent(
+ cxxRecordDecl(unless(isTemplateInstantiation()))))))))));
+ EXPECT_TRUE(matches(
+ "template <typename T> struct C { static void f() { 42; } };"
+ "void t() { C<int>::f(); }",
+ integerLiteral(equals(42),
+ hasParent(compoundStmt(
+ allOf(hasParent(functionDecl(hasParent(
+ cxxRecordDecl(isTemplateInstantiation())))),
+ hasParent(functionDecl(hasParent(cxxRecordDecl(
+ unless(isTemplateInstantiation())))))))))));
+ EXPECT_TRUE(
+ notMatches("template <typename T> struct C { static void f() {} };"
+ "void t() { C<int>::f(); }",
+ compoundStmt(hasParent(recordDecl()))));
+}
+
+TEST(HasParent, NoDuplicateParents) {
+ class HasDuplicateParents : public BoundNodesCallback {
+ public:
+ bool run(const BoundNodes *Nodes) override { return false; }
+ bool run(const BoundNodes *Nodes, ASTContext *Context) override {
+ const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
+ std::set<const void *> Parents;
+ for (const auto &Parent : Context->getParents(*Node)) {
+ if (!Parents.insert(Parent.getMemoizationData()).second) {
+ return true;
+ }
+ }
+ return false;
+ }
+ };
+ EXPECT_FALSE(matchAndVerifyResultTrue(
+ "template <typename T> int Foo() { return 1 + 2; }\n"
+ "int x = Foo<int>() + Foo<unsigned>();",
+ stmt().bind("node"), llvm::make_unique<HasDuplicateParents>()));
+}
+
+TEST(TypeMatching, PointeeTypes) {
+ EXPECT_TRUE(matches("int b; int &a = b;",
+ referenceType(pointee(builtinType()))));
+ EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
+
+ EXPECT_TRUE(matches("int *a;",
+ loc(pointerType(pointee(builtinType())))));
+
+ EXPECT_TRUE(matches(
+ "int const *A;",
+ pointerType(pointee(isConstQualified(), builtinType()))));
+ EXPECT_TRUE(notMatches(
+ "int *A;",
+ pointerType(pointee(isConstQualified(), builtinType()))));
+}
+
+TEST(ElaboratedTypeNarrowing, hasQualifier) {
+ EXPECT_TRUE(matches(
+ "namespace N {"
+ " namespace M {"
+ " class D {};"
+ " }"
+ "}"
+ "N::M::D d;",
+ elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
+ EXPECT_TRUE(notMatches(
+ "namespace M {"
+ " class D {};"
+ "}"
+ "M::D d;",
+ elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
+ EXPECT_TRUE(notMatches(
+ "struct D {"
+ "} d;",
+ elaboratedType(hasQualifier(nestedNameSpecifier()))));
+}
+
+TEST(ElaboratedTypeNarrowing, namesType) {
+ EXPECT_TRUE(matches(
+ "namespace N {"
+ " namespace M {"
+ " class D {};"
+ " }"
+ "}"
+ "N::M::D d;",
+ elaboratedType(elaboratedType(namesType(recordType(
+ hasDeclaration(namedDecl(hasName("D")))))))));
+ EXPECT_TRUE(notMatches(
+ "namespace M {"
+ " class D {};"
+ "}"
+ "M::D d;",
+ elaboratedType(elaboratedType(namesType(typedefType())))));
+}
+
+TEST(NNS, BindsNestedNameSpecifiers) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
+ nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
+ llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>(
+ "nns", "ns::struct E::")));
+}
+
+TEST(NNS, BindsNestedNameSpecifierLocs) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "namespace ns { struct B {}; } ns::B b;",
+ loc(nestedNameSpecifier()).bind("loc"),
+ llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("loc", 1)));
+}
+
+TEST(NNS, DescendantsOfNestedNameSpecifiers) {
+ std::string Fragment =
+ "namespace a { struct A { struct B { struct C {}; }; }; };"
+ "void f() { a::A::B::C c; }";
+ EXPECT_TRUE(matches(
+ Fragment,
+ nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
+ hasDescendant(nestedNameSpecifier(
+ specifiesNamespace(hasName("a")))))));
+ EXPECT_TRUE(notMatches(
+ Fragment,
+ nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
+ has(nestedNameSpecifier(
+ specifiesNamespace(hasName("a")))))));
+ EXPECT_TRUE(matches(
+ Fragment,
+ nestedNameSpecifier(specifiesType(asString("struct a::A")),
+ has(nestedNameSpecifier(
+ specifiesNamespace(hasName("a")))))));
+
+ // Not really useful because a NestedNameSpecifier can af at most one child,
+ // but to complete the interface.
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Fragment,
+ nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
+ forEach(nestedNameSpecifier().bind("x"))),
+ llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>("x", 1)));
+}
+
+TEST(NNS, NestedNameSpecifiersAsDescendants) {
+ std::string Fragment =
+ "namespace a { struct A { struct B { struct C {}; }; }; };"
+ "void f() { a::A::B::C c; }";
+ EXPECT_TRUE(matches(
+ Fragment,
+ decl(hasDescendant(nestedNameSpecifier(specifiesType(
+ asString("struct a::A")))))));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Fragment,
+ functionDecl(hasName("f"),
+ forEachDescendant(nestedNameSpecifier().bind("x"))),
+ // Nested names: a, a::A and a::A::B.
+ llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>("x", 3)));
+}
+
+TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
+ std::string Fragment =
+ "namespace a { struct A { struct B { struct C {}; }; }; };"
+ "void f() { a::A::B::C c; }";
+ EXPECT_TRUE(matches(
+ Fragment,
+ nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
+ hasDescendant(loc(nestedNameSpecifier(
+ specifiesNamespace(hasName("a"))))))));
+ EXPECT_TRUE(notMatches(
+ Fragment,
+ nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
+ has(loc(nestedNameSpecifier(
+ specifiesNamespace(hasName("a"))))))));
+ EXPECT_TRUE(matches(
+ Fragment,
+ nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
+ has(loc(nestedNameSpecifier(
+ specifiesNamespace(hasName("a"))))))));
+
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Fragment,
+ nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
+ forEach(nestedNameSpecifierLoc().bind("x"))),
+ llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("x", 1)));
+}
+
+TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
+ std::string Fragment =
+ "namespace a { struct A { struct B { struct C {}; }; }; };"
+ "void f() { a::A::B::C c; }";
+ EXPECT_TRUE(matches(
+ Fragment,
+ decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
+ asString("struct a::A"))))))));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Fragment,
+ functionDecl(hasName("f"),
+ forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
+ // Nested names: a, a::A and a::A::B.
+ llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("x", 3)));
+}
+template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
+public:
+ VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
+ StringRef InnerId)
+ : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
+ }
+
+ bool run(const BoundNodes *Nodes) override { return false; }
+
+ bool run(const BoundNodes *Nodes, ASTContext *Context) override {
+ const T *Node = Nodes->getNodeAs<T>(Id);
+ return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
+ nullptr;
+ }
+private:
+ std::string Id;
+ internal::Matcher<T> InnerMatcher;
+ std::string InnerId;
+};
+
+TEST(MatchFinder, CanMatchDeclarationsRecursively) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
+ llvm::make_unique<VerifyMatchOnNode<Decl>>(
+ "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
+ "Y")));
+ EXPECT_TRUE(matchAndVerifyResultFalse(
+ "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
+ llvm::make_unique<VerifyMatchOnNode<Decl>>(
+ "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
+ "Z")));
+}
+
+TEST(MatchFinder, CanMatchStatementsRecursively) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
+ llvm::make_unique<VerifyMatchOnNode<Stmt>>(
+ "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
+ EXPECT_TRUE(matchAndVerifyResultFalse(
+ "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
+ llvm::make_unique<VerifyMatchOnNode<Stmt>>(
+ "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
+}
+
+TEST(MatchFinder, CanMatchSingleNodesRecursively) {
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
+ llvm::make_unique<VerifyMatchOnNode<Decl>>(
+ "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
+ EXPECT_TRUE(matchAndVerifyResultFalse(
+ "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
+ llvm::make_unique<VerifyMatchOnNode<Decl>>(
+ "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
+}
+
+TEST(StatementMatcher, HasReturnValue) {
+ StatementMatcher RetVal = returnStmt(hasReturnValue(binaryOperator()));
+ EXPECT_TRUE(matches("int F() { int a, b; return a + b; }", RetVal));
+ EXPECT_FALSE(matches("int F() { int a; return a; }", RetVal));
+ EXPECT_FALSE(matches("void F() { return; }", RetVal));
+}
+
+TEST(StatementMatcher, ForFunction) {
+ const auto CppString1 =
+ "struct PosVec {"
+ " PosVec& operator=(const PosVec&) {"
+ " auto x = [] { return 1; };"
+ " return *this;"
+ " }"
+ "};";
+ const auto CppString2 =
+ "void F() {"
+ " struct S {"
+ " void F2() {"
+ " return;"
+ " }"
+ " };"
+ "}";
+ EXPECT_TRUE(
+ matches(
+ CppString1,
+ returnStmt(forFunction(hasName("operator=")),
+ has(unaryOperator(hasOperatorName("*"))))));
+ EXPECT_TRUE(
+ notMatches(
+ CppString1,
+ returnStmt(forFunction(hasName("operator=")),
+ has(integerLiteral()))));
+ EXPECT_TRUE(
+ matches(
+ CppString1,
+ returnStmt(forFunction(hasName("operator()")),
+ has(integerLiteral()))));
+ EXPECT_TRUE(matches(CppString2, returnStmt(forFunction(hasName("F2")))));
+ EXPECT_TRUE(notMatches(CppString2, returnStmt(forFunction(hasName("F")))));
+}
+
+TEST(Matcher, ForEachOverriden) {
+ const auto ForEachOverriddenInClass = [](const char *ClassName) {
+ return cxxMethodDecl(ofClass(hasName(ClassName)), isVirtual(),
+ forEachOverridden(cxxMethodDecl().bind("overridden")))
+ .bind("override");
+ };
+ static const char Code1[] = "class A { virtual void f(); };"
+ "class B : public A { void f(); };"
+ "class C : public B { void f(); };";
+ // C::f overrides A::f.
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Code1, ForEachOverriddenInClass("C"),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override", "f", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Code1, ForEachOverriddenInClass("C"),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden", "f",
+ 1)));
+ // B::f overrides A::f.
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Code1, ForEachOverriddenInClass("B"),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override", "f", 1)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Code1, ForEachOverriddenInClass("B"),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden", "f",
+ 1)));
+ // A::f overrides nothing.
+ EXPECT_TRUE(notMatches(Code1, ForEachOverriddenInClass("A")));
+
+ static const char Code2[] =
+ "class A1 { virtual void f(); };"
+ "class A2 { virtual void f(); };"
+ "class B : public A1, public A2 { void f(); };";
+ // B::f overrides A1::f and A2::f. This produces two matches.
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Code2, ForEachOverriddenInClass("B"),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override", "f", 2)));
+ EXPECT_TRUE(matchAndVerifyResultTrue(
+ Code2, ForEachOverriddenInClass("B"),
+ llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden", "f",
+ 2)));
+ // A1::f overrides nothing.
+ EXPECT_TRUE(notMatches(Code2, ForEachOverriddenInClass("A1")));
+}
+
+} // namespace ast_matchers
+} // namespace clang
diff --git a/unittests/ASTMatchers/CMakeLists.txt b/unittests/ASTMatchers/CMakeLists.txt
index 3ace9fe264..563303157a 100644
--- a/unittests/ASTMatchers/CMakeLists.txt
+++ b/unittests/ASTMatchers/CMakeLists.txt
@@ -2,8 +2,20 @@ set(LLVM_LINK_COMPONENTS
Support
)
+# By default MSVC has a 2^16 limit on the number of sections in an object file,
+# and this needs more than that.
+if (MSVC)
+ set_source_files_properties(InternalASTMatchersTest.cpp PROPERTIES COMPILE_FLAGS /bigobj)
+ set_source_files_properties(NodeMatchersTest.cpp PROPERTIES COMPILE_FLAGS /bigobj)
+ set_source_files_properties(NarrowingMatchersTest.cpp PROPERTIES COMPILE_FLAGS /bigobj)
+ set_source_files_properties(ASTTraversalMatchersTest.cpp PROPERTIES COMPILE_FLAGS /bigobj)
+endif()
+
add_clang_unittest(ASTMatchersTests
- ASTMatchersTest.cpp)
+ ASTMatchersInternalTest.cpp
+ ASTMatchersNodeTest.cpp
+ ASTMatchersNarrowingTest.cpp
+ ASTMatchersTraversalTest.cpp)
target_link_libraries(ASTMatchersTests
clangAST
diff --git a/unittests/ASTMatchers/Dynamic/Makefile b/unittests/ASTMatchers/Dynamic/Makefile
deleted file mode 100644
index df253b8a1d..0000000000
--- a/unittests/ASTMatchers/Dynamic/Makefile
+++ /dev/null
@@ -1,22 +0,0 @@
-##===- unittests/ASTMatchers/Dynamic/Makefile --------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../../..
-
-TESTNAME = DynamicASTMatchers
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc option
-USEDLIBS = clangTooling.a clangFrontend.a clangSerialization.a clangDriver.a \
- clangRewrite.a clangRewriteFrontend.a clangParse.a clangSema.a \
- clangDynamicASTMatchers.a \
- clangAnalysis.a clangEdit.a clangAST.a clangASTMatchers.a \
- clangLex.a \
- clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/ASTMatchers/Dynamic/ParserTest.cpp b/unittests/ASTMatchers/Dynamic/ParserTest.cpp
index 0de6242a67..553427c9a4 100644
--- a/unittests/ASTMatchers/Dynamic/ParserTest.cpp
+++ b/unittests/ASTMatchers/Dynamic/ParserTest.cpp
@@ -263,7 +263,7 @@ TEST(ParserTest, Errors) {
"1:1: Matcher does not support binding.",
ParseWithError("isArrow().bind(\"foo\")"));
EXPECT_EQ("Input value has unresolved overloaded type: "
- "Matcher<DoStmt|ForStmt|WhileStmt|CXXForRangeStmt>",
+ "Matcher<DoStmt|ForStmt|WhileStmt|CXXForRangeStmt|FunctionDecl>",
ParseMatcherWithError("hasBody(stmt())"));
}
@@ -320,7 +320,7 @@ TEST(ParserTest, CompletionNamedValues) {
EXPECT_EQ("arent(", Comps[2].TypedText);
EXPECT_EQ(
"Matcher<Decl> "
- "hasParent(Matcher<TemplateArgument|NestedNameSpecifierLoc|Decl|...>)",
+ "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)",
Comps[2].MatcherDecl);
}
diff --git a/unittests/ASTMatchers/Dynamic/RegistryTest.cpp b/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
index 8e97566f69..6bbbc2bd35 100644
--- a/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
+++ b/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
@@ -421,7 +421,7 @@ TEST_F(RegistryTest, Errors) {
constructMatcher("parameterCountIs", 3), Error.get())
.isNull());
EXPECT_EQ("Incorrect type for arg 2. (Expected = Matcher<CXXRecordDecl>) != "
- "(Actual = Matcher<FunctionDecl>)",
+ "(Actual = Matcher<FunctionDecl|FunctionProtoType>)",
Error->toString());
// Bad argument type with variadic.
@@ -449,26 +449,25 @@ TEST_F(RegistryTest, Completion) {
// Overloaded
EXPECT_TRUE(hasCompletion(
Comps, "hasParent(",
- "Matcher<TemplateArgument|NestedNameSpecifierLoc|Decl|...> "
- "hasParent(Matcher<TemplateArgument|NestedNameSpecifierLoc|Decl|...>)"));
+ "Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...> "
+ "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)"));
// Variadic.
EXPECT_TRUE(hasCompletion(Comps, "whileStmt(",
"Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)"));
// Polymorphic.
EXPECT_TRUE(hasCompletion(
Comps, "hasDescendant(",
- "Matcher<TemplateArgument|NestedNameSpecifier|NestedNameSpecifierLoc|...>"
- " hasDescendant(Matcher<TemplateArgument|NestedNameSpecifier|"
- "NestedNameSpecifierLoc|...>)"));
+ "Matcher<NestedNameSpecifierLoc|QualType|TypeLoc|...> "
+ "hasDescendant(Matcher<NestedNameSpecifierLoc|QualType|TypeLoc|...>)"));
CompVector WhileComps = getCompletions("whileStmt", 0);
EXPECT_TRUE(hasCompletion(WhileComps, "hasBody(",
"Matcher<WhileStmt> hasBody(Matcher<Stmt>)"));
- EXPECT_TRUE(hasCompletion(WhileComps, "hasParent(",
- "Matcher<Stmt> "
- "hasParent(Matcher<TemplateArgument|"
- "NestedNameSpecifierLoc|Decl|...>)"));
+ EXPECT_TRUE(hasCompletion(
+ WhileComps, "hasParent(",
+ "Matcher<Stmt> "
+ "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)"));
EXPECT_TRUE(
hasCompletion(WhileComps, "allOf(", "Matcher<T> allOf(Matcher<T>...)"));
@@ -506,6 +505,12 @@ TEST_F(RegistryTest, HasArgs) {
EXPECT_FALSE(matches("struct X {};", Value));
}
+TEST_F(RegistryTest, ParenExpr) {
+ Matcher<Stmt> Value = constructMatcher("parenExpr").getTypedMatcher<Stmt>();
+ EXPECT_TRUE(matches("int i = (1);", Value));
+ EXPECT_FALSE(matches("int i = 1;", Value));
+}
+
} // end anonymous namespace
} // end namespace dynamic
} // end namespace ast_matchers
diff --git a/unittests/ASTMatchers/Dynamic/VariantValueTest.cpp b/unittests/ASTMatchers/Dynamic/VariantValueTest.cpp
index 268463da45..9df7b780d4 100644
--- a/unittests/ASTMatchers/Dynamic/VariantValueTest.cpp
+++ b/unittests/ASTMatchers/Dynamic/VariantValueTest.cpp
@@ -16,9 +16,6 @@ namespace ast_matchers {
namespace dynamic {
namespace {
-using ast_matchers::internal::DynTypedMatcher;
-using ast_matchers::internal::Matcher;
-
TEST(VariantValueTest, Unsigned) {
const unsigned kUnsigned = 17;
VariantValue Value = kUnsigned;
diff --git a/unittests/ASTMatchers/Makefile b/unittests/ASTMatchers/Makefile
deleted file mode 100644
index 92f2fa0e5d..0000000000
--- a/unittests/ASTMatchers/Makefile
+++ /dev/null
@@ -1,22 +0,0 @@
-##===- unittests/ASTMatchers/Makefile ----------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-
-PARALLEL_DIRS = Dynamic
-
-TESTNAME = ASTMatchers
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc option
-USEDLIBS = clangTooling.a clangFrontend.a clangSerialization.a clangDriver.a \
- clangRewrite.a clangRewriteFrontend.a \
- clangParse.a clangSema.a clangAnalysis.a \
- clangEdit.a clangAST.a clangASTMatchers.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Analysis/CFGTest.cpp b/unittests/Analysis/CFGTest.cpp
new file mode 100644
index 0000000000..a8d397e9a5
--- /dev/null
+++ b/unittests/Analysis/CFGTest.cpp
@@ -0,0 +1,58 @@
+//===- unittests/Analysis/CFGTest.cpp - CFG tests -------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+#include <string>
+#include <vector>
+
+namespace clang {
+namespace analysis {
+namespace {
+
+// Constructing a CFG for a range-based for over a dependent type fails (but
+// should not crash).
+TEST(CFG, RangeBasedForOverDependentType) {
+ const char *Code = "class Foo;\n"
+ "template <typename T>\n"
+ "void f(const T &Range) {\n"
+ " for (const Foo *TheFoo : Range) {\n"
+ " }\n"
+ "}\n";
+
+ class CFGCallback : public ast_matchers::MatchFinder::MatchCallback {
+ public:
+ bool SawFunctionBody = false;
+
+ void run(const ast_matchers::MatchFinder::MatchResult &Result) override {
+ const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func");
+ Stmt *Body = Func->getBody();
+ if (!Body)
+ return;
+ SawFunctionBody = true;
+ std::unique_ptr<CFG> cfg =
+ CFG::buildCFG(nullptr, Body, Result.Context, CFG::BuildOptions());
+ EXPECT_EQ(nullptr, cfg);
+ }
+ } Callback;
+
+ ast_matchers::MatchFinder Finder;
+ Finder.addMatcher(ast_matchers::functionDecl().bind("func"), &Callback);
+ std::unique_ptr<tooling::FrontendActionFactory> Factory(
+ tooling::newFrontendActionFactory(&Finder));
+ std::vector<std::string> Args = {"-std=c++11", "-fno-delayed-template-parsing"};
+ ASSERT_TRUE(tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args));
+ EXPECT_TRUE(Callback.SawFunctionBody);
+}
+
+} // namespace
+} // namespace analysis
+} // namespace clang
diff --git a/unittests/Analysis/CMakeLists.txt b/unittests/Analysis/CMakeLists.txt
new file mode 100644
index 0000000000..926f586be3
--- /dev/null
+++ b/unittests/Analysis/CMakeLists.txt
@@ -0,0 +1,16 @@
+set(LLVM_LINK_COMPONENTS
+ Support
+ )
+
+add_clang_unittest(CFGTests
+ CFGTest.cpp
+ )
+
+target_link_libraries(CFGTests
+ clangAnalysis
+ clangAST
+ clangASTMatchers
+ clangBasic
+ clangFrontend
+ clangTooling
+ )
diff --git a/unittests/Basic/DiagnosticTest.cpp b/unittests/Basic/DiagnosticTest.cpp
index fa2b56e083..4ffa0837bd 100644
--- a/unittests/Basic/DiagnosticTest.cpp
+++ b/unittests/Basic/DiagnosticTest.cpp
@@ -46,4 +46,27 @@ TEST(DiagnosticTest, suppressAndTrap) {
EXPECT_FALSE(Diags.hasUnrecoverableErrorOccurred());
}
+// Check that FatalsAsErrors works as intended
+TEST(DiagnosticTest, fatalsAsErrors) {
+ DiagnosticsEngine Diags(new DiagnosticIDs(),
+ new DiagnosticOptions,
+ new IgnoringDiagConsumer());
+ Diags.setFatalsAsError(true);
+
+ // Diag that would set UncompilableErrorOccurred and ErrorOccurred.
+ Diags.Report(diag::err_target_unknown_triple) << "unknown";
+
+ // Diag that would set UnrecoverableErrorOccurred and ErrorOccurred.
+ Diags.Report(diag::err_cannot_open_file) << "file" << "error";
+
+ // Diag that would set FatalErrorOccurred
+ // (via non-note following a fatal error).
+ Diags.Report(diag::warn_mt_message) << "warning";
+
+ EXPECT_TRUE(Diags.hasErrorOccurred());
+ EXPECT_FALSE(Diags.hasFatalErrorOccurred());
+ EXPECT_TRUE(Diags.hasUncompilableErrorOccurred());
+ EXPECT_TRUE(Diags.hasUnrecoverableErrorOccurred());
+}
+
}
diff --git a/unittests/Basic/Makefile b/unittests/Basic/Makefile
deleted file mode 100644
index 82de790598..0000000000
--- a/unittests/Basic/Makefile
+++ /dev/null
@@ -1,15 +0,0 @@
-##===- unittests/Basic/Makefile ----------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = Basic
-LINK_COMPONENTS := support mc
-USEDLIBS = clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Basic/SourceManagerTest.cpp b/unittests/Basic/SourceManagerTest.cpp
index 5a1a393fbf..f41876147c 100644
--- a/unittests/Basic/SourceManagerTest.cpp
+++ b/unittests/Basic/SourceManagerTest.cpp
@@ -23,7 +23,6 @@
#include "llvm/Config/llvm-config.h"
#include "gtest/gtest.h"
-using namespace llvm;
using namespace clang;
namespace {
@@ -73,7 +72,8 @@ TEST_F(SourceManagerTest, isBeforeInTranslationUnit) {
const char *source =
"#define M(x) [x]\n"
"M(foo)";
- std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(source);
+ std::unique_ptr<llvm::MemoryBuffer> Buf =
+ llvm::MemoryBuffer::getMemBuffer(source);
FileID mainFileID = SourceMgr.createFileID(std::move(Buf));
SourceMgr.setMainFileID(mainFileID);
@@ -126,7 +126,8 @@ TEST_F(SourceManagerTest, getColumnNumber) {
"int x;\n"
"int y;";
- std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Source);
+ std::unique_ptr<llvm::MemoryBuffer> Buf =
+ llvm::MemoryBuffer::getMemBuffer(Source);
FileID MainFileID = SourceMgr.createFileID(std::move(Buf));
SourceMgr.setMainFileID(MainFileID);
@@ -185,8 +186,10 @@ TEST_F(SourceManagerTest, getMacroArgExpandedLocation) {
"#define CONCAT(X, Y) X##Y\n"
"CONCAT(1,1)\n";
- std::unique_ptr<MemoryBuffer> HeaderBuf = MemoryBuffer::getMemBuffer(header);
- std::unique_ptr<MemoryBuffer> MainBuf = MemoryBuffer::getMemBuffer(main);
+ std::unique_ptr<llvm::MemoryBuffer> HeaderBuf =
+ llvm::MemoryBuffer::getMemBuffer(header);
+ std::unique_ptr<llvm::MemoryBuffer> MainBuf =
+ llvm::MemoryBuffer::getMemBuffer(main);
FileID mainFileID = SourceMgr.createFileID(std::move(MainBuf));
SourceMgr.setMainFileID(mainFileID);
@@ -284,8 +287,10 @@ TEST_F(SourceManagerTest, isBeforeInTranslationUnitWithMacroInInclude) {
"#define INC2 </test-header.h>\n"
"#include M(INC2)\n";
- std::unique_ptr<MemoryBuffer> HeaderBuf = MemoryBuffer::getMemBuffer(header);
- std::unique_ptr<MemoryBuffer> MainBuf = MemoryBuffer::getMemBuffer(main);
+ std::unique_ptr<llvm::MemoryBuffer> HeaderBuf =
+ llvm::MemoryBuffer::getMemBuffer(header);
+ std::unique_ptr<llvm::MemoryBuffer> MainBuf =
+ llvm::MemoryBuffer::getMemBuffer(main);
SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(MainBuf)));
const FileEntry *headerFile = FileMgr.getVirtualFile("/test-header.h",
diff --git a/unittests/Basic/VirtualFileSystemTest.cpp b/unittests/Basic/VirtualFileSystemTest.cpp
index ac07035d3e..3b26488a7f 100644
--- a/unittests/Basic/VirtualFileSystemTest.cpp
+++ b/unittests/Basic/VirtualFileSystemTest.cpp
@@ -8,7 +8,9 @@
//===----------------------------------------------------------------------===//
#include "clang/Basic/VirtualFileSystem.h"
+#include "llvm/ADT/Triple.h"
#include "llvm/Support/Errc.h"
+#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
@@ -29,7 +31,7 @@ struct DummyFile : public vfs::File {
bool IsVolatile) override {
llvm_unreachable("unimplemented");
}
- virtual std::error_code close() override { return std::error_code(); }
+ std::error_code close() override { return std::error_code(); }
};
class DummyFileSystem : public vfs::FileSystem {
@@ -348,7 +350,6 @@ TEST(VirtualFileSystemTest, BasicRealFSRecursiveIteration) {
ASSERT_FALSE(EC);
ASSERT_NE(vfs::recursive_directory_iterator(), I);
-
std::vector<std::string> Contents;
for (auto E = vfs::recursive_directory_iterator(); !EC && I != E;
I.increment(EC)) {
@@ -370,25 +371,24 @@ TEST(VirtualFileSystemTest, BasicRealFSRecursiveIteration) {
EXPECT_EQ(1, Counts[3]); // d
}
-template <typename T, size_t N>
-std::vector<StringRef> makeStringRefVector(const T (&Arr)[N]) {
- std::vector<StringRef> Vec;
- for (size_t i = 0; i != N; ++i)
- Vec.push_back(Arr[i]);
- return Vec;
-}
-
template <typename DirIter>
-static void checkContents(DirIter I, ArrayRef<StringRef> Expected) {
+static void checkContents(DirIter I, ArrayRef<StringRef> ExpectedOut) {
std::error_code EC;
- auto ExpectedIter = Expected.begin(), ExpectedEnd = Expected.end();
- for (DirIter E;
- !EC && I != E && ExpectedIter != ExpectedEnd;
- I.increment(EC), ++ExpectedIter)
- EXPECT_EQ(*ExpectedIter, I->getName());
-
- EXPECT_EQ(ExpectedEnd, ExpectedIter);
- EXPECT_EQ(DirIter(), I);
+ SmallVector<StringRef, 4> Expected(ExpectedOut.begin(), ExpectedOut.end());
+ SmallVector<std::string, 4> InputToCheck;
+
+ // Do not rely on iteration order to check for contents, sort both
+ // content vectors before comparison.
+ for (DirIter E; !EC && I != E; I.increment(EC))
+ InputToCheck.push_back(I->getName());
+
+ std::sort(InputToCheck.begin(), InputToCheck.end());
+ std::sort(Expected.begin(), Expected.end());
+ EXPECT_EQ(InputToCheck.size(), Expected.size());
+
+ unsigned LastElt = std::min(InputToCheck.size(), Expected.size());
+ for (unsigned Idx = 0; Idx != LastElt; ++Idx)
+ EXPECT_EQ(StringRef(InputToCheck[Idx]), Expected[Idx]);
}
TEST(VirtualFileSystemTest, OverlayIteration) {
@@ -405,20 +405,14 @@ TEST(VirtualFileSystemTest, OverlayIteration) {
checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file1"));
Upper->addRegularFile("/file2");
- {
- const char *Contents[] = {"/file2", "/file1"};
- checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
- }
+ checkContents(O->dir_begin("/", EC), {"/file2", "/file1"});
Lower->addDirectory("/dir1");
Lower->addRegularFile("/dir1/foo");
Upper->addDirectory("/dir2");
Upper->addRegularFile("/dir2/foo");
checkContents(O->dir_begin("/dir2", EC), ArrayRef<StringRef>("/dir2/foo"));
- {
- const char *Contents[] = {"/dir2", "/file2", "/dir1", "/file1"};
- checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
- }
+ checkContents(O->dir_begin("/", EC), {"/dir2", "/file2", "/dir1", "/file1"});
}
TEST(VirtualFileSystemTest, OverlayRecursiveIteration) {
@@ -440,11 +434,8 @@ TEST(VirtualFileSystemTest, OverlayRecursiveIteration) {
Upper->addDirectory("/dir");
Upper->addRegularFile("/dir/file2");
- {
- const char *Contents[] = {"/dir", "/dir/file2", "/file1"};
- checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
- makeStringRefVector(Contents));
- }
+ checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
+ {"/dir", "/dir/file2", "/file1"});
Lower->addDirectory("/dir1");
Lower->addRegularFile("/dir1/foo");
@@ -460,13 +451,10 @@ TEST(VirtualFileSystemTest, OverlayRecursiveIteration) {
Upper->addRegularFile("/hiddenByUp");
checkContents(vfs::recursive_directory_iterator(*O, "/dir2", EC),
ArrayRef<StringRef>("/dir2/foo"));
- {
- const char *Contents[] = { "/dir", "/dir/file2", "/dir2", "/dir2/foo",
- "/hiddenByUp", "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a",
- "/dir1/a/b", "/dir1/foo", "/file1" };
- checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
- makeStringRefVector(Contents));
- }
+ checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
+ {"/dir", "/dir/file2", "/dir2", "/dir2/foo", "/hiddenByUp",
+ "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a",
+ "/dir1/a/b", "/dir1/foo", "/file1"});
}
TEST(VirtualFileSystemTest, ThreeLevelIteration) {
@@ -486,10 +474,7 @@ TEST(VirtualFileSystemTest, ThreeLevelIteration) {
Lower->addRegularFile("/file1");
Upper->addRegularFile("/file3");
- {
- const char *Contents[] = {"/file3", "/file2", "/file1"};
- checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
- }
+ checkContents(O->dir_begin("/", EC), {"/file3", "/file2", "/file1"});
}
TEST(VirtualFileSystemTest, HiddenInIteration) {
@@ -510,11 +495,9 @@ TEST(VirtualFileSystemTest, HiddenInIteration) {
Middle->addRegularFile("/hiddenByUp", sys::fs::owner_write);
Upper->addRegularFile("/onlyInUp", sys::fs::owner_all);
Upper->addRegularFile("/hiddenByUp", sys::fs::owner_all);
- {
- const char *Contents[] = {"/hiddenByUp", "/onlyInUp", "/hiddenByMid",
- "/onlyInMid", "/onlyInLow"};
- checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
- }
+ checkContents(
+ O->dir_begin("/", EC),
+ {"/hiddenByUp", "/onlyInUp", "/hiddenByMid", "/onlyInMid", "/onlyInLow"});
// Make sure we get the top-most entry
{
@@ -657,6 +640,18 @@ TEST_F(InMemoryFileSystemTest, WorkingDirectory) {
Stat = FS.status("c");
ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
+
+ auto ReplaceBackslashes = [](std::string S) {
+ std::replace(S.begin(), S.end(), '\\', '/');
+ return S;
+ };
+ NormalizedFS.setCurrentWorkingDirectory("/b/c");
+ NormalizedFS.setCurrentWorkingDirectory(".");
+ ASSERT_EQ("/b/c", ReplaceBackslashes(
+ NormalizedFS.getCurrentWorkingDirectory().get()));
+ NormalizedFS.setCurrentWorkingDirectory("..");
+ ASSERT_EQ("/b", ReplaceBackslashes(
+ NormalizedFS.getCurrentWorkingDirectory().get()));
}
// NOTE: in the tests below, we use '//root/' as our root directory, since it is
@@ -676,7 +671,7 @@ public:
getFromYAMLRawString(StringRef Content,
IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS) {
std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer(Content);
- return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, this,
+ return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, "", this,
ExternalFS);
}
@@ -687,6 +682,12 @@ public:
VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos);
return getFromYAMLRawString(VersionPlusContent, ExternalFS);
}
+
+ // This is intended as a "XFAIL" for windows hosts.
+ bool supportsSameDirMultipleYAMLEntries() {
+ Triple Host(Triple::normalize(sys::getProcessTriple()));
+ return !Host.isOSWindows();
+ }
};
TEST_F(VFSFromYAMLTest, BasicVFSFromYAML) {
@@ -1067,15 +1068,99 @@ TEST_F(VFSFromYAMLTest, DirectoryIteration) {
O->pushOverlay(FS);
std::error_code EC;
- {
- const char *Contents[] = {"//root/file1", "//root/file2", "//root/file3",
- "//root/foo"};
- checkContents(O->dir_begin("//root/", EC), makeStringRefVector(Contents));
- }
+ checkContents(O->dir_begin("//root/", EC),
+ {"//root/file1", "//root/file2", "//root/file3", "//root/foo"});
- {
- const char *Contents[] = {"//root/foo/bar/a", "//root/foo/bar/b"};
- checkContents(O->dir_begin("//root/foo/bar", EC),
- makeStringRefVector(Contents));
+ checkContents(O->dir_begin("//root/foo/bar", EC),
+ {"//root/foo/bar/a", "//root/foo/bar/b"});
+}
+
+TEST_F(VFSFromYAMLTest, DirectoryIterationSameDirMultipleEntries) {
+ // https://llvm.org/bugs/show_bug.cgi?id=27725
+ if (!supportsSameDirMultipleYAMLEntries())
+ return;
+
+ IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
+ Lower->addDirectory("//root/zab");
+ Lower->addDirectory("//root/baz");
+ Lower->addRegularFile("//root/zab/a");
+ Lower->addRegularFile("//root/zab/b");
+ IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
+ "{ 'use-external-names': false,\n"
+ " 'roots': [\n"
+ "{\n"
+ " 'type': 'directory',\n"
+ " 'name': '//root/baz/',\n"
+ " 'contents': [ {\n"
+ " 'type': 'file',\n"
+ " 'name': 'x',\n"
+ " 'external-contents': '//root/zab/a'\n"
+ " }\n"
+ " ]\n"
+ "},\n"
+ "{\n"
+ " 'type': 'directory',\n"
+ " 'name': '//root/baz/',\n"
+ " 'contents': [ {\n"
+ " 'type': 'file',\n"
+ " 'name': 'y',\n"
+ " 'external-contents': '//root/zab/b'\n"
+ " }\n"
+ " ]\n"
+ "}\n"
+ "]\n"
+ "}",
+ Lower);
+ ASSERT_TRUE(FS.get() != nullptr);
+
+ IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
+ new vfs::OverlayFileSystem(Lower));
+ O->pushOverlay(FS);
+
+ std::error_code EC;
+
+ checkContents(O->dir_begin("//root/baz/", EC),
+ {"//root/baz/x", "//root/baz/y"});
+}
+
+TEST_F(VFSFromYAMLTest, RecursiveDirectoryIterationLevel) {
+
+ IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
+ Lower->addDirectory("//root/a");
+ Lower->addDirectory("//root/a/b");
+ Lower->addDirectory("//root/a/b/c");
+ Lower->addRegularFile("//root/a/b/c/file");
+ IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
+ "{ 'use-external-names': false,\n"
+ " 'roots': [\n"
+ "{\n"
+ " 'type': 'directory',\n"
+ " 'name': '//root/a/b/c/',\n"
+ " 'contents': [ {\n"
+ " 'type': 'file',\n"
+ " 'name': 'file',\n"
+ " 'external-contents': '//root/a/b/c/file'\n"
+ " }\n"
+ " ]\n"
+ "},\n"
+ "]\n"
+ "}",
+ Lower);
+ ASSERT_TRUE(FS.get() != nullptr);
+
+ IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
+ new vfs::OverlayFileSystem(Lower));
+ O->pushOverlay(FS);
+
+ std::error_code EC;
+
+ // Test recursive_directory_iterator level()
+ vfs::recursive_directory_iterator I = vfs::recursive_directory_iterator(
+ *O, "//root", EC), E;
+ ASSERT_FALSE(EC);
+ for (int l = 0; I != E; I.increment(EC), ++l) {
+ ASSERT_FALSE(EC);
+ EXPECT_EQ(I.level(), l);
}
+ EXPECT_EQ(I, E);
}
diff --git a/unittests/CMakeLists.txt b/unittests/CMakeLists.txt
index b85ec7e6df..7d407ce3f6 100644
--- a/unittests/CMakeLists.txt
+++ b/unittests/CMakeLists.txt
@@ -13,6 +13,7 @@ add_subdirectory(Basic)
add_subdirectory(Lex)
add_subdirectory(Driver)
if(CLANG_ENABLE_STATIC_ANALYZER)
+ add_subdirectory(Analysis)
add_subdirectory(StaticAnalyzer)
add_subdirectory(Frontend)
endif()
diff --git a/unittests/CodeGen/BufferSourceTest.cpp b/unittests/CodeGen/BufferSourceTest.cpp
index 85df768aa1..1934e66138 100644
--- a/unittests/CodeGen/BufferSourceTest.cpp
+++ b/unittests/CodeGen/BufferSourceTest.cpp
@@ -39,6 +39,7 @@ const char TestProgram[] =
"EmitCXXGlobalInitFunc test; ";
TEST(BufferSourceTest, EmitCXXGlobalInitFunc) {
+ LLVMContext Context;
CompilerInstance compiler;
compiler.createDiagnostics();
@@ -65,7 +66,7 @@ TEST(BufferSourceTest, EmitCXXGlobalInitFunc) {
compiler.getHeaderSearchOpts(),
compiler.getPreprocessorOpts(),
compiler.getCodeGenOpts(),
- llvm::getGlobalContext())));
+ Context)));
compiler.createSema(clang::TU_Prefix, nullptr);
diff --git a/unittests/CodeGen/Makefile b/unittests/CodeGen/Makefile
deleted file mode 100644
index de347e1afd..0000000000
--- a/unittests/CodeGen/Makefile
+++ /dev/null
@@ -1,20 +0,0 @@
-##===- unittests/CodeGen/Makefile --------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = CodeGen
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader mc option \
- profiledata support
-USEDLIBS = clangCodeGen.a clangFrontend.a clangSerialization.a \
- clangDriver.a \
- clangParse.a clangSema.a clangAnalysis.a \
- clangEdit.a clangAST.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Driver/Makefile b/unittests/Driver/Makefile
deleted file mode 100644
index 21d19f34f6..0000000000
--- a/unittests/Driver/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- unittests/Driver/Makefile ---------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = Multilib
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) support option
-USEDLIBS = clangDriver.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Format/CMakeLists.txt b/unittests/Format/CMakeLists.txt
index 01af435fff..240be6ead2 100644
--- a/unittests/Format/CMakeLists.txt
+++ b/unittests/Format/CMakeLists.txt
@@ -3,15 +3,20 @@ set(LLVM_LINK_COMPONENTS
)
add_clang_unittest(FormatTests
+ CleanupTest.cpp
FormatTest.cpp
FormatTestJava.cpp
FormatTestJS.cpp
FormatTestProto.cpp
FormatTestSelective.cpp
+ SortImportsTestJS.cpp
SortIncludesTest.cpp
)
target_link_libraries(FormatTests
+ clangBasic
clangFormat
+ clangFrontend
+ clangRewrite
clangToolingCore
)
diff --git a/unittests/Format/CleanupTest.cpp b/unittests/Format/CleanupTest.cpp
new file mode 100644
index 0000000000..5f85c53b78
--- /dev/null
+++ b/unittests/Format/CleanupTest.cpp
@@ -0,0 +1,726 @@
+//===- unittest/Format/CleanupTest.cpp - Code cleanup unit tests ----------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Format/Format.h"
+
+#include "../Tooling/RewriterTestContext.h"
+#include "clang/Tooling/Core/Replacement.h"
+
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace format {
+namespace {
+
+class CleanupTest : public ::testing::Test {
+protected:
+ std::string cleanup(llvm::StringRef Code,
+ const std::vector<tooling::Range> &Ranges,
+ const FormatStyle &Style = getLLVMStyle()) {
+ tooling::Replacements Replaces = format::cleanup(Style, Code, Ranges);
+
+ auto Result = applyAllReplacements(Code, Replaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ return *Result;
+ }
+};
+
+TEST_F(CleanupTest, DeleteEmptyNamespaces) {
+ std::string Code = "namespace A {\n"
+ "namespace B {\n"
+ "} // namespace B\n"
+ "} // namespace A\n\n"
+ "namespace C {\n"
+ "namespace D { int i; }\n"
+ "inline namespace E { namespace { } }\n"
+ "}";
+ std::string Expected = "\n\n\n\n\nnamespace C {\n"
+ "namespace D { int i; }\n \n"
+ "}";
+ std::vector<tooling::Range> Ranges;
+ Ranges.push_back(tooling::Range(28, 0));
+ Ranges.push_back(tooling::Range(91, 6));
+ Ranges.push_back(tooling::Range(132, 0));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, NamespaceWithSyntaxError) {
+ std::string Code = "namespace A {\n"
+ "namespace B {\n" // missing r_brace
+ "} // namespace A\n\n"
+ "namespace C {\n"
+ "namespace D int i; }\n"
+ "inline namespace E { namespace { } }\n"
+ "}";
+ std::string Expected = "namespace A {\n"
+ "\n\n\nnamespace C {\n"
+ "namespace D int i; }\n \n"
+ "}";
+ std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, EmptyNamespaceNotAffected) {
+ std::string Code = "namespace A {\n\n"
+ "namespace {\n\n}}";
+ // Even though the namespaces are empty, but the inner most empty namespace
+ // block is not affected by the changed ranges.
+ std::string Expected = "namespace A {\n\n"
+ "namespace {\n\n}}";
+ // Set the changed range to be the second "\n".
+ std::vector<tooling::Range> Ranges(1, tooling::Range(14, 0));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, EmptyNamespaceWithCommentsNoBreakBeforeBrace) {
+ std::string Code = "namespace A {\n"
+ "namespace B {\n"
+ "// Yo\n"
+ "} // namespace B\n"
+ "} // namespace A\n"
+ "namespace C { // Yo\n"
+ "}";
+ std::string Expected = "\n\n\n\n\n\n";
+ std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, EmptyNamespaceWithCommentsBreakBeforeBrace) {
+ std::string Code = "namespace A\n"
+ "/* Yo */ {\n"
+ "namespace B\n"
+ "{\n"
+ "// Yo\n"
+ "} // namespace B\n"
+ "} // namespace A\n"
+ "namespace C\n"
+ "{ // Yo\n"
+ "}\n";
+ std::string Expected = "\n\n\n\n\n\n\n\n\n\n";
+ std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
+ FormatStyle Style = getLLVMStyle();
+ Style.BraceWrapping.AfterNamespace = true;
+ std::string Result = cleanup(Code, Ranges, Style);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, CtorInitializationSimpleRedundantComma) {
+ std::string Code = "class A {\nA() : , {} };";
+ std::string Expected = "class A {\nA() {} };";
+ std::vector<tooling::Range> Ranges;
+ Ranges.push_back(tooling::Range(17, 0));
+ Ranges.push_back(tooling::Range(19, 0));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+
+ Code = "class A {\nA() : x(1), {} };";
+ Expected = "class A {\nA() : x(1) {} };";
+ Ranges.clear();
+ Ranges.push_back(tooling::Range(23, 0));
+ Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+
+ Code = "class A {\nA() :,,,,{} };";
+ Expected = "class A {\nA() {} };";
+ Ranges.clear();
+ Ranges.push_back(tooling::Range(15, 0));
+ Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, ListSimpleRedundantComma) {
+ std::string Code = "void f() { std::vector<int> v = {1,2,,,3,{4,5}}; }";
+ std::string Expected = "void f() { std::vector<int> v = {1,2,3,{4,5}}; }";
+ std::vector<tooling::Range> Ranges;
+ Ranges.push_back(tooling::Range(40, 0));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+
+ Code = "int main() { f(1,,2,3,,4);}";
+ Expected = "int main() { f(1,2,3,4);}";
+ Ranges.clear();
+ Ranges.push_back(tooling::Range(17, 0));
+ Ranges.push_back(tooling::Range(22, 0));
+ Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, CtorInitializationBracesInParens) {
+ std::string Code = "class A {\nA() : x({1}),, {} };";
+ std::string Expected = "class A {\nA() : x({1}) {} };";
+ std::vector<tooling::Range> Ranges;
+ Ranges.push_back(tooling::Range(24, 0));
+ Ranges.push_back(tooling::Range(26, 0));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, RedundantCommaNotInAffectedRanges) {
+ std::string Code =
+ "class A {\nA() : x({1}), /* comment */, { int x = 0; } };";
+ std::string Expected =
+ "class A {\nA() : x({1}), /* comment */, { int x = 0; } };";
+ // Set the affected range to be "int x = 0", which does not intercept the
+ // constructor initialization list.
+ std::vector<tooling::Range> Ranges(1, tooling::Range(42, 9));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+
+ Code = "class A {\nA() : x(1), {} };";
+ Expected = "class A {\nA() : x(1), {} };";
+ // No range. Fixer should do nothing.
+ Ranges.clear();
+ Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+// FIXME: delete comments too.
+TEST_F(CleanupTest, CtorInitializationCommentAroundCommas) {
+ // Remove redundant commas around comment.
+ std::string Code = "class A {\nA() : x({1}), /* comment */, {} };";
+ std::string Expected = "class A {\nA() : x({1}) /* comment */ {} };";
+ std::vector<tooling::Range> Ranges;
+ Ranges.push_back(tooling::Range(25, 0));
+ Ranges.push_back(tooling::Range(40, 0));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+
+ // Remove trailing comma and ignore comment.
+ Code = "class A {\nA() : x({1}), // comment\n{} };";
+ Expected = "class A {\nA() : x({1}) // comment\n{} };";
+ Ranges = std::vector<tooling::Range>(1, tooling::Range(25, 0));
+ Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+
+ // Remove trailing comma and ignore comment.
+ Code = "class A {\nA() : x({1}), // comment\n , y(1),{} };";
+ Expected = "class A {\nA() : x({1}), // comment\n y(1){} };";
+ Ranges = std::vector<tooling::Range>(1, tooling::Range(38, 0));
+ Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+
+ // Remove trailing comma and ignore comment.
+ Code = "class A {\nA() : x({1}), \n/* comment */, y(1),{} };";
+ Expected = "class A {\nA() : x({1}), \n/* comment */ y(1){} };";
+ Ranges = std::vector<tooling::Range>(1, tooling::Range(40, 0));
+ Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+
+ // Remove trailing comma and ignore comment.
+ Code = "class A {\nA() : , // comment\n y(1),{} };";
+ Expected = "class A {\nA() : // comment\n y(1){} };";
+ Ranges = std::vector<tooling::Range>(1, tooling::Range(17, 0));
+ Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+TEST_F(CleanupTest, CtorInitializerInNamespace) {
+ std::string Code = "namespace A {\n"
+ "namespace B {\n" // missing r_brace
+ "} // namespace A\n\n"
+ "namespace C {\n"
+ "class A { A() : x(0),, {} };\n"
+ "inline namespace E { namespace { } }\n"
+ "}";
+ std::string Expected = "namespace A {\n"
+ "\n\n\nnamespace C {\n"
+ "class A { A() : x(0) {} };\n \n"
+ "}";
+ std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
+ std::string Result = cleanup(Code, Ranges);
+ EXPECT_EQ(Expected, Result);
+}
+
+class CleanUpReplacementsTest : public ::testing::Test {
+protected:
+ tooling::Replacement createReplacement(unsigned Offset, unsigned Length,
+ StringRef Text) {
+ return tooling::Replacement(FileName, Offset, Length, Text);
+ }
+
+ tooling::Replacement createInsertion(StringRef HeaderName) {
+ return createReplacement(UINT_MAX, 0, HeaderName);
+ }
+
+ inline std::string apply(StringRef Code,
+ const tooling::Replacements Replaces) {
+ auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
+ EXPECT_TRUE(static_cast<bool>(CleanReplaces))
+ << llvm::toString(CleanReplaces.takeError()) << "\n";
+ auto Result = applyAllReplacements(Code, *CleanReplaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ return *Result;
+ }
+
+ inline std::string formatAndApply(StringRef Code,
+ const tooling::Replacements Replaces) {
+
+ auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
+ EXPECT_TRUE(static_cast<bool>(CleanReplaces))
+ << llvm::toString(CleanReplaces.takeError()) << "\n";
+ auto FormattedReplaces = formatReplacements(Code, *CleanReplaces, Style);
+ EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
+ << llvm::toString(FormattedReplaces.takeError()) << "\n";
+ auto Result = applyAllReplacements(Code, *FormattedReplaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ return *Result;
+ }
+
+ int getOffset(StringRef Code, int Line, int Column) {
+ RewriterTestContext Context;
+ FileID ID = Context.createInMemoryFile(FileName, Code);
+ auto DecomposedLocation =
+ Context.Sources.getDecomposedLoc(Context.getLocation(ID, Line, Column));
+ return DecomposedLocation.second;
+ }
+
+ const std::string FileName = "fix.cpp";
+ FormatStyle Style = getLLVMStyle();
+};
+
+TEST_F(CleanUpReplacementsTest, FixOnlyAffectedCodeAfterReplacements) {
+ std::string Code = "namespace A {\n"
+ "namespace B {\n"
+ " int x;\n"
+ "} // namespace B\n"
+ "} // namespace A\n"
+ "\n"
+ "namespace C {\n"
+ "namespace D { int i; }\n"
+ "inline namespace E { namespace { int y; } }\n"
+ "int x= 0;"
+ "}";
+ std::string Expected = "\n\nnamespace C {\n"
+ "namespace D { int i; }\n\n"
+ "int x= 0;"
+ "}";
+ tooling::Replacements Replaces = {
+ createReplacement(getOffset(Code, 3, 3), 6, ""),
+ createReplacement(getOffset(Code, 9, 34), 6, "")};
+
+ EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, NoExistingIncludeWithoutDefine) {
+ std::string Code = "int main() {}";
+ std::string Expected = "#include \"a.h\"\n"
+ "int main() {}";
+ tooling::Replacements Replaces = {createInsertion("#include \"a.h\"")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, NoExistingIncludeWithDefine) {
+ std::string Code = "#ifndef A_H\n"
+ "#define A_H\n"
+ "class A {};\n"
+ "#define MMM 123\n"
+ "#endif";
+ std::string Expected = "#ifndef A_H\n"
+ "#define A_H\n"
+ "#include \"b.h\"\n"
+ "class A {};\n"
+ "#define MMM 123\n"
+ "#endif";
+
+ tooling::Replacements Replaces = {createInsertion("#include \"b.h\"")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertBeforeCategoryWithLowerPriority) {
+ std::string Code = "#ifndef A_H\n"
+ "#define A_H\n"
+ "\n"
+ "\n"
+ "\n"
+ "#include <vector>\n"
+ "class A {};\n"
+ "#define MMM 123\n"
+ "#endif";
+ std::string Expected = "#ifndef A_H\n"
+ "#define A_H\n"
+ "\n"
+ "\n"
+ "\n"
+ "#include \"a.h\"\n"
+ "#include <vector>\n"
+ "class A {};\n"
+ "#define MMM 123\n"
+ "#endif";
+
+ tooling::Replacements Replaces = {createInsertion("#include \"a.h\"")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertAfterMainHeader) {
+ std::string Code = "#include \"fix.h\"\n"
+ "\n"
+ "int main() {}";
+ std::string Expected = "#include \"fix.h\"\n"
+ "#include <a>\n"
+ "\n"
+ "int main() {}";
+ tooling::Replacements Replaces = {createInsertion("#include <a>")};
+ Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp);
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertBeforeSystemHeaderLLVM) {
+ std::string Code = "#include <memory>\n"
+ "\n"
+ "int main() {}";
+ std::string Expected = "#include \"z.h\"\n"
+ "#include <memory>\n"
+ "\n"
+ "int main() {}";
+ tooling::Replacements Replaces = {createInsertion("#include \"z.h\"")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertAfterSystemHeaderGoogle) {
+ std::string Code = "#include <memory>\n"
+ "\n"
+ "int main() {}";
+ std::string Expected = "#include <memory>\n"
+ "#include \"z.h\"\n"
+ "\n"
+ "int main() {}";
+ tooling::Replacements Replaces = {createInsertion("#include \"z.h\"")};
+ Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp);
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertOneIncludeLLVMStyle) {
+ std::string Code = "#include \"x/fix.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"b.h\"\n"
+ "#include \"clang/Format/Format.h\"\n"
+ "#include <memory>\n";
+ std::string Expected = "#include \"x/fix.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"b.h\"\n"
+ "#include \"d.h\"\n"
+ "#include \"clang/Format/Format.h\"\n"
+ "#include \"llvm/x/y.h\"\n"
+ "#include <memory>\n";
+ tooling::Replacements Replaces = {createInsertion("#include \"d.h\""),
+ createInsertion("#include \"llvm/x/y.h\"")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertMultipleIncludesLLVMStyle) {
+ std::string Code = "#include \"x/fix.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"b.h\"\n"
+ "#include \"clang/Format/Format.h\"\n"
+ "#include <memory>\n";
+ std::string Expected = "#include \"x/fix.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"b.h\"\n"
+ "#include \"new/new.h\"\n"
+ "#include \"clang/Format/Format.h\"\n"
+ "#include <memory>\n"
+ "#include <list>\n";
+ tooling::Replacements Replaces = {createInsertion("#include <list>"),
+ createInsertion("#include \"new/new.h\"")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertNewSystemIncludeGoogleStyle) {
+ std::string Code = "#include \"x/fix.h\"\n"
+ "\n"
+ "#include \"y/a.h\"\n"
+ "#include \"z/b.h\"\n";
+ // FIXME: inserting after the empty line following the main header might be
+ // prefered.
+ std::string Expected = "#include \"x/fix.h\"\n"
+ "#include <vector>\n"
+ "\n"
+ "#include \"y/a.h\"\n"
+ "#include \"z/b.h\"\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp);
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertMultipleIncludesGoogleStyle) {
+ std::string Code = "#include \"x/fix.h\"\n"
+ "\n"
+ "#include <vector>\n"
+ "\n"
+ "#include \"y/a.h\"\n"
+ "#include \"z/b.h\"\n";
+ std::string Expected = "#include \"x/fix.h\"\n"
+ "\n"
+ "#include <vector>\n"
+ "#include <list>\n"
+ "\n"
+ "#include \"y/a.h\"\n"
+ "#include \"z/b.h\"\n"
+ "#include \"x/x.h\"\n";
+ tooling::Replacements Replaces = {createInsertion("#include <list>"),
+ createInsertion("#include \"x/x.h\"")};
+ Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp);
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertMultipleNewHeadersAndSortLLVM) {
+ std::string Code = "\nint x;";
+ std::string Expected = "\n#include \"fix.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"b.h\"\n"
+ "#include \"c.h\"\n"
+ "#include <list>\n"
+ "#include <vector>\n"
+ "int x;";
+ tooling::Replacements Replaces = {createInsertion("#include \"a.h\""),
+ createInsertion("#include \"c.h\""),
+ createInsertion("#include \"b.h\""),
+ createInsertion("#include <vector>"),
+ createInsertion("#include <list>"),
+ createInsertion("#include \"fix.h\"")};
+ EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, InsertMultipleNewHeadersAndSortGoogle) {
+ std::string Code = "\nint x;";
+ std::string Expected = "\n#include \"fix.h\"\n"
+ "#include <list>\n"
+ "#include <vector>\n"
+ "#include \"a.h\"\n"
+ "#include \"b.h\"\n"
+ "#include \"c.h\"\n"
+ "int x;";
+ tooling::Replacements Replaces = {createInsertion("#include \"a.h\""),
+ createInsertion("#include \"c.h\""),
+ createInsertion("#include \"b.h\""),
+ createInsertion("#include <vector>"),
+ createInsertion("#include <list>"),
+ createInsertion("#include \"fix.h\"")};
+ Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp);
+ EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, FormatCorrectLineWhenHeadersAreInserted) {
+ std::string Code = "\n"
+ "int x;\n"
+ "int a;\n"
+ "int a;\n"
+ "int a;";
+
+ std::string Expected = "\n#include \"x.h\"\n"
+ "#include \"y.h\"\n"
+ "#include \"clang/x/x.h\"\n"
+ "#include <list>\n"
+ "#include <vector>\n"
+ "int x;\n"
+ "int a;\n"
+ "int b;\n"
+ "int a;";
+ tooling::Replacements Replaces = {
+ createReplacement(getOffset(Code, 4, 8), 1, "b"),
+ createInsertion("#include <vector>"),
+ createInsertion("#include <list>"),
+ createInsertion("#include \"clang/x/x.h\""),
+ createInsertion("#include \"y.h\""),
+ createInsertion("#include \"x.h\"")};
+ EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, NotConfusedByDefine) {
+ std::string Code = "void f() {}\n"
+ "#define A \\\n"
+ " int i;";
+ std::string Expected = "#include <vector>\n"
+ "void f() {}\n"
+ "#define A \\\n"
+ " int i;";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, SkippedTopComment) {
+ std::string Code = "// comment\n"
+ "\n"
+ " // comment\n";
+ std::string Expected = "// comment\n"
+ "\n"
+ " // comment\n"
+ "#include <vector>\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, SkippedMixedComments) {
+ std::string Code = "// comment\n"
+ "// comment \\\n"
+ " comment continued\n"
+ "/*\n"
+ "* comment\n"
+ "*/\n";
+ std::string Expected = "// comment\n"
+ "// comment \\\n"
+ " comment continued\n"
+ "/*\n"
+ "* comment\n"
+ "*/\n"
+ "#include <vector>\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, MultipleBlockCommentsInOneLine) {
+ std::string Code = "/*\n"
+ "* comment\n"
+ "*/ /* comment\n"
+ "*/\n"
+ "\n\n"
+ "/* c1 */ /*c2 */\n";
+ std::string Expected = "/*\n"
+ "* comment\n"
+ "*/ /* comment\n"
+ "*/\n"
+ "\n\n"
+ "/* c1 */ /*c2 */\n"
+ "#include <vector>\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, CodeAfterComments) {
+ std::string Code = "/*\n"
+ "* comment\n"
+ "*/ /* comment\n"
+ "*/\n"
+ "\n\n"
+ "/* c1 */ /*c2 */\n"
+ "\n"
+ "int x;\n";
+ std::string Expected = "/*\n"
+ "* comment\n"
+ "*/ /* comment\n"
+ "*/\n"
+ "\n\n"
+ "/* c1 */ /*c2 */\n"
+ "\n"
+ "#include <vector>\n"
+ "int x;\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, FakeHeaderGuardIfDef) {
+ std::string Code = "// comment \n"
+ "#ifdef X\n"
+ "#define X\n";
+ std::string Expected = "// comment \n"
+ "#include <vector>\n"
+ "#ifdef X\n"
+ "#define X\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, RealHeaderGuardAfterComments) {
+ std::string Code = "// comment \n"
+ "#ifndef X\n"
+ "#define X\n"
+ "int x;\n"
+ "#define Y 1\n";
+ std::string Expected = "// comment \n"
+ "#ifndef X\n"
+ "#define X\n"
+ "#include <vector>\n"
+ "int x;\n"
+ "#define Y 1\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, IfNDefWithNoDefine) {
+ std::string Code = "// comment \n"
+ "#ifndef X\n"
+ "int x;\n"
+ "#define Y 1\n";
+ std::string Expected = "// comment \n"
+ "#include <vector>\n"
+ "#ifndef X\n"
+ "int x;\n"
+ "#define Y 1\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, HeaderGuardWithComment) {
+ std::string Code = "// comment \n"
+ "#ifndef X // comment\n"
+ "// comment\n"
+ "/* comment\n"
+ "*/\n"
+ "/* comment */ #define X\n"
+ "int x;\n"
+ "#define Y 1\n";
+ std::string Expected = "// comment \n"
+ "#ifndef X // comment\n"
+ "// comment\n"
+ "/* comment\n"
+ "*/\n"
+ "/* comment */ #define X\n"
+ "#include <vector>\n"
+ "int x;\n"
+ "#define Y 1\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, EmptyCode) {
+ std::string Code = "";
+ std::string Expected = "#include <vector>\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+// FIXME: although this case does not crash, the insertion is wrong. A '\n'
+// should be inserted between the two #includes.
+TEST_F(CleanUpReplacementsTest, NoNewLineAtTheEndOfCode) {
+ std::string Code = "#include <map>";
+ std::string Expected = "#include <map>#include <vector>\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, SkipExistingHeaders) {
+ std::string Code = "#include \"a.h\"\n"
+ "#include <vector>\n";
+ std::string Expected = "#include \"a.h\"\n"
+ "#include <vector>\n";
+ tooling::Replacements Replaces = {createInsertion("#include <vector>"),
+ createInsertion("#include \"a.h\"")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, AddIncludesWithDifferentForms) {
+ std::string Code = "#include \"a.h\"\n"
+ "#include <vector>\n";
+ // FIXME: this might not be the best behavior.
+ std::string Expected = "#include \"a.h\"\n"
+ "#include \"vector\"\n"
+ "#include <vector>\n"
+ "#include <a.h>\n";
+ tooling::Replacements Replaces = {createInsertion("#include \"vector\""),
+ createInsertion("#include <a.h>")};
+ EXPECT_EQ(Expected, apply(Code, Replaces));
+}
+
+} // end namespace
+} // end namespace format
+} // end namespace clang
diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp
index 6245f8c043..8d46ba6efc 100644
--- a/unittests/Format/FormatTest.cpp
+++ b/unittests/Format/FormatTest.cpp
@@ -7,9 +7,14 @@
//
//===----------------------------------------------------------------------===//
-#include "FormatTestUtils.h"
#include "clang/Format/Format.h"
+
+#include "../Tooling/RewriterTestContext.h"
+#include "FormatTestUtils.h"
+
+#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/Support/Debug.h"
+#include "llvm/Support/MemoryBuffer.h"
#include "gtest/gtest.h"
#define DEBUG_TYPE "format-test"
@@ -42,10 +47,10 @@ protected:
EXPECT_EQ(ExpectedIncompleteFormat, IncompleteFormat) << Code << "\n\n";
}
ReplacementCount = Replaces.size();
- std::string Result = applyAllReplacements(Code, Replaces);
- EXPECT_NE("", Result);
- DEBUG(llvm::errs() << "\n" << Result << "\n\n");
- return Result;
+ auto Result = applyAllReplacements(Code, Replaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+ return *Result;
}
FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
@@ -291,11 +296,23 @@ TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
verifyFormat("if (a)\n if (b) {\n f();\n }\ng();");
FormatStyle AllowsMergedIf = getLLVMStyle();
+ AllowsMergedIf.AlignEscapedNewlinesLeft = true;
AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
verifyFormat("if (a)\n"
" // comment\n"
" f();",
AllowsMergedIf);
+ verifyFormat("{\n"
+ " if (a)\n"
+ " label:\n"
+ " f();\n"
+ "}",
+ AllowsMergedIf);
+ verifyFormat("#define A \\\n"
+ " if (a) \\\n"
+ " label: \\\n"
+ " f()",
+ AllowsMergedIf);
verifyFormat("if (a)\n"
" ;",
AllowsMergedIf);
@@ -738,6 +755,7 @@ TEST_F(FormatTest, CaseRanges) {
verifyFormat("switch (x) {\n"
"case 'A' ... 'Z':\n"
"case 1 ... 5:\n"
+ "case a ... b:\n"
" break;\n"
"}");
}
@@ -962,6 +980,14 @@ TEST_F(FormatTest, UnderstandsSingleLineComments) {
"// at start\n"
"otherLine();"));
EXPECT_EQ("lineWith(); // comment\n"
+ "/*\n"
+ " * at start */\n"
+ "otherLine();",
+ format("lineWith(); // comment\n"
+ "/*\n"
+ " * at start */\n"
+ "otherLine();"));
+ EXPECT_EQ("lineWith(); // comment\n"
" // at start\n"
"otherLine();",
format("lineWith(); // comment\n"
@@ -1022,6 +1048,15 @@ TEST_F(FormatTest, UnderstandsSingleLineComments) {
" lineWith(); // comment\n"
" // at start\n"
"}"));
+ EXPECT_EQ("int xy; // a\n"
+ "int z; // b",
+ format("int xy; // a\n"
+ "int z; //b"));
+ EXPECT_EQ("int xy; // a\n"
+ "int z; // bb",
+ format("int xy; // a\n"
+ "int z; //bb",
+ getLLVMStyleWithColumns(12)));
verifyFormat("#define A \\\n"
" int i; /* iiiiiiiiiiiiiiiiiiiii */ \\\n"
@@ -1088,7 +1123,7 @@ TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) {
TEST_F(FormatTest, UnderstandsBlockComments) {
verifyFormat("f(/*noSpaceAfterParameterNamingComment=*/true);");
- verifyFormat("void f() { g(/*aaa=*/x, /*bbb=*/!y); }");
+ verifyFormat("void f() { g(/*aaa=*/x, /*bbb=*/!y, /*c=*/::c); }");
EXPECT_EQ("f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
" bbbbbbbbbbbbbbbbbbbbbbbbb);",
format("f(aaaaaaaaaaaaaaaaaaaaaaaaa , \\\n"
@@ -1108,6 +1143,8 @@ TEST_F(FormatTest, UnderstandsBlockComments) {
" aaaaaaaaaaaaaaaaaa ,\n"
" aaaaaaaaaaaaaaaaaa) { /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
"}"));
+ verifyFormat("f(/* aaaaaaaaaaaaaaaaaa = */\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackParameters = false;
@@ -2732,6 +2769,12 @@ TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
" case 1: \\\n"
" case 2\n",
getLLVMStyleWithColumns(20));
+ verifyFormat("#define MACRO(a) \\\n"
+ " if (a) \\\n"
+ " f(); \\\n"
+ " else \\\n"
+ " g()",
+ getLLVMStyleWithColumns(18));
verifyFormat("#define A template <typename T>");
verifyIncompleteFormat("#define STR(x) #x\n"
"f(STR(this_is_a_string_literal{));");
@@ -3607,6 +3650,7 @@ TEST_F(FormatTest, ConstructorInitializers) {
FormatStyle OnePerLine = getLLVMStyle();
OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
+ OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
verifyFormat("SomeClass::Constructor()\n"
" : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
@@ -3633,6 +3677,13 @@ TEST_F(FormatTest, ConstructorInitializers) {
" : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaa) {}",
OnePerLine);
+ OnePerLine.BinPackParameters = false;
+ verifyFormat(
+ "Constructor()\n"
+ " : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaa().aaa(),\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
+ OnePerLine);
OnePerLine.ColumnLimit = 60;
verifyFormat("Constructor()\n"
" : aaaaaaaaaaaaaaaaaaaa(a),\n"
@@ -3825,6 +3876,11 @@ TEST_F(FormatTest, BreaksFunctionDeclarations) {
"typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
"aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
+ verifyGoogleFormat(
+ "template <typename T>\n"
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
FormatStyle Style = getLLVMStyle();
Style.PointerAlignment = FormatStyle::PAS_Left;
@@ -3962,6 +4018,12 @@ TEST_F(FormatTest, FunctionAnnotations) {
" << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
" ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
+ verifyFormat("MACRO(abc).function() // wrap\n"
+ " << abc;");
+ verifyFormat("MACRO(abc)->function() // wrap\n"
+ " << abc;");
+ verifyFormat("MACRO(abc)::function() // wrap\n"
+ " << abc;");
}
TEST_F(FormatTest, BreaksDesireably) {
@@ -4054,6 +4116,23 @@ TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
" int aaaaaaaaaaaaaaaaaaaa,\n"
" int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
NoBinPacking);
+
+ NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
+ verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " vector<int> bbbbbbbbbbbbbbb);",
+ NoBinPacking);
+ // FIXME: This behavior difference is probably not wanted. However, currently
+ // we cannot distinguish BreakBeforeParameter being set because of the wrapped
+ // template arguments from BreakBeforeParameter being set because of the
+ // one-per-line formatting.
+ verifyFormat(
+ "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaa> aaaaaaaaaa);",
+ NoBinPacking);
+ verifyFormat(
+ "void fffffffffff(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
+ " aaaaaaaaaa);");
}
TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
@@ -4157,8 +4236,9 @@ TEST_F(FormatTest, FormatsBuilderPattern) {
verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
" aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
verifyFormat(
- "aaaaaaa->aaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ "aaaaaaa->aaaaaaa\n"
+ " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" ->aaaaaaaa(aaaaaaaaaaaaaaa);");
verifyFormat(
"aaaaaaa->aaaaaaa\n"
@@ -4234,6 +4314,25 @@ TEST_F(FormatTest, FormatsBuilderPattern) {
"return !soooooooooooooome_map\n"
" .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
" .second;");
+ verifyFormat(
+ "return aaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
+ " .aaaa(aaaaaaaaaaaaaa);");
+ // No hanging indent here.
+ verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ getLLVMStyleWithColumns(60));
+ verifyFormat("aaaaaaaaaaaaaaaaaa\n"
+ " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ getLLVMStyleWithColumns(59));
+ verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
}
TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
@@ -4372,6 +4471,11 @@ TEST_F(FormatTest, AlignsAfterOpenBracket) {
" aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
Style);
+ verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
+ " ccccccc(aaaaaaaaaaaaaaaaa, //\n"
+ " b));",
+ Style);
+
Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
Style.BinPackArguments = false;
Style.BinPackParameters = false;
@@ -4385,12 +4489,31 @@ TEST_F(FormatTest, AlignsAfterOpenBracket) {
" aaaaaaaaaaa aaaaaaaaa,\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
Style);
- verifyFormat("SomeLongVariableName->someFunction(\n"
- " foooooooo(\n"
- " aaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaa,\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
+ verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
+ " aaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaa,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
Style);
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
+ Style);
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
+ Style);
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
+ " aaaaaaaaaaaaaaaa);",
+ Style);
+ verifyFormat(
+ "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
+ " aaaaaaaaaaaaaaaa);",
+ Style);
}
TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
@@ -4632,6 +4755,14 @@ TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
" ccccccccccccccc :\n"
" ddddddddddddddd);",
Style);
+ verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
+ " ccccccccccccccccccccccccccc;",
+ Style);
+ verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
+ " aaaaa :\n"
+ " bbbbbbbbbbbbbbb + cccccccccccccccc;",
+ Style);
}
TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
@@ -5029,6 +5160,13 @@ TEST_F(FormatTest, AlignsPipes) {
" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
" << BEF << IsTemplate << Description << E->getType();");
+ verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
+ " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+ " << aaa;");
verifyFormat(
"llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
@@ -5048,6 +5186,15 @@ TEST_F(FormatTest, AlignsPipes) {
verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
" << bbbbbbbbbbbbbbbbbbbbbb << endl;");
verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
+
+ // Handle '\n'.
+ verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
+ " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
+ verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
+ " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
+ verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
+ " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
+ verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
}
TEST_F(FormatTest, UnderstandsEquals) {
@@ -5243,6 +5390,10 @@ TEST_F(FormatTest, WrapsTemplateDeclarations) {
verifyFormat("template <typename T> // T can be A, B or C.\n"
"struct C {};",
AlwaysBreak);
+ verifyFormat("template <enum E> class A {\n"
+ "public:\n"
+ " E *f();\n"
+ "};");
}
TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
@@ -5319,6 +5470,10 @@ TEST_F(FormatTest, UnderstandsTemplateParameters) {
verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
"sizeof(char)>::type>;");
verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
+ verifyFormat("f(a.operator()<A>());");
+ verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ " .template operator()<A>());",
+ getLLVMStyleWithColumns(35));
// Not template parameters.
verifyFormat("return a < b && c > d;");
@@ -5339,6 +5494,7 @@ TEST_F(FormatTest, UnderstandsTemplateParameters) {
TEST_F(FormatTest, UnderstandsBinaryOperators) {
verifyFormat("COMPARE(a, ==, b);");
+ verifyFormat("auto s = sizeof...(Ts) - 1;");
}
TEST_F(FormatTest, UnderstandsPointersToMembers) {
@@ -5421,6 +5577,7 @@ TEST_F(FormatTest, UnderstandsOverloadedOperators) {
verifyFormat("bool operator!=();");
verifyFormat("int operator+();");
verifyFormat("int operator++();");
+ verifyFormat("bool operator,();");
verifyFormat("bool operator();");
verifyFormat("bool operator()();");
verifyFormat("bool operator[]();");
@@ -5436,6 +5593,8 @@ TEST_F(FormatTest, UnderstandsOverloadedOperators) {
verifyFormat("void operator delete[](void *ptr);");
verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
"AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
+ " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
verifyFormat(
"ostream &operator<<(ostream &OutputStream,\n"
@@ -5468,14 +5627,21 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
+ verifyFormat("SomeType MemberFunction(const Deleted &) const &;");
FormatStyle AlignLeft = getLLVMStyle();
AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
+ verifyFormat("void A::b() && {}", AlignLeft);
verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
AlignLeft);
verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
+ verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
+ verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
+ verifyFormat("auto Function(T) & -> void {}", AlignLeft);
+ verifyFormat("auto Function(T) & -> void;", AlignLeft);
+ verifyFormat("SomeType MemberFunction(const Deleted&) const &;", AlignLeft);
FormatStyle Spaces = getLLVMStyle();
Spaces.SpacesInCStyleCastParentheses = true;
@@ -5560,6 +5726,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
verifyFormat("[](const decltype(*a) &value) {}");
verifyFormat("decltype(a * b) F();");
verifyFormat("#define MACRO() [](A *a) { return 1; }");
+ verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
verifyIndependentOfContext("typedef void (*f)(int *a);");
verifyIndependentOfContext("int i{a * b};");
verifyIndependentOfContext("aaa && aaa->f();");
@@ -5588,6 +5755,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+ verifyGoogleFormat("int const* a = &b;");
verifyGoogleFormat("**outparam = 1;");
verifyGoogleFormat("*outparam = a * b;");
verifyGoogleFormat("int main(int argc, char** argv) {}");
@@ -5613,6 +5781,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
Left.PointerAlignment = FormatStyle::PAS_Left;
verifyFormat("x = *a(x) = *a(y);", Left);
verifyFormat("for (;; * = b) {\n}", Left);
+ verifyFormat("return *this += 1;", Left);
verifyIndependentOfContext("a = *(x + y);");
verifyIndependentOfContext("a = &(x + y);");
@@ -5855,6 +6024,7 @@ TEST_F(FormatTest, FormatsCasts) {
verifyFormat("my_int a = (my_int)(my_int)-1;");
verifyFormat("my_int a = (ns::my_int)-2;");
verifyFormat("case (my_int)ONE:");
+ verifyFormat("auto x = (X)this;");
// FIXME: single value wrapped with paren will be treated as cast.
verifyFormat("void f(int i = (kValue)*kMask) {}");
@@ -5927,6 +6097,8 @@ TEST_F(FormatTest, FormatsFunctionTypes) {
verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
verifyFormat("some_var = function(*some_pointer_var)[0];");
verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
+ verifyFormat("int x = f(&h)();");
+ verifyFormat("returnsFunction(&param1, &param2)(param);");
}
TEST_F(FormatTest, FormatsPointersToArrayTypes) {
@@ -5970,6 +6142,10 @@ TEST_F(FormatTest, BreaksLongDeclarations) {
"LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
"LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
+ "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
+ verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
+ "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
FormatStyle Indented = getLLVMStyle();
Indented.IndentWrappedFunctionNames = true;
verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
@@ -6043,6 +6219,10 @@ TEST_F(FormatTest, BreaksLongDeclarations) {
TEST_F(FormatTest, FormatsArrays) {
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
" [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
+ " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
+ verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
+ " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
" [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
@@ -6054,6 +6234,8 @@ TEST_F(FormatTest, FormatsArrays) {
"llvm::outs() << \"aaaaaaaaaaaa: \"\n"
" << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
" [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
+ verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
+ " .aaaaaaaaaaaaaaaaaaaaaa();");
verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
@@ -6061,8 +6243,12 @@ TEST_F(FormatTest, FormatsArrays) {
"aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
" .aaaaaaa[0]\n"
" .aaaaaaaaaaaaaaaaaaaaaa();");
+ verifyFormat("a[::b::c];");
verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
+
+ FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
+ verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
}
TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
@@ -6532,12 +6718,21 @@ TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
verifyNoCrash("a<,");
-
+
// No braced initializer here.
verifyFormat("void f() {\n"
" struct Dummy {};\n"
" f(v);\n"
"}");
+
+ // Long lists should be formatted in columns even if they are nested.
+ verifyFormat(
+ "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
+ " 1, 22, 333, 4444, 55555, 666666, 7777777});");
}
TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
@@ -6834,6 +7029,14 @@ TEST_F(FormatTest, BlockComments) {
"* aaaaaa aaaaaa\n"
"*/",
getLLVMStyleWithColumns(10)));
+ EXPECT_EQ("int aaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " /* line 1\n"
+ " bbbbbbbbbbbb */\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+ format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+ " /* line 1\n"
+ " bbbbbbbbbbbb */ bbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+ getLLVMStyleWithColumns(50)));
FormatStyle NoBinPacking = getLLVMStyle();
NoBinPacking.BinPackParameters = false;
@@ -6942,10 +7145,9 @@ TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
}
TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
- // FIXME: This is not what we want...
verifyFormat("{\n"
- "// a"
- "// b");
+ " // a\n"
+ " // b");
}
TEST_F(FormatTest, FormatStarDependingOnContext) {
@@ -7275,6 +7477,11 @@ TEST_F(FormatTest, FormatObjCMethodDeclarations) {
" interval:(float)theInterval {\n"
"}");
verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
+ " longKeyword:(NSRect)theRect\n"
+ " longerKeyword:(float)theInterval\n"
+ " error:(NSError **)theError {\n"
+ "}");
+ verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
" longKeyword:(NSRect)theRect\n"
" evenLongerKeyword:(float)theInterval\n"
" error:(NSError **)theError {\n"
@@ -7463,8 +7670,8 @@ TEST_F(FormatTest, FormatObjCMethodExpr) {
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaa[aaaaaaaaaaaaaaaaaaaaa]\n"
" aaaaaaaaaaaaaaaaaaaaaa];");
- verifyFormat("[call aaaaaaaa.aaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa\n"
- " .aaaaaaaa.aaaaaaaa];", // FIXME: Indentation seems off.
+ verifyFormat("[call aaaaaaaa.aaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa\n"
+ " .aaaaaaaa];", // FIXME: Indentation seems off.
getLLVMStyleWithColumns(60));
verifyFormat(
@@ -7677,7 +7884,12 @@ TEST_F(FormatTest, ObjCArrayLiterals) {
" aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
" @\"aaaaaaaaaaaaaaaaa\",\n"
" @\"aaaaaaaaaaaaaaaaa\",\n"
- " @\"aaaaaaaaaaaaaaaaa\"\n"
+ " @\"aaaaaaaaaaaaaaaaa\",\n"
+ "];");
+ verifyFormat(
+ "NSArray *some_variable = @[\n"
+ " aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
+ " @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\"\n"
"];");
verifyFormat("NSArray *some_variable = @[\n"
" @\"aaaaaaaaaaaaaaaaa\",\n"
@@ -7685,12 +7897,6 @@ TEST_F(FormatTest, ObjCArrayLiterals) {
" @\"aaaaaaaaaaaaaaaaa\",\n"
" @\"aaaaaaaaaaaaaaaaa\",\n"
"];");
- verifyGoogleFormat("NSArray *some_variable = @[\n"
- " @\"aaaaaaaaaaaaaaaaa\",\n"
- " @\"aaaaaaaaaaaaaaaaa\",\n"
- " @\"aaaaaaaaaaaaaaaaa\",\n"
- " @\"aaaaaaaaaaaaaaaaa\"\n"
- "];");
verifyFormat("NSArray *array = @[\n"
" @\"a\",\n"
" @\"a\",\n" // Trailing comma -> one per line.
@@ -7861,6 +8067,10 @@ TEST_F(FormatTest, BreaksStringLiterals) {
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
getGoogleStyle()));
+ FormatStyle Style = getLLVMStyleWithColumns(12);
+ Style.BreakStringLiterals = false;
+ EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
+
FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
AlignLeft.AlignEscapedNewlinesLeft = true;
EXPECT_EQ("#define A \\\n"
@@ -8259,7 +8469,7 @@ TEST_F(FormatTest, ConfigurableUseOfTab) {
"\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
"};",
Tab);
- verifyFormat("enum A {\n"
+ verifyFormat("enum AA {\n"
"\ta1, // Force multiple lines\n"
"\ta2,\n"
"\ta3\n"
@@ -8396,6 +8606,230 @@ TEST_F(FormatTest, ConfigurableUseOfTab) {
"\t */\n"
"\t int i;\n"
"}"));
+
+ Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 8;
+ EXPECT_EQ("if (aaaaaaaa && // q\n"
+ " bb) // w\n"
+ "\t;",
+ format("if (aaaaaaaa &&// q\n"
+ "bb)// w\n"
+ ";",
+ Tab));
+ EXPECT_EQ("if (aaa && bbb) // w\n"
+ "\t;",
+ format("if(aaa&&bbb)// w\n"
+ ";",
+ Tab));
+ verifyFormat("class X {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ verifyFormat("#define A \\\n"
+ "\tvoid f() { \\\n"
+ "\t\tsomeFunction( \\\n"
+ "\t\t parameter1, \\\n"
+ "\t\t parameter2); \\\n"
+ "\t}",
+ Tab);
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 8;
+ verifyFormat("class TabWidth4Indent8 {\n"
+ "\t\tvoid f() {\n"
+ "\t\t\t\tsomeFunction(parameter1,\n"
+ "\t\t\t\t\t\t\t parameter2);\n"
+ "\t\t}\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 4;
+ verifyFormat("class TabWidth4Indent4 {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t\t\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 4;
+ verifyFormat("class TabWidth8Indent4 {\n"
+ " void f() {\n"
+ "\tsomeFunction(parameter1,\n"
+ "\t\t parameter2);\n"
+ " }\n"
+ "};",
+ Tab);
+ Tab.TabWidth = 8;
+ Tab.IndentWidth = 8;
+ EXPECT_EQ("/*\n"
+ "\t a\t\tcomment\n"
+ "\t in multiple lines\n"
+ " */",
+ format(" /*\t \t \n"
+ " \t \t a\t\tcomment\t \t\n"
+ " \t \t in multiple lines\t\n"
+ " \t */",
+ Tab));
+ verifyFormat("{\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
+ "};",
+ Tab);
+ verifyFormat("enum AA {\n"
+ "\ta1, // Force multiple lines\n"
+ "\ta2,\n"
+ "\ta3\n"
+ "};",
+ Tab);
+ EXPECT_EQ("if (aaaaaaaa && // q\n"
+ " bb) // w\n"
+ "\t;",
+ format("if (aaaaaaaa &&// q\n"
+ "bb)// w\n"
+ ";",
+ Tab));
+ verifyFormat("class X {\n"
+ "\tvoid f() {\n"
+ "\t\tsomeFunction(parameter1,\n"
+ "\t\t\t parameter2);\n"
+ "\t}\n"
+ "};",
+ Tab);
+ verifyFormat("{\n"
+ "\tQ(\n"
+ "\t {\n"
+ "\t\t int a;\n"
+ "\t\t someFunction(aaaaaaaa,\n"
+ "\t\t\t\t bbbbbbb);\n"
+ "\t },\n"
+ "\t p);\n"
+ "}",
+ Tab);
+ EXPECT_EQ("{\n"
+ "\t/* aaaa\n"
+ "\t bbbb */\n"
+ "}",
+ format("{\n"
+ "/* aaaa\n"
+ " bbbb */\n"
+ "}",
+ Tab));
+ EXPECT_EQ("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ format("{\n"
+ "/*\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "*/\n"
+ "}",
+ Tab));
+ EXPECT_EQ("{\n"
+ "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t// bbbbbbbbbbbbb\n"
+ "}",
+ format("{\n"
+ "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "}",
+ Tab));
+ EXPECT_EQ("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "\t bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ format("{\n"
+ "\t/*\n"
+ "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
+ "\t*/\n"
+ "}",
+ Tab));
+ EXPECT_EQ("{\n"
+ "\t/*\n"
+ "\n"
+ "\t*/\n"
+ "}",
+ format("{\n"
+ "\t/*\n"
+ "\n"
+ "\t*/\n"
+ "}",
+ Tab));
+ EXPECT_EQ("{\n"
+ "\t/*\n"
+ " asdf\n"
+ "\t*/\n"
+ "}",
+ format("{\n"
+ "\t/*\n"
+ " asdf\n"
+ "\t*/\n"
+ "}",
+ Tab));
+ EXPECT_EQ("/*\n"
+ "\t a\t\tcomment\n"
+ "\t in multiple lines\n"
+ " */",
+ format(" /*\t \t \n"
+ " \t \t a\t\tcomment\t \t\n"
+ " \t \t in multiple lines\t\n"
+ " \t */",
+ Tab));
+ EXPECT_EQ("/* some\n"
+ " comment */",
+ format(" \t \t /* some\n"
+ " \t \t comment */",
+ Tab));
+ EXPECT_EQ("int a; /* some\n"
+ " comment */",
+ format(" \t \t int a; /* some\n"
+ " \t \t comment */",
+ Tab));
+ EXPECT_EQ("int a; /* some\n"
+ "comment */",
+ format(" \t \t int\ta; /* some\n"
+ " \t \t comment */",
+ Tab));
+ EXPECT_EQ("f(\"\t\t\"); /* some\n"
+ " comment */",
+ format(" \t \t f(\"\t\t\"); /* some\n"
+ " \t \t comment */",
+ Tab));
+ EXPECT_EQ("{\n"
+ " /*\n"
+ " * Comment\n"
+ " */\n"
+ " int i;\n"
+ "}",
+ format("{\n"
+ "\t/*\n"
+ "\t * Comment\n"
+ "\t */\n"
+ "\t int i;\n"
+ "}"));
+ Tab.AlignConsecutiveAssignments = true;
+ Tab.AlignConsecutiveDeclarations = true;
+ Tab.TabWidth = 4;
+ Tab.IndentWidth = 4;
+ verifyFormat("class Assign {\n"
+ "\tvoid f() {\n"
+ "\t\tint x = 123;\n"
+ "\t\tint random = 4;\n"
+ "\t\tstd::string alphabet =\n"
+ "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
+ "\t}\n"
+ "};",
+ Tab);
}
TEST_F(FormatTest, CalculatesOriginalColumn) {
@@ -8556,7 +8990,8 @@ TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
verifyFormat("#define x (( int )-1)", Spaces);
// Run the first set of tests again with:
- Spaces.SpacesInParentheses = false, Spaces.SpaceInEmptyParentheses = true;
+ Spaces.SpacesInParentheses = false;
+ Spaces.SpaceInEmptyParentheses = true;
Spaces.SpacesInCStyleCastParentheses = true;
verifyFormat("call(x, y, z);", Spaces);
verifyFormat("call( );", Spaces);
@@ -9726,8 +10161,10 @@ TEST_F(FormatTest, ParsesConfigurationBools) {
CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
CHECK_PARSE_BOOL(BinPackArguments);
CHECK_PARSE_BOOL(BinPackParameters);
+ CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
CHECK_PARSE_BOOL(BreakConstructorInitializersBeforeComma);
+ CHECK_PARSE_BOOL(BreakStringLiterals);
CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
CHECK_PARSE_BOOL(DerivePointerAlignment);
CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
@@ -9782,6 +10219,7 @@ TEST_F(FormatTest, ParsesConfiguration) {
SpacesBeforeTrailingComments, 1234u);
CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
+ CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
Style.PointerAlignment = FormatStyle::PAS_Middle;
CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
@@ -9835,6 +10273,8 @@ TEST_F(FormatTest, ParsesConfiguration) {
CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
+ CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
+ FormatStyle::UT_ForContinuationAndIndentation);
// For backward compatibility:
CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
@@ -9940,6 +10380,7 @@ TEST_F(FormatTest, ParsesConfiguration) {
" - Regex: .*\n"
" Priority: 1",
IncludeCategories, ExpectedCategories);
+ CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeIsMainRegex, "abc$");
}
TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
@@ -10221,6 +10662,15 @@ TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
" aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
Style);
+ Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
+ verifyFormat(
+ "SomeLongTemplateVariableName<\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
+ Style);
+ verifyFormat(
+ "bool smaller = 1 < bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
+ Style);
}
TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
@@ -10240,6 +10690,9 @@ TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
verifyFormat("SomeClass::Constructor()\n"
" : a(a) {}",
Style);
+ verifyFormat("SomeClass::Constructor() noexcept\n"
+ " : a(a) {}",
+ Style);
verifyFormat("SomeClass::Constructor()\n"
" : a(a)\n"
" , b(b)\n"
@@ -10501,6 +10954,8 @@ TEST_F(FormatTest, FormatsLambdas) {
verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
" return some_parameter.size();\n"
"};");
+ verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
+ " [](const string &s) { return s; };");
verifyFormat("int i = aaaaaa ? 1 //\n"
" : [] {\n"
" return 2; //\n"
@@ -10547,6 +11002,10 @@ TEST_F(FormatTest, FormatsLambdas) {
" return aaaaaaaaaaaaaaaaa;\n"
" });",
getLLVMStyleWithColumns(70));
+ verifyFormat("[]() //\n"
+ " -> int {\n"
+ " return 1; //\n"
+ "};");
// Multiple lambdas in the same parentheses change indentation rules.
verifyFormat("SomeFunction(\n"
@@ -10579,6 +11038,7 @@ TEST_F(FormatTest, FormatsLambdas) {
// Lambdas created through weird macros.
verifyFormat("void f() {\n"
" MACRO((const AA &a) { return 1; });\n"
+ " MACRO((AA &a) { return 1; });\n"
"}");
verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
@@ -11017,6 +11477,119 @@ TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
verifyNoCrash("#define a\\\n /**/}");
}
+TEST_F(FormatTest, FormatsTableGenCode) {
+ FormatStyle Style = getLLVMStyle();
+ Style.Language = FormatStyle::LK_TableGen;
+ verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
+}
+
+// Since this test case uses UNIX-style file path. We disable it for MS
+// compiler.
+#if !defined(_MSC_VER) && !defined(__MINGW32__)
+
+TEST(FormatStyle, GetStyleOfFile) {
+ vfs::InMemoryFileSystem FS;
+ // Test 1: format file in the same directory.
+ ASSERT_TRUE(
+ FS.addFile("/a/.clang-format", 0,
+ llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
+ ASSERT_TRUE(
+ FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
+ auto Style1 = getStyle("file", "/a/.clang-format", "Google", &FS);
+ ASSERT_EQ(Style1, getLLVMStyle());
+
+ // Test 2: fallback to default.
+ ASSERT_TRUE(
+ FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
+ auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", &FS);
+ ASSERT_EQ(Style2, getMozillaStyle());
+
+ // Test 3: format file in parent directory.
+ ASSERT_TRUE(
+ FS.addFile("/c/.clang-format", 0,
+ llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
+ ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
+ llvm::MemoryBuffer::getMemBuffer("int i;")));
+ auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", &FS);
+ ASSERT_EQ(Style3, getGoogleStyle());
+}
+
+#endif // _MSC_VER
+
+class ReplacementTest : public ::testing::Test {
+protected:
+ tooling::Replacement createReplacement(SourceLocation Start, unsigned Length,
+ llvm::StringRef ReplacementText) {
+ return tooling::Replacement(Context.Sources, Start, Length,
+ ReplacementText);
+ }
+
+ RewriterTestContext Context;
+};
+
+TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
+ // Column limit is 20.
+ std::string Code = "Type *a =\n"
+ " new Type();\n"
+ "g(iiiii, 0, jjjjj,\n"
+ " 0, kkkkk, 0, mm);\n"
+ "int bad = format ;";
+ std::string Expected = "auto a = new Type();\n"
+ "g(iiiii, nullptr,\n"
+ " jjjjj, nullptr,\n"
+ " kkkkk, nullptr,\n"
+ " mm);\n"
+ "int bad = format ;";
+ FileID ID = Context.createInMemoryFile("format.cpp", Code);
+ tooling::Replacements Replaces;
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID, 1, 1), 6, "auto "));
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID, 3, 10), 1, "nullptr"));
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID, 4, 3), 1, "nullptr"));
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID, 4, 13), 1, "nullptr"));
+
+ format::FormatStyle Style = format::getLLVMStyle();
+ Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
+ auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
+ EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
+ << llvm::toString(FormattedReplaces.takeError()) << "\n";
+ auto Result = applyAllReplacements(Code, *FormattedReplaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ EXPECT_EQ(Expected, *Result);
+}
+
+TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
+ std::string Code = "#include \"a.h\"\n"
+ "#include \"c.h\"\n"
+ "\n"
+ "int main() {\n"
+ " return 0;\n"
+ "}";
+ std::string Expected = "#include \"a.h\"\n"
+ "#include \"b.h\"\n"
+ "#include \"c.h\"\n"
+ "\n"
+ "int main() {\n"
+ " return 0;\n"
+ "}";
+ FileID ID = Context.createInMemoryFile("fix.cpp", Code);
+ tooling::Replacements Replaces;
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID, 1, 1), 0, "#include \"b.h\"\n"));
+
+ format::FormatStyle Style = format::getLLVMStyle();
+ Style.SortIncludes = true;
+ auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
+ EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
+ << llvm::toString(FormattedReplaces.takeError()) << "\n";
+ auto Result = applyAllReplacements(Code, *FormattedReplaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ EXPECT_EQ(Expected, *Result);
+}
+
} // end namespace
} // end namespace format
} // end namespace clang
diff --git a/unittests/Format/FormatTestJS.cpp b/unittests/Format/FormatTestJS.cpp
index fdcc0b75ad..2819383a35 100644
--- a/unittests/Format/FormatTestJS.cpp
+++ b/unittests/Format/FormatTestJS.cpp
@@ -28,10 +28,10 @@ protected:
tooling::Replacements Replaces =
reformat(Style, Code, Ranges, "<stdin>", &IncompleteFormat);
EXPECT_FALSE(IncompleteFormat);
- std::string Result = applyAllReplacements(Code, Replaces);
- EXPECT_NE("", Result);
- DEBUG(llvm::errs() << "\n" << Result << "\n\n");
- return Result;
+ auto Result = applyAllReplacements(Code, Replaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+ return *Result;
}
static std::string format(
@@ -49,11 +49,24 @@ protected:
static void verifyFormat(
llvm::StringRef Code,
const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
- std::string result = format(test::messUp(Code), Style);
- EXPECT_EQ(Code.str(), result) << "Formatted:\n" << result;
+ std::string Result = format(test::messUp(Code), Style);
+ EXPECT_EQ(Code.str(), Result) << "Formatted:\n" << Result;
+ }
+
+ static void verifyFormat(
+ llvm::StringRef Expected,
+ llvm::StringRef Code,
+ const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_JavaScript)) {
+ std::string Result = format(Code, Style);
+ EXPECT_EQ(Expected.str(), Result) << "Formatted:\n" << Result;
}
};
+TEST_F(FormatTestJS, BlockComments) {
+ verifyFormat("/* aaaaaaaaaaaaa */ aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
+}
+
TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
verifyFormat("a == = b;");
verifyFormat("a != = b;");
@@ -86,6 +99,17 @@ TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
verifyFormat("var b = a.map((x) => x + 1);");
verifyFormat("return ('aaa') in bbbb;");
+ verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
+ " aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
+ FormatStyle Style = getGoogleJSStyleWithColumns(80);
+ Style.AlignOperands = true;
+ verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa() in\n"
+ " aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
+ Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+ verifyFormat("var x = aaaaaaaaaaaaaaaaaaaaaaaaa()\n"
+ " in aaaa.aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+ Style);
// ES6 spread operator.
verifyFormat("someFunction(...a);");
@@ -106,6 +130,11 @@ TEST_F(FormatTestJS, ReservedWords) {
verifyFormat("x.class.struct = 1;");
verifyFormat("x.case = 1;");
verifyFormat("x.interface = 1;");
+ verifyFormat("x.for = 1;");
+ verifyFormat("x.of() = 1;");
+ verifyFormat("x.in() = 1;");
+ verifyFormat("x.let() = 1;");
+ verifyFormat("x.var() = 1;");
verifyFormat("x = {\n"
" a: 12,\n"
" interface: 1,\n"
@@ -113,10 +142,19 @@ TEST_F(FormatTestJS, ReservedWords) {
"};");
verifyFormat("var struct = 2;");
verifyFormat("var union = 2;");
+ verifyFormat("var interface = 2;");
+ verifyFormat("interface = 2;");
+ verifyFormat("x = interface instanceof y;");
+}
+
+TEST_F(FormatTestJS, CppKeywords) {
+ // Make sure we don't mess stuff up because of C++ keywords.
+ verifyFormat("return operator && (aa);");
}
TEST_F(FormatTestJS, ES6DestructuringAssignment) {
verifyFormat("var [a, b, c] = [1, 2, 3];");
+ verifyFormat("const [a, b, c] = [1, 2, 3];");
verifyFormat("let [a, b, c] = [1, 2, 3];");
verifyFormat("var {a, b} = {a: 1, b: 2};");
verifyFormat("let {a, b} = {a: 1, b: 2};");
@@ -184,6 +222,18 @@ TEST_F(FormatTestJS, ContainerLiterals) {
" b: 2,\n"
" [c]: 3,\n"
"};");
+
+ // Object literals can leave out labels.
+ verifyFormat("f({a}, () => {\n"
+ " g(); //\n"
+ "});");
+
+ // Keys can be quoted.
+ verifyFormat("var x = {\n"
+ " a: a,\n"
+ " b: b,\n"
+ " 'c': c,\n"
+ "};");
}
TEST_F(FormatTestJS, MethodsInObjectLiterals) {
@@ -229,7 +279,7 @@ TEST_F(FormatTestJS, SpacesInContainerLiterals) {
verifyFormat("f({'a': [{}]});");
}
-TEST_F(FormatTestJS, SingleQuoteStrings) {
+TEST_F(FormatTestJS, SingleQuotedStrings) {
verifyFormat("this.function('', true);");
}
@@ -256,6 +306,8 @@ TEST_F(FormatTestJS, GoogModules) {
getGoogleJSStyleWithColumns(40));
verifyFormat("goog.setTestOnly('this.is.really.absurdly.long');",
getGoogleJSStyleWithColumns(40));
+ verifyFormat("goog.forwardDeclare('this.is.really.absurdly.long');",
+ getGoogleJSStyleWithColumns(40));
// These should be wrapped normally.
verifyFormat(
@@ -263,6 +315,15 @@ TEST_F(FormatTestJS, GoogModules) {
" goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
}
+TEST_F(FormatTestJS, FormatsNamespaces) {
+ verifyFormat("namespace Foo {\n"
+ " export let x = 1;\n"
+ "}\n");
+ verifyFormat("declare namespace Foo {\n"
+ " export let x: number;\n"
+ "}\n");
+}
+
TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
verifyFormat("function outer1(a, b) {\n"
" function inner1(a, b) { return a; }\n"
@@ -275,17 +336,58 @@ TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
verifyFormat("function f() {}");
}
+TEST_F(FormatTestJS, GeneratorFunctions) {
+ verifyFormat("function* f() {\n"
+ " let x = 1;\n"
+ " yield x;\n"
+ " yield* something();\n"
+ "}");
+ verifyFormat("function*\n"
+ " f() {\n"
+ "}",
+ getGoogleJSStyleWithColumns(8));
+ verifyFormat("export function* f() {\n"
+ " yield 1;\n"
+ "}\n");
+ verifyFormat("class X {\n"
+ " * generatorMethod() { yield x; }\n"
+ "}");
+}
+
+TEST_F(FormatTestJS, AsyncFunctions) {
+ verifyFormat("async function f() {\n"
+ " let x = 1;\n"
+ " return fetch(x);\n"
+ "}");
+ verifyFormat("async function* f() {\n"
+ " yield fetch(x);\n"
+ "}");
+ verifyFormat("export async function f() {\n"
+ " return fetch(x);\n"
+ "}");
+ verifyFormat("class X {\n"
+ " async asyncMethod() { return fetch(1); }\n"
+ "}");
+ verifyFormat("function initialize() {\n"
+ " // Comment.\n"
+ " return async.then();\n"
+ "}\n");
+}
+
TEST_F(FormatTestJS, ArrayLiterals) {
verifyFormat("var aaaaa: List<SomeThing> =\n"
" [new SomeThingAAAAAAAAAAAA(), new SomeThingBBBBBBBBB()];");
verifyFormat("return [\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
" ccccccccccccccccccccccccccc\n"
"];");
+ verifyFormat("return [\n"
+ " aaaa().bbbbbbbb('A'),\n"
+ " aaaa().bbbbbbbb('B'),\n"
+ " aaaa().bbbbbbbb('C'),\n"
+ "];");
verifyFormat("var someVariable = SomeFunction([\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
" ccccccccccccccccccccccccccc\n"
"]);");
verifyFormat("var someVariable = SomeFunction([\n"
@@ -293,22 +395,33 @@ TEST_F(FormatTestJS, ArrayLiterals) {
"]);",
getGoogleJSStyleWithColumns(51));
verifyFormat("var someVariable = SomeFunction(aaaa, [\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
" ccccccccccccccccccccccccccc\n"
"]);");
verifyFormat("var someVariable = SomeFunction(\n"
" aaaa,\n"
" [\n"
- " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
- " bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
- " ccccccccccccccccccccccccccc\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
+ " cccccccccccccccccccccccccc\n"
" ],\n"
" aaaa);");
+ verifyFormat("var aaaa = aaaaa || // wrap\n"
+ " [];");
verifyFormat("someFunction([], {a: a});");
}
+TEST_F(FormatTestJS, ColumnLayoutForArrayLiterals) {
+ verifyFormat("var array = [\n"
+ " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
+ " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
+ "];");
+ verifyFormat("var array = someFunction([\n"
+ " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
+ " a, a, a, a, a, a, a, a, a, a, a, a, a, a, a,\n"
+ "]);");
+}
+
TEST_F(FormatTestJS, FunctionLiterals) {
verifyFormat("doFoo(function() {});");
verifyFormat("doFoo(function() { return 1; });");
@@ -507,6 +620,12 @@ TEST_F(FormatTestJS, MultipleFunctionLiterals) {
verifyFormat("getSomeLongPromise()\n"
" .then(function(value) { body(); })\n"
" .thenCatch(function(error) { body(); });");
+
+ verifyFormat("return [aaaaaaaaaaaaaaaaaaaaaa]\n"
+ " .aaaaaaa(function() {\n"
+ " //\n"
+ " })\n"
+ " .bbbbbb();");
}
TEST_F(FormatTestJS, ArrowFunctions) {
@@ -554,9 +673,15 @@ TEST_F(FormatTestJS, ReturnStatements) {
TEST_F(FormatTestJS, ForLoops) {
verifyFormat("for (var i in [2, 3]) {\n"
"}");
+ verifyFormat("for (var i of [2, 3]) {\n"
+ "}");
+ verifyFormat("for (let {a, b} of x) {\n"
+ "}");
+ verifyFormat("for (let {a, b} in x) {\n"
+ "}");
}
-TEST_F(FormatTestJS, AutomaticSemicolonInsertion) {
+TEST_F(FormatTestJS, WrapRespectsAutomaticSemicolonInsertion) {
// The following statements must not wrap, as otherwise the program meaning
// would change due to automatic semicolon insertion.
// See http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1.
@@ -566,6 +691,60 @@ TEST_F(FormatTestJS, AutomaticSemicolonInsertion) {
verifyFormat("throw aaaaa;", getGoogleJSStyleWithColumns(10));
verifyFormat("aaaaaaaaa++;", getGoogleJSStyleWithColumns(10));
verifyFormat("aaaaaaaaa--;", getGoogleJSStyleWithColumns(10));
+ verifyFormat("return [\n"
+ " aaa\n"
+ "];",
+ getGoogleJSStyleWithColumns(12));
+}
+
+TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
+ verifyFormat("a\n"
+ "b;",
+ " a \n"
+ " b ;");
+ verifyFormat("a()\n"
+ "b;",
+ " a ()\n"
+ " b ;");
+ verifyFormat("a[b]\n"
+ "c;",
+ "a [b]\n"
+ "c ;");
+ verifyFormat("1\n"
+ "a;",
+ "1 \n"
+ "a ;");
+ verifyFormat("a\n"
+ "1;",
+ "a \n"
+ "1 ;");
+ verifyFormat("a\n"
+ "'x';",
+ "a \n"
+ " 'x';");
+ verifyFormat("a++\n"
+ "b;",
+ "a ++\n"
+ "b ;");
+ verifyFormat("a\n"
+ "!b && c;",
+ "a \n"
+ " ! b && c;");
+ verifyFormat("a\n"
+ "if (1) f();",
+ " a\n"
+ " if (1) f();");
+ verifyFormat("a\n"
+ "class X {}",
+ " a\n"
+ " class X {}");
+ verifyFormat("var a", "var\n"
+ "a");
+ verifyFormat("x instanceof String", "x\n"
+ "instanceof\n"
+ "String");
+ verifyFormat("function f(@Foo bar) {}", "function f(@Foo\n"
+ " bar) {}");
}
TEST_F(FormatTestJS, ClosureStyleCasts) {
@@ -666,13 +845,13 @@ TEST_F(FormatTestJS, RegexLiteralSpecialCharacters) {
verifyFormat("var regex = /\a\\//g;");
verifyFormat("var regex = /a\\//;\n"
"var x = 0;");
- EXPECT_EQ("var regex = /'/g;", format("var regex = /'/g ;"));
- EXPECT_EQ("var regex = /'/g; //'", format("var regex = /'/g ; //'"));
- EXPECT_EQ("var regex = /\\/*/;\n"
- "var x = 0;",
- format("var regex = /\\/*/;\n"
- "var x=0;"));
- EXPECT_EQ("var x = /a\\//;", format("var x = /a\\// \n;"));
+ verifyFormat("var regex = /'/g;", "var regex = /'/g ;");
+ verifyFormat("var regex = /'/g; //'", "var regex = /'/g ; //'");
+ verifyFormat("var regex = /\\/*/;\n"
+ "var x = 0;",
+ "var regex = /\\/*/;\n"
+ "var x=0;");
+ verifyFormat("var x = /a\\//;", "var x = /a\\// \n;");
verifyFormat("var regex = /\"/;", getGoogleJSStyleWithColumns(16));
verifyFormat("var regex =\n"
" /\"/;",
@@ -708,15 +887,39 @@ TEST_F(FormatTestJS, RegexLiteralExamples) {
TEST_F(FormatTestJS, TypeAnnotations) {
verifyFormat("var x: string;");
+ verifyFormat("var x: {a: string; b: number;} = {};");
verifyFormat("function x(): string {\n return 'x';\n}");
verifyFormat("function x(): {x: string} {\n return {x: 'x'};\n}");
verifyFormat("function x(y: string): string {\n return 'x';\n}");
verifyFormat("for (var y: string in x) {\n x();\n}");
+ verifyFormat("for (var y: string of x) {\n x();\n}");
+ verifyFormat("function x(y: {a?: number;} = {}): number {\n"
+ " return 12;\n"
+ "}");
verifyFormat("((a: string, b: number): string => a + b);");
verifyFormat("var x: (y: number) => string;");
verifyFormat("var x: P<string, (a: number) => string>;");
verifyFormat("var x = {y: function(): z { return 1; }};");
verifyFormat("var x = {y: function(): {a: number} { return 1; }};");
+ verifyFormat("function someFunc(args: string[]):\n"
+ " {longReturnValue: string[]} {}",
+ getGoogleJSStyleWithColumns(60));
+}
+
+TEST_F(FormatTestJS, UnionIntersectionTypes) {
+ verifyFormat("let x: A|B = A | B;");
+ verifyFormat("let x: A&B|C = A & B;");
+ verifyFormat("let x: Foo<A|B> = new Foo<A|B>();");
+ verifyFormat("function(x: A|B): C&D {}");
+ verifyFormat("function(x: A|B = A | B): C&D {}");
+ verifyFormat("function x(path: number|string) {}");
+ verifyFormat("function x(): string|number {}");
+ verifyFormat("type Foo = Bar|Baz;");
+ verifyFormat("type Foo = Bar<X>|Baz;");
+ verifyFormat("type Foo = (Bar<X>|Baz);");
+ verifyFormat("let x: Bar|Baz;");
+ verifyFormat("let x: Bar<X>|Baz;");
+ verifyFormat("let x: (Foo|Bar)[];");
}
TEST_F(FormatTestJS, ClassDeclarations) {
@@ -732,6 +935,16 @@ TEST_F(FormatTestJS, ClassDeclarations) {
" aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa: aaaaaaaaaaaaaaaaaaaa):\n"
" aaaaaaaaaaaaaaaaaaaaaa {}\n"
"}");
+ verifyFormat("foo = class Name {\n"
+ " constructor() {}\n"
+ "};");
+ verifyFormat("foo = class {\n"
+ " constructor() {}\n"
+ "};");
+ verifyFormat("class C {\n"
+ " x: {y: Z;} = {};\n"
+ " private y: {y: Z;} = {};\n"
+ "}");
// ':' is not a type declaration here.
verifyFormat("class X {\n"
@@ -741,17 +954,29 @@ TEST_F(FormatTestJS, ClassDeclarations) {
" },\n"
" };\n"
"}");
+ verifyFormat("@Component({\n"
+ " moduleId: module.id,\n"
+ "})\n"
+ "class SessionListComponent implements OnDestroy, OnInit {\n"
+ "}");
}
TEST_F(FormatTestJS, InterfaceDeclarations) {
verifyFormat("interface I {\n"
" x: string;\n"
+ " enum: string[];\n"
+ " enum?: string[];\n"
"}\n"
"var y;");
// Ensure that state is reset after parsing the interface.
verifyFormat("interface a {}\n"
"export function b() {}\n"
"var x;");
+
+ // Arrays of object type literals.
+ verifyFormat("interface I {\n"
+ " o: {}[];\n"
+ "}");
}
TEST_F(FormatTestJS, EnumDeclarations) {
@@ -781,29 +1006,32 @@ TEST_F(FormatTestJS, MetadataAnnotations) {
" return 'y';\n"
" }\n"
"}");
+ verifyFormat("class C {\n"
+ " private x(@A x: string) {}\n"
+ "}");
verifyFormat("class X {}\n"
"class Y {}");
}
+TEST_F(FormatTestJS, TypeAliases) {
+ verifyFormat("type X = number;\n"
+ "class C {}");
+ verifyFormat("type X<Y> = Z<Y>;");
+ verifyFormat("type X = {\n"
+ " y: number\n"
+ "};\n"
+ "class C {}");
+}
+
TEST_F(FormatTestJS, Modules) {
verifyFormat("import SomeThing from 'some/module.js';");
verifyFormat("import {X, Y} from 'some/module.js';");
- verifyFormat("import {\n"
- " VeryLongImportsAreAnnoying,\n"
- " VeryLongImportsAreAnnoying,\n"
- " VeryLongImportsAreAnnoying,\n"
- " VeryLongImportsAreAnnoying\n"
- "} from 'some/module.js';");
- verifyFormat("import {\n"
- " X,\n"
- " Y,\n"
- "} from 'some/module.js';");
- verifyFormat("import {\n"
- " X,\n"
- " Y,\n"
- "} from 'some/long/module.js';",
- getGoogleJSStyleWithColumns(20));
+ verifyFormat("import a, {X, Y} from 'some/module.js';");
+ verifyFormat("import {X, Y,} from 'some/module.js';");
verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
+ // Ensure Automatic Semicolon Insertion does not break on "as\n".
+ verifyFormat("import {X as myX} from 'm';", "import {X as\n"
+ " myX} from 'm';");
verifyFormat("import * as lib from 'some/module.js';");
verifyFormat("var x = {import: 1};\nx.import = 2;");
@@ -813,18 +1041,32 @@ TEST_F(FormatTestJS, Modules) {
verifyFormat("export function A() {}\n"
"export default function B() {}\n"
"export function C() {}");
+ verifyFormat("export default () => {\n"
+ " let x = 1;\n"
+ " return x;\n"
+ "}");
verifyFormat("export const x = 12;");
verifyFormat("export default class X {}");
verifyFormat("export {X, Y} from 'some/module.js';");
+ verifyFormat("export {X, Y,} from 'some/module.js';");
+ verifyFormat("export {SomeVeryLongExport as X, "
+ "SomeOtherVeryLongExport as Y} from 'some/module.js';");
+ // export without 'from' is wrapped.
+ verifyFormat("export let someRatherLongVariableName =\n"
+ " someSurprisinglyLongVariable + someOtherRatherLongVar;");
+ // ... but not if from is just an identifier.
verifyFormat("export {\n"
- " X,\n"
- " Y,\n"
- "} from 'some/module.js';");
+ " from as from,\n"
+ " someSurprisinglyLongVariable as\n"
+ " from\n"
+ "};",
+ getGoogleJSStyleWithColumns(20));
verifyFormat("export class C {\n"
" x: number;\n"
" y: string;\n"
"}");
verifyFormat("export class X { y: number; }");
+ verifyFormat("export abstract class X { y: number; }");
verifyFormat("export default class X { y: number }");
verifyFormat("export default function() {\n return 1;\n}");
verifyFormat("export var x = 12;");
@@ -841,44 +1083,86 @@ TEST_F(FormatTestJS, Modules) {
" // adsdasd\n"
" BAZ\n"
"}");
+ verifyFormat("export default [\n"
+ " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+ " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+ "];");
+ verifyFormat("export default [];");
+ verifyFormat("export default () => {};");
+ verifyFormat("export interface Foo { foo: number; }\n"
+ "export class Bar {\n"
+ " blah(): string { return this.blah; };\n"
+ "}");
+}
+
+TEST_F(FormatTestJS, ImportWrapping) {
+ verifyFormat("import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,"
+ " VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying"
+ "} from 'some/module.js';");
+ FormatStyle Style = getGoogleJSStyleWithColumns(80);
+ Style.JavaScriptWrapImports = true;
+ verifyFormat("import {\n"
+ " VeryLongImportsAreAnnoying,\n"
+ " VeryLongImportsAreAnnoying,\n"
+ " VeryLongImportsAreAnnoying,\n"
+ "} from 'some/module.js';",
+ Style);
+ verifyFormat("import {\n"
+ " A,\n"
+ " A,\n"
+ "} from 'some/module.js';",
+ Style);
+ verifyFormat("export {\n"
+ " A,\n"
+ " A,\n"
+ "} from 'some/module.js';",
+ Style);
}
TEST_F(FormatTestJS, TemplateStrings) {
// Keeps any whitespace/indentation within the template string.
- EXPECT_EQ("var x = `hello\n"
+ verifyFormat("var x = `hello\n"
" ${ name }\n"
" !`;",
- format("var x = `hello\n"
+ "var x = `hello\n"
" ${ name }\n"
- " !`;"));
+ " !`;");
verifyFormat("var x =\n"
" `hello ${world}` >= some();",
getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
verifyFormat("var x = `hello ${world}` >= some();",
getGoogleJSStyleWithColumns(35)); // Barely fits.
- EXPECT_EQ("var x = `hello\n"
+ verifyFormat("var x = `hellö ${wörld}` >= söme();",
+ getGoogleJSStyleWithColumns(35)); // Fits due to UTF-8.
+ verifyFormat("var x = `hello\n"
" ${world}` >=\n"
" some();",
- format("var x =\n"
+ "var x =\n"
" `hello\n"
" ${world}` >= some();",
- getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
- EXPECT_EQ("var x = `hello\n"
+ getGoogleJSStyleWithColumns(21)); // Barely doesn't fit.
+ verifyFormat("var x = `hello\n"
" ${world}` >= some();",
- format("var x =\n"
+ "var x =\n"
" `hello\n"
" ${world}` >= some();",
- getGoogleJSStyleWithColumns(22))); // Barely fits.
+ getGoogleJSStyleWithColumns(22)); // Barely fits.
verifyFormat("var x =\n"
" `h`;",
getGoogleJSStyleWithColumns(11));
- EXPECT_EQ(
- "var x =\n `multi\n line`;",
- format("var x = `multi\n line`;", getGoogleJSStyleWithColumns(13)));
+ verifyFormat("var x =\n `multi\n line`;", "var x = `multi\n line`;",
+ getGoogleJSStyleWithColumns(13));
verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
" `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`);");
+ // Repro for an obscure width-miscounting issue with template strings.
+ verifyFormat(
+ "someLongVariable =\n"
+ " "
+ "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;",
+ "someLongVariable = "
+ "`${logPrefix[11]}/${logPrefix[12]}/${logPrefix[13]}${logPrefix[14]}`;");
// Make sure template strings get a proper ColumnWidth assigned, even if they
// are first token in line.
@@ -890,39 +1174,51 @@ TEST_F(FormatTestJS, TemplateStrings) {
verifyFormat("var x = `hello` == `hello`;");
// Comments in template strings.
- EXPECT_EQ("var x = `//a`;\n"
+ verifyFormat("var x = `//a`;\n"
"var y;",
- format("var x =\n `//a`;\n"
- "var y ;"));
- EXPECT_EQ("var x = `/*a`;\n"
- "var y;",
- format("var x =\n `/*a`;\n"
- "var y;"));
+ "var x =\n `//a`;\n"
+ "var y ;");
+ verifyFormat("var x = `/*a`;\n"
+ "var y;",
+ "var x =\n `/*a`;\n"
+ "var y;");
// Unterminated string literals in a template string.
verifyFormat("var x = `'`; // comment with matching quote '\n"
"var y;");
verifyFormat("var x = `\"`; // comment with matching quote \"\n"
"var y;");
+ verifyFormat("it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa);",
+ "it(`'aaaaaaaaaaaaaaa `, aaaaaaaaa) ;",
+ getGoogleJSStyleWithColumns(40));
// Backticks in a comment - not a template string.
- EXPECT_EQ("var x = 1 // `/*a`;\n"
- " ;",
- format("var x =\n 1 // `/*a`;\n"
- " ;"));
- EXPECT_EQ("/* ` */ var x = 1; /* ` */",
- format("/* ` */ var x\n= 1; /* ` */"));
+ verifyFormat("var x = 1 // `/*a`;\n"
+ " ;",
+ "var x =\n 1 // `/*a`;\n"
+ " ;");
+ verifyFormat("/* ` */ var x = 1; /* ` */", "/* ` */ var x\n= 1; /* ` */");
// Comment spans multiple template strings.
- EXPECT_EQ("var x = `/*a`;\n"
- "var y = ` */ `;",
- format("var x =\n `/*a`;\n"
- "var y =\n ` */ `;"));
+ verifyFormat("var x = `/*a`;\n"
+ "var y = ` */ `;",
+ "var x =\n `/*a`;\n"
+ "var y =\n ` */ `;");
// Escaped backtick.
- EXPECT_EQ("var x = ` \\` a`;\n"
- "var y;",
- format("var x = ` \\` a`;\n"
- "var y;"));
+ verifyFormat("var x = ` \\` a`;\n"
+ "var y;",
+ "var x = ` \\` a`;\n"
+ "var y;");
}
-TEST_F(FormatTestJS, CastSyntax) { verifyFormat("var x = <type>foo;"); }
+TEST_F(FormatTestJS, CastSyntax) {
+ verifyFormat("var x = <type>foo;");
+ verifyFormat("var x = foo as type;");
+ verifyFormat("let x = (a + b) as\n"
+ " LongTypeIsLong;",
+ getGoogleJSStyleWithColumns(20));
+ verifyFormat("foo = <Bar[]>[\n"
+ " 1, //\n"
+ " 2\n"
+ "];");
+}
TEST_F(FormatTestJS, TypeArguments) {
verifyFormat("class X<Y> {}");
@@ -940,6 +1236,14 @@ TEST_F(FormatTestJS, TypeArguments) {
" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa {}");
}
+TEST_F(FormatTestJS, UserDefinedTypeGuards) {
+ verifyFormat(
+ "function foo(check: Object):\n"
+ " check is {foo: string, bar: string, baz: string, foobar: string} {\n"
+ " return 'bar' in check;\n"
+ "}\n");
+}
+
TEST_F(FormatTestJS, OptionalTypes) {
verifyFormat("function x(a?: b, c?, d?) {}");
verifyFormat("class X {\n"
@@ -949,7 +1253,6 @@ TEST_F(FormatTestJS, OptionalTypes) {
verifyFormat("interface X {\n"
" y?(): z;\n"
"}");
- verifyFormat("x ? 1 : 2;");
verifyFormat("constructor({aa}: {\n"
" aa?: string,\n"
" aaaaaaaa?: string,\n"
@@ -980,5 +1283,80 @@ TEST_F(FormatTestJS, WrapAfterParen) {
" bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
}
+TEST_F(FormatTestJS, JSDocAnnotations) {
+ verifyFormat("/**\n"
+ " * @export {this.is.a.long.path.to.a.Type}\n"
+ " */",
+ "/**\n"
+ " * @export {this.is.a.long.path.to.a.Type}\n"
+ " */",
+ getGoogleJSStyleWithColumns(20));
+}
+
+TEST_F(FormatTestJS, RequoteStringsSingle) {
+ verifyFormat("var x = 'foo';", "var x = \"foo\";");
+ verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo'o'\";");
+ verifyFormat("var x = 'fo\\'o\\'';", "var x = \"fo\\'o'\";");
+ verifyFormat(
+ "var x =\n"
+ " 'foo\\'';",
+ // Code below is 15 chars wide, doesn't fit into the line with the
+ // \ escape added.
+ "var x = \"foo'\";", getGoogleJSStyleWithColumns(15));
+ // Removes no-longer needed \ escape from ".
+ verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";");
+ // Code below fits into 15 chars *after* removing the \ escape.
+ verifyFormat("var x = 'fo\"o';", "var x = \"fo\\\"o\";",
+ getGoogleJSStyleWithColumns(15));
+ verifyFormat("// clang-format off\n"
+ "let x = \"double\";\n"
+ "// clang-format on\n"
+ "let x = 'single';\n",
+ "// clang-format off\n"
+ "let x = \"double\";\n"
+ "// clang-format on\n"
+ "let x = \"single\";\n");
+}
+
+TEST_F(FormatTestJS, RequoteStringsDouble) {
+ FormatStyle DoubleQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
+ DoubleQuotes.JavaScriptQuotes = FormatStyle::JSQS_Double;
+ verifyFormat("var x = \"foo\";", DoubleQuotes);
+ verifyFormat("var x = \"foo\";", "var x = 'foo';", DoubleQuotes);
+ verifyFormat("var x = \"fo'o\";", "var x = 'fo\\'o';", DoubleQuotes);
+}
+
+TEST_F(FormatTestJS, RequoteStringsLeave) {
+ FormatStyle LeaveQuotes = getGoogleStyle(FormatStyle::LK_JavaScript);
+ LeaveQuotes.JavaScriptQuotes = FormatStyle::JSQS_Leave;
+ verifyFormat("var x = \"foo\";", LeaveQuotes);
+ verifyFormat("var x = 'foo';", LeaveQuotes);
+}
+
+TEST_F(FormatTestJS, SupportShebangLines) {
+ verifyFormat("#!/usr/bin/env node\n"
+ "var x = hello();",
+ "#!/usr/bin/env node\n"
+ "var x = hello();");
+}
+
+TEST_F(FormatTestJS, NonNullAssertionOperator) {
+ verifyFormat("let x = foo!.bar();\n");
+ verifyFormat("let x = foo ? bar! : baz;\n");
+ verifyFormat("let x = !foo;\n");
+ verifyFormat("let x = foo[0]!;\n");
+ verifyFormat("let x = (foo)!;\n");
+ verifyFormat("let x = {foo: 1}!;\n");
+}
+
+TEST_F(FormatTestJS, Conditional) {
+ verifyFormat("y = x ? 1 : 2;");
+ verifyFormat("x ? 1 : 2;");
+ verifyFormat("class Foo {\n"
+ " field = true ? 1 : 2;\n"
+ " method(a = true ? 1 : 2) {}\n"
+ "}");
+}
+
} // end namespace tooling
} // end namespace clang
diff --git a/unittests/Format/FormatTestJava.cpp b/unittests/Format/FormatTestJava.cpp
index 160c22022d..dfc3debc46 100644
--- a/unittests/Format/FormatTestJava.cpp
+++ b/unittests/Format/FormatTestJava.cpp
@@ -25,10 +25,10 @@ protected:
DEBUG(llvm::errs() << Code << "\n\n");
std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
tooling::Replacements Replaces = reformat(Style, Code, Ranges);
- std::string Result = applyAllReplacements(Code, Replaces);
- EXPECT_NE("", Result);
- DEBUG(llvm::errs() << "\n" << Result << "\n\n");
- return Result;
+ auto Result = applyAllReplacements(Code, Replaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+ return *Result;
}
static std::string
@@ -312,6 +312,9 @@ TEST_F(FormatTestJava, Annotations) {
" String bbbbbbbbbbbbbbb) {}\n"
"}",
getStyleWithColumns(60));
+ verifyFormat("@Annotation(\"Some\"\n"
+ " + \" text\")\n"
+ "List<Integer> list;");
}
TEST_F(FormatTestJava, Generics) {
@@ -426,6 +429,7 @@ TEST_F(FormatTestJava, CppKeywords) {
verifyFormat("public void union(Type a, Type b);");
verifyFormat("public void struct(Object o);");
verifyFormat("public void delete(Object o);");
+ verifyFormat("return operator && (aa);");
}
TEST_F(FormatTestJava, NeverAlignAfterReturn) {
diff --git a/unittests/Format/FormatTestProto.cpp b/unittests/Format/FormatTestProto.cpp
index cd2c0c8aa4..6881af4361 100644
--- a/unittests/Format/FormatTestProto.cpp
+++ b/unittests/Format/FormatTestProto.cpp
@@ -25,10 +25,10 @@ protected:
DEBUG(llvm::errs() << Code << "\n\n");
std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
tooling::Replacements Replaces = reformat(Style, Code, Ranges);
- std::string Result = applyAllReplacements(Code, Replaces);
- EXPECT_NE("", Result);
- DEBUG(llvm::errs() << "\n" << Result << "\n\n");
- return Result;
+ auto Result = applyAllReplacements(Code, Replaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+ return *Result;
}
static std::string format(llvm::StringRef Code) {
@@ -74,8 +74,11 @@ TEST_F(FormatTestProto, FormatsEnums) {
" TYPE_B = 2;\n"
"};");
verifyFormat("enum Type {\n"
+ " UNKNOWN = 0 [(some_options) = {a: aa, b: bb}];\n"
+ "};");
+ verifyFormat("enum Type {\n"
" UNKNOWN = 0 [(some_options) = {\n"
- " a: aa,\n"
+ " a: aa, // wrap\n"
" b: bb\n"
" }];\n"
"};");
@@ -88,9 +91,10 @@ TEST_F(FormatTestProto, UnderstandsReturns) {
TEST_F(FormatTestProto, MessageFieldAttributes) {
verifyFormat("optional string test = 1 [default = \"test\"];");
verifyFormat("optional bool a = 1 [default = true, deprecated = true];");
- verifyFormat("optional LongMessageType long_proto_field = 1\n"
- " [default = REALLY_REALLY_LONG_CONSTANT_VALUE,\n"
- " deprecated = true];");
+ verifyFormat("optional LongMessageType long_proto_field = 1 [\n"
+ " default = REALLY_REALLY_LONG_CONSTANT_VALUE,\n"
+ " deprecated = true\n"
+ "];");
verifyFormat("optional LongMessageType long_proto_field = 1\n"
" [default = REALLY_REALLY_LONG_CONSTANT_VALUE];");
verifyFormat("repeated double value = 1\n"
@@ -103,6 +107,16 @@ TEST_F(FormatTestProto, MessageFieldAttributes) {
" aaaaaaaaaaaaaaaa: AAAAAAAAAA\n"
" bbbbbbbbbbbbbbbb: BBBBBBBBBB\n"
"}];");
+ verifyFormat("repeated double value = 1 [\n"
+ " (aaaaaaa.aaaaaaaaa) = {\n"
+ " aaaaaaaaaaaaaaaa: AAAAAAAAAA\n"
+ " bbbbbbbbbbbbbbbb: BBBBBBBBBB\n"
+ " },\n"
+ " (bbbbbbb.bbbbbbbbb) = {\n"
+ " aaaaaaaaaaaaaaaa: AAAAAAAAAA\n"
+ " bbbbbbbbbbbbbbbb: BBBBBBBBBB\n"
+ " }\n"
+ "];");
verifyFormat("repeated double value = 1 [(aaaaaaa.aaaaaaaaa) = {\n"
" type: \"AAAAAAAAAA\"\n"
" is: \"AAAAAAAAAA\"\n"
@@ -113,6 +127,14 @@ TEST_F(FormatTestProto, MessageFieldAttributes) {
" bbbbbbb: BBBB,\n"
" bbbb: BBB\n"
"}];");
+ verifyFormat("optional AAA aaa = 1 [\n"
+ " foo = {\n"
+ " key: 'a' //\n"
+ " },\n"
+ " bar = {\n"
+ " key: 'a' //\n"
+ " }\n"
+ "];");
}
TEST_F(FormatTestProto, DoesntWrapFileOptions) {
@@ -130,28 +152,28 @@ TEST_F(FormatTestProto, FormatsOptions) {
" field_c: \"OK\"\n"
" msg_field: {field_d: 123}\n"
"};");
-
verifyFormat("option (MyProto.options) = {\n"
" field_a: OK\n"
" field_b: \"OK\"\n"
" field_c: \"OK\"\n"
- " msg_field: {\n"
- " field_d: 123\n"
- " field_e: OK\n"
- " }\n"
+ " msg_field: {field_d: 123 field_e: OK}\n"
"};");
-
verifyFormat("option (MyProto.options) = {\n"
" field_a: OK // Comment\n"
" field_b: \"OK\"\n"
" field_c: \"OK\"\n"
" msg_field: {field_d: 123}\n"
"};");
-
verifyFormat("option (MyProto.options) = {\n"
" field_c: \"OK\"\n"
" msg_field{field_d: 123}\n"
"};");
+
+ // Support syntax with <> instead of {}.
+ verifyFormat("option (MyProto.options) = {\n"
+ " field_c: \"OK\",\n"
+ " msg_field: <field_d: 123>\n"
+ "};");
}
TEST_F(FormatTestProto, FormatsService) {
@@ -167,5 +189,26 @@ TEST_F(FormatTestProto, ExtendingMessage) {
"}");
}
+TEST_F(FormatTestProto, FormatsImports) {
+ verifyFormat("import \"a.proto\";\n"
+ "import \"b.proto\";\n"
+ "// comment\n"
+ "message A {\n"
+ "}");
+
+ verifyFormat("import public \"a.proto\";\n"
+ "import \"b.proto\";\n"
+ "// comment\n"
+ "message A {\n"
+ "}");
+
+ // Missing semicolons should not confuse clang-format.
+ verifyFormat("import \"a.proto\"\n"
+ "import \"b.proto\"\n"
+ "// comment\n"
+ "message A {\n"
+ "}");
+}
+
} // end namespace tooling
} // end namespace clang
diff --git a/unittests/Format/FormatTestSelective.cpp b/unittests/Format/FormatTestSelective.cpp
index d53d1c0429..2bc60fd1e0 100644
--- a/unittests/Format/FormatTestSelective.cpp
+++ b/unittests/Format/FormatTestSelective.cpp
@@ -28,10 +28,10 @@ protected:
tooling::Replacements Replaces =
reformat(Style, Code, Ranges, "<stdin>", &IncompleteFormat);
EXPECT_FALSE(IncompleteFormat) << Code << "\n\n";
- std::string Result = applyAllReplacements(Code, Replaces);
- EXPECT_NE("", Result);
- DEBUG(llvm::errs() << "\n" << Result << "\n\n");
- return Result;
+ auto Result = applyAllReplacements(Code, Replaces);
+ EXPECT_TRUE(static_cast<bool>(Result));
+ DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+ return *Result;
}
FormatStyle Style = getLLVMStyle();
@@ -162,6 +162,13 @@ TEST_F(FormatTestSelective, FormatsCommentsLocally) {
"// This is\n"
"// not formatted. ",
0, 0));
+ EXPECT_EQ("int x; // Format this line.\n"
+ "int xx; //\n"
+ "int xxxxx; //",
+ format("int x; // Format this line.\n"
+ "int xx; //\n"
+ "int xxxxx; //",
+ 0, 0));
}
TEST_F(FormatTestSelective, IndividualStatementsOfNestedBlocks) {
@@ -271,6 +278,23 @@ TEST_F(FormatTestSelective, IndividualStatementsOfNestedBlocks) {
" };\n"
"});",
0, 0));
+ EXPECT_EQ("SomeFunction(\n"
+ " [] {\n"
+ " int i;\n"
+ " return i;\n" // Format this line.
+ " },\n"
+ " [] {\n"
+ " return 2;\n" // Don't fix this.
+ " });",
+ format("SomeFunction(\n"
+ " [] {\n"
+ " int i;\n"
+ " return i;\n" // Format this line.
+ " },\n"
+ " [] {\n"
+ " return 2;\n" // Don't fix this.
+ " });",
+ 40, 0));
}
TEST_F(FormatTestSelective, WrongIndent) {
@@ -488,6 +512,18 @@ TEST_F(FormatTestSelective, StopFormattingWhenLeavingScope) {
15, 0));
}
+TEST_F(FormatTestSelective, SelectivelyRequoteJavaScript) {
+ Style = getGoogleStyle(FormatStyle::LK_JavaScript);
+ EXPECT_EQ(
+ "var x = \"a\";\n"
+ "var x = 'a';\n"
+ "var x = \"a\";",
+ format("var x = \"a\";\n"
+ "var x = \"a\";\n"
+ "var x = \"a\";",
+ 20, 0));
+}
+
} // end namespace
} // end namespace format
} // end namespace clang
diff --git a/unittests/Format/Makefile b/unittests/Format/Makefile
deleted file mode 100644
index f95d6d3412..0000000000
--- a/unittests/Format/Makefile
+++ /dev/null
@@ -1,19 +0,0 @@
-##===- unittests/Format/Makefile ---------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = Format
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc option
-USEDLIBS = clangFormat.a clangTooling.a clangToolingCore.a clangFrontend.a \
- clangSerialization.a clangDriver.a clangParse.a clangRewrite.a \
- clangRewriteFrontend.a clangSema.a clangAnalysis.a clangEdit.a \
- clangAST.a clangASTMatchers.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Format/SortImportsTestJS.cpp b/unittests/Format/SortImportsTestJS.cpp
new file mode 100644
index 0000000000..77c37e337d
--- /dev/null
+++ b/unittests/Format/SortImportsTestJS.cpp
@@ -0,0 +1,269 @@
+//===- unittest/Format/SortImportsTestJS.cpp - JS import sort unit tests --===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "FormatTestUtils.h"
+#include "clang/Format/Format.h"
+#include "llvm/Support/Debug.h"
+#include "gtest/gtest.h"
+
+#define DEBUG_TYPE "format-test"
+
+namespace clang {
+namespace format {
+namespace {
+
+class SortImportsTestJS : public ::testing::Test {
+protected:
+ std::string sort(StringRef Code, unsigned Offset = 0, unsigned Length = 0) {
+ StringRef FileName = "input.js";
+ if (Length == 0U)
+ Length = Code.size() - Offset;
+ std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
+ auto Sorted =
+ applyAllReplacements(Code, sortIncludes(Style, Code, Ranges, FileName));
+ EXPECT_TRUE(static_cast<bool>(Sorted));
+ auto Formatted = applyAllReplacements(
+ *Sorted, reformat(Style, *Sorted, Ranges, FileName));
+ EXPECT_TRUE(static_cast<bool>(Formatted));
+ return *Formatted;
+ }
+
+ void verifySort(llvm::StringRef Expected, llvm::StringRef Code,
+ unsigned Offset = 0, unsigned Length = 0) {
+ std::string Result = sort(Code, Offset, Length);
+ EXPECT_EQ(Expected.str(), Result) << "Expected:\n"
+ << Expected << "\nActual:\n"
+ << Result;
+ }
+
+ FormatStyle Style = getGoogleStyle(FormatStyle::LK_JavaScript);
+};
+
+TEST_F(SortImportsTestJS, AlreadySorted) {
+ verifySort("import {sym} from 'a';\n"
+ "import {sym} from 'b';\n"
+ "import {sym} from 'c';\n"
+ "\n"
+ "let x = 1;",
+ "import {sym} from 'a';\n"
+ "import {sym} from 'b';\n"
+ "import {sym} from 'c';\n"
+ "\n"
+ "let x = 1;");
+}
+
+TEST_F(SortImportsTestJS, BasicSorting) {
+ verifySort("import {sym} from 'a';\n"
+ "import {sym} from 'b';\n"
+ "import {sym} from 'c';\n"
+ "\n"
+ "let x = 1;",
+ "import {sym} from 'a';\n"
+ "import {sym} from 'c';\n"
+ "import {sym} from 'b';\n"
+ "let x = 1;");
+}
+
+TEST_F(SortImportsTestJS, WrappedImportStatements) {
+ verifySort("import {sym1, sym2} from 'a';\n"
+ "import {sym} from 'b';\n"
+ "\n"
+ "1;",
+ "import\n"
+ " {sym}\n"
+ " from 'b';\n"
+ "import {\n"
+ " sym1,\n"
+ " sym2\n"
+ "} from 'a';\n"
+ "1;");
+}
+
+TEST_F(SortImportsTestJS, SeparateMainCodeBody) {
+ verifySort("import {sym} from 'a';"
+ "\n"
+ "let x = 1;\n",
+ "import {sym} from 'a'; let x = 1;\n");
+}
+
+TEST_F(SortImportsTestJS, Comments) {
+ verifySort("/** @fileoverview This is a great file. */\n"
+ "// A very important import follows.\n"
+ "import {sym} from 'a'; /* more comments */\n"
+ "import {sym} from 'b'; // from //foo:bar\n",
+ "/** @fileoverview This is a great file. */\n"
+ "import {sym} from 'b'; // from //foo:bar\n"
+ "// A very important import follows.\n"
+ "import {sym} from 'a'; /* more comments */\n");
+}
+
+TEST_F(SortImportsTestJS, SortStar) {
+ verifySort("import * as foo from 'a';\n"
+ "import {sym} from 'a';\n"
+ "import * as bar from 'b';\n",
+ "import {sym} from 'a';\n"
+ "import * as foo from 'a';\n"
+ "import * as bar from 'b';\n");
+}
+
+TEST_F(SortImportsTestJS, AliasesSymbols) {
+ verifySort("import {sym1 as alias1} from 'b';\n"
+ "import {sym2 as alias2, sym3 as alias3} from 'c';\n",
+ "import {sym2 as alias2, sym3 as alias3} from 'c';\n"
+ "import {sym1 as alias1} from 'b';\n");
+}
+
+TEST_F(SortImportsTestJS, SortSymbols) {
+ verifySort("import {sym1, sym2 as a, sym3} from 'b';\n",
+ "import {sym2 as a, sym1, sym3} from 'b';\n");
+ verifySort("import {sym1 /* important! */, /*!*/ sym2 as a} from 'b';\n",
+ "import {/*!*/ sym2 as a, sym1 /* important! */} from 'b';\n");
+ verifySort("import {sym1, sym2} from 'b';\n", "import {\n"
+ " sym2 \n"
+ ",\n"
+ " sym1 \n"
+ "} from 'b';\n");
+}
+
+TEST_F(SortImportsTestJS, GroupImports) {
+ verifySort("import {a} from 'absolute';\n"
+ "\n"
+ "import {b} from '../parent';\n"
+ "import {b} from '../parent/nested';\n"
+ "\n"
+ "import {b} from './relative/path';\n"
+ "import {b} from './relative/path/nested';\n"
+ "\n"
+ "let x = 1;\n",
+ "import {b} from './relative/path/nested';\n"
+ "import {b} from './relative/path';\n"
+ "import {b} from '../parent/nested';\n"
+ "import {b} from '../parent';\n"
+ "import {a} from 'absolute';\n"
+ "let x = 1;\n");
+}
+
+TEST_F(SortImportsTestJS, Exports) {
+ verifySort("import {S} from 'bpath';\n"
+ "\n"
+ "import {T} from './cpath';\n"
+ "\n"
+ "export {A, B} from 'apath';\n"
+ "export {P} from '../parent';\n"
+ "export {R} from './relative';\n"
+ "export {S};\n"
+ "\n"
+ "let x = 1;\n"
+ "export y = 1;\n",
+ "export {R} from './relative';\n"
+ "import {T} from './cpath';\n"
+ "export {S};\n"
+ "export {A, B} from 'apath';\n"
+ "import {S} from 'bpath';\n"
+ "export {P} from '../parent';\n"
+ "let x = 1;\n"
+ "export y = 1;\n");
+ verifySort("import {S} from 'bpath';\n"
+ "\n"
+ "export {T} from 'epath';\n",
+ "export {T} from 'epath';\n"
+ "import {S} from 'bpath';\n");
+}
+
+TEST_F(SortImportsTestJS, SideEffectImports) {
+ verifySort("import 'ZZside-effect';\n"
+ "import 'AAside-effect';\n"
+ "\n"
+ "import {A} from 'absolute';\n"
+ "\n"
+ "import {R} from './relative';\n",
+ "import {R} from './relative';\n"
+ "import 'ZZside-effect';\n"
+ "import {A} from 'absolute';\n"
+ "import 'AAside-effect';\n");
+}
+
+TEST_F(SortImportsTestJS, AffectedRange) {
+ // Sort excluding a suffix.
+ verifySort("import {sym} from 'b';\n"
+ "import {sym} from 'c';\n"
+ "import {sym} from 'a';\n"
+ "let x = 1;",
+ "import {sym} from 'c';\n"
+ "import {sym} from 'b';\n"
+ "import {sym} from 'a';\n"
+ "let x = 1;",
+ 0, 30);
+ // Sort excluding a prefix.
+ verifySort("import {sym} from 'c';\n"
+ "import {sym} from 'a';\n"
+ "import {sym} from 'b';\n"
+ "\n"
+ "let x = 1;",
+ "import {sym} from 'c';\n"
+ "import {sym} from 'b';\n"
+ "import {sym} from 'a';\n"
+ "\n"
+ "let x = 1;",
+ 30, 0);
+ // Sort a range within imports.
+ verifySort("import {sym} from 'c';\n"
+ "import {sym} from 'a';\n"
+ "import {sym} from 'b';\n"
+ "import {sym} from 'c';\n"
+ "let x = 1;",
+ "import {sym} from 'c';\n"
+ "import {sym} from 'b';\n"
+ "import {sym} from 'a';\n"
+ "import {sym} from 'c';\n"
+ "let x = 1;",
+ 24, 30);
+}
+
+TEST_F(SortImportsTestJS, SortingCanShrink) {
+ // Sort excluding a suffix.
+ verifySort("import {B} from 'a';\n"
+ "import {A} from 'b';\n"
+ "\n"
+ "1;",
+ "import {A} from 'b';\n"
+ "\n"
+ "import {B} from 'a';\n"
+ "\n"
+ "1;");
+}
+
+TEST_F(SortImportsTestJS, TrailingComma) {
+ verifySort("import {A, B,} from 'aa';\n", "import {B, A,} from 'aa';\n");
+}
+
+TEST_F(SortImportsTestJS, SortCaseInsensitive) {
+ verifySort("import {A} from 'aa';\n"
+ "import {A} from 'Ab';\n"
+ "import {A} from 'b';\n"
+ "import {A} from 'Bc';\n"
+ "\n"
+ "1;",
+ "import {A} from 'b';\n"
+ "import {A} from 'Bc';\n"
+ "import {A} from 'Ab';\n"
+ "import {A} from 'aa';\n"
+ "\n"
+ "1;");
+ verifySort("import {aa, Ab, b, Bc} from 'x';\n"
+ "\n"
+ "1;",
+ "import {b, Bc, Ab, aa} from 'x';\n"
+ "\n"
+ "1;");
+}
+
+} // end namespace
+} // end namespace format
+} // end namespace clang
diff --git a/unittests/Format/SortIncludesTest.cpp b/unittests/Format/SortIncludesTest.cpp
index dbe1174957..13a1b9adee 100644
--- a/unittests/Format/SortIncludesTest.cpp
+++ b/unittests/Format/SortIncludesTest.cpp
@@ -20,17 +20,23 @@ namespace {
class SortIncludesTest : public ::testing::Test {
protected:
- std::string sort(llvm::StringRef Code, StringRef FileName = "input.cpp") {
- std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
- std::string Sorted =
+ std::vector<tooling::Range> GetCodeRange(StringRef Code) {
+ return std::vector<tooling::Range>(1, tooling::Range(0, Code.size()));
+ }
+
+ std::string sort(StringRef Code, StringRef FileName = "input.cpp") {
+ auto Ranges = GetCodeRange(Code);
+ auto Sorted =
applyAllReplacements(Code, sortIncludes(Style, Code, Ranges, FileName));
- return applyAllReplacements(Sorted,
- reformat(Style, Sorted, Ranges, FileName));
+ EXPECT_TRUE(static_cast<bool>(Sorted));
+ auto Result = applyAllReplacements(
+ *Sorted, reformat(Style, *Sorted, Ranges, FileName));
+ EXPECT_TRUE(static_cast<bool>(Result));
+ return *Result;
}
unsigned newCursor(llvm::StringRef Code, unsigned Cursor) {
- std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
- sortIncludes(Style, Code, Ranges, "input.cpp", &Cursor);
+ sortIncludes(Style, Code, GetCodeRange(Code), "input.cpp", &Cursor);
return Cursor;
}
@@ -47,6 +53,17 @@ TEST_F(SortIncludesTest, BasicSorting) {
"#include \"b.h\"\n"));
}
+TEST_F(SortIncludesTest, NoReplacementsForValidIncludes) {
+ // Identical #includes have led to a failure with an unstable sort.
+ std::string Code = "#include <a>\n"
+ "#include <b>\n"
+ "#include <b>\n"
+ "#include <b>\n"
+ "#include <b>\n"
+ "#include <c>\n";
+ EXPECT_TRUE(sortIncludes(Style, Code, GetCodeRange(Code), "a.cc").empty());
+}
+
TEST_F(SortIncludesTest, SupportClangFormatOff) {
EXPECT_EQ("#include <a>\n"
"#include <b>\n"
@@ -161,6 +178,7 @@ TEST_F(SortIncludesTest, HandlesMultilineIncludes) {
}
TEST_F(SortIncludesTest, LeavesMainHeaderFirst) {
+ Style.IncludeIsMainRegex = "([-_](test|unittest))?$";
EXPECT_EQ("#include \"llvm/a.h\"\n"
"#include \"b.h\"\n"
"#include \"c.h\"\n",
@@ -174,7 +192,7 @@ TEST_F(SortIncludesTest, LeavesMainHeaderFirst) {
sort("#include \"llvm/a.h\"\n"
"#include \"c.h\"\n"
"#include \"b.h\"\n",
- "a_main.cc"));
+ "a_test.cc"));
EXPECT_EQ("#include \"llvm/input.h\"\n"
"#include \"b.h\"\n"
"#include \"c.h\"\n",
@@ -183,6 +201,24 @@ TEST_F(SortIncludesTest, LeavesMainHeaderFirst) {
"#include \"b.h\"\n",
"input.mm"));
+ // Don't allow prefixes.
+ EXPECT_EQ("#include \"b.h\"\n"
+ "#include \"c.h\"\n"
+ "#include \"llvm/not_a.h\"\n",
+ sort("#include \"llvm/not_a.h\"\n"
+ "#include \"c.h\"\n"
+ "#include \"b.h\"\n",
+ "a.cc"));
+
+ // Don't do this for _main and other suffixes.
+ EXPECT_EQ("#include \"b.h\"\n"
+ "#include \"c.h\"\n"
+ "#include \"llvm/a.h\"\n",
+ sort("#include \"llvm/a.h\"\n"
+ "#include \"c.h\"\n"
+ "#include \"b.h\"\n",
+ "a_main.cc"));
+
// Don't do this in headers.
EXPECT_EQ("#include \"b.h\"\n"
"#include \"c.h\"\n"
diff --git a/unittests/Frontend/CMakeLists.txt b/unittests/Frontend/CMakeLists.txt
index 5b5fdc9a54..674f77bd01 100644
--- a/unittests/Frontend/CMakeLists.txt
+++ b/unittests/Frontend/CMakeLists.txt
@@ -4,6 +4,7 @@ set(LLVM_LINK_COMPONENTS
add_clang_unittest(FrontendTests
FrontendActionTest.cpp
+ CodeGenActionTest.cpp
)
target_link_libraries(FrontendTests
clangAST
@@ -11,4 +12,5 @@ target_link_libraries(FrontendTests
clangFrontend
clangLex
clangSema
+ clangCodeGen
)
diff --git a/unittests/Frontend/CodeGenActionTest.cpp b/unittests/Frontend/CodeGenActionTest.cpp
new file mode 100644
index 0000000000..71446fd4d7
--- /dev/null
+++ b/unittests/Frontend/CodeGenActionTest.cpp
@@ -0,0 +1,61 @@
+//===- unittests/Frontend/CodeGenActionTest.cpp --- FrontendAction tests --===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// Unit tests for CodeGenAction.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/CodeGen/CodeGenAction.h"
+#include "clang/CodeGen/BackendUtil.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace clang;
+using namespace clang::frontend;
+
+namespace {
+
+
+class NullCodeGenAction : public CodeGenAction {
+public:
+ NullCodeGenAction(llvm::LLVMContext *_VMContext = nullptr)
+ : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
+
+ // The action does not call methods of ATContext.
+ void ExecuteAction() override {
+ CompilerInstance &CI = getCompilerInstance();
+ if (!CI.hasPreprocessor())
+ return;
+ if (!CI.hasSema())
+ CI.createSema(getTranslationUnitKind(), nullptr);
+ }
+};
+
+
+TEST(CodeGenTest, TestNullCodeGen) {
+ CompilerInvocation *Invocation = new CompilerInvocation;
+ Invocation->getPreprocessorOpts().addRemappedFile(
+ "test.cc",
+ MemoryBuffer::getMemBuffer("").release());
+ Invocation->getFrontendOpts().Inputs.push_back(
+ FrontendInputFile("test.cc", IK_CXX));
+ Invocation->getFrontendOpts().ProgramAction = EmitLLVM;
+ Invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu";
+ CompilerInstance Compiler;
+ Compiler.setInvocation(Invocation);
+ Compiler.createDiagnostics();
+ EXPECT_TRUE(Compiler.hasDiagnostics());
+
+ std::unique_ptr<FrontendAction> Act(new NullCodeGenAction);
+ bool Success = Compiler.ExecuteAction(*Act);
+ EXPECT_TRUE(Success);
+}
+
+}
diff --git a/unittests/Frontend/Makefile b/unittests/Frontend/Makefile
deleted file mode 100644
index a63ae18245..0000000000
--- a/unittests/Frontend/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@
-##===- unittests/Frontend/Makefile -------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = Frontend
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc option
-USEDLIBS = clangFrontendTool.a clangFrontend.a clangDriver.a \
- clangSerialization.a clangCodeGen.a clangParse.a clangSema.a \
- clangStaticAnalyzerCheckers.a clangStaticAnalyzerCore.a \
- clangARCMigrate.a clangRewrite.a \
- clangRewriteFrontend.a clangEdit.a \
- clangAnalysis.a clangAST.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Lex/CMakeLists.txt b/unittests/Lex/CMakeLists.txt
index 461e0d95fc..ef0f06c0b3 100644
--- a/unittests/Lex/CMakeLists.txt
+++ b/unittests/Lex/CMakeLists.txt
@@ -3,6 +3,7 @@ set(LLVM_LINK_COMPONENTS
)
add_clang_unittest(LexTests
+ HeaderMapTest.cpp
LexerTest.cpp
PPCallbacksTest.cpp
PPConditionalDirectiveRecordTest.cpp
diff --git a/unittests/Lex/HeaderMapTest.cpp b/unittests/Lex/HeaderMapTest.cpp
new file mode 100644
index 0000000000..d16efe82c1
--- /dev/null
+++ b/unittests/Lex/HeaderMapTest.cpp
@@ -0,0 +1,258 @@
+//===- unittests/Lex/HeaderMapTest.cpp - HeaderMap tests ----------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--------------------------------------------------------------===//
+
+#include "clang/Basic/CharInfo.h"
+#include "clang/Lex/HeaderMap.h"
+#include "clang/Lex/HeaderMapTypes.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Support/SwapByteOrder.h"
+#include "gtest/gtest.h"
+#include <cassert>
+#include <type_traits>
+
+using namespace clang;
+using namespace llvm;
+
+namespace {
+
+// Lay out a header file for testing.
+template <unsigned NumBuckets, unsigned NumBytes> struct MapFile {
+ HMapHeader Header;
+ HMapBucket Buckets[NumBuckets];
+ unsigned char Bytes[NumBytes];
+
+ void init() {
+ memset(this, 0, sizeof(MapFile));
+ Header.Magic = HMAP_HeaderMagicNumber;
+ Header.Version = HMAP_HeaderVersion;
+ Header.NumBuckets = NumBuckets;
+ Header.StringsOffset = sizeof(Header) + sizeof(Buckets);
+ }
+
+ void swapBytes() {
+ using llvm::sys::getSwappedBytes;
+ Header.Magic = getSwappedBytes(Header.Magic);
+ Header.Version = getSwappedBytes(Header.Version);
+ Header.NumBuckets = getSwappedBytes(Header.NumBuckets);
+ Header.StringsOffset = getSwappedBytes(Header.StringsOffset);
+ }
+
+ std::unique_ptr<const MemoryBuffer> getBuffer() const {
+ return MemoryBuffer::getMemBuffer(
+ StringRef(reinterpret_cast<const char *>(this), sizeof(MapFile)),
+ "header",
+ /* RequresNullTerminator */ false);
+ }
+};
+
+// The header map hash function.
+static inline unsigned getHash(StringRef Str) {
+ unsigned Result = 0;
+ for (char C : Str)
+ Result += toLowercase(C) * 13;
+ return Result;
+}
+
+template <class FileTy> struct FileMaker {
+ FileTy &File;
+ unsigned SI = 1;
+ unsigned BI = 0;
+ FileMaker(FileTy &File) : File(File) {}
+
+ unsigned addString(StringRef S) {
+ assert(SI + S.size() + 1 <= sizeof(File.Bytes));
+ std::copy(S.begin(), S.end(), File.Bytes + SI);
+ auto OldSI = SI;
+ SI += S.size() + 1;
+ return OldSI;
+ }
+ void addBucket(unsigned Hash, unsigned Key, unsigned Prefix, unsigned Suffix) {
+ assert(!(File.Header.NumBuckets & (File.Header.NumBuckets - 1)));
+ unsigned I = Hash & (File.Header.NumBuckets - 1);
+ do {
+ if (!File.Buckets[I].Key) {
+ File.Buckets[I].Key = Key;
+ File.Buckets[I].Prefix = Prefix;
+ File.Buckets[I].Suffix = Suffix;
+ ++File.Header.NumEntries;
+ return;
+ }
+ ++I;
+ I &= File.Header.NumBuckets - 1;
+ } while (I != (Hash & (File.Header.NumBuckets - 1)));
+ llvm_unreachable("no empty buckets");
+ }
+};
+
+TEST(HeaderMapTest, checkHeaderEmpty) {
+ bool NeedsSwap;
+ ASSERT_FALSE(HeaderMapImpl::checkHeader(
+ *MemoryBuffer::getMemBufferCopy("", "empty"), NeedsSwap));
+ ASSERT_FALSE(HeaderMapImpl::checkHeader(
+ *MemoryBuffer::getMemBufferCopy("", "empty"), NeedsSwap));
+}
+
+TEST(HeaderMapTest, checkHeaderMagic) {
+ MapFile<1, 1> File;
+ File.init();
+ File.Header.Magic = 0;
+ bool NeedsSwap;
+ ASSERT_FALSE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+}
+
+TEST(HeaderMapTest, checkHeaderReserved) {
+ MapFile<1, 1> File;
+ File.init();
+ File.Header.Reserved = 1;
+ bool NeedsSwap;
+ ASSERT_FALSE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+}
+
+TEST(HeaderMapTest, checkHeaderVersion) {
+ MapFile<1, 1> File;
+ File.init();
+ ++File.Header.Version;
+ bool NeedsSwap;
+ ASSERT_FALSE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+}
+
+TEST(HeaderMapTest, checkHeaderValidButEmpty) {
+ MapFile<1, 1> File;
+ File.init();
+ bool NeedsSwap;
+ ASSERT_TRUE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+ ASSERT_FALSE(NeedsSwap);
+
+ File.swapBytes();
+ ASSERT_TRUE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+ ASSERT_TRUE(NeedsSwap);
+}
+
+TEST(HeaderMapTest, checkHeader3Buckets) {
+ MapFile<3, 1> File;
+ ASSERT_EQ(3 * sizeof(HMapBucket), sizeof(File.Buckets));
+
+ File.init();
+ bool NeedsSwap;
+ ASSERT_FALSE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+}
+
+TEST(HeaderMapTest, checkHeader0Buckets) {
+ // Create with 1 bucket to avoid 0-sized arrays.
+ MapFile<1, 1> File;
+ File.init();
+ File.Header.NumBuckets = 0;
+ bool NeedsSwap;
+ ASSERT_FALSE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+}
+
+TEST(HeaderMapTest, checkHeaderNotEnoughBuckets) {
+ MapFile<1, 1> File;
+ File.init();
+ File.Header.NumBuckets = 8;
+ bool NeedsSwap;
+ ASSERT_FALSE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+}
+
+TEST(HeaderMapTest, lookupFilename) {
+ typedef MapFile<2, 7> FileTy;
+ FileTy File;
+ File.init();
+
+ FileMaker<FileTy> Maker(File);
+ auto a = Maker.addString("a");
+ auto b = Maker.addString("b");
+ auto c = Maker.addString("c");
+ Maker.addBucket(getHash("a"), a, b, c);
+
+ bool NeedsSwap;
+ ASSERT_TRUE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+ ASSERT_FALSE(NeedsSwap);
+ HeaderMapImpl Map(File.getBuffer(), NeedsSwap);
+
+ SmallString<8> DestPath;
+ ASSERT_EQ("bc", Map.lookupFilename("a", DestPath));
+}
+
+template <class FileTy, class PaddingTy> struct PaddedFile {
+ FileTy File;
+ PaddingTy Padding;
+};
+
+TEST(HeaderMapTest, lookupFilenameTruncatedSuffix) {
+ typedef MapFile<2, 64 - sizeof(HMapHeader) - 2 * sizeof(HMapBucket)> FileTy;
+ static_assert(std::is_standard_layout<FileTy>::value,
+ "Expected standard layout");
+ static_assert(sizeof(FileTy) == 64, "check the math");
+ PaddedFile<FileTy, uint64_t> P;
+ auto &File = P.File;
+ auto &Padding = P.Padding;
+ File.init();
+
+ FileMaker<FileTy> Maker(File);
+ auto a = Maker.addString("a");
+ auto b = Maker.addString("b");
+ auto c = Maker.addString("c");
+ Maker.addBucket(getHash("a"), a, b, c);
+
+ // Add 'x' characters to cause an overflow into Padding.
+ ASSERT_EQ('c', File.Bytes[5]);
+ for (unsigned I = 6; I < sizeof(File.Bytes); ++I) {
+ ASSERT_EQ(0, File.Bytes[I]);
+ File.Bytes[I] = 'x';
+ }
+ Padding = 0xffffffff; // Padding won't stop it either.
+
+ bool NeedsSwap;
+ ASSERT_TRUE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+ ASSERT_FALSE(NeedsSwap);
+ HeaderMapImpl Map(File.getBuffer(), NeedsSwap);
+
+ // The string for "c" runs to the end of File. Check that the suffix
+ // ("cxxxx...") is detected as truncated, and an empty string is returned.
+ SmallString<24> DestPath;
+ ASSERT_EQ("", Map.lookupFilename("a", DestPath));
+}
+
+TEST(HeaderMapTest, lookupFilenameTruncatedPrefix) {
+ typedef MapFile<2, 64 - sizeof(HMapHeader) - 2 * sizeof(HMapBucket)> FileTy;
+ static_assert(std::is_standard_layout<FileTy>::value,
+ "Expected standard layout");
+ static_assert(sizeof(FileTy) == 64, "check the math");
+ PaddedFile<FileTy, uint64_t> P;
+ auto &File = P.File;
+ auto &Padding = P.Padding;
+ File.init();
+
+ FileMaker<FileTy> Maker(File);
+ auto a = Maker.addString("a");
+ auto c = Maker.addString("c");
+ auto b = Maker.addString("b"); // Store the prefix last.
+ Maker.addBucket(getHash("a"), a, b, c);
+
+ // Add 'x' characters to cause an overflow into Padding.
+ ASSERT_EQ('b', File.Bytes[5]);
+ for (unsigned I = 6; I < sizeof(File.Bytes); ++I) {
+ ASSERT_EQ(0, File.Bytes[I]);
+ File.Bytes[I] = 'x';
+ }
+ Padding = 0xffffffff; // Padding won't stop it either.
+
+ bool NeedsSwap;
+ ASSERT_TRUE(HeaderMapImpl::checkHeader(*File.getBuffer(), NeedsSwap));
+ ASSERT_FALSE(NeedsSwap);
+ HeaderMapImpl Map(File.getBuffer(), NeedsSwap);
+
+ // The string for "b" runs to the end of File. Check that the prefix
+ // ("bxxxx...") is detected as truncated, and an empty string is returned.
+ SmallString<24> DestPath;
+ ASSERT_EQ("", Map.lookupFilename("a", DestPath));
+}
+
+} // end namespace
diff --git a/unittests/Lex/LexerTest.cpp b/unittests/Lex/LexerTest.cpp
index 42f8eb5a5c..2046018181 100644
--- a/unittests/Lex/LexerTest.cpp
+++ b/unittests/Lex/LexerTest.cpp
@@ -22,7 +22,6 @@
#include "clang/Lex/PreprocessorOptions.h"
#include "gtest/gtest.h"
-using namespace llvm;
using namespace clang;
namespace {
@@ -59,9 +58,9 @@ protected:
Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
}
- std::vector<Token> CheckLex(StringRef Source,
- ArrayRef<tok::TokenKind> ExpectedTokens) {
- std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Source);
+ std::vector<Token> Lex(StringRef Source) {
+ std::unique_ptr<llvm::MemoryBuffer> Buf =
+ llvm::MemoryBuffer::getMemBuffer(Source);
SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
VoidModuleLoader ModLoader;
@@ -82,6 +81,12 @@ protected:
toks.push_back(tok);
}
+ return toks;
+ }
+
+ std::vector<Token> CheckLex(StringRef Source,
+ ArrayRef<tok::TokenKind> ExpectedTokens) {
+ auto toks = Lex(Source);
EXPECT_EQ(ExpectedTokens.size(), toks.size());
for (unsigned i = 0, e = ExpectedTokens.size(); i != e; ++i) {
EXPECT_EQ(ExpectedTokens[i], toks[i].getKind());
@@ -358,4 +363,21 @@ TEST_F(LexerTest, LexAPI) {
EXPECT_EQ("N", Lexer::getImmediateMacroName(idLoc4, SourceMgr, LangOpts));
}
+TEST_F(LexerTest, DontMergeMacroArgsFromDifferentMacroFiles) {
+ std::vector<Token> toks =
+ Lex("#define helper1 0\n"
+ "void helper2(const char *, ...);\n"
+ "#define M1(a, ...) helper2(a, ##__VA_ARGS__)\n"
+ "#define M2(a, ...) M1(a, helper1, ##__VA_ARGS__)\n"
+ "void f1() { M2(\"a\", \"b\"); }");
+
+ // Check the file corresponding to the "helper1" macro arg in M2.
+ //
+ // The lexer used to report its size as 31, meaning that the end of the
+ // expansion would be on the *next line* (just past `M2("a", "b")`). Make
+ // sure that we get the correct end location (the comma after "helper1").
+ SourceLocation helper1ArgLoc = toks[20].getLocation();
+ EXPECT_EQ(SourceMgr.getFileIDSize(SourceMgr.getFileID(helper1ArgLoc)), 8U);
+}
+
} // anonymous namespace
diff --git a/unittests/Lex/Makefile b/unittests/Lex/Makefile
deleted file mode 100644
index 071d01c8b5..0000000000
--- a/unittests/Lex/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- unittests/Lex/Makefile ------------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = Lex
-LINK_COMPONENTS := mcparser support mc bitreader
-USEDLIBS = clangParse.a clangSema.a clangAnalysis.a clangEdit.a \
- clangSerialization.a clangAST.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Lex/PPConditionalDirectiveRecordTest.cpp b/unittests/Lex/PPConditionalDirectiveRecordTest.cpp
index 9345fc2390..bceeac57ea 100644
--- a/unittests/Lex/PPConditionalDirectiveRecordTest.cpp
+++ b/unittests/Lex/PPConditionalDirectiveRecordTest.cpp
@@ -22,7 +22,6 @@
#include "clang/Lex/PreprocessorOptions.h"
#include "gtest/gtest.h"
-using namespace llvm;
using namespace clang;
namespace {
@@ -89,7 +88,8 @@ TEST_F(PPConditionalDirectiveRecordTest, PPRecAPI) {
"#endif\n"
"9\n";
- std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(source);
+ std::unique_ptr<llvm::MemoryBuffer> Buf =
+ llvm::MemoryBuffer::getMemBuffer(source);
SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
VoidModuleLoader ModLoader;
diff --git a/unittests/Makefile b/unittests/Makefile
deleted file mode 100644
index 2a0b5bc9dd..0000000000
--- a/unittests/Makefile
+++ /dev/null
@@ -1,35 +0,0 @@
-##===- unittests/Makefile ----------------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-# If CLANG_LEVEL is not set, then we are the top-level Makefile. Otherwise, we
-# are being included from a subdirectory makefile.
-
-ifndef CLANG_LEVEL
-
-IS_UNITTEST_LEVEL := 1
-CLANG_LEVEL := ..
-PARALLEL_DIRS = CodeGen Basic Lex Driver Format ASTMatchers AST Tooling \
- Rewrite Sema
-
-include $(CLANG_LEVEL)/../..//Makefile.config
-
-ifeq ($(ENABLE_CLANG_ARCMT),1)
-PARALLEL_DIRS += Frontend libclang StaticAnalyzer
-endif
-
-endif # CLANG_LEVEL
-
-include $(CLANG_LEVEL)/Makefile
-
-ifndef IS_UNITTEST_LEVEL
-
-MAKEFILE_UNITTEST_NO_INCLUDE_COMMON := 1
-include $(LLVM_SRC_ROOT)/unittests/Makefile.unittest
-
-endif # IS_UNITTEST_LEVEL
diff --git a/unittests/Rewrite/Makefile b/unittests/Rewrite/Makefile
deleted file mode 100644
index 43538d5607..0000000000
--- a/unittests/Rewrite/Makefile
+++ /dev/null
@@ -1,16 +0,0 @@
-##===- unittests/Rewrite/Makefile --------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = Rewrite
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) support
-USEDLIBS = clangRewrite.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Sema/ExternalSemaSourceTest.cpp b/unittests/Sema/ExternalSemaSourceTest.cpp
index 703e97b4ac..d2cdd633fa 100644
--- a/unittests/Sema/ExternalSemaSourceTest.cpp
+++ b/unittests/Sema/ExternalSemaSourceTest.cpp
@@ -39,19 +39,18 @@ public:
bool Result;
};
-// \brief Counts the number of err_using_directive_member_suggest diagnostics
-// correcting from one namespace to another while still passing all diagnostics
-// along a chain of consumers.
-class NamespaceDiagnosticWatcher : public clang::DiagnosticConsumer {
+/// Counts the number of typo-correcting diagnostics correcting from one name to
+/// another while still passing all diagnostics along a chain of consumers.
+class DiagnosticWatcher : public clang::DiagnosticConsumer {
DiagnosticConsumer *Chained;
- std::string FromNS;
- std::string ToNS;
+ std::string FromName;
+ std::string ToName;
public:
- NamespaceDiagnosticWatcher(StringRef From, StringRef To)
- : Chained(nullptr), FromNS(From), ToNS("'"), SeenCount(0) {
- ToNS.append(To);
- ToNS.append("'");
+ DiagnosticWatcher(StringRef From, StringRef To)
+ : Chained(nullptr), FromName(From), ToName("'"), SeenCount(0) {
+ ToName.append(To);
+ ToName.append("'");
}
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
@@ -61,7 +60,12 @@ public:
if (Info.getID() - 1 == diag::err_using_directive_member_suggest) {
const IdentifierInfo *Ident = Info.getArgIdentifier(0);
const std::string &CorrectedQuotedStr = Info.getArgStdStr(1);
- if (Ident->getName() == FromNS && CorrectedQuotedStr == ToNS)
+ if (Ident->getName() == FromName && CorrectedQuotedStr == ToName)
+ ++SeenCount;
+ } else if (Info.getID() == diag::err_no_member_suggest) {
+ auto Ident = DeclarationName::getFromOpaqueInteger(Info.getRawArg(0));
+ const std::string &CorrectedQuotedStr = Info.getArgStdStr(3);
+ if (Ident.getAsString() == FromName && CorrectedQuotedStr == ToName)
++SeenCount;
}
}
@@ -78,7 +82,7 @@ public:
return false;
}
- NamespaceDiagnosticWatcher *Chain(DiagnosticConsumer *ToChain) {
+ DiagnosticWatcher *Chain(DiagnosticConsumer *ToChain) {
Chained = ToChain;
return this;
}
@@ -130,11 +134,53 @@ public:
int CallCount;
};
-// \brief Chains together a vector of NamespaceDiagnosticWatchers and
+class FunctionTypoProvider : public clang::ExternalSemaSource {
+ std::string CorrectFrom;
+ std::string CorrectTo;
+ Sema *CurrentSema;
+
+public:
+ FunctionTypoProvider(StringRef From, StringRef To)
+ : CorrectFrom(From), CorrectTo(To), CurrentSema(nullptr), CallCount(0) {}
+
+ void InitializeSema(Sema &S) override { CurrentSema = &S; }
+
+ void ForgetSema() override { CurrentSema = nullptr; }
+
+ TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, int LookupKind,
+ Scope *S, CXXScopeSpec *SS,
+ CorrectionCandidateCallback &CCC,
+ DeclContext *MemberContext, bool EnteringContext,
+ const ObjCObjectPointerType *OPT) override {
+ ++CallCount;
+ if (CurrentSema && Typo.getName().getAsString() == CorrectFrom) {
+ DeclContext *DestContext = nullptr;
+ ASTContext &Context = CurrentSema->getASTContext();
+ if (SS)
+ DestContext = CurrentSema->computeDeclContext(*SS, EnteringContext);
+ if (!DestContext)
+ DestContext = Context.getTranslationUnitDecl();
+ IdentifierInfo *ToIdent =
+ CurrentSema->getPreprocessor().getIdentifierInfo(CorrectTo);
+ auto *NewFunction = FunctionDecl::Create(
+ Context, DestContext, SourceLocation(), SourceLocation(), ToIdent,
+ Context.getFunctionType(Context.VoidTy, {}, {}), nullptr, SC_Static);
+ DestContext->addDecl(NewFunction);
+ TypoCorrection Correction(ToIdent);
+ Correction.addCorrectionDecl(NewFunction);
+ return Correction;
+ }
+ return TypoCorrection();
+ }
+
+ int CallCount;
+};
+
+// \brief Chains together a vector of DiagnosticWatchers and
// adds a vector of ExternalSemaSources to the CompilerInstance before
// performing semantic analysis.
class ExternalSemaSourceInstaller : public clang::ASTFrontendAction {
- std::vector<NamespaceDiagnosticWatcher *> Watchers;
+ std::vector<DiagnosticWatcher *> Watchers;
std::vector<clang::ExternalSemaSource *> Sources;
std::unique_ptr<DiagnosticConsumer> OwnedClient;
@@ -170,16 +216,14 @@ public:
Sources.push_back(Source);
}
- void PushWatcher(NamespaceDiagnosticWatcher *Watcher) {
- Watchers.push_back(Watcher);
- }
+ void PushWatcher(DiagnosticWatcher *Watcher) { Watchers.push_back(Watcher); }
};
-// Make sure that the NamespaceDiagnosticWatcher is not miscounting.
+// Make sure that the DiagnosticWatcher is not miscounting.
TEST(ExternalSemaSource, SanityCheck) {
std::unique_ptr<ExternalSemaSourceInstaller> Installer(
new ExternalSemaSourceInstaller);
- NamespaceDiagnosticWatcher Watcher("AAB", "BBB");
+ DiagnosticWatcher Watcher("AAB", "BBB");
Installer->PushWatcher(&Watcher);
std::vector<std::string> Args(1, "-std=c++11");
ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
@@ -193,7 +237,7 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionPrioritized) {
std::unique_ptr<ExternalSemaSourceInstaller> Installer(
new ExternalSemaSourceInstaller);
NamespaceTypoProvider Provider("AAB", "BBB");
- NamespaceDiagnosticWatcher Watcher("AAB", "BBB");
+ DiagnosticWatcher Watcher("AAB", "BBB");
Installer->PushSource(&Provider);
Installer->PushWatcher(&Watcher);
std::vector<std::string> Args(1, "-std=c++11");
@@ -211,7 +255,7 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionOrdering) {
NamespaceTypoProvider First("XXX", "BBB");
NamespaceTypoProvider Second("AAB", "CCC");
NamespaceTypoProvider Third("AAB", "DDD");
- NamespaceDiagnosticWatcher Watcher("AAB", "CCC");
+ DiagnosticWatcher Watcher("AAB", "CCC");
Installer->PushSource(&First);
Installer->PushSource(&Second);
Installer->PushSource(&Third);
@@ -225,6 +269,21 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionOrdering) {
ASSERT_EQ(1, Watcher.SeenCount);
}
+TEST(ExternalSemaSource, ExternalDelayedTypoCorrection) {
+ std::unique_ptr<ExternalSemaSourceInstaller> Installer(
+ new ExternalSemaSourceInstaller);
+ FunctionTypoProvider Provider("aaa", "bbb");
+ DiagnosticWatcher Watcher("aaa", "bbb");
+ Installer->PushSource(&Provider);
+ Installer->PushWatcher(&Watcher);
+ std::vector<std::string> Args(1, "-std=c++11");
+ ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
+ Installer.release(), "namespace AAA { } void foo() { AAA::aaa(); }",
+ Args));
+ ASSERT_LE(0, Provider.CallCount);
+ ASSERT_EQ(1, Watcher.SeenCount);
+}
+
// We should only try MaybeDiagnoseMissingCompleteType if we can't otherwise
// solve the problem.
TEST(ExternalSemaSource, TryOtherTacticsBeforeDiagnosing) {
diff --git a/unittests/Sema/Makefile b/unittests/Sema/Makefile
deleted file mode 100644
index 7fd5c27ad6..0000000000
--- a/unittests/Sema/Makefile
+++ /dev/null
@@ -1,19 +0,0 @@
-##===- unittests/Sema/Makefile -----------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = Sema
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc option
-USEDLIBS = clangTooling.a clangFrontend.a clangSerialization.a clangDriver.a \
- clangRewrite.a clangRewriteFrontend.a \
- clangParse.a clangSema.a clangAnalysis.a \
- clangEdit.a clangAST.a clangASTMatchers.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/StaticAnalyzer/Makefile b/unittests/StaticAnalyzer/Makefile
deleted file mode 100644
index af85b711e5..0000000000
--- a/unittests/StaticAnalyzer/Makefile
+++ /dev/null
@@ -1,15 +0,0 @@
-##===- unittests/Basic/Makefile ----------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = StaticAnalysis
-LINK_COMPONENTS := support mc
-USEDLIBS = clangBasic.a clangAnalysis.a clangStaticAnalyzerCore.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Tooling/CMakeLists.txt b/unittests/Tooling/CMakeLists.txt
index 33b2046ae9..b4b3f404e2 100644
--- a/unittests/Tooling/CMakeLists.txt
+++ b/unittests/Tooling/CMakeLists.txt
@@ -3,26 +3,35 @@ set(LLVM_LINK_COMPONENTS
Support
)
+# By default MSVC has a 2^16 limit on the number of sections in an object file,
+# and this needs more than that.
+if (MSVC)
+ set_source_files_properties(RecursiveASTVisitorTestExprVisitor.cpp PROPERTIES COMPILE_FLAGS /bigobj)
+endif()
+
add_clang_unittest(ToolingTests
CommentHandlerTest.cpp
CompilationDatabaseTest.cpp
+ FixItTest.cpp
LookupTest.cpp
- ToolingTest.cpp
+ QualTypeNamesTest.cpp
RecursiveASTVisitorTest.cpp
RecursiveASTVisitorTestCallVisitor.cpp
RecursiveASTVisitorTestDeclVisitor.cpp
RecursiveASTVisitorTestExprVisitor.cpp
RecursiveASTVisitorTestTypeLocVisitor.cpp
- RefactoringTest.cpp
- RewriterTest.cpp
RefactoringCallbacksTest.cpp
+ RefactoringTest.cpp
ReplacementsYamlTest.cpp
+ RewriterTest.cpp
+ ToolingTest.cpp
)
target_link_libraries(ToolingTests
clangAST
clangASTMatchers
clangBasic
+ clangFormat
clangFrontend
clangLex
clangRewrite
diff --git a/unittests/Tooling/FixItTest.cpp b/unittests/Tooling/FixItTest.cpp
new file mode 100644
index 0000000000..365180e67f
--- /dev/null
+++ b/unittests/Tooling/FixItTest.cpp
@@ -0,0 +1,232 @@
+//===- unittest/Tooling/FixitTest.cpp ------------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestVisitor.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Tooling/FixIt.h"
+
+using namespace clang;
+
+using tooling::fixit::getText;
+using tooling::fixit::createRemoval;
+using tooling::fixit::createReplacement;
+
+namespace {
+
+struct CallsVisitor : TestVisitor<CallsVisitor> {
+ bool VisitCallExpr(CallExpr *Expr) {
+ OnCall(Expr, Context);
+ return true;
+ }
+
+ std::function<void(CallExpr *, ASTContext *Context)> OnCall;
+};
+
+std::string LocationToString(SourceLocation Loc, ASTContext *Context) {
+ return Loc.printToString(Context->getSourceManager());
+}
+
+TEST(FixItTest, getText) {
+ CallsVisitor Visitor;
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ EXPECT_EQ("foo(x, y)", getText(*CE, *Context));
+ EXPECT_EQ("foo(x, y)", getText(CE->getSourceRange(), *Context));
+
+ Expr *P0 = CE->getArg(0);
+ Expr *P1 = CE->getArg(1);
+ EXPECT_EQ("x", getText(*P0, *Context));
+ EXPECT_EQ("y", getText(*P1, *Context));
+ };
+ Visitor.runOver("void foo(int x, int y) { foo(x, y); }");
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ EXPECT_EQ("APPLY(foo, x, y)", getText(*CE, *Context));
+ };
+ Visitor.runOver("#define APPLY(f, x, y) f(x, y)\n"
+ "void foo(int x, int y) { APPLY(foo, x, y); }");
+}
+
+TEST(FixItTest, getTextWithMacro) {
+ CallsVisitor Visitor;
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ EXPECT_EQ("F OO", getText(*CE, *Context));
+ Expr *P0 = CE->getArg(0);
+ Expr *P1 = CE->getArg(1);
+ EXPECT_EQ("", getText(*P0, *Context));
+ EXPECT_EQ("", getText(*P1, *Context));
+ };
+ Visitor.runOver("#define F foo(\n"
+ "#define OO x, y)\n"
+ "void foo(int x, int y) { F OO ; }");
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ EXPECT_EQ("", getText(*CE, *Context));
+ Expr *P0 = CE->getArg(0);
+ Expr *P1 = CE->getArg(1);
+ EXPECT_EQ("x", getText(*P0, *Context));
+ EXPECT_EQ("y", getText(*P1, *Context));
+ };
+ Visitor.runOver("#define FOO(x, y) (void)x; (void)y; foo(x, y);\n"
+ "void foo(int x, int y) { FOO(x,y) }");
+}
+
+TEST(FixItTest, createRemoval) {
+ CallsVisitor Visitor;
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ FixItHint Hint = createRemoval(*CE);
+ EXPECT_EQ("foo(x, y)", getText(Hint.RemoveRange.getAsRange(), *Context));
+ EXPECT_TRUE(Hint.InsertFromRange.isInvalid());
+ EXPECT_TRUE(Hint.CodeToInsert.empty());
+
+ Expr *P0 = CE->getArg(0);
+ FixItHint Hint0 = createRemoval(*P0);
+ EXPECT_EQ("x", getText(Hint0.RemoveRange.getAsRange(), *Context));
+ EXPECT_TRUE(Hint0.InsertFromRange.isInvalid());
+ EXPECT_TRUE(Hint0.CodeToInsert.empty());
+
+ Expr *P1 = CE->getArg(1);
+ FixItHint Hint1 = createRemoval(*P1);
+ EXPECT_EQ("y", getText(Hint1.RemoveRange.getAsRange(), *Context));
+ EXPECT_TRUE(Hint1.InsertFromRange.isInvalid());
+ EXPECT_TRUE(Hint1.CodeToInsert.empty());
+ };
+ Visitor.runOver("void foo(int x, int y) { foo(x, y); }");
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ Expr *P0 = CE->getArg(0);
+ FixItHint Hint0 = createRemoval(*P0);
+ EXPECT_EQ("x + y", getText(Hint0.RemoveRange.getAsRange(), *Context));
+
+ Expr *P1 = CE->getArg(1);
+ FixItHint Hint1 = createRemoval(*P1);
+ EXPECT_EQ("y + x", getText(Hint1.RemoveRange.getAsRange(), *Context));
+ };
+ Visitor.runOver("void foo(int x, int y) { foo(x + y, y + x); }");
+}
+
+TEST(FixItTest, createRemovalWithMacro) {
+ CallsVisitor Visitor;
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ FixItHint Hint = createRemoval(*CE);
+ EXPECT_EQ("FOO", getText(Hint.RemoveRange.getAsRange(), *Context));
+ EXPECT_TRUE(Hint.InsertFromRange.isInvalid());
+ EXPECT_TRUE(Hint.CodeToInsert.empty());
+
+ Expr *P0 = CE->getArg(0);
+ FixItHint Hint0 = createRemoval(*P0);
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:1:17>",
+ LocationToString(Hint0.RemoveRange.getBegin(), Context));
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:1:17>",
+ LocationToString(Hint0.RemoveRange.getEnd(), Context));
+ EXPECT_TRUE(Hint0.InsertFromRange.isInvalid());
+ EXPECT_TRUE(Hint0.CodeToInsert.empty());
+
+ Expr *P1 = CE->getArg(1);
+ FixItHint Hint1 = createRemoval(*P1);
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:1:20>",
+ LocationToString(Hint1.RemoveRange.getBegin(), Context));
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:1:20>",
+ LocationToString(Hint1.RemoveRange.getEnd(), Context));
+ EXPECT_TRUE(Hint1.InsertFromRange.isInvalid());
+ EXPECT_TRUE(Hint1.CodeToInsert.empty());
+ };
+ Visitor.runOver("#define FOO foo(1, 1)\n"
+ "void foo(int x, int y) { FOO; }");
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ FixItHint Hint = createRemoval(*CE);
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:1:37>",
+ LocationToString(Hint.RemoveRange.getBegin(), Context));
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:1:45>",
+ LocationToString(Hint.RemoveRange.getEnd(), Context));
+ EXPECT_TRUE(Hint.InsertFromRange.isInvalid());
+ EXPECT_TRUE(Hint.CodeToInsert.empty());
+ };
+ Visitor.runOver("#define FOO(x, y) (void)x; (void)y; foo(x, y);\n"
+ "void foo(int x, int y) { FOO(x,y) }");
+}
+
+TEST(FixItTest, createReplacement) {
+ CallsVisitor Visitor;
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ Expr *P0 = CE->getArg(0);
+ Expr *P1 = CE->getArg(1);
+ FixItHint Hint0 = createReplacement(*P0, *P1, *Context);
+ FixItHint Hint1 = createReplacement(*P1, *P0, *Context);
+
+ // Validate Hint0 fields.
+ EXPECT_EQ("x", getText(Hint0.RemoveRange.getAsRange(), *Context));
+ EXPECT_TRUE(Hint0.InsertFromRange.isInvalid());
+ EXPECT_EQ(Hint0.CodeToInsert, "y");
+
+ // Validate Hint1 fields.
+ EXPECT_EQ("y", getText(Hint1.RemoveRange.getAsRange(), *Context));
+ EXPECT_TRUE(Hint1.InsertFromRange.isInvalid());
+ EXPECT_EQ(Hint1.CodeToInsert, "x");
+ };
+
+ Visitor.runOver("void foo(int x, int y) { foo(x, y); }");
+
+ Visitor.runOver("#define APPLY(f, x, y) f(x, y)\n"
+ "void foo(int x, int y) { APPLY(foo, x, y); }");
+
+ Visitor.runOver("#define APPLY(f, P) f(P)\n"
+ "#define PAIR(x, y) x, y\n"
+ "void foo(int x, int y) { APPLY(foo, PAIR(x, y)); }\n");
+}
+
+TEST(FixItTest, createReplacementWithMacro) {
+ CallsVisitor Visitor;
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ Expr *P0 = CE->getArg(0);
+ Expr *P1 = CE->getArg(1);
+ FixItHint Hint = createReplacement(*P0, *P1, *Context);
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:1:17>",
+ LocationToString(Hint.RemoveRange.getBegin(), Context));
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:1:17>",
+ LocationToString(Hint.RemoveRange.getEnd(), Context));
+ EXPECT_TRUE(Hint.InsertFromRange.isInvalid());
+ EXPECT_TRUE(Hint.CodeToInsert.empty());
+ };
+
+ Visitor.runOver("#define FOO foo(1, 1)\n"
+ "void foo(int x, int y) { FOO; }");
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ Expr *P0 = CE->getArg(0);
+ Expr *P1 = CE->getArg(1);
+ FixItHint Hint = createReplacement(*P0, *P1, *Context);
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:2:30>",
+ LocationToString(Hint.RemoveRange.getBegin(), Context));
+ EXPECT_EQ("input.cc:2:26 <Spelling=input.cc:2:30>",
+ LocationToString(Hint.RemoveRange.getEnd(), Context));
+ EXPECT_TRUE(Hint.InsertFromRange.isInvalid());
+ EXPECT_EQ("y", Hint.CodeToInsert);
+ };
+ Visitor.runOver("#define FOO(x, y) (void)x; (void)y; foo(x, y);\n"
+ "void foo(int x, int y) { FOO(x,y) }");
+
+ Visitor.OnCall = [](CallExpr *CE, ASTContext *Context) {
+ Expr *P0 = CE->getArg(0);
+ Expr *P1 = CE->getArg(1);
+ FixItHint Hint = createReplacement(*P0, *P1, *Context);
+ EXPECT_EQ("x + y", getText(Hint.RemoveRange.getAsRange(), *Context));
+ EXPECT_TRUE(Hint.InsertFromRange.isInvalid());
+ EXPECT_EQ("y + x", Hint.CodeToInsert);
+ };
+ Visitor.runOver("void foo(int x, int y) { foo(x + y, y + x); }");
+}
+
+} // end anonymous namespace
diff --git a/unittests/Tooling/Makefile b/unittests/Tooling/Makefile
deleted file mode 100644
index 514e80bd03..0000000000
--- a/unittests/Tooling/Makefile
+++ /dev/null
@@ -1,20 +0,0 @@
-##===- unittests/Tooling/Makefile --------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = Tooling
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc option
-USEDLIBS = clangTooling.a clangToolingCore.a clangFrontend.a \
- clangSerialization.a clangDriver.a \
- clangParse.a clangRewrite.a clangRewriteFrontend.a \
- clangSema.a clangAnalysis.a clangEdit.a \
- clangAST.a clangASTMatchers.a clangLex.a clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile
diff --git a/unittests/Tooling/QualTypeNamesTest.cpp b/unittests/Tooling/QualTypeNamesTest.cpp
new file mode 100644
index 0000000000..edd5060ba0
--- /dev/null
+++ b/unittests/Tooling/QualTypeNamesTest.cpp
@@ -0,0 +1,222 @@
+//===- unittest/Tooling/QualTypeNameTest.cpp ------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Tooling/Core/QualTypeNames.h"
+#include "TestVisitor.h"
+using namespace clang;
+
+namespace {
+struct TypeNameVisitor : TestVisitor<TypeNameVisitor> {
+ llvm::StringMap<std::string> ExpectedQualTypeNames;
+ bool WithGlobalNsPrefix = false;
+
+ // ValueDecls are the least-derived decl with both a qualtype and a
+ // name.
+ bool traverseDecl(Decl *D) {
+ return true; // Always continue
+ }
+
+ bool VisitValueDecl(const ValueDecl *VD) {
+ std::string ExpectedName =
+ ExpectedQualTypeNames.lookup(VD->getNameAsString());
+ if (ExpectedName != "") {
+ std::string ActualName =
+ TypeName::getFullyQualifiedName(VD->getType(), *Context,
+ WithGlobalNsPrefix);
+ if (ExpectedName != ActualName) {
+ // A custom message makes it much easier to see what declaration
+ // failed compared to EXPECT_EQ.
+ EXPECT_TRUE(false) << "Typename::getFullyQualifiedName failed for "
+ << VD->getQualifiedNameAsString() << std::endl
+ << " Actual: " << ActualName << std::endl
+ << " Exepcted: " << ExpectedName;
+ }
+ }
+ return true;
+ }
+};
+
+// named namespaces inside anonymous namespaces
+
+TEST(QualTypeNameTest, getFullyQualifiedName) {
+ TypeNameVisitor Visitor;
+ // Simple case to test the test framework itself.
+ Visitor.ExpectedQualTypeNames["CheckInt"] = "int";
+
+ // Keeping the names of the variables whose types we check unique
+ // within the entire test--regardless of their own scope--makes it
+ // easier to diagnose test failures.
+
+ // Simple namespace qualifier
+ Visitor.ExpectedQualTypeNames["CheckA"] = "A::B::Class0";
+ // Lookup up the enclosing scopes, then down another one. (These
+ // appear as elaborated type in the AST. In that case--even if
+ // policy.SuppressScope = 0--qual_type.getAsString(policy) only
+ // gives the name as it appears in the source, not the full name.
+ Visitor.ExpectedQualTypeNames["CheckB"] = "A::B::C::Class1";
+ // Template parameter expansion.
+ Visitor.ExpectedQualTypeNames["CheckC"] =
+ "A::B::Template0<A::B::C::MyInt, A::B::AnotherClass>";
+ // Recursive template parameter expansion.
+ Visitor.ExpectedQualTypeNames["CheckD"] =
+ "A::B::Template0<A::B::Template1<A::B::C::MyInt, A::B::AnotherClass>, "
+ "A::B::Template0<int, long> >";
+ // Variadic Template expansion.
+ Visitor.ExpectedQualTypeNames["CheckE"] =
+ "A::Variadic<int, A::B::Template0<int, char>, "
+ "A::B::Template1<int, long>, A::B::C::MyInt>";
+ // Using declarations should be fully expanded.
+ Visitor.ExpectedQualTypeNames["CheckF"] = "A::B::Class0";
+ // Elements found within "using namespace foo;" should be fully
+ // expanded.
+ Visitor.ExpectedQualTypeNames["CheckG"] = "A::B::C::MyInt";
+ // Type inside function
+ Visitor.ExpectedQualTypeNames["CheckH"] = "struct X";
+ // Anonymous Namespaces
+ Visitor.ExpectedQualTypeNames["CheckI"] = "aClass";
+ // Keyword inclusion with namespaces
+ Visitor.ExpectedQualTypeNames["CheckJ"] = "struct A::aStruct";
+ // Anonymous Namespaces nested in named namespaces and vice-versa.
+ Visitor.ExpectedQualTypeNames["CheckK"] = "D::aStruct";
+ // Namespace alias
+ Visitor.ExpectedQualTypeNames["CheckL"] = "A::B::C::MyInt";
+ Visitor.ExpectedQualTypeNames["non_dependent_type_var"] =
+ "Foo<X>::non_dependent_type";
+ Visitor.ExpectedQualTypeNames["AnEnumVar"] = "EnumScopeClass::AnEnum";
+ Visitor.ExpectedQualTypeNames["AliasTypeVal"] = "A::B::C::InnerAlias<int>";
+ Visitor.ExpectedQualTypeNames["CheckM"] = "const A::B::Class0 *";
+ Visitor.ExpectedQualTypeNames["CheckN"] = "const X *";
+ Visitor.runOver(
+ "int CheckInt;\n"
+ "template <typename T>\n"
+ "class OuterTemplateClass { };\n"
+ "namespace A {\n"
+ " namespace B {\n"
+ " class Class0 { };\n"
+ " namespace C {\n"
+ " typedef int MyInt;"
+ " template <typename T>\n"
+ " using InnerAlias = OuterTemplateClass<T>;\n"
+ " InnerAlias<int> AliasTypeVal;\n"
+ " }\n"
+ " template<class X, class Y> class Template0;"
+ " template<class X, class Y> class Template1;"
+ " typedef B::Class0 AnotherClass;\n"
+ " void Function1(Template0<C::MyInt,\n"
+ " AnotherClass> CheckC);\n"
+ " void Function2(Template0<Template1<C::MyInt, AnotherClass>,\n"
+ " Template0<int, long> > CheckD);\n"
+ " void Function3(const B::Class0* CheckM);\n"
+ " }\n"
+ "template<typename... Values> class Variadic {};\n"
+ "Variadic<int, B::Template0<int, char>, "
+ " B::Template1<int, long>, "
+ " B::C::MyInt > CheckE;\n"
+ " namespace BC = B::C;\n"
+ " BC::MyInt CheckL;\n"
+ "}\n"
+ "using A::B::Class0;\n"
+ "void Function(Class0 CheckF);\n"
+ "using namespace A::B::C;\n"
+ "void Function(MyInt CheckG);\n"
+ "void f() {\n"
+ " struct X {} CheckH;\n"
+ "}\n"
+ "struct X;\n"
+ "void f(const ::X* CheckN) {}\n"
+ "namespace {\n"
+ " class aClass {};\n"
+ " aClass CheckI;\n"
+ "}\n"
+ "namespace A {\n"
+ " struct aStruct {} CheckJ;\n"
+ "}\n"
+ "namespace {\n"
+ " namespace D {\n"
+ " namespace {\n"
+ " class aStruct {};\n"
+ " aStruct CheckK;\n"
+ " }\n"
+ " }\n"
+ "}\n"
+ "template<class T> struct Foo {\n"
+ " typedef typename T::A dependent_type;\n"
+ " typedef int non_dependent_type;\n"
+ " dependent_type dependent_type_var;\n"
+ " non_dependent_type non_dependent_type_var;\n"
+ "};\n"
+ "struct X { typedef int A; };"
+ "Foo<X> var;"
+ "void F() {\n"
+ " var.dependent_type_var = 0;\n"
+ "var.non_dependent_type_var = 0;\n"
+ "}\n"
+ "class EnumScopeClass {\n"
+ "public:\n"
+ " enum AnEnum { ZERO, ONE };\n"
+ "};\n"
+ "EnumScopeClass::AnEnum AnEnumVar;\n",
+ TypeNameVisitor::Lang_CXX11
+);
+
+ TypeNameVisitor Complex;
+ Complex.ExpectedQualTypeNames["CheckTX"] = "B::TX";
+ Complex.runOver(
+ "namespace A {"
+ " struct X {};"
+ "}"
+ "using A::X;"
+ "namespace fake_std {"
+ " template<class... Types > class tuple {};"
+ "}"
+ "namespace B {"
+ " using fake_std::tuple;"
+ " typedef tuple<X> TX;"
+ " TX CheckTX;"
+ " struct A { typedef int X; };"
+ "}");
+
+ TypeNameVisitor GlobalNsPrefix;
+ GlobalNsPrefix.WithGlobalNsPrefix = true;
+ GlobalNsPrefix.ExpectedQualTypeNames["IntVal"] = "int";
+ GlobalNsPrefix.ExpectedQualTypeNames["BoolVal"] = "bool";
+ GlobalNsPrefix.ExpectedQualTypeNames["XVal"] = "::A::B::X";
+ GlobalNsPrefix.ExpectedQualTypeNames["IntAliasVal"] = "::A::B::Alias<int>";
+ GlobalNsPrefix.ExpectedQualTypeNames["ZVal"] = "::A::B::Y::Z";
+ GlobalNsPrefix.ExpectedQualTypeNames["GlobalZVal"] = "::Z";
+ GlobalNsPrefix.ExpectedQualTypeNames["CheckK"] = "D::aStruct";
+ GlobalNsPrefix.runOver(
+ "namespace A {\n"
+ " namespace B {\n"
+ " int IntVal;\n"
+ " bool BoolVal;\n"
+ " struct X {};\n"
+ " X XVal;\n"
+ " template <typename T> class CCC { };\n"
+ " template <typename T>\n"
+ " using Alias = CCC<T>;\n"
+ " Alias<int> IntAliasVal;\n"
+ " struct Y { struct Z {}; };\n"
+ " Y::Z ZVal;\n"
+ " }\n"
+ "}\n"
+ "struct Z {};\n"
+ "Z GlobalZVal;\n"
+ "namespace {\n"
+ " namespace D {\n"
+ " namespace {\n"
+ " class aStruct {};\n"
+ " aStruct CheckK;\n"
+ " }\n"
+ " }\n"
+ "}\n"
+ );
+}
+
+} // end anonymous namespace
diff --git a/unittests/Tooling/RecursiveASTVisitorTest.cpp b/unittests/Tooling/RecursiveASTVisitorTest.cpp
index c28704532a..991ae8bb7f 100644
--- a/unittests/Tooling/RecursiveASTVisitorTest.cpp
+++ b/unittests/Tooling/RecursiveASTVisitorTest.cpp
@@ -42,13 +42,13 @@ TEST(RecursiveASTVisitor, VisitsLambdaExpr) {
LambdaExprVisitor Visitor;
Visitor.ExpectMatch("", 1, 12);
EXPECT_TRUE(Visitor.runOver("void f() { []{ return; }(); }",
- LambdaExprVisitor::Lang_CXX11));
+ LambdaExprVisitor::Lang_CXX11));
}
TEST(RecursiveASTVisitor, TraverseLambdaBodyCanBeOverridden) {
LambdaExprVisitor Visitor;
EXPECT_TRUE(Visitor.runOver("void f() { []{ return; }(); }",
- LambdaExprVisitor::Lang_CXX11));
+ LambdaExprVisitor::Lang_CXX11));
EXPECT_TRUE(Visitor.allBodiesHaveBeenTraversed());
}
@@ -92,8 +92,7 @@ private:
TEST(RecursiveASTVisitor, LambdaClosureTypesAreImplicit) {
ClassVisitor Visitor;
- EXPECT_TRUE(Visitor.runOver("auto lambda = []{};",
- ClassVisitor::Lang_CXX11));
+ EXPECT_TRUE(Visitor.runOver("auto lambda = []{};", ClassVisitor::Lang_CXX11));
EXPECT_TRUE(Visitor.sawOnlyImplicitLambdaClasses());
}
@@ -134,4 +133,23 @@ TEST(RecursiveASTVisitor, AttributesAreVisited) {
"};\n"));
}
+// Check to ensure that VarDecls are visited.
+class VarDeclVisitor : public ExpectedLocationVisitor<VarDeclVisitor> {
+public:
+ bool VisitVarDecl(VarDecl *VD) {
+ Match(VD->getNameAsString(), VD->getLocStart());
+ return true;
+ }
+};
+
+TEST(RecursiveASTVisitor, ArrayInitializersAreVisited) {
+ VarDeclVisitor Visitor;
+ Visitor.ExpectMatch("__i0", 1, 8);
+ EXPECT_TRUE(
+ Visitor.runOver("struct MyClass {\n"
+ " int c[1];\n"
+ " static MyClass Create() { return MyClass(); }\n"
+ "};\n"));
+}
+
} // end anonymous namespace
diff --git a/unittests/Tooling/RefactoringTest.cpp b/unittests/Tooling/RefactoringTest.cpp
index ff11aeae11..df96bb159d 100644
--- a/unittests/Tooling/RefactoringTest.cpp
+++ b/unittests/Tooling/RefactoringTest.cpp
@@ -18,6 +18,7 @@
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
+#include "clang/Format/Format.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
@@ -166,6 +167,39 @@ TEST_F(ReplacementTest, ApplyAllFailsIfOneApplyFails) {
EXPECT_EQ("z", Context.getRewrittenText(IDz));
}
+TEST_F(ReplacementTest, MultipleFilesReplaceAndFormat) {
+ // Column limit is 20.
+ std::string Code1 = "Long *a =\n"
+ " new Long();\n"
+ "long x = 1;";
+ std::string Expected1 = "auto a = new Long();\n"
+ "long x =\n"
+ " 12345678901;";
+ std::string Code2 = "int x = 123;\n"
+ "int y = 0;";
+ std::string Expected2 = "int x =\n"
+ " 1234567890123;\n"
+ "int y = 10;";
+ FileID ID1 = Context.createInMemoryFile("format_1.cpp", Code1);
+ FileID ID2 = Context.createInMemoryFile("format_2.cpp", Code2);
+
+ tooling::Replacements Replaces;
+ // Scrambled the order of replacements.
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID2, 1, 12), 0, "4567890123"));
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID1, 1, 1), 6, "auto "));
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID2, 2, 9), 1, "10"));
+ Replaces.insert(tooling::Replacement(
+ Context.Sources, Context.getLocation(ID1, 3, 10), 1, "12345678901"));
+
+ EXPECT_TRUE(formatAndApplyAllReplacements(
+ Replaces, Context.Rewrite, "{BasedOnStyle: LLVM, ColumnLimit: 20}"));
+ EXPECT_EQ(Expected1, Context.getRewrittenText(ID1));
+ EXPECT_EQ(Expected2, Context.getRewrittenText(ID2));
+}
+
TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
Replacements Replaces;
Replaces.insert(Replacement("", 0, 1, ""));
@@ -418,6 +452,108 @@ TEST(Range, contains) {
EXPECT_FALSE(Range(0, 10).contains(Range(0, 11)));
}
+TEST(Range, CalculateRangesOfReplacements) {
+ // Before: aaaabbbbbbz
+ // After : bbbbbbzzzzzzoooooooooooooooo
+ Replacements Replaces;
+ Replaces.insert(Replacement("foo", 0, 4, ""));
+ Replaces.insert(Replacement("foo", 10, 1, "zzzzzz"));
+ Replaces.insert(Replacement("foo", 11, 0, "oooooooooooooooo"));
+
+ std::vector<Range> Ranges = calculateChangedRanges(Replaces);
+
+ EXPECT_EQ(2ul, Ranges.size());
+ EXPECT_TRUE(Ranges[0].getOffset() == 0);
+ EXPECT_TRUE(Ranges[0].getLength() == 0);
+ EXPECT_TRUE(Ranges[1].getOffset() == 6);
+ EXPECT_TRUE(Ranges[1].getLength() == 22);
+}
+
+TEST(Range, RangesAfterReplacements) {
+ std::vector<Range> Ranges = {Range(5, 2), Range(10, 5)};
+ Replacements Replaces = {Replacement("foo", 0, 2, "1234")};
+ std::vector<Range> Expected = {Range(0, 4), Range(7, 2), Range(12, 5)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, RangesBeforeReplacements) {
+ std::vector<Range> Ranges = {Range(5, 2), Range(10, 5)};
+ Replacements Replaces = {Replacement("foo", 20, 2, "1234")};
+ std::vector<Range> Expected = {Range(5, 2), Range(10, 5), Range(20, 4)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, NotAffectedByReplacements) {
+ std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(10, 5)};
+ Replacements Replaces = {Replacement("foo", 3, 2, "12"),
+ Replacement("foo", 12, 2, "12"),
+ Replacement("foo", 20, 5, "")};
+ std::vector<Range> Expected = {Range(0, 2), Range(3, 4), Range(10, 5),
+ Range(20, 0)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, RangesWithNonOverlappingReplacements) {
+ std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(10, 5)};
+ Replacements Replaces = {Replacement("foo", 3, 1, ""),
+ Replacement("foo", 6, 1, "123"),
+ Replacement("foo", 20, 2, "12345")};
+ std::vector<Range> Expected = {Range(0, 2), Range(3, 0), Range(4, 4),
+ Range(11, 5), Range(21, 5)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, RangesWithOverlappingReplacements) {
+ std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5),
+ Range(30, 5)};
+ Replacements Replaces = {
+ Replacement("foo", 1, 3, ""), Replacement("foo", 6, 1, "123"),
+ Replacement("foo", 13, 3, "1"), Replacement("foo", 25, 15, "")};
+ std::vector<Range> Expected = {Range(0, 1), Range(2, 4), Range(12, 5),
+ Range(22, 0)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, MergeIntoOneRange) {
+ std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5)};
+ Replacements Replaces = {Replacement("foo", 1, 15, "1234567890")};
+ std::vector<Range> Expected = {Range(0, 15)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, ReplacementsStartingAtRangeOffsets) {
+ std::vector<Range> Ranges = {Range(0, 2), Range(5, 5), Range(15, 5)};
+ Replacements Replaces = {
+ Replacement("foo", 0, 2, "12"), Replacement("foo", 5, 1, "123"),
+ Replacement("foo", 7, 4, "12345"), Replacement("foo", 15, 10, "12")};
+ std::vector<Range> Expected = {Range(0, 2), Range(5, 9), Range(18, 2)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, ReplacementsEndingAtRangeEnds) {
+ std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5)};
+ Replacements Replaces = {Replacement("foo", 6, 1, "123"),
+ Replacement("foo", 17, 3, "12")};
+ std::vector<Range> Expected = {Range(0, 2), Range(5, 4), Range(17, 4)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, AjacentReplacements) {
+ std::vector<Range> Ranges = {Range(0, 0), Range(15, 5)};
+ Replacements Replaces = {Replacement("foo", 1, 2, "123"),
+ Replacement("foo", 12, 3, "1234")};
+ std::vector<Range> Expected = {Range(0, 0), Range(1, 3), Range(13, 9)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
+TEST(Range, MergeRangesAfterReplacements) {
+ std::vector<Range> Ranges = {Range(8, 0), Range(5, 2), Range(9, 0), Range(0, 1)};
+ Replacements Replaces = {Replacement("foo", 1, 3, ""),
+ Replacement("foo", 7, 0, "12"), Replacement("foo", 9, 2, "")};
+ std::vector<Range> Expected = {Range(0, 1), Range(2, 4), Range(7, 0), Range(8, 0)};
+ EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
+}
+
TEST(DeduplicateTest, removesDuplicates) {
std::vector<Replacement> Input;
Input.push_back(Replacement("fileA", 50, 0, " foo "));
@@ -504,27 +640,32 @@ protected:
StringRef Result, const Replacements &First,
const Replacements &Second) {
// These are mainly to verify the test itself and make it easier to read.
- std::string AfterFirst = applyAllReplacements(Code, First);
- std::string InSequenceRewrite = applyAllReplacements(AfterFirst, Second);
- EXPECT_EQ(Intermediate, AfterFirst);
- EXPECT_EQ(Result, InSequenceRewrite);
+ auto AfterFirst = applyAllReplacements(Code, First);
+ EXPECT_TRUE(static_cast<bool>(AfterFirst));
+ auto InSequenceRewrite = applyAllReplacements(*AfterFirst, Second);
+ EXPECT_TRUE(static_cast<bool>(InSequenceRewrite));
+ EXPECT_EQ(Intermediate, *AfterFirst);
+ EXPECT_EQ(Result, *InSequenceRewrite);
tooling::Replacements Merged = mergeReplacements(First, Second);
- std::string MergedRewrite = applyAllReplacements(Code, Merged);
- EXPECT_EQ(InSequenceRewrite, MergedRewrite);
- if (InSequenceRewrite != MergedRewrite)
+ auto MergedRewrite = applyAllReplacements(Code, Merged);
+ EXPECT_TRUE(static_cast<bool>(MergedRewrite));
+ EXPECT_EQ(*InSequenceRewrite, *MergedRewrite);
+ if (*InSequenceRewrite != *MergedRewrite)
for (tooling::Replacement M : Merged)
llvm::errs() << M.getOffset() << " " << M.getLength() << " "
<< M.getReplacementText() << "\n";
}
void mergeAndTestRewrite(StringRef Code, const Replacements &First,
const Replacements &Second) {
- std::string InSequenceRewrite =
- applyAllReplacements(applyAllReplacements(Code, First), Second);
+ auto AfterFirst = applyAllReplacements(Code, First);
+ EXPECT_TRUE(static_cast<bool>(AfterFirst));
+ auto InSequenceRewrite = applyAllReplacements(*AfterFirst, Second);
tooling::Replacements Merged = mergeReplacements(First, Second);
- std::string MergedRewrite = applyAllReplacements(Code, Merged);
- EXPECT_EQ(InSequenceRewrite, MergedRewrite);
- if (InSequenceRewrite != MergedRewrite)
+ auto MergedRewrite = applyAllReplacements(Code, Merged);
+ EXPECT_TRUE(static_cast<bool>(MergedRewrite));
+ EXPECT_EQ(*InSequenceRewrite, *MergedRewrite);
+ if (*InSequenceRewrite != *MergedRewrite)
for (tooling::Replacement M : Merged)
llvm::errs() << M.getOffset() << " " << M.getLength() << " "
<< M.getReplacementText() << "\n";
diff --git a/unittests/Tooling/RewriterTest.cpp b/unittests/Tooling/RewriterTest.cpp
index 93f69eb9fa..e8afedb011 100644
--- a/unittests/Tooling/RewriterTest.cpp
+++ b/unittests/Tooling/RewriterTest.cpp
@@ -41,8 +41,9 @@ TEST(Rewriter, AdjacentInsertAndDelete) {
Replacements Replaces;
Replaces.insert(Replacement("<file>", 6, 6, ""));
Replaces.insert(Replacement("<file>", 6, 0, "replaced\n"));
- EXPECT_EQ("line1\nreplaced\nline3\nline4",
- applyAllReplacements("line1\nline2\nline3\nline4", Replaces));
+ auto Rewritten = applyAllReplacements("line1\nline2\nline3\nline4", Replaces);
+ EXPECT_TRUE(static_cast<bool>(Rewritten));
+ EXPECT_EQ("line1\nreplaced\nline3\nline4", *Rewritten);
}
} // end namespace
diff --git a/unittests/Tooling/ToolingTest.cpp b/unittests/Tooling/ToolingTest.cpp
index c4b174f183..10ac0c33ed 100644
--- a/unittests/Tooling/ToolingTest.cpp
+++ b/unittests/Tooling/ToolingTest.cpp
@@ -241,7 +241,7 @@ TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) {
struct SkipBodyConsumer : public clang::ASTConsumer {
/// Skip the 'skipMe' function.
bool shouldSkipFunctionBody(Decl *D) override {
- FunctionDecl *F = dyn_cast<FunctionDecl>(D);
+ NamedDecl *F = dyn_cast<NamedDecl>(D);
return F && F->getNameAsString() == "skipMe";
}
};
@@ -255,10 +255,65 @@ struct SkipBodyAction : public clang::ASTFrontendAction {
};
TEST(runToolOnCode, TestSkipFunctionBody) {
+ std::vector<std::string> Args = {"-std=c++11"};
+ std::vector<std::string> Args2 = {"-fno-delayed-template-parsing"};
+
EXPECT_TRUE(runToolOnCode(new SkipBodyAction,
"int skipMe() { an_error_here }"));
EXPECT_FALSE(runToolOnCode(new SkipBodyAction,
"int skipMeNot() { an_error_here }"));
+
+ // Test constructors with initializers
+ EXPECT_TRUE(runToolOnCodeWithArgs(
+ new SkipBodyAction,
+ "struct skipMe { skipMe() : an_error() { more error } };", Args));
+ EXPECT_TRUE(runToolOnCodeWithArgs(
+ new SkipBodyAction, "struct skipMe { skipMe(); };"
+ "skipMe::skipMe() : an_error([](){;}) { more error }",
+ Args));
+ EXPECT_TRUE(runToolOnCodeWithArgs(
+ new SkipBodyAction, "struct skipMe { skipMe(); };"
+ "skipMe::skipMe() : an_error{[](){;}} { more error }",
+ Args));
+ EXPECT_TRUE(runToolOnCodeWithArgs(
+ new SkipBodyAction,
+ "struct skipMe { skipMe(); };"
+ "skipMe::skipMe() : a<b<c>(e)>>(), f{}, g() { error }",
+ Args));
+ EXPECT_TRUE(runToolOnCodeWithArgs(
+ new SkipBodyAction, "struct skipMe { skipMe() : bases()... { error } };",
+ Args));
+
+ EXPECT_FALSE(runToolOnCodeWithArgs(
+ new SkipBodyAction, "struct skipMeNot { skipMeNot() : an_error() { } };",
+ Args));
+ EXPECT_FALSE(runToolOnCodeWithArgs(new SkipBodyAction,
+ "struct skipMeNot { skipMeNot(); };"
+ "skipMeNot::skipMeNot() : an_error() { }",
+ Args));
+
+ // Try/catch
+ EXPECT_TRUE(runToolOnCode(
+ new SkipBodyAction,
+ "void skipMe() try { an_error() } catch(error) { error };"));
+ EXPECT_TRUE(runToolOnCode(
+ new SkipBodyAction,
+ "struct S { void skipMe() try { an_error() } catch(error) { error } };"));
+ EXPECT_TRUE(
+ runToolOnCode(new SkipBodyAction,
+ "void skipMe() try { an_error() } catch(error) { error; }"
+ "catch(error) { error } catch (error) { }"));
+ EXPECT_FALSE(runToolOnCode(
+ new SkipBodyAction,
+ "void skipMe() try something;")); // don't crash while parsing
+
+ // Template
+ EXPECT_TRUE(runToolOnCode(
+ new SkipBodyAction, "template<typename T> int skipMe() { an_error_here }"
+ "int x = skipMe<int>();"));
+ EXPECT_FALSE(runToolOnCodeWithArgs(
+ new SkipBodyAction,
+ "template<typename T> int skipMeNot() { an_error_here }", Args2));
}
TEST(runToolOnCodeWithArgs, TestNoDepFile) {
diff --git a/unittests/libclang/LibclangTest.cpp b/unittests/libclang/LibclangTest.cpp
index e190dec89a..d5c78272af 100644
--- a/unittests/libclang/LibclangTest.cpp
+++ b/unittests/libclang/LibclangTest.cpp
@@ -485,7 +485,7 @@ TEST_F(LibclangReparseTest, clang_parseTranslationUnit2FullArgv) {
WriteFile(Clang, "");
const char *Argv[] = {Clang.c_str(), "-target", "arm-linux-gnueabi",
- "--gcc-toolchain="};
+ "-stdlib=libstdc++", "--gcc-toolchain="};
EXPECT_EQ(CXError_Success,
clang_parseTranslationUnit2FullArgv(Index, Filename.c_str(), Argv,
diff --git a/unittests/libclang/Makefile b/unittests/libclang/Makefile
deleted file mode 100644
index 037dea34d2..0000000000
--- a/unittests/libclang/Makefile
+++ /dev/null
@@ -1,37 +0,0 @@
-##===- unittests/libclang/Makefile -------------------------*- Makefile -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-
-CLANG_LEVEL = ../..
-TESTNAME = libclang
-LINK_LIBS_IN_SHARED := 1
-
-include $(CLANG_LEVEL)/../../Makefile.config
-LINK_COMPONENTS := $(TARGETS_TO_BUILD) \
- AsmParser \
- BitReader \
- BitWriter \
- IPO \
- MC \
- ObjCArcOpts \
- Option \
- Support
-
-# Note that 'USEDLIBS' must include all of the core clang libraries
-# when -static is given to linker on cygming.
-USEDLIBS = clang.a \
- clangCodeGen.a \
- clangIndex.a clangFormat.a clangRewrite.a \
- clangFrontend.a clangDriver.a \
- clangTooling.a \
- clangToolingCore.a \
- clangSerialization.a clangParse.a clangSema.a \
- clangAnalysis.a clangEdit.a clangAST.a clangLex.a \
- clangBasic.a
-
-include $(CLANG_LEVEL)/unittests/Makefile