diff options
Diffstat (limited to 'unittests')
38 files changed, 5354 insertions, 378 deletions
diff --git a/unittests/AST/ASTContextParentMapTest.cpp b/unittests/AST/ASTContextParentMapTest.cpp new file mode 100644 index 0000000..c1910a8 --- /dev/null +++ b/unittests/AST/ASTContextParentMapTest.cpp @@ -0,0 +1,71 @@ +//===- unittest/AST/ASTContextParentMapTest.cpp - AST parent map 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 getParents(...) methods of ASTContext. +// +//===----------------------------------------------------------------------===// + +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Tooling/Tooling.h" +#include "gtest/gtest.h" +#include "MatchVerifier.h" + +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(Verifier.match("class C { void f(); };", + methodDecl(hasParent(recordDecl(hasName("C")))))); +} + +TEST(GetParents, ReturnsParentForStmt) { + MatchVerifier<Stmt> Verifier; + EXPECT_TRUE(Verifier.match("class C { void f() { if (true) {} } };", + ifStmt(hasParent(compoundStmt())))); +} + +TEST(GetParents, ReturnsParentInsideTemplateInstantiations) { + MatchVerifier<Decl> DeclVerifier; + EXPECT_TRUE(DeclVerifier.match( + "template<typename T> struct C { void f() {} };" + "void g() { C<int> c; c.f(); }", + methodDecl(hasName("f"), + hasParent(recordDecl(isTemplateInstantiation()))))); + EXPECT_TRUE(DeclVerifier.match( + "template<typename T> struct C { void f() {} };" + "void g() { C<int> c; c.f(); }", + methodDecl(hasName("f"), + hasParent(recordDecl(unless(isTemplateInstantiation())))))); + EXPECT_FALSE(DeclVerifier.match( + "template<typename T> struct C { void f() {} };" + "void g() { C<int> c; c.f(); }", + methodDecl(hasName("f"), + allOf(hasParent(recordDecl(unless(isTemplateInstantiation()))), + hasParent(recordDecl(isTemplateInstantiation())))))); +} + +TEST(GetParents, ReturnsMultipleParentsInTemplateInstantiations) { + MatchVerifier<Stmt> TemplateVerifier; + EXPECT_TRUE(TemplateVerifier.match( + "template<typename T> struct C { void f() {} };" + "void g() { C<int> c; c.f(); }", + compoundStmt( + allOf(hasAncestor(recordDecl(isTemplateInstantiation())), + hasAncestor(recordDecl(unless(isTemplateInstantiation()))))))); +} + +} // end namespace ast_matchers +} // end namespace clang diff --git a/unittests/AST/CMakeLists.txt b/unittests/AST/CMakeLists.txt index 1ea293e..ad29428 100644 --- a/unittests/AST/CMakeLists.txt +++ b/unittests/AST/CMakeLists.txt @@ -1,4 +1,5 @@ add_clang_unittest(ASTTests + ASTContextParentMapTest.cpp CommentLexer.cpp CommentParser.cpp DeclPrinterTest.cpp diff --git a/unittests/AST/CommentLexer.cpp b/unittests/AST/CommentLexer.cpp index 2723a61..507daf8 100644 --- a/unittests/AST/CommentLexer.cpp +++ b/unittests/AST/CommentLexer.cpp @@ -7,16 +7,16 @@ // //===----------------------------------------------------------------------===// -#include "clang/Basic/SourceManager.h" -#include "clang/Basic/FileManager.h" -#include "clang/Basic/Diagnostic.h" -#include "clang/Basic/DiagnosticOptions.h" #include "clang/AST/CommentLexer.h" #include "clang/AST/CommentCommandTraits.h" +#include "clang/Basic/CommentOptions.h" +#include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticOptions.h" +#include "clang/Basic/FileManager.h" +#include "clang/Basic/SourceManager.h" #include "llvm/ADT/STLExtras.h" -#include <vector> - #include "gtest/gtest.h" +#include <vector> using namespace llvm; using namespace clang; @@ -32,7 +32,7 @@ protected: DiagID(new DiagnosticIDs()), Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), - Traits(Allocator) { + Traits(Allocator, CommentOptions()) { } FileSystemOptions FileMgrOpts; @@ -301,8 +301,10 @@ TEST_F(CommentLexerTest, DoxygenCommand3) { // Doxygen escape sequences. TEST_F(CommentLexerTest, DoxygenCommand4) { - const char *Source = - "/// \\\\ \\@ \\& \\$ \\# \\< \\> \\% \\\" \\. \\::"; + const char *Sources[] = { + "/// \\\\ \\@ \\& \\$ \\# \\< \\> \\% \\\" \\. \\::", + "/// @\\ @@ @& @$ @# @< @> @% @\" @. @::" + }; const char *Text[] = { " ", "\\", " ", "@", " ", "&", " ", "$", " ", "#", " ", @@ -310,16 +312,18 @@ TEST_F(CommentLexerTest, DoxygenCommand4) { "::", "" }; - std::vector<Token> Toks; + for (size_t i = 0, e = array_lengthof(Sources); i != e; i++) { + std::vector<Token> Toks; - lexString(Source, Toks); + lexString(Sources[i], Toks); - ASSERT_EQ(array_lengthof(Text), Toks.size()); + ASSERT_EQ(array_lengthof(Text), Toks.size()); - for (size_t i = 0, e = Toks.size(); i != e; i++) { - if(Toks[i].is(tok::text)) - ASSERT_EQ(StringRef(Text[i]), Toks[i].getText()) - << "index " << i; + for (size_t j = 0, e = Toks.size(); j != e; j++) { + if(Toks[j].is(tok::text)) + ASSERT_EQ(StringRef(Text[j]), Toks[j].getText()) + << "index " << i; + } } } @@ -362,7 +366,7 @@ TEST_F(CommentLexerTest, DoxygenCommand6) { ASSERT_EQ(tok::text, Toks[0].getKind()); ASSERT_EQ(StringRef(" "), Toks[0].getText()); - ASSERT_EQ(tok::command, Toks[1].getKind()); + ASSERT_EQ(tok::backslash_command, Toks[1].getKind()); ASSERT_EQ(StringRef("brief"), getCommandName(Toks[1])); ASSERT_EQ(tok::text, Toks[2].getKind()); @@ -382,28 +386,60 @@ TEST_F(CommentLexerTest, DoxygenCommand7) { ASSERT_EQ(tok::text, Toks[0].getKind()); ASSERT_EQ(StringRef(" "), Toks[0].getText()); - ASSERT_EQ(tok::command, Toks[1].getKind()); + ASSERT_EQ(tok::backslash_command, Toks[1].getKind()); ASSERT_EQ(StringRef("em"), getCommandName(Toks[1])); - ASSERT_EQ(tok::command, Toks[2].getKind()); + ASSERT_EQ(tok::backslash_command, Toks[2].getKind()); ASSERT_EQ(StringRef("em"), getCommandName(Toks[2])); ASSERT_EQ(tok::text, Toks[3].getKind()); ASSERT_EQ(StringRef(" "), Toks[3].getText()); - ASSERT_EQ(tok::command, Toks[4].getKind()); + ASSERT_EQ(tok::backslash_command, Toks[4].getKind()); ASSERT_EQ(StringRef("em"), getCommandName(Toks[4])); ASSERT_EQ(tok::text, Toks[5].getKind()); ASSERT_EQ(StringRef("\t"), Toks[5].getText()); - ASSERT_EQ(tok::command, Toks[6].getKind()); + ASSERT_EQ(tok::backslash_command, Toks[6].getKind()); ASSERT_EQ(StringRef("em"), getCommandName(Toks[6])); ASSERT_EQ(tok::newline, Toks[7].getKind()); } TEST_F(CommentLexerTest, DoxygenCommand8) { + const char *Source = "/// @em@em @em\t@em\n"; + std::vector<Token> Toks; + + lexString(Source, Toks); + + ASSERT_EQ(8U, Toks.size()); + + ASSERT_EQ(tok::text, Toks[0].getKind()); + ASSERT_EQ(StringRef(" "), Toks[0].getText()); + + ASSERT_EQ(tok::at_command, Toks[1].getKind()); + ASSERT_EQ(StringRef("em"), getCommandName(Toks[1])); + + ASSERT_EQ(tok::at_command, Toks[2].getKind()); + ASSERT_EQ(StringRef("em"), getCommandName(Toks[2])); + + ASSERT_EQ(tok::text, Toks[3].getKind()); + ASSERT_EQ(StringRef(" "), Toks[3].getText()); + + ASSERT_EQ(tok::at_command, Toks[4].getKind()); + ASSERT_EQ(StringRef("em"), getCommandName(Toks[4])); + + ASSERT_EQ(tok::text, Toks[5].getKind()); + ASSERT_EQ(StringRef("\t"), Toks[5].getText()); + + ASSERT_EQ(tok::at_command, Toks[6].getKind()); + ASSERT_EQ(StringRef("em"), getCommandName(Toks[6])); + + ASSERT_EQ(tok::newline, Toks[7].getKind()); +} + +TEST_F(CommentLexerTest, DoxygenCommand9) { const char *Source = "/// \\aaa\\bbb \\ccc\t\\ddd\n"; std::vector<Token> Toks; @@ -435,7 +471,7 @@ TEST_F(CommentLexerTest, DoxygenCommand8) { ASSERT_EQ(tok::newline, Toks[7].getKind()); } -TEST_F(CommentLexerTest, DoxygenCommand9) { +TEST_F(CommentLexerTest, DoxygenCommand10) { const char *Source = "// \\c\n"; std::vector<Token> Toks; @@ -446,12 +482,95 @@ TEST_F(CommentLexerTest, DoxygenCommand9) { ASSERT_EQ(tok::text, Toks[0].getKind()); ASSERT_EQ(StringRef(" "), Toks[0].getText()); - ASSERT_EQ(tok::command, Toks[1].getKind()); + ASSERT_EQ(tok::backslash_command, Toks[1].getKind()); ASSERT_EQ(StringRef("c"), getCommandName(Toks[1])); ASSERT_EQ(tok::newline, Toks[2].getKind()); } +TEST_F(CommentLexerTest, RegisterCustomBlockCommand) { + const char *Source = + "/// \\NewBlockCommand Aaa.\n" + "/// @NewBlockCommand Aaa.\n"; + + Traits.registerBlockCommand(StringRef("NewBlockCommand")); + + std::vector<Token> Toks; + + lexString(Source, Toks); + + ASSERT_EQ(8U, Toks.size()); + + ASSERT_EQ(tok::text, Toks[0].getKind()); + ASSERT_EQ(StringRef(" "), Toks[0].getText()); + + ASSERT_EQ(tok::backslash_command, Toks[1].getKind()); + ASSERT_EQ(StringRef("NewBlockCommand"), getCommandName(Toks[1])); + + ASSERT_EQ(tok::text, Toks[2].getKind()); + ASSERT_EQ(StringRef(" Aaa."), Toks[2].getText()); + + ASSERT_EQ(tok::newline, Toks[3].getKind()); + + ASSERT_EQ(tok::text, Toks[4].getKind()); + ASSERT_EQ(StringRef(" "), Toks[4].getText()); + + ASSERT_EQ(tok::at_command, Toks[5].getKind()); + ASSERT_EQ(StringRef("NewBlockCommand"), getCommandName(Toks[5])); + + ASSERT_EQ(tok::text, Toks[6].getKind()); + ASSERT_EQ(StringRef(" Aaa."), Toks[6].getText()); + + ASSERT_EQ(tok::newline, Toks[7].getKind()); +} + +TEST_F(CommentLexerTest, RegisterMultipleBlockCommands) { + const char *Source = + "/// \\Foo\n" + "/// \\Bar Baz\n" + "/// \\Blech quux=corge\n"; + + Traits.registerBlockCommand(StringRef("Foo")); + Traits.registerBlockCommand(StringRef("Bar")); + Traits.registerBlockCommand(StringRef("Blech")); + + std::vector<Token> Toks; + + lexString(Source, Toks); + + ASSERT_EQ(11U, Toks.size()); + + ASSERT_EQ(tok::text, Toks[0].getKind()); + ASSERT_EQ(StringRef(" "), Toks[0].getText()); + + ASSERT_EQ(tok::backslash_command, Toks[1].getKind()); + ASSERT_EQ(StringRef("Foo"), getCommandName(Toks[1])); + + ASSERT_EQ(tok::newline, Toks[2].getKind()); + + ASSERT_EQ(tok::text, Toks[3].getKind()); + ASSERT_EQ(StringRef(" "), Toks[3].getText()); + + ASSERT_EQ(tok::backslash_command, Toks[4].getKind()); + ASSERT_EQ(StringRef("Bar"), getCommandName(Toks[4])); + + ASSERT_EQ(tok::text, Toks[5].getKind()); + ASSERT_EQ(StringRef(" Baz"), Toks[5].getText()); + + ASSERT_EQ(tok::newline, Toks[6].getKind()); + + ASSERT_EQ(tok::text, Toks[7].getKind()); + ASSERT_EQ(StringRef(" "), Toks[7].getText()); + + ASSERT_EQ(tok::backslash_command, Toks[8].getKind()); + ASSERT_EQ(StringRef("Blech"), getCommandName(Toks[8])); + + ASSERT_EQ(tok::text, Toks[9].getKind()); + ASSERT_EQ(StringRef(" quux=corge"), Toks[9].getText()); + + ASSERT_EQ(tok::newline, Toks[10].getKind()); +} + // Empty verbatim block. TEST_F(CommentLexerTest, VerbatimBlock1) { const char *Sources[] = { @@ -1662,7 +1781,8 @@ TEST_F(CommentLexerTest, HTMLCharacterReferences16) { const char *Sources[] = { "// =", "// =", - "// =" + "// =", + "// =" }; for (size_t i = 0, e = array_lengthof(Sources); i != e; i++) { diff --git a/unittests/AST/CommentParser.cpp b/unittests/AST/CommentParser.cpp index 8fde247..3dce60a 100644 --- a/unittests/AST/CommentParser.cpp +++ b/unittests/AST/CommentParser.cpp @@ -7,20 +7,20 @@ // //===----------------------------------------------------------------------===// -#include "clang/Basic/SourceManager.h" -#include "clang/Basic/FileManager.h" -#include "clang/Basic/Diagnostic.h" -#include "clang/Basic/DiagnosticOptions.h" +#include "clang/AST/CommentParser.h" #include "clang/AST/Comment.h" +#include "clang/AST/CommentCommandTraits.h" #include "clang/AST/CommentLexer.h" -#include "clang/AST/CommentParser.h" #include "clang/AST/CommentSema.h" -#include "clang/AST/CommentCommandTraits.h" +#include "clang/Basic/CommentOptions.h" +#include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticOptions.h" +#include "clang/Basic/FileManager.h" +#include "clang/Basic/SourceManager.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Allocator.h" -#include <vector> - #include "gtest/gtest.h" +#include <vector> using namespace llvm; using namespace clang; @@ -39,7 +39,7 @@ protected: DiagID(new DiagnosticIDs()), Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), - Traits(Allocator) { + Traits(Allocator, CommentOptions()) { } FileSystemOptions FileMgrOpts; diff --git a/unittests/AST/DeclPrinterTest.cpp b/unittests/AST/DeclPrinterTest.cpp index a2fc839..44fa742 100644 --- a/unittests/AST/DeclPrinterTest.cpp +++ b/unittests/AST/DeclPrinterTest.cpp @@ -412,8 +412,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl1) { " A();" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); - // WRONG; Should be: "A();" + "A()")); } TEST(DeclPrinter, TestCXXConstructorDecl2) { @@ -422,8 +421,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl2) { " A(int a);" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); - // WRONG; Should be: "A(int a);" + "A(int a)")); } TEST(DeclPrinter, TestCXXConstructorDecl3) { @@ -432,8 +430,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl3) { " A(const A &a);" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); - // WRONG; Should be: "A(const A &a);" + "A(const A &a)")); } TEST(DeclPrinter, TestCXXConstructorDecl4) { @@ -442,8 +439,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl4) { " A(const A &a, int = 0);" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); - // WRONG; Should be: "A(const A &a, int = 0);" + "A(const A &a, int = 0)")); } TEST(DeclPrinter, TestCXXConstructorDecl5) { @@ -452,8 +448,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl5) { " A(const A &&a);" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); - // WRONG; Should be: "A(const A &&a);" + "A(const A &&a)")); } TEST(DeclPrinter, TestCXXConstructorDecl6) { @@ -462,8 +457,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl6) { " explicit A(int a);" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); - // WRONG; Should be: "explicit A(int a);" + "explicit A(int a)")); } TEST(DeclPrinter, TestCXXConstructorDecl7) { @@ -472,7 +466,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl7) { " constexpr A();" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); + "A()")); // WRONG; Should be: "constexpr A();" } @@ -482,8 +476,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl8) { " A() = default;" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); - // WRONG; Should be: "A() = default;" + "A() = default")); } TEST(DeclPrinter, TestCXXConstructorDecl9) { @@ -492,8 +485,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl9) { " A() = delete;" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - " = delete")); - // WRONG; Should be: "A() = delete;" + "A() = delete")); } TEST(DeclPrinter, TestCXXConstructorDecl10) { @@ -503,8 +495,7 @@ TEST(DeclPrinter, TestCXXConstructorDecl10) { " A(const A &a);" "};", constructorDecl(ofClass(hasName("A"))).bind("id"), - "")); - // WRONG; Should be: "A(const A &a);" + "A<T...>(const A<T...> &a)")); } #if !defined(_MSC_VER) @@ -1246,3 +1237,21 @@ TEST(DeclPrinter, TestObjCMethod1) { "- (int) A:(id)anObject inRange:(long)range")); } +TEST(DeclPrinter, TestObjCProtocol1) { + ASSERT_TRUE(PrintedDeclObjCMatches( + "@protocol P1, P2;", + namedDecl(hasName("P1")).bind("id"), + "@protocol P1;\n")); + ASSERT_TRUE(PrintedDeclObjCMatches( + "@protocol P1, P2;", + namedDecl(hasName("P2")).bind("id"), + "@protocol P2;\n")); +} + +TEST(DeclPrinter, TestObjCProtocol2) { + ASSERT_TRUE(PrintedDeclObjCMatches( + "@protocol P2 @end" + "@protocol P1<P2> @end", + namedDecl(hasName("P1")).bind("id"), + "@protocol P1<P2>\n@end")); +} diff --git a/unittests/AST/Makefile b/unittests/AST/Makefile index e07fc45..4fb2f5b 100644 --- a/unittests/AST/Makefile +++ b/unittests/AST/Makefile @@ -10,10 +10,10 @@ CLANG_LEVEL = ../.. TESTNAME = AST include $(CLANG_LEVEL)/../../Makefile.config -LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser support mc +LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc USEDLIBS = clangTooling.a clangFrontend.a clangSerialization.a clangDriver.a \ clangRewriteCore.a clangRewriteFrontend.a \ - clangParse.a clangSema.a clangAnalysis.a \ - clangAST.a clangASTMatchers.a clangLex.a clangBasic.a clangEdit.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 new file mode 100644 index 0000000..7aa7886 --- /dev/null +++ b/unittests/AST/MatchVerifier.h @@ -0,0 +1,196 @@ +//===- unittest/AST/MatchVerifier.h - AST unit test support ---------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// Provides MatchVerifier, a base class to implement gtest matchers that +// verify things that can be matched on the AST. +// +// Also implements matchers based on MatchVerifier: +// LocationVerifier and RangeVerifier to verify whether a matched node has +// the expected source location or source range. +// +//===----------------------------------------------------------------------===// + +#include "clang/AST/ASTContext.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 { + +enum Language { Lang_C, Lang_C89, Lang_CXX, Lang_OpenCL }; + +/// \brief Base class for verifying some property of nodes found by a matcher. +template <typename NodeType> +class MatchVerifier : public MatchFinder::MatchCallback { +public: + template <typename MatcherType> + testing::AssertionResult match(const std::string &Code, + const MatcherType &AMatcher) { + return match(Code, AMatcher, Lang_CXX); + } + + template <typename MatcherType> + testing::AssertionResult match(const std::string &Code, + const MatcherType &AMatcher, Language L); + +protected: + virtual void run(const MatchFinder::MatchResult &Result); + virtual void verify(const MatchFinder::MatchResult &Result, + const NodeType &Node) {} + + void setFailure(const Twine &Result) { + Verified = false; + VerifyResult = Result.str(); + } + + void setSuccess() { + Verified = true; + } + +private: + bool Verified; + std::string VerifyResult; +}; + +/// \brief Runs a matcher over some code, and returns the result of the +/// verifier for the matched node. +template <typename NodeType> template <typename MatcherType> +testing::AssertionResult MatchVerifier<NodeType>::match( + const std::string &Code, const MatcherType &AMatcher, Language L) { + MatchFinder Finder; + Finder.addMatcher(AMatcher.bind(""), this); + OwningPtr<tooling::FrontendActionFactory> Factory( + tooling::newFrontendActionFactory(&Finder)); + + std::vector<std::string> Args; + StringRef FileName; + switch (L) { + case Lang_C: + Args.push_back("-std=c99"); + FileName = "input.c"; + break; + case Lang_C89: + Args.push_back("-std=c89"); + FileName = "input.c"; + break; + case Lang_CXX: + Args.push_back("-std=c++98"); + FileName = "input.cc"; + break; + case Lang_OpenCL: + FileName = "input.cl"; + } + + // Default to failure in case callback is never called + setFailure("Could not find match"); + if (!tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args, FileName)) + return testing::AssertionFailure() << "Parsing error"; + 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>(""); + if (!Node) { + setFailure("Matched node has wrong type"); + } else { + // Callback has been called, default to success. + setSuccess(); + verify(Result, *Node); + } +} + +/// \brief Verify whether a node has the correct source location. +/// +/// By default, Node.getSourceLocation() is checked. This can be changed +/// by overriding getLocation(). +template <typename NodeType> +class LocationVerifier : public MatchVerifier<NodeType> { +public: + void expectLocation(unsigned Line, unsigned Column) { + ExpectLine = Line; + ExpectColumn = Column; + } + +protected: + void verify(const MatchFinder::MatchResult &Result, const NodeType &Node) { + SourceLocation Loc = getLocation(Node); + unsigned Line = Result.SourceManager->getSpellingLineNumber(Loc); + unsigned Column = Result.SourceManager->getSpellingColumnNumber(Loc); + if (Line != ExpectLine || Column != ExpectColumn) { + std::string MsgStr; + llvm::raw_string_ostream Msg(MsgStr); + Msg << "Expected location <" << ExpectLine << ":" << ExpectColumn + << ">, found <"; + Loc.print(Msg, *Result.SourceManager); + Msg << '>'; + this->setFailure(Msg.str()); + } + } + + virtual SourceLocation getLocation(const NodeType &Node) { + return Node.getLocation(); + } + +private: + unsigned ExpectLine, ExpectColumn; +}; + +/// \brief Verify whether a node has the correct source range. +/// +/// By default, Node.getSourceRange() is checked. This can be changed +/// by overriding getRange(). +template <typename NodeType> +class RangeVerifier : public MatchVerifier<NodeType> { +public: + void expectRange(unsigned BeginLine, unsigned BeginColumn, + unsigned EndLine, unsigned EndColumn) { + ExpectBeginLine = BeginLine; + ExpectBeginColumn = BeginColumn; + ExpectEndLine = EndLine; + ExpectEndColumn = EndColumn; + } + +protected: + void verify(const MatchFinder::MatchResult &Result, const NodeType &Node) { + SourceRange R = getRange(Node); + SourceLocation Begin = R.getBegin(); + SourceLocation End = R.getEnd(); + unsigned BeginLine = Result.SourceManager->getSpellingLineNumber(Begin); + unsigned BeginColumn = Result.SourceManager->getSpellingColumnNumber(Begin); + unsigned EndLine = Result.SourceManager->getSpellingLineNumber(End); + unsigned EndColumn = Result.SourceManager->getSpellingColumnNumber(End); + if (BeginLine != ExpectBeginLine || BeginColumn != ExpectBeginColumn || + EndLine != ExpectEndLine || EndColumn != ExpectEndColumn) { + std::string MsgStr; + llvm::raw_string_ostream Msg(MsgStr); + Msg << "Expected range <" << ExpectBeginLine << ":" << ExpectBeginColumn + << '-' << ExpectEndLine << ":" << ExpectEndColumn << ">, found <"; + Begin.print(Msg, *Result.SourceManager); + Msg << '-'; + End.print(Msg, *Result.SourceManager); + Msg << '>'; + this->setFailure(Msg.str()); + } + } + + virtual SourceRange getRange(const NodeType &Node) { + return Node.getSourceRange(); + } + +private: + unsigned ExpectBeginLine, ExpectBeginColumn, ExpectEndLine, ExpectEndColumn; +}; + +} // end namespace ast_matchers +} // end namespace clang diff --git a/unittests/AST/SourceLocationTest.cpp b/unittests/AST/SourceLocationTest.cpp index dec833d..b8d8b02 100644 --- a/unittests/AST/SourceLocationTest.cpp +++ b/unittests/AST/SourceLocationTest.cpp @@ -17,179 +17,16 @@ //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" -#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/Tooling.h" #include "gtest/gtest.h" +#include "MatchVerifier.h" namespace clang { namespace ast_matchers { -using clang::tooling::newFrontendActionFactory; -using clang::tooling::runToolOnCodeWithArgs; -using clang::tooling::FrontendActionFactory; - -enum Language { Lang_C, Lang_C89, Lang_CXX }; - -/// \brief Base class for verifying some property of nodes found by a matcher. -/// -/// FIXME: This class should be shared with other AST tests. -template <typename NodeType> -class MatchVerifier : public MatchFinder::MatchCallback { -public: - template <typename MatcherType> - testing::AssertionResult match(const std::string &Code, - const MatcherType &AMatcher) { - return match(Code, AMatcher, Lang_CXX); - } - - template <typename MatcherType> - testing::AssertionResult match(const std::string &Code, - const MatcherType &AMatcher, Language L); - -protected: - virtual void run(const MatchFinder::MatchResult &Result); - virtual void verify(const MatchFinder::MatchResult &Result, - const NodeType &Node) = 0; - - void setFailure(const Twine &Result) { - Verified = false; - VerifyResult = Result.str(); - } - -private: - bool Verified; - std::string VerifyResult; -}; - -/// \brief Runs a matcher over some code, and returns the result of the -/// verifier for the matched node. -template <typename NodeType> template <typename MatcherType> -testing::AssertionResult MatchVerifier<NodeType>::match( - const std::string &Code, const MatcherType &AMatcher, Language L) { - MatchFinder Finder; - Finder.addMatcher(AMatcher.bind(""), this); - OwningPtr<FrontendActionFactory> Factory(newFrontendActionFactory(&Finder)); - - std::vector<std::string> Args; - StringRef FileName; - switch (L) { - case Lang_C: - Args.push_back("-std=c99"); - FileName = "input.c"; - break; - case Lang_C89: - Args.push_back("-std=c89"); - FileName = "input.c"; - break; - case Lang_CXX: - Args.push_back("-std=c++98"); - FileName = "input.cc"; - break; - } - - // Default to failure in case callback is never called - setFailure("Could not find match"); - if (!runToolOnCodeWithArgs(Factory->create(), Code, Args, FileName)) - return testing::AssertionFailure() << "Parsing error"; - 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>(""); - if (!Node) { - setFailure("Matched node has wrong type"); - } else { - // Callback has been called, default to success - Verified = true; - verify(Result, *Node); - } -} - -/// \brief Verify whether a node has the correct source location. -/// -/// By default, Node.getSourceLocation() is checked. This can be changed -/// by overriding getLocation(). -template <typename NodeType> -class LocationVerifier : public MatchVerifier<NodeType> { -public: - void expectLocation(unsigned Line, unsigned Column) { - ExpectLine = Line; - ExpectColumn = Column; - } - -protected: - void verify(const MatchFinder::MatchResult &Result, const NodeType &Node) { - SourceLocation Loc = getLocation(Node); - unsigned Line = Result.SourceManager->getSpellingLineNumber(Loc); - unsigned Column = Result.SourceManager->getSpellingColumnNumber(Loc); - if (Line != ExpectLine || Column != ExpectColumn) { - std::string MsgStr; - llvm::raw_string_ostream Msg(MsgStr); - Msg << "Expected location <" << ExpectLine << ":" << ExpectColumn - << ">, found <"; - Loc.print(Msg, *Result.SourceManager); - Msg << '>'; - this->setFailure(Msg.str()); - } - } - - virtual SourceLocation getLocation(const NodeType &Node) { - return Node.getLocation(); - } - -private: - unsigned ExpectLine, ExpectColumn; -}; - -/// \brief Verify whether a node has the correct source range. -/// -/// By default, Node.getSourceRange() is checked. This can be changed -/// by overriding getRange(). -template <typename NodeType> -class RangeVerifier : public MatchVerifier<NodeType> { -public: - void expectRange(unsigned BeginLine, unsigned BeginColumn, - unsigned EndLine, unsigned EndColumn) { - ExpectBeginLine = BeginLine; - ExpectBeginColumn = BeginColumn; - ExpectEndLine = EndLine; - ExpectEndColumn = EndColumn; - } - -protected: - void verify(const MatchFinder::MatchResult &Result, const NodeType &Node) { - SourceRange R = getRange(Node); - SourceLocation Begin = R.getBegin(); - SourceLocation End = R.getEnd(); - unsigned BeginLine = Result.SourceManager->getSpellingLineNumber(Begin); - unsigned BeginColumn = Result.SourceManager->getSpellingColumnNumber(Begin); - unsigned EndLine = Result.SourceManager->getSpellingLineNumber(End); - unsigned EndColumn = Result.SourceManager->getSpellingColumnNumber(End); - if (BeginLine != ExpectBeginLine || BeginColumn != ExpectBeginColumn || - EndLine != ExpectEndLine || EndColumn != ExpectEndColumn) { - std::string MsgStr; - llvm::raw_string_ostream Msg(MsgStr); - Msg << "Expected range <" << ExpectBeginLine << ":" << ExpectBeginColumn - << '-' << ExpectEndLine << ":" << ExpectEndColumn << ">, found <"; - Begin.print(Msg, *Result.SourceManager); - Msg << '-'; - End.print(Msg, *Result.SourceManager); - Msg << '>'; - this->setFailure(Msg.str()); - } - } - - virtual SourceRange getRange(const NodeType &Node) { - return Node.getSourceRange(); - } - -private: - unsigned ExpectBeginLine, ExpectBeginColumn, ExpectEndLine, ExpectEndColumn; -}; +// FIXME: Pull the *Verifier tests into their own test file. TEST(MatchVerifier, ParseError) { LocationVerifier<VarDecl> Verifier; @@ -285,5 +122,38 @@ TEST(CXXConstructorDecl, NoRetFunTypeLocRange) { EXPECT_TRUE(Verifier.match("class C { C(); };", functionDecl())); } +TEST(CompoundLiteralExpr, CompoundVectorLiteralRange) { + RangeVerifier<CompoundLiteralExpr> Verifier; + Verifier.expectRange(2, 11, 2, 22); + EXPECT_TRUE(Verifier.match( + "typedef int int2 __attribute__((ext_vector_type(2)));\n" + "int2 i2 = (int2){1, 2};", compoundLiteralExpr())); +} + +TEST(CompoundLiteralExpr, ParensCompoundVectorLiteralRange) { + RangeVerifier<CompoundLiteralExpr> Verifier; + Verifier.expectRange(2, 11, 2, 22); + EXPECT_TRUE(Verifier.match( + "typedef int int2 __attribute__((ext_vector_type(2)));\n" + "int2 i2 = (int2)(1, 2);", + compoundLiteralExpr(), Lang_OpenCL)); +} + +TEST(InitListExpr, VectorLiteralListBraceRange) { + RangeVerifier<InitListExpr> Verifier; + Verifier.expectRange(2, 17, 2, 22); + EXPECT_TRUE(Verifier.match( + "typedef int int2 __attribute__((ext_vector_type(2)));\n" + "int2 i2 = (int2){1, 2};", initListExpr())); +} + +TEST(InitListExpr, VectorLiteralInitListParens) { + RangeVerifier<InitListExpr> Verifier; + Verifier.expectRange(2, 17, 2, 22); + EXPECT_TRUE(Verifier.match( + "typedef int int2 __attribute__((ext_vector_type(2)));\n" + "int2 i2 = (int2)(1, 2);", initListExpr(), Lang_OpenCL)); +} + } // end namespace ast_matchers } // end namespace clang diff --git a/unittests/AST/StmtPrinterTest.cpp b/unittests/AST/StmtPrinterTest.cpp index 0fd1b2e..473ee13 100644 --- a/unittests/AST/StmtPrinterTest.cpp +++ b/unittests/AST/StmtPrinterTest.cpp @@ -146,20 +146,14 @@ TEST(StmtPrinter, TestMSIntegerLiteral) { " 1i8, -1i8, 1ui8, " " 1i16, -1i16, 1ui16, " " 1i32, -1i32, 1ui32, " - " 1i64, -1i64, 1ui64, " - " 1i128, -1i128, 1ui128, 1Ui128," - " 0x10000000000000000i128;" + " 1i64, -1i64, 1ui64;" "}", "A", "1 , -1 , 1U , " "1 , -1 , 1U , " "1L , -1L , 1UL , " - "1LL , -1LL , 1ULL , " - "1 , -1 , 1U , 1U , " - "18446744073709551616i128")); + "1LL , -1LL , 1ULL")); // Should be: with semicolon - // WRONG; all 128-bit literals should be printed as 128-bit. - // (This is because currently we do semantic analysis incorrectly.) } TEST(StmtPrinter, TestFloatingPointLiteral) { @@ -169,4 +163,3 @@ TEST(StmtPrinter, TestFloatingPointLiteral) { "1.F , -1.F , 1. , -1. , 1.L , -1.L")); // Should be: with semicolon } - diff --git a/unittests/ASTMatchers/ASTMatchersTest.cpp b/unittests/ASTMatchers/ASTMatchersTest.cpp index e15940a..301b4f7 100644 --- a/unittests/ASTMatchers/ASTMatchersTest.cpp +++ b/unittests/ASTMatchers/ASTMatchersTest.cpp @@ -8,8 +8,9 @@ //===----------------------------------------------------------------------===// #include "ASTMatchersTest.h" -#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/AST/PrettyPrinter.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/Tooling.h" #include "gtest/gtest.h" @@ -79,6 +80,13 @@ TEST(NameableDeclaration, REMatchesVariousDecls) { 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) { @@ -231,6 +239,17 @@ TEST(DeclarationMatcher, ClassIsDerived) { "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> {};", + recordDecl(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> {};", + recordDecl(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 @@ -294,6 +313,13 @@ TEST(DeclarationMatcher, ClassIsDerived) { recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test"))))); } +TEST(DeclarationMatcher, hasMethod) { + EXPECT_TRUE(matches("class A { void func(); };", + recordDecl(hasMethod(hasName("func"))))); + EXPECT_TRUE(notMatches("class A { void func(); };", + recordDecl(hasMethod(isPublic())))); +} + TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) { EXPECT_TRUE(matches( "template <typename T> struct A {" @@ -304,6 +330,23 @@ TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) { recordDecl(hasName("B"), isDerivedFrom(recordDecl())))); } +TEST(DeclarationMatcher, hasDeclContext) { + EXPECT_TRUE(matches( + "namespace N {" + " namespace M {" + " class D {};" + " }" + "}", + recordDecl(hasDeclContext(namedDecl(hasName("M")))))); + EXPECT_TRUE(notMatches( + "namespace N {" + " namespace M {" + " class D {};" + " }" + "}", + recordDecl(hasDeclContext(namedDecl(hasName("N")))))); +} + TEST(ClassTemplate, DoesNotMatchClass) { DeclarationMatcher ClassX = classTemplateDecl(hasName("X")); EXPECT_TRUE(notMatches("class X;", ClassX)); @@ -332,7 +375,9 @@ TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) { TEST(AllOf, AllOverloadsWork) { const char Program[] = - "struct T { }; int f(int, T*); void g(int x) { T t; f(x, &t); }"; + "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()))))))); @@ -341,6 +386,19 @@ TEST(AllOf, AllOverloadsWork) { 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, MatchAnyOf) { @@ -574,8 +632,10 @@ public: // 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) - : Id(Id), ExpectedCount(1), Count(0), ExpectedName(ExpectedName) {} + VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName, + int ExpectedCount = 1) + : Id(Id), ExpectedCount(ExpectedCount), Count(0), + ExpectedName(ExpectedName) {} ~VerifyIdIsBoundTo() { if (ExpectedCount != -1) @@ -639,7 +699,7 @@ TEST(HasDescendant, MatchesDescendantsOfTypes) { qualType(hasDescendant( pointerType(pointee(builtinType())))))); EXPECT_TRUE(matches("void f() { int*** i; }", - typeLoc(hasDescendant(builtinTypeLoc())))); + typeLoc(hasDescendant(loc(builtinType()))))); EXPECT_TRUE(matchAndVerifyResultTrue( "void f() { int*** i; }", @@ -778,6 +838,32 @@ TEST(Matcher, BindsIDForMemoizedResults) { 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( @@ -945,6 +1031,31 @@ TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) { "bool operator&&(Y x, Y y) { return true; }; " "Y a; Y b; bool c = a && b;", OpCallLessLess)); + DeclarationMatcher ClassWithOpStar = + recordDecl(hasMethod(hasOverloadedOperatorName("*"))); + EXPECT_TRUE(matches("class Y { int operator*(); };", + ClassWithOpStar)); + EXPECT_TRUE(notMatches("class Y { void myOperator(); };", + ClassWithOpStar)) ; +} + +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;", + operatorCallExpr(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;", + operatorCallExpr(hasParent(operatorCallExpr())))); + EXPECT_TRUE(matches( + "class Y { }; " + "Y& operator&&(Y& x, Y& y) { return x; }; " + "Y a; Y b; Y c; Y d = a && b && c;", + operatorCallExpr(hasDescendant(operatorCallExpr())))); } TEST(Matcher, ThisPointerType) { @@ -1003,7 +1114,7 @@ TEST(Matcher, VariableUsage) { "}", Reference)); } -TEST(Matcher, FindsVarDeclInFuncitonParameter) { +TEST(Matcher, FindsVarDeclInFunctionParameter) { EXPECT_TRUE(matches( "void f(int i) {}", varDecl(hasName("i")))); @@ -1212,6 +1323,14 @@ TEST(Matcher, ArgumentCount) { 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"))))); @@ -1225,6 +1344,29 @@ TEST(Matcher, References) { 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) {} };", methodDecl(hasParameter(0, varDecl())))); @@ -1338,6 +1480,18 @@ TEST(Matcher, MatchesSpecificArgument) { 1, refersToType(asString("int")))))); } +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, ConstructorCall) { StatementMatcher Constructor = constructExpr(); @@ -2208,6 +2362,34 @@ TEST(Member, MatchesMember) { 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( @@ -2758,6 +2940,22 @@ TEST(ForEachDescendant, BindsOneNode) { 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"))); + + // FIXME: This is not really a useful matcher, but the result is still + // surprising (currently binds "A"). + //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; }; " @@ -2786,6 +2984,58 @@ TEST(ForEachDescendant, BindsCorrectNodes) { 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 @@ -2955,6 +3205,20 @@ TEST(HasAncestor, BindsCombinationsWithHasDescendant) { 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; }; }; }; " @@ -2983,6 +3247,46 @@ TEST(HasParent, MatchesOnlyParent) { 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(recordDecl(isTemplateInstantiation())), + hasAncestor(recordDecl(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(recordDecl(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(recordDecl(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(recordDecl(isTemplateInstantiation())))), + hasParent(functionDecl(hasParent(recordDecl( + unless(isTemplateInstantiation()))))))))))); + EXPECT_TRUE( + notMatches("template <typename T> struct C { static void f() {} };" + "void t() { C<int>::f(); }", + compoundStmt(hasParent(recordDecl())))); +} + TEST(TypeMatching, MatchesTypes) { EXPECT_TRUE(matches("struct S {};", qualType().bind("loc"))); } @@ -3094,6 +3398,19 @@ TEST(TypeMatching, MatchesFunctionTypes) { 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 @@ -3108,7 +3425,7 @@ TEST(TypeMatching, PointerTypes) { // new VerifyIdIsBoundTo<TypeLoc>("loc", 1))); EXPECT_TRUE(matches( "int** a;", - pointerTypeLoc(pointeeLoc(loc(qualType()))))); + loc(pointerType(pointee(qualType()))))); EXPECT_TRUE(matches( "int** a;", loc(pointerType(pointee(pointerType()))))); @@ -3125,6 +3442,10 @@ TEST(TypeMatching, PointerTypes) { 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"), @@ -3145,6 +3466,54 @@ TEST(TypeMatching, PointerTypes) { 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) { @@ -3153,7 +3522,7 @@ TEST(TypeMatching, PointeeTypes) { EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType())))); EXPECT_TRUE(matches("int *a;", - pointerTypeLoc(pointeeLoc(loc(builtinType()))))); + loc(pointerType(pointee(builtinType()))))); EXPECT_TRUE(matches( "int const *A;", @@ -3167,10 +3536,10 @@ TEST(TypeMatching, MatchesPointersToConstTypes) { EXPECT_TRUE(matches("int b; int * const a = &b;", loc(pointerType()))); EXPECT_TRUE(matches("int b; int * const a = &b;", - pointerTypeLoc())); + loc(pointerType()))); EXPECT_TRUE(matches( "int b; const int * a = &b;", - pointerTypeLoc(pointeeLoc(builtinTypeLoc())))); + loc(pointerType(pointee(builtinType()))))); EXPECT_TRUE(matches( "int b; const int * a = &b;", pointerType(pointee(builtinType())))); @@ -3179,10 +3548,70 @@ TEST(TypeMatching, MatchesPointersToConstTypes) { TEST(TypeMatching, MatchesTypedefTypes) { EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"), hasType(typedefType())))); +} - EXPECT_TRUE(matches("typedef int X; X a;", - varDecl(hasName("a"), - hasType(typedefType(hasDecl(decl())))))); +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(NNS, MatchesNestedNameSpecifiers) { @@ -3335,46 +3764,90 @@ TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) { new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3))); } -template <typename T> -class VerifyRecursiveMatch : public BoundNodesCallback { +template <typename T> class VerifyMatchOnNode : public BoundNodesCallback { public: - explicit VerifyRecursiveMatch(StringRef Id, - const internal::Matcher<T> &InnerMatcher) - : Id(Id), InnerMatcher(InnerMatcher) {} - - virtual bool run(const BoundNodes *Nodes) { - return false; + VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher, + StringRef InnerId) + : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) { } + virtual bool run(const BoundNodes *Nodes) { return false; } + virtual bool run(const BoundNodes *Nodes, ASTContext *Context) { const T *Node = Nodes->getNodeAs<T>(Id); - bool Found = false; - MatchFinder Finder; - Finder.addMatcher(InnerMatcher, new VerifyMatch(0, &Found)); - Finder.findAll(*Node, *Context); - return Found; + return selectFirst<const T>(InnerId, + match(InnerMatcher, *Node, *Context)) != NULL; } 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 VerifyRecursiveMatch<clang::Decl>("X", recordDecl(hasName("X::Y"))))); - EXPECT_TRUE(matchAndVerifyResultFalse("class X { class Y {}; };", - recordDecl(hasName("::X")).bind("X"), - new VerifyRecursiveMatch<clang::Decl>("X", recordDecl(hasName("X::Z"))))); + 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 VerifyRecursiveMatch<clang::Stmt>("if", forStmt()))); - EXPECT_TRUE(matchAndVerifyResultFalse("void f() { if (1) { for (;;) { } } }", - ifStmt().bind("if"), - new VerifyRecursiveMatch<clang::Stmt>("if", declStmt()))); + 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: + virtual bool run(const BoundNodes *Nodes) { return false; } + + virtual bool run(const BoundNodes *Nodes, ASTContext *Context) { + const T *Node = Nodes->getNodeAs<T>(""); + return verify(*Nodes, *Context, Node); + } + + bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) { + return selectFirst<const T>( + "", match(stmt(hasParent(stmt(has(stmt(equalsNode(Node)))).bind(""))), + *Node, Context)) != NULL; + } + bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) { + return selectFirst<const T>( + "", match(decl(hasParent(decl(has(decl(equalsNode(Node)))).bind(""))), + *Node, Context)) != NULL; + } +}; + +TEST(IsEqualTo, MatchesNodesByIdentity) { + EXPECT_TRUE(matchAndVerifyResultTrue( + "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""), + new VerifyAncestorHasChildIsEqual<Decl>())); + EXPECT_TRUE( + matchAndVerifyResultTrue("void f() { if(true) {} }", ifStmt().bind(""), + new VerifyAncestorHasChildIsEqual<Stmt>())); } class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback { diff --git a/unittests/ASTMatchers/ASTMatchersTest.h b/unittests/ASTMatchers/ASTMatchersTest.h index 3b23ada..5fed85b 100644 --- a/unittests/ASTMatchers/ASTMatchersTest.h +++ b/unittests/ASTMatchers/ASTMatchersTest.h @@ -89,7 +89,7 @@ testing::AssertionResult matchAndVerifyResultConditionally(const std::string &Code, const T &AMatcher, BoundNodesCallback *FindResultVerifier, bool ExpectResult) { - llvm::OwningPtr<BoundNodesCallback> ScopedVerifier(FindResultVerifier); + OwningPtr<BoundNodesCallback> ScopedVerifier(FindResultVerifier); bool VerifiedResult = false; MatchFinder Finder; Finder.addMatcher( diff --git a/unittests/ASTMatchers/CMakeLists.txt b/unittests/ASTMatchers/CMakeLists.txt index b56d756..91feaac 100644 --- a/unittests/ASTMatchers/CMakeLists.txt +++ b/unittests/ASTMatchers/CMakeLists.txt @@ -1,6 +1,7 @@ set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} asmparser + bitreader support mc ) diff --git a/unittests/ASTMatchers/Makefile b/unittests/ASTMatchers/Makefile index 9ca1006..2abe6ee 100644 --- a/unittests/ASTMatchers/Makefile +++ b/unittests/ASTMatchers/Makefile @@ -11,10 +11,10 @@ CLANG_LEVEL = ../.. TESTNAME = ASTMatchers include $(CLANG_LEVEL)/../../Makefile.config -LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser support mc +LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc USEDLIBS = clangTooling.a clangFrontend.a clangSerialization.a clangDriver.a \ clangRewriteCore.a clangRewriteFrontend.a \ - clangParse.a clangSema.a clangAnalysis.a \ - clangAST.a clangASTMatchers.a clangLex.a clangBasic.a clangEdit.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/Basic/CMakeLists.txt b/unittests/Basic/CMakeLists.txt index 300dcd5..51db6ce 100644 --- a/unittests/Basic/CMakeLists.txt +++ b/unittests/Basic/CMakeLists.txt @@ -1,4 +1,5 @@ add_clang_unittest(BasicTests + CharInfoTest.cpp FileManagerTest.cpp SourceManagerTest.cpp ) diff --git a/unittests/Basic/CharInfoTest.cpp b/unittests/Basic/CharInfoTest.cpp new file mode 100644 index 0000000..348e6ff --- /dev/null +++ b/unittests/Basic/CharInfoTest.cpp @@ -0,0 +1,499 @@ +//===- unittests/Basic/CharInfoTest.cpp -- ASCII classification 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 "gtest/gtest.h" + +using namespace llvm; +using namespace clang; + +// Check that the CharInfo table has been constructed reasonably. +TEST(CharInfoTest, validateInfoTable) { + using namespace charinfo; + EXPECT_EQ((unsigned)CHAR_SPACE, InfoTable[(unsigned)' ']); + EXPECT_EQ((unsigned)CHAR_HORZ_WS, InfoTable[(unsigned)'\t']); + EXPECT_EQ((unsigned)CHAR_HORZ_WS, InfoTable[(unsigned)'\f']); // ?? + EXPECT_EQ((unsigned)CHAR_HORZ_WS, InfoTable[(unsigned)'\v']); // ?? + EXPECT_EQ((unsigned)CHAR_VERT_WS, InfoTable[(unsigned)'\n']); + EXPECT_EQ((unsigned)CHAR_VERT_WS, InfoTable[(unsigned)'\r']); + EXPECT_EQ((unsigned)CHAR_UNDER, InfoTable[(unsigned)'_']); + EXPECT_EQ((unsigned)CHAR_PERIOD, InfoTable[(unsigned)'.']); + + for (unsigned i = 'a'; i <= 'f'; ++i) { + EXPECT_EQ((unsigned)CHAR_XLOWER, InfoTable[i]); + EXPECT_EQ((unsigned)CHAR_XUPPER, InfoTable[i+'A'-'a']); + } + + for (unsigned i = 'g'; i <= 'z'; ++i) { + EXPECT_EQ((unsigned)CHAR_LOWER, InfoTable[i]); + EXPECT_EQ((unsigned)CHAR_UPPER, InfoTable[i+'A'-'a']); + } + + for (unsigned i = '0'; i <= '9'; ++i) + EXPECT_EQ((unsigned)CHAR_DIGIT, InfoTable[i]); +} + +// Check various predicates. +TEST(CharInfoTest, isASCII) { + EXPECT_TRUE(isASCII('\0')); + EXPECT_TRUE(isASCII('\n')); + EXPECT_TRUE(isASCII(' ')); + EXPECT_TRUE(isASCII('a')); + EXPECT_TRUE(isASCII('\x7f')); + EXPECT_FALSE(isASCII('\x80')); + EXPECT_FALSE(isASCII('\xc2')); + EXPECT_FALSE(isASCII('\xff')); +} + +TEST(CharInfoTest, isIdentifierHead) { + EXPECT_TRUE(isIdentifierHead('a')); + EXPECT_TRUE(isIdentifierHead('A')); + EXPECT_TRUE(isIdentifierHead('z')); + EXPECT_TRUE(isIdentifierHead('Z')); + EXPECT_TRUE(isIdentifierHead('_')); + + EXPECT_FALSE(isIdentifierHead('0')); + EXPECT_FALSE(isIdentifierHead('.')); + EXPECT_FALSE(isIdentifierHead('`')); + EXPECT_FALSE(isIdentifierHead('\0')); + + EXPECT_FALSE(isIdentifierHead('$')); + EXPECT_TRUE(isIdentifierHead('$', /*AllowDollar=*/true)); + + EXPECT_FALSE(isIdentifierHead('\x80')); + EXPECT_FALSE(isIdentifierHead('\xc2')); + EXPECT_FALSE(isIdentifierHead('\xff')); +} + +TEST(CharInfoTest, isIdentifierBody) { + EXPECT_TRUE(isIdentifierBody('a')); + EXPECT_TRUE(isIdentifierBody('A')); + EXPECT_TRUE(isIdentifierBody('z')); + EXPECT_TRUE(isIdentifierBody('Z')); + EXPECT_TRUE(isIdentifierBody('_')); + + EXPECT_TRUE(isIdentifierBody('0')); + EXPECT_FALSE(isIdentifierBody('.')); + EXPECT_FALSE(isIdentifierBody('`')); + EXPECT_FALSE(isIdentifierBody('\0')); + + EXPECT_FALSE(isIdentifierBody('$')); + EXPECT_TRUE(isIdentifierBody('$', /*AllowDollar=*/true)); + + EXPECT_FALSE(isIdentifierBody('\x80')); + EXPECT_FALSE(isIdentifierBody('\xc2')); + EXPECT_FALSE(isIdentifierBody('\xff')); +} + +TEST(CharInfoTest, isHorizontalWhitespace) { + EXPECT_FALSE(isHorizontalWhitespace('a')); + EXPECT_FALSE(isHorizontalWhitespace('_')); + EXPECT_FALSE(isHorizontalWhitespace('0')); + EXPECT_FALSE(isHorizontalWhitespace('.')); + EXPECT_FALSE(isHorizontalWhitespace('`')); + EXPECT_FALSE(isHorizontalWhitespace('\0')); + EXPECT_FALSE(isHorizontalWhitespace('\x7f')); + + EXPECT_TRUE(isHorizontalWhitespace(' ')); + EXPECT_TRUE(isHorizontalWhitespace('\t')); + EXPECT_TRUE(isHorizontalWhitespace('\f')); // ?? + EXPECT_TRUE(isHorizontalWhitespace('\v')); // ?? + + EXPECT_FALSE(isHorizontalWhitespace('\n')); + EXPECT_FALSE(isHorizontalWhitespace('\r')); + + EXPECT_FALSE(isHorizontalWhitespace('\x80')); + EXPECT_FALSE(isHorizontalWhitespace('\xc2')); + EXPECT_FALSE(isHorizontalWhitespace('\xff')); +} + +TEST(CharInfoTest, isVerticalWhitespace) { + EXPECT_FALSE(isVerticalWhitespace('a')); + EXPECT_FALSE(isVerticalWhitespace('_')); + EXPECT_FALSE(isVerticalWhitespace('0')); + EXPECT_FALSE(isVerticalWhitespace('.')); + EXPECT_FALSE(isVerticalWhitespace('`')); + EXPECT_FALSE(isVerticalWhitespace('\0')); + EXPECT_FALSE(isVerticalWhitespace('\x7f')); + + EXPECT_FALSE(isVerticalWhitespace(' ')); + EXPECT_FALSE(isVerticalWhitespace('\t')); + EXPECT_FALSE(isVerticalWhitespace('\f')); // ?? + EXPECT_FALSE(isVerticalWhitespace('\v')); // ?? + + EXPECT_TRUE(isVerticalWhitespace('\n')); + EXPECT_TRUE(isVerticalWhitespace('\r')); + + EXPECT_FALSE(isVerticalWhitespace('\x80')); + EXPECT_FALSE(isVerticalWhitespace('\xc2')); + EXPECT_FALSE(isVerticalWhitespace('\xff')); +} + +TEST(CharInfoTest, isWhitespace) { + EXPECT_FALSE(isWhitespace('a')); + EXPECT_FALSE(isWhitespace('_')); + EXPECT_FALSE(isWhitespace('0')); + EXPECT_FALSE(isWhitespace('.')); + EXPECT_FALSE(isWhitespace('`')); + EXPECT_FALSE(isWhitespace('\0')); + EXPECT_FALSE(isWhitespace('\x7f')); + + EXPECT_TRUE(isWhitespace(' ')); + EXPECT_TRUE(isWhitespace('\t')); + EXPECT_TRUE(isWhitespace('\f')); + EXPECT_TRUE(isWhitespace('\v')); + + EXPECT_TRUE(isWhitespace('\n')); + EXPECT_TRUE(isWhitespace('\r')); + + EXPECT_FALSE(isWhitespace('\x80')); + EXPECT_FALSE(isWhitespace('\xc2')); + EXPECT_FALSE(isWhitespace('\xff')); +} + +TEST(CharInfoTest, isDigit) { + EXPECT_TRUE(isDigit('0')); + EXPECT_TRUE(isDigit('9')); + + EXPECT_FALSE(isDigit('a')); + EXPECT_FALSE(isDigit('A')); + + EXPECT_FALSE(isDigit('z')); + EXPECT_FALSE(isDigit('Z')); + + EXPECT_FALSE(isDigit('.')); + EXPECT_FALSE(isDigit('_')); + + EXPECT_FALSE(isDigit('/')); + EXPECT_FALSE(isDigit('\0')); + + EXPECT_FALSE(isDigit('\x80')); + EXPECT_FALSE(isDigit('\xc2')); + EXPECT_FALSE(isDigit('\xff')); +} + +TEST(CharInfoTest, isHexDigit) { + EXPECT_TRUE(isHexDigit('0')); + EXPECT_TRUE(isHexDigit('9')); + + EXPECT_TRUE(isHexDigit('a')); + EXPECT_TRUE(isHexDigit('A')); + + EXPECT_FALSE(isHexDigit('z')); + EXPECT_FALSE(isHexDigit('Z')); + + EXPECT_FALSE(isHexDigit('.')); + EXPECT_FALSE(isHexDigit('_')); + + EXPECT_FALSE(isHexDigit('/')); + EXPECT_FALSE(isHexDigit('\0')); + + EXPECT_FALSE(isHexDigit('\x80')); + EXPECT_FALSE(isHexDigit('\xc2')); + EXPECT_FALSE(isHexDigit('\xff')); +} + +TEST(CharInfoTest, isLetter) { + EXPECT_FALSE(isLetter('0')); + EXPECT_FALSE(isLetter('9')); + + EXPECT_TRUE(isLetter('a')); + EXPECT_TRUE(isLetter('A')); + + EXPECT_TRUE(isLetter('z')); + EXPECT_TRUE(isLetter('Z')); + + EXPECT_FALSE(isLetter('.')); + EXPECT_FALSE(isLetter('_')); + + EXPECT_FALSE(isLetter('/')); + EXPECT_FALSE(isLetter('(')); + EXPECT_FALSE(isLetter('\0')); + + EXPECT_FALSE(isLetter('\x80')); + EXPECT_FALSE(isLetter('\xc2')); + EXPECT_FALSE(isLetter('\xff')); +} + +TEST(CharInfoTest, isLowercase) { + EXPECT_FALSE(isLowercase('0')); + EXPECT_FALSE(isLowercase('9')); + + EXPECT_TRUE(isLowercase('a')); + EXPECT_FALSE(isLowercase('A')); + + EXPECT_TRUE(isLowercase('z')); + EXPECT_FALSE(isLowercase('Z')); + + EXPECT_FALSE(isLowercase('.')); + EXPECT_FALSE(isLowercase('_')); + + EXPECT_FALSE(isLowercase('/')); + EXPECT_FALSE(isLowercase('(')); + EXPECT_FALSE(isLowercase('\0')); + + EXPECT_FALSE(isLowercase('\x80')); + EXPECT_FALSE(isLowercase('\xc2')); + EXPECT_FALSE(isLowercase('\xff')); +} + +TEST(CharInfoTest, isUppercase) { + EXPECT_FALSE(isUppercase('0')); + EXPECT_FALSE(isUppercase('9')); + + EXPECT_FALSE(isUppercase('a')); + EXPECT_TRUE(isUppercase('A')); + + EXPECT_FALSE(isUppercase('z')); + EXPECT_TRUE(isUppercase('Z')); + + EXPECT_FALSE(isUppercase('.')); + EXPECT_FALSE(isUppercase('_')); + + EXPECT_FALSE(isUppercase('/')); + EXPECT_FALSE(isUppercase('(')); + EXPECT_FALSE(isUppercase('\0')); + + EXPECT_FALSE(isUppercase('\x80')); + EXPECT_FALSE(isUppercase('\xc2')); + EXPECT_FALSE(isUppercase('\xff')); +} + +TEST(CharInfoTest, isAlphanumeric) { + EXPECT_TRUE(isAlphanumeric('0')); + EXPECT_TRUE(isAlphanumeric('9')); + + EXPECT_TRUE(isAlphanumeric('a')); + EXPECT_TRUE(isAlphanumeric('A')); + + EXPECT_TRUE(isAlphanumeric('z')); + EXPECT_TRUE(isAlphanumeric('Z')); + + EXPECT_FALSE(isAlphanumeric('.')); + EXPECT_FALSE(isAlphanumeric('_')); + + EXPECT_FALSE(isAlphanumeric('/')); + EXPECT_FALSE(isAlphanumeric('(')); + EXPECT_FALSE(isAlphanumeric('\0')); + + EXPECT_FALSE(isAlphanumeric('\x80')); + EXPECT_FALSE(isAlphanumeric('\xc2')); + EXPECT_FALSE(isAlphanumeric('\xff')); +} + +TEST(CharInfoTest, isPunctuation) { + EXPECT_FALSE(isPunctuation('0')); + EXPECT_FALSE(isPunctuation('9')); + + EXPECT_FALSE(isPunctuation('a')); + EXPECT_FALSE(isPunctuation('A')); + + EXPECT_FALSE(isPunctuation('z')); + EXPECT_FALSE(isPunctuation('Z')); + + EXPECT_TRUE(isPunctuation('.')); + EXPECT_TRUE(isPunctuation('_')); + + EXPECT_TRUE(isPunctuation('/')); + EXPECT_TRUE(isPunctuation('(')); + + EXPECT_FALSE(isPunctuation(' ')); + EXPECT_FALSE(isPunctuation('\n')); + EXPECT_FALSE(isPunctuation('\0')); + + EXPECT_FALSE(isPunctuation('\x80')); + EXPECT_FALSE(isPunctuation('\xc2')); + EXPECT_FALSE(isPunctuation('\xff')); +} + +TEST(CharInfoTest, isPrintable) { + EXPECT_TRUE(isPrintable('0')); + EXPECT_TRUE(isPrintable('9')); + + EXPECT_TRUE(isPrintable('a')); + EXPECT_TRUE(isPrintable('A')); + + EXPECT_TRUE(isPrintable('z')); + EXPECT_TRUE(isPrintable('Z')); + + EXPECT_TRUE(isPrintable('.')); + EXPECT_TRUE(isPrintable('_')); + + EXPECT_TRUE(isPrintable('/')); + EXPECT_TRUE(isPrintable('(')); + + EXPECT_TRUE(isPrintable(' ')); + EXPECT_FALSE(isPrintable('\t')); + EXPECT_FALSE(isPrintable('\n')); + EXPECT_FALSE(isPrintable('\0')); + + EXPECT_FALSE(isPrintable('\x80')); + EXPECT_FALSE(isPrintable('\xc2')); + EXPECT_FALSE(isPrintable('\xff')); +} + +TEST(CharInfoTest, isPreprocessingNumberBody) { + EXPECT_TRUE(isPreprocessingNumberBody('0')); + EXPECT_TRUE(isPreprocessingNumberBody('9')); + + EXPECT_TRUE(isPreprocessingNumberBody('a')); + EXPECT_TRUE(isPreprocessingNumberBody('A')); + + EXPECT_TRUE(isPreprocessingNumberBody('z')); + EXPECT_TRUE(isPreprocessingNumberBody('Z')); + EXPECT_TRUE(isPreprocessingNumberBody('.')); + EXPECT_TRUE(isPreprocessingNumberBody('_')); + + EXPECT_FALSE(isPreprocessingNumberBody('/')); + EXPECT_FALSE(isPreprocessingNumberBody('(')); + EXPECT_FALSE(isPreprocessingNumberBody('\0')); + + EXPECT_FALSE(isPreprocessingNumberBody('\x80')); + EXPECT_FALSE(isPreprocessingNumberBody('\xc2')); + EXPECT_FALSE(isPreprocessingNumberBody('\xff')); +} + +TEST(CharInfoTest, isRawStringDelimBody) { + EXPECT_TRUE(isRawStringDelimBody('0')); + EXPECT_TRUE(isRawStringDelimBody('9')); + + EXPECT_TRUE(isRawStringDelimBody('a')); + EXPECT_TRUE(isRawStringDelimBody('A')); + + EXPECT_TRUE(isRawStringDelimBody('z')); + EXPECT_TRUE(isRawStringDelimBody('Z')); + EXPECT_TRUE(isRawStringDelimBody('.')); + EXPECT_TRUE(isRawStringDelimBody('_')); + + EXPECT_TRUE(isRawStringDelimBody('/')); + EXPECT_FALSE(isRawStringDelimBody('(')); + EXPECT_FALSE(isRawStringDelimBody('\0')); + + EXPECT_FALSE(isRawStringDelimBody('\x80')); + EXPECT_FALSE(isRawStringDelimBody('\xc2')); + EXPECT_FALSE(isRawStringDelimBody('\xff')); +} + +TEST(CharInfoTest, toLowercase) { + EXPECT_EQ('0', toLowercase('0')); + EXPECT_EQ('9', toLowercase('9')); + + EXPECT_EQ('a', toLowercase('a')); + EXPECT_EQ('a', toLowercase('A')); + + EXPECT_EQ('z', toLowercase('z')); + EXPECT_EQ('z', toLowercase('Z')); + + EXPECT_EQ('.', toLowercase('.')); + EXPECT_EQ('_', toLowercase('_')); + + EXPECT_EQ('/', toLowercase('/')); + EXPECT_EQ('\0', toLowercase('\0')); +} + +TEST(CharInfoTest, toUppercase) { + EXPECT_EQ('0', toUppercase('0')); + EXPECT_EQ('9', toUppercase('9')); + + EXPECT_EQ('A', toUppercase('a')); + EXPECT_EQ('A', toUppercase('A')); + + EXPECT_EQ('Z', toUppercase('z')); + EXPECT_EQ('Z', toUppercase('Z')); + + EXPECT_EQ('.', toUppercase('.')); + EXPECT_EQ('_', toUppercase('_')); + + EXPECT_EQ('/', toUppercase('/')); + EXPECT_EQ('\0', toUppercase('\0')); +} + +TEST(CharInfoTest, isValidIdentifier) { + EXPECT_FALSE(isValidIdentifier("")); + + // 1 character + EXPECT_FALSE(isValidIdentifier(".")); + EXPECT_FALSE(isValidIdentifier("\n")); + EXPECT_FALSE(isValidIdentifier(" ")); + EXPECT_FALSE(isValidIdentifier("\x80")); + EXPECT_FALSE(isValidIdentifier("\xc2")); + EXPECT_FALSE(isValidIdentifier("\xff")); + EXPECT_FALSE(isValidIdentifier("$")); + EXPECT_FALSE(isValidIdentifier("1")); + + EXPECT_TRUE(isValidIdentifier("_")); + EXPECT_TRUE(isValidIdentifier("a")); + EXPECT_TRUE(isValidIdentifier("z")); + EXPECT_TRUE(isValidIdentifier("A")); + EXPECT_TRUE(isValidIdentifier("Z")); + + // 2 characters, '_' suffix + EXPECT_FALSE(isValidIdentifier("._")); + EXPECT_FALSE(isValidIdentifier("\n_")); + EXPECT_FALSE(isValidIdentifier(" _")); + EXPECT_FALSE(isValidIdentifier("\x80_")); + EXPECT_FALSE(isValidIdentifier("\xc2_")); + EXPECT_FALSE(isValidIdentifier("\xff_")); + EXPECT_FALSE(isValidIdentifier("$_")); + EXPECT_FALSE(isValidIdentifier("1_")); + + EXPECT_TRUE(isValidIdentifier("__")); + EXPECT_TRUE(isValidIdentifier("a_")); + EXPECT_TRUE(isValidIdentifier("z_")); + EXPECT_TRUE(isValidIdentifier("A_")); + EXPECT_TRUE(isValidIdentifier("Z_")); + + // 2 characters, '_' prefix + EXPECT_FALSE(isValidIdentifier("_.")); + EXPECT_FALSE(isValidIdentifier("_\n")); + EXPECT_FALSE(isValidIdentifier("_ ")); + EXPECT_FALSE(isValidIdentifier("_\x80")); + EXPECT_FALSE(isValidIdentifier("_\xc2")); + EXPECT_FALSE(isValidIdentifier("_\xff")); + EXPECT_FALSE(isValidIdentifier("_$")); + EXPECT_TRUE(isValidIdentifier("_1")); + + EXPECT_TRUE(isValidIdentifier("__")); + EXPECT_TRUE(isValidIdentifier("_a")); + EXPECT_TRUE(isValidIdentifier("_z")); + EXPECT_TRUE(isValidIdentifier("_A")); + EXPECT_TRUE(isValidIdentifier("_Z")); + + // 3 characters, '__' prefix + EXPECT_FALSE(isValidIdentifier("__.")); + EXPECT_FALSE(isValidIdentifier("__\n")); + EXPECT_FALSE(isValidIdentifier("__ ")); + EXPECT_FALSE(isValidIdentifier("__\x80")); + EXPECT_FALSE(isValidIdentifier("__\xc2")); + EXPECT_FALSE(isValidIdentifier("__\xff")); + EXPECT_FALSE(isValidIdentifier("__$")); + EXPECT_TRUE(isValidIdentifier("__1")); + + EXPECT_TRUE(isValidIdentifier("___")); + EXPECT_TRUE(isValidIdentifier("__a")); + EXPECT_TRUE(isValidIdentifier("__z")); + EXPECT_TRUE(isValidIdentifier("__A")); + EXPECT_TRUE(isValidIdentifier("__Z")); + + // 3 characters, '_' prefix and suffix + EXPECT_FALSE(isValidIdentifier("_._")); + EXPECT_FALSE(isValidIdentifier("_\n_")); + EXPECT_FALSE(isValidIdentifier("_ _")); + EXPECT_FALSE(isValidIdentifier("_\x80_")); + EXPECT_FALSE(isValidIdentifier("_\xc2_")); + EXPECT_FALSE(isValidIdentifier("_\xff_")); + EXPECT_FALSE(isValidIdentifier("_$_")); + EXPECT_TRUE(isValidIdentifier("_1_")); + + EXPECT_TRUE(isValidIdentifier("___")); + EXPECT_TRUE(isValidIdentifier("_a_")); + EXPECT_TRUE(isValidIdentifier("_z_")); + EXPECT_TRUE(isValidIdentifier("_A_")); + EXPECT_TRUE(isValidIdentifier("_Z_")); +} diff --git a/unittests/Basic/FileManagerTest.cpp b/unittests/Basic/FileManagerTest.cpp index 91998b6..a55fcbf 100644 --- a/unittests/Basic/FileManagerTest.cpp +++ b/unittests/Basic/FileManagerTest.cpp @@ -7,10 +7,9 @@ // //===----------------------------------------------------------------------===// +#include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/FileSystemStatCache.h" -#include "clang/Basic/FileManager.h" - #include "gtest/gtest.h" using namespace llvm; @@ -52,7 +51,7 @@ public: // Implement FileSystemStatCache::getStat(). virtual LookupResult getStat(const char *Path, struct stat &StatBuf, - int *FileDescriptor) { + bool isFile, int *FileDescriptor) { if (StatCalls.count(Path) != 0) { StatBuf = StatCalls[Path]; return CacheExists; diff --git a/unittests/Basic/SourceManagerTest.cpp b/unittests/Basic/SourceManagerTest.cpp index 6f404b5..3f09cbb 100644 --- a/unittests/Basic/SourceManagerTest.cpp +++ b/unittests/Basic/SourceManagerTest.cpp @@ -8,20 +8,19 @@ //===----------------------------------------------------------------------===// #include "clang/Basic/SourceManager.h" -#include "clang/Basic/FileManager.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" +#include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" -#include "clang/Basic/TargetOptions.h" #include "clang/Basic/TargetInfo.h" -#include "clang/Lex/ModuleLoader.h" +#include "clang/Basic/TargetOptions.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" +#include "clang/Lex/ModuleLoader.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" - #include "gtest/gtest.h" using namespace llvm; @@ -39,7 +38,7 @@ protected: SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; - Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); + Target = TargetInfo::CreateTargetInfo(Diags, &*TargetOpts); } FileSystemOptions FileMgrOpts; @@ -53,11 +52,17 @@ protected: }; class VoidModuleLoader : public ModuleLoader { - virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, - Module::NameVisibilityKind Visibility, - bool IsInclusionDirective) { - return 0; + virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, + ModuleIdPath Path, + Module::NameVisibilityKind Visibility, + bool IsInclusionDirective) { + return ModuleLoadResult(); } + + virtual void makeModuleVisible(Module *Mod, + Module::NameVisibilityKind Visibility, + SourceLocation ImportLoc, + bool Complain) { } }; TEST_F(SourceManagerTest, isBeforeInTranslationUnit) { @@ -245,12 +250,13 @@ class MacroTracker : public PPCallbacks { public: explicit MacroTracker(std::vector<MacroAction> &Macros) : Macros(Macros) { } - virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) { - Macros.push_back(MacroAction(MI->getDefinitionLoc(), + virtual void MacroDefined(const Token &MacroNameTok, + const MacroDirective *MD) { + Macros.push_back(MacroAction(MD->getLocation(), MacroNameTok.getIdentifierInfo()->getName(), true)); } - virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo* MI, + virtual void MacroExpands(const Token &MacroNameTok, const MacroDirective *MD, SourceRange Range) { Macros.push_back(MacroAction(MacroNameTok.getLocation(), MacroNameTok.getIdentifierInfo()->getName(), diff --git a/unittests/CMakeLists.txt b/unittests/CMakeLists.txt index 989025a..334ea41 100644 --- a/unittests/CMakeLists.txt +++ b/unittests/CMakeLists.txt @@ -15,3 +15,4 @@ add_subdirectory(Basic) add_subdirectory(Lex) add_subdirectory(Frontend) add_subdirectory(Tooling) +add_subdirectory(Format) diff --git a/unittests/Format/CMakeLists.txt b/unittests/Format/CMakeLists.txt new file mode 100644 index 0000000..16d5764 --- /dev/null +++ b/unittests/Format/CMakeLists.txt @@ -0,0 +1,18 @@ +set(LLVM_LINK_COMPONENTS + ${LLVM_TARGETS_TO_BUILD} + asmparser + bitreader + support + mc + ) + +add_clang_unittest(FormatTests + FormatTest.cpp + ) + +target_link_libraries(FormatTests + clangAST + clangFormat + clangTooling + clangRewriteCore + ) diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp new file mode 100644 index 0000000..e01034b --- /dev/null +++ b/unittests/Format/FormatTest.cpp @@ -0,0 +1,3590 @@ +//===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#define DEBUG_TYPE "format-test" + +#include "clang/Format/Format.h" +#include "../Tooling/RewriterTestContext.h" +#include "clang/Lex/Lexer.h" +#include "llvm/Support/Debug.h" +#include "gtest/gtest.h" + +namespace clang { +namespace format { + +class FormatTest : public ::testing::Test { +protected: + std::string format(llvm::StringRef Code, unsigned Offset, unsigned Length, + const FormatStyle &Style) { + DEBUG(llvm::errs() << "---\n"); + RewriterTestContext Context; + FileID ID = Context.createInMemoryFile("input.cc", Code); + SourceLocation Start = + Context.Sources.getLocForStartOfFile(ID).getLocWithOffset(Offset); + std::vector<CharSourceRange> Ranges( + 1, + CharSourceRange::getCharRange(Start, Start.getLocWithOffset(Length))); + Lexer Lex(ID, Context.Sources.getBuffer(ID), Context.Sources, + getFormattingLangOpts()); + tooling::Replacements Replace = reformat( + Style, Lex, Context.Sources, Ranges, new IgnoringDiagConsumer()); + ReplacementCount = Replace.size(); + EXPECT_TRUE(applyAllReplacements(Replace, Context.Rewrite)); + DEBUG(llvm::errs() << "\n" << Context.getRewrittenText(ID) << "\n\n"); + return Context.getRewrittenText(ID); + } + + std::string + format(llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle()) { + return format(Code, 0, Code.size(), Style); + } + + std::string messUp(llvm::StringRef Code) { + std::string MessedUp(Code.str()); + bool InComment = false; + bool InPreprocessorDirective = false; + bool JustReplacedNewline = false; + for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) { + if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') { + if (JustReplacedNewline) + MessedUp[i - 1] = '\n'; + InComment = true; + } else if (MessedUp[i] == '#' && (JustReplacedNewline || i == 0)) { + if (i != 0) + MessedUp[i - 1] = '\n'; + InPreprocessorDirective = true; + } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') { + MessedUp[i] = ' '; + MessedUp[i + 1] = ' '; + } else if (MessedUp[i] == '\n') { + if (InComment) { + InComment = false; + } else if (InPreprocessorDirective) { + InPreprocessorDirective = false; + } else { + JustReplacedNewline = true; + MessedUp[i] = ' '; + } + } else if (MessedUp[i] != ' ') { + JustReplacedNewline = false; + } + } + return MessedUp; + } + + FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) { + FormatStyle Style = getLLVMStyle(); + Style.ColumnLimit = ColumnLimit; + return Style; + } + + FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) { + FormatStyle Style = getGoogleStyle(); + Style.ColumnLimit = ColumnLimit; + return Style; + } + + void verifyFormat(llvm::StringRef Code, + const FormatStyle &Style = getLLVMStyle()) { + EXPECT_EQ(Code.str(), format(messUp(Code), Style)); + } + + void verifyGoogleFormat(llvm::StringRef Code) { + verifyFormat(Code, getGoogleStyle()); + } + + void verifyIndependentOfContext(llvm::StringRef text) { + verifyFormat(text); + verifyFormat(llvm::Twine("void f() { " + text + " }").str()); + } + + int ReplacementCount; +}; + +TEST_F(FormatTest, MessUp) { + EXPECT_EQ("1 2 3", messUp("1 2 3")); + EXPECT_EQ("1 2 3\n", messUp("1\n2\n3\n")); + EXPECT_EQ("a\n//b\nc", messUp("a\n//b\nc")); + EXPECT_EQ("a\n#b\nc", messUp("a\n#b\nc")); + EXPECT_EQ("a\n#b c d\ne", messUp("a\n#b\\\nc\\\nd\ne")); +} + +//===----------------------------------------------------------------------===// +// Basic function tests. +//===----------------------------------------------------------------------===// + +TEST_F(FormatTest, DoesNotChangeCorrectlyFormatedCode) { + EXPECT_EQ(";", format(";")); +} + +TEST_F(FormatTest, FormatsGlobalStatementsAt0) { + EXPECT_EQ("int i;", format(" int i;")); + EXPECT_EQ("\nint i;", format(" \n\t \r int i;")); + EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); + EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); +} + +TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { + EXPECT_EQ("int i;", format("int\ni;")); +} + +TEST_F(FormatTest, FormatsNestedBlockStatements) { + EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); +} + +TEST_F(FormatTest, FormatsNestedCall) { + verifyFormat("Method(f1, f2(f3));"); + verifyFormat("Method(f1(f2, f3()));"); + verifyFormat("Method(f1(f2, (f3())));"); +} + +TEST_F(FormatTest, NestedNameSpecifiers) { + verifyFormat("vector< ::Type> v;"); + verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); +} + +TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { + EXPECT_EQ("if (a) {\n" + " f();\n" + "}", + format("if(a){f();}")); + EXPECT_EQ(4, ReplacementCount); + EXPECT_EQ("if (a) {\n" + " f();\n" + "}", + format("if (a) {\n" + " f();\n" + "}")); + EXPECT_EQ(0, ReplacementCount); +} + +TEST_F(FormatTest, RemovesTrailingWhitespaceOfFormattedLine) { + EXPECT_EQ("int a;\nint b;", format("int a; \nint b;", 0, 0, getLLVMStyle())); + EXPECT_EQ("int a;", format("int a; ")); + EXPECT_EQ("int a;\n", format("int a; \n \n \n ")); + EXPECT_EQ("int a;\nint b; ", + format("int a; \nint b; ", 0, 0, getLLVMStyle())); +} + +TEST_F(FormatTest, FormatsCorrectRegionForLeadingWhitespace) { + EXPECT_EQ("int b;\nint a;", + format("int b;\n int a;", 7, 0, getLLVMStyle())); + EXPECT_EQ("int b;\n int a;", + format("int b;\n int a;", 6, 0, getLLVMStyle())); + + EXPECT_EQ("#define A \\\n" + " int a; \\\n" + " int b;", + format("#define A \\\n" + " int a; \\\n" + " int b;", + 26, 0, getLLVMStyleWithColumns(12))); + EXPECT_EQ("#define A \\\n" + " int a; \\\n" + " int b;", + format("#define A \\\n" + " int a; \\\n" + " int b;", + 25, 0, getLLVMStyleWithColumns(12))); +} + +TEST_F(FormatTest, RemovesWhitespaceWhenTriggeredOnEmptyLine) { + EXPECT_EQ("int a;\n\n int b;", + format("int a;\n \n\n int b;", 7, 0, getLLVMStyle())); + EXPECT_EQ("int a;\n\n int b;", + format("int a;\n \n\n int b;", 9, 0, getLLVMStyle())); +} + +TEST_F(FormatTest, ReformatsMovedLines) { + EXPECT_EQ( + "template <typename T> T *getFETokenInfo() const {\n" + " return static_cast<T *>(FETokenInfo);\n" + "}\n" + " int a; // <- Should not be formatted", + format( + "template<typename T>\n" + "T *getFETokenInfo() const { return static_cast<T*>(FETokenInfo); }\n" + " int a; // <- Should not be formatted", + 9, 5, getLLVMStyle())); +} + +//===----------------------------------------------------------------------===// +// Tests for control statements. +//===----------------------------------------------------------------------===// + +TEST_F(FormatTest, FormatIfWithoutCompountStatement) { + verifyFormat("if (true)\n f();\ng();"); + verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); + verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); + + FormatStyle AllowsMergedIf = getGoogleStyle(); + AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true; + verifyFormat("if (a)\n" + " // comment\n" + " f();", + AllowsMergedIf); + + verifyFormat("if (a) // Can't merge this\n" + " f();\n", + AllowsMergedIf); + verifyFormat("if (a) /* still don't merge */\n" + " f();", + AllowsMergedIf); + verifyFormat("if (a) { // Never merge this\n" + " f();\n" + "}", + AllowsMergedIf); + verifyFormat("if (a) { /* Never merge this */\n" + " f();\n" + "}", + AllowsMergedIf); + + AllowsMergedIf.ColumnLimit = 14; + verifyFormat("if (a) return;", AllowsMergedIf); + verifyFormat("if (aaaaaaaaa)\n" + " return;", + AllowsMergedIf); + + AllowsMergedIf.ColumnLimit = 13; + verifyFormat("if (a)\n return;", AllowsMergedIf); +} + +TEST_F(FormatTest, ParseIfElse) { + verifyFormat("if (true)\n" + " if (true)\n" + " if (true)\n" + " f();\n" + " else\n" + " g();\n" + " else\n" + " h();\n" + "else\n" + " i();"); + verifyFormat("if (true)\n" + " if (true)\n" + " if (true) {\n" + " if (true)\n" + " f();\n" + " } else {\n" + " g();\n" + " }\n" + " else\n" + " h();\n" + "else {\n" + " i();\n" + "}"); +} + +TEST_F(FormatTest, ElseIf) { + verifyFormat("if (a) {\n} else if (b) {\n}"); + verifyFormat("if (a)\n" + " f();\n" + "else if (b)\n" + " g();\n" + "else\n" + " h();"); +} + +TEST_F(FormatTest, FormatsForLoop) { + verifyFormat( + "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" + " ++VeryVeryLongLoopVariable)\n" + " ;"); + verifyFormat("for (;;)\n" + " f();"); + verifyFormat("for (;;) {\n}"); + verifyFormat("for (;;) {\n" + " f();\n" + "}"); + + verifyFormat( + "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" + " E = UnwrappedLines.end();\n" + " I != E; ++I) {\n}"); + + verifyFormat( + "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" + " ++IIIII) {\n}"); + verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" + " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" + " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); + verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" + " I = FD->getDeclsInPrototypeScope().begin(),\n" + " E = FD->getDeclsInPrototypeScope().end();\n" + " I != E; ++I) {\n}"); + + // FIXME: Not sure whether we want extra identation in line 3 here: + verifyFormat( + "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" + " ++aaaaaaaaaaa) {\n}"); + verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" + " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" + "}"); + verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" + " aaaaaaaaaa);\n" + " iter; ++iter) {\n" + "}"); + + FormatStyle NoBinPacking = getLLVMStyle(); + NoBinPacking.BinPackParameters = false; + verifyFormat("for (int aaaaaaaaaaa = 1;\n" + " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaa);\n" + " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" + "}", + NoBinPacking); + verifyFormat( + "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" + " E = UnwrappedLines.end();\n" + " I != E;\n" + " ++I) {\n}", + NoBinPacking); +} + +TEST_F(FormatTest, RangeBasedForLoops) { + verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); + verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" + " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); + verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); +} + +TEST_F(FormatTest, FormatsWhileLoop) { + verifyFormat("while (true) {\n}"); + verifyFormat("while (true)\n" + " f();"); + verifyFormat("while () {\n}"); + verifyFormat("while () {\n" + " f();\n" + "}"); +} + +TEST_F(FormatTest, FormatsDoWhile) { + verifyFormat("do {\n" + " do_something();\n" + "} while (something());"); + verifyFormat("do\n" + " do_something();\n" + "while (something());"); +} + +TEST_F(FormatTest, FormatsSwitchStatement) { + verifyFormat("switch (x) {\n" + "case 1:\n" + " f();\n" + " break;\n" + "case kFoo:\n" + "case ns::kBar:\n" + "case kBaz:\n" + " break;\n" + "default:\n" + " g();\n" + " break;\n" + "}"); + verifyFormat("switch (x) {\n" + "case 1: {\n" + " f();\n" + " break;\n" + "}\n" + "}"); + verifyFormat("switch (x) {\n" + "case 1: {\n" + " f();\n" + " {\n" + " g();\n" + " h();\n" + " }\n" + " break;\n" + "}\n" + "}"); + verifyFormat("switch (x) {\n" + "case 1: {\n" + " f();\n" + " if (foo) {\n" + " g();\n" + " h();\n" + " }\n" + " break;\n" + "}\n" + "}"); + verifyFormat("switch (x) {\n" + "case 1: {\n" + " f();\n" + " g();\n" + "} break;\n" + "}"); + verifyFormat("switch (test)\n" + " ;"); + verifyFormat("switch (x) {\n" + "default: {\n" + " // Do nothing.\n" + "}"); + verifyFormat("switch (x) {\n" + "// if 1, do f()\n" + "case 1:\n" + " f();\n" + "}"); + verifyFormat("switch (x) {\n" + "case 1:\n" + " // Do amazing stuff\n" + " {\n" + " f();\n" + " g();\n" + " }\n" + " break;\n" + "}"); + verifyFormat("#define A \\\n" + " switch (x) { \\\n" + " case a: \\\n" + " foo = b; \\\n" + " }", getLLVMStyleWithColumns(20)); + + verifyGoogleFormat("switch (x) {\n" + " case 1:\n" + " f();\n" + " break;\n" + " case kFoo:\n" + " case ns::kBar:\n" + " case kBaz:\n" + " break;\n" + " default:\n" + " g();\n" + " break;\n" + "}"); + verifyGoogleFormat("switch (x) {\n" + " case 1: {\n" + " f();\n" + " break;\n" + " }\n" + "}"); + verifyGoogleFormat("switch (test)\n" + " ;"); +} + +TEST_F(FormatTest, FormatsLabels) { + verifyFormat("void f() {\n" + " some_code();\n" + "test_label:\n" + " some_other_code();\n" + " {\n" + " some_more_code();\n" + " another_label:\n" + " some_more_code();\n" + " }\n" + "}"); + verifyFormat("some_code();\n" + "test_label:\n" + "some_other_code();"); +} + +//===----------------------------------------------------------------------===// +// Tests for comments. +//===----------------------------------------------------------------------===// + +TEST_F(FormatTest, UnderstandsSingleLineComments) { + verifyFormat("//* */"); + verifyFormat("// line 1\n" + "// line 2\n" + "void f() {}\n"); + + verifyFormat("void f() {\n" + " // Doesn't do anything\n" + "}"); + verifyFormat("void f(int i, // some comment (probably for i)\n" + " int j, // some comment (probably for j)\n" + " int k); // some comment (probably for k)"); + verifyFormat("void f(int i,\n" + " // some comment (probably for j)\n" + " int j,\n" + " // some comment (probably for k)\n" + " int k);"); + + verifyFormat("int i // This is a fancy variable\n" + " = 5; // with nicely aligned comment."); + + verifyFormat("// Leading comment.\n" + "int a; // Trailing comment."); + verifyFormat("int a; // Trailing comment\n" + " // on 2\n" + " // or 3 lines.\n" + "int b;"); + verifyFormat("int a; // Trailing comment\n" + "\n" + "// Leading comment.\n" + "int b;"); + verifyFormat("int a; // Comment.\n" + " // More details.\n" + "int bbbb; // Another comment."); + verifyFormat( + "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n" + "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // comment\n" + "int cccccccccccccccccccccccccccccc; // comment\n" + "int ddd; // looooooooooooooooooooooooong comment\n" + "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n" + "int bbbbbbbbbbbbbbbbbbbbb; // comment\n" + "int ccccccccccccccccccc; // comment"); + + verifyFormat("#include \"a\" // comment\n" + "#include \"a/b/c\" // comment"); + verifyFormat("#include <a> // comment\n" + "#include <a/b/c> // comment"); + + verifyFormat("enum E {\n" + " // comment\n" + " VAL_A, // comment\n" + " VAL_B\n" + "};"); + + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" + " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment"); + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" + " // Comment inside a statement.\n" + " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); + verifyFormat( + "bool aaaaaaaaaaaaa = // comment\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); + + verifyFormat("int aaaa; // aaaaa\n" + "int aa; // aaaaaaa", + getLLVMStyleWithColumns(20)); + + EXPECT_EQ("void f() { // This does something ..\n" + "}\n" + "int a; // This is unrelated", + format("void f() { // This does something ..\n" + " }\n" + "int a; // This is unrelated")); + EXPECT_EQ("void f() { // This does something ..\n" + "} // awesome..\n" + "\n" + "int a; // This is unrelated", + format("void f() { // This does something ..\n" + " } // awesome..\n" + " \n" + "int a; // This is unrelated")); + + EXPECT_EQ("int i; // single line trailing comment", + format("int i;\\\n// single line trailing comment")); + + verifyGoogleFormat("int a; // Trailing comment."); + + verifyFormat("someFunction(anotherFunction( // Force break.\n" + " parameter));"); + + verifyGoogleFormat("#endif // HEADER_GUARD"); + + verifyFormat("const char *test[] = {\n" + " // A\n" + " \"aaaa\",\n" + " // B\n" + " \"aaaaa\",\n" + "};"); + verifyGoogleFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaa); // 81 cols with this comment"); + EXPECT_EQ("D(a, {\n" + " // test\n" + " int a;\n" + "});", + format("D(a, {\n" + "// test\n" + "int a;\n" + "});")); +} + +TEST_F(FormatTest, CanFormatCommentsLocally) { + EXPECT_EQ("int a; // comment\n" + "int b; // comment", + format("int a; // comment\n" + "int b; // comment", + 0, 0, getLLVMStyle())); + EXPECT_EQ("int a; // comment\n" + " // line 2\n" + "int b;", + format("int a; // comment\n" + " // line 2\n" + "int b;", + 28, 0, getLLVMStyle())); +} + +TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) { + EXPECT_EQ("// comment", format("// comment ")); + EXPECT_EQ("int aaaaaaa, bbbbbbb; // comment", + format("int aaaaaaa, bbbbbbb; // comment ", + getLLVMStyleWithColumns(33))); +} + +TEST_F(FormatTest, UnderstandsMultiLineComments) { + verifyFormat("f(/*test=*/ true);"); + EXPECT_EQ( + "f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n" + " bbbbbbbbbbbbbbbbbbbbbbbbb);", + format("f(aaaaaaaaaaaaaaaaaaaaaaaaa , /* Trailing comment for aa... */\n" + " bbbbbbbbbbbbbbbbbbbbbbbbb);")); + EXPECT_EQ( + "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);", + format("f(aaaaaaaaaaaaaaaaaaaaaaaaa , \n" + "/* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);")); + + FormatStyle NoBinPacking = getLLVMStyle(); + NoBinPacking.BinPackParameters = false; + verifyFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n" + " /* parameter 2 */ aaaaaa,\n" + " /* parameter 3 */ aaaaaa,\n" + " /* parameter 4 */ aaaaaa);", + NoBinPacking); +} + +TEST_F(FormatTest, AlignsMultiLineComments) { + EXPECT_EQ("/*\n" + " * Really multi-line\n" + " * comment.\n" + " */\n" + "void f() {}", + format(" /*\n" + " * Really multi-line\n" + " * comment.\n" + " */\n" + " void f() {}")); + EXPECT_EQ("class C {\n" + " /*\n" + " * Another multi-line\n" + " * comment.\n" + " */\n" + " void f() {}\n" + "};", + format("class C {\n" + "/*\n" + " * Another multi-line\n" + " * comment.\n" + " */\n" + "void f() {}\n" + "};")); + EXPECT_EQ("/*\n" + " 1. This is a comment with non-trivial formatting.\n" + " 1.1. We have to indent/outdent all lines equally\n" + " 1.1.1. to keep the formatting.\n" + " */", + format(" /*\n" + " 1. This is a comment with non-trivial formatting.\n" + " 1.1. We have to indent/outdent all lines equally\n" + " 1.1.1. to keep the formatting.\n" + " */")); + EXPECT_EQ("/*\n" + " Don't try to outdent if there's not enough inentation.\n" + " */", + format(" /*\n" + " Don't try to outdent if there's not enough inentation.\n" + " */")); +} + +TEST_F(FormatTest, SplitsLongCxxComments) { + EXPECT_EQ("// A comment that\n" + "// doesn't fit on\n" + "// one line", + format("// A comment that doesn't fit on one line", + getLLVMStyleWithColumns(20))); + EXPECT_EQ("if (true) // A comment that\n" + " // doesn't fit on\n" + " // one line", + format("if (true) // A comment that doesn't fit on one line ", + getLLVMStyleWithColumns(30))); + EXPECT_EQ("// Don't_touch_leading_whitespace", + format("// Don't_touch_leading_whitespace", + getLLVMStyleWithColumns(20))); + EXPECT_EQ( + "//Don't add leading\n" + "//whitespace", + format("//Don't add leading whitespace", getLLVMStyleWithColumns(20))); + EXPECT_EQ("// A comment before\n" + "// a macro\n" + "// definition\n" + "#define a b", + format("// A comment before a macro definition\n" + "#define a b", + getLLVMStyleWithColumns(20))); +} + +TEST_F(FormatTest, ParsesCommentsAdjacentToPPDirectives) { + EXPECT_EQ("namespace {}\n// Test\n#define A", + format("namespace {}\n // Test\n#define A")); + EXPECT_EQ("namespace {}\n/* Test */\n#define A", + format("namespace {}\n /* Test */\n#define A")); + EXPECT_EQ("namespace {}\n/* Test */ #define A", + format("namespace {}\n /* Test */ #define A")); +} + +TEST_F(FormatTest, SplitsLongLinesInComments) { + EXPECT_EQ("/* This is a long\n" + " * comment that\n" + " * doesn't\n" + " * fit on one line.\n" + " */", + format("/* " + "This is a long " + "comment that " + "doesn't " + "fit on one line. */", + getLLVMStyleWithColumns(20))); + EXPECT_EQ("/*\n" + "This is a long\n" + "comment that doesn't\n" + "fit on one line.\n" + "*/", + format("/*\n" + "This is a long " + "comment that doesn't " + "fit on one line. \n" + "*/", getLLVMStyleWithColumns(20))); + EXPECT_EQ("/*\n" + " * This is a long\n" + " * comment that\n" + " * doesn't fit on\n" + " * one line.\n" + " */", + format("/* \n" + " * This is a long " + " comment that " + " doesn't fit on " + " one line. \n" + " */", getLLVMStyleWithColumns(20))); + EXPECT_EQ("/*\n" + " * This_is_a_comment_with_words_that_dont_fit_on_one_line\n" + " * so_it_should_be_broken\n" + " * wherever_a_space_occurs\n" + " */", + format("/*\n" + " * This_is_a_comment_with_words_that_dont_fit_on_one_line " + " so_it_should_be_broken " + " wherever_a_space_occurs \n" + " */", + getLLVMStyleWithColumns(20))); + EXPECT_EQ("/*\n" + " * This_comment_can_not_be_broken_into_lines\n" + " */", + format("/*\n" + " * This_comment_can_not_be_broken_into_lines\n" + " */", + getLLVMStyleWithColumns(20))); + EXPECT_EQ("{\n" + " /*\n" + " This is another\n" + " long comment that\n" + " doesn't fit on one\n" + " line 1234567890\n" + " */\n" + "}", + format("{\n" + "/*\n" + "This is another " + " long comment that " + " doesn't fit on one" + " line 1234567890\n" + "*/\n" + "}", getLLVMStyleWithColumns(20))); + EXPECT_EQ("{\n" + " /*\n" + " * This i s\n" + " * another comment\n" + " * t hat doesn' t\n" + " * fit on one l i\n" + " * n e\n" + " */\n" + "}", + format("{\n" + "/*\n" + " * This i s" + " another comment" + " t hat doesn' t" + " fit on one l i" + " n e\n" + " */\n" + "}", getLLVMStyleWithColumns(20))); + EXPECT_EQ("/*\n" + " * This is a long\n" + " * comment that\n" + " * doesn't fit on\n" + " * one line\n" + " */", + format(" /*\n" + " * This is a long comment that doesn't fit on one line\n" + " */", getLLVMStyleWithColumns(20))); + EXPECT_EQ("{\n" + " if (something) /* This is a\n" + "long comment */\n" + " ;\n" + "}", + format("{\n" + " if (something) /* This is a long comment */\n" + " ;\n" + "}", + getLLVMStyleWithColumns(30))); +} + +TEST_F(FormatTest, SplitsLongLinesInCommentsInPreprocessor) { + EXPECT_EQ("#define X \\\n" + " /* \\\n" + " Test \\\n" + " Macro comment \\\n" + " with a long \\\n" + " line \\\n" + // FIXME: We should look at the length of the last line of the token + // instead of the full token's length. + //" */ \\\n" + " */\\\n" + " A + B", + format("#define X \\\n" + " /*\n" + " Test\n" + " Macro comment with a long line\n" + " */ \\\n" + " A + B", + getLLVMStyleWithColumns(20))); + EXPECT_EQ("#define X \\\n" + " /* Macro comment \\\n" + " with a long \\\n" + // FIXME: We should look at the length of the last line of the token + // instead of the full token's length. + //" line */ \\\n" + " line */\\\n" + " A + B", + format("#define X \\\n" + " /* Macro comment with a long\n" + " line */ \\\n" + " A + B", + getLLVMStyleWithColumns(20))); + EXPECT_EQ("#define X \\\n" + " /* Macro comment \\\n" + " * with a long \\\n" + // FIXME: We should look at the length of the last line of the token + // instead of the full token's length. + //" * line */ \\\n" + " * line */\\\n" + " A + B", + format("#define X \\\n" + " /* Macro comment with a long line */ \\\n" + " A + B", + getLLVMStyleWithColumns(20))); +} + +TEST_F(FormatTest, CommentsInStaticInitializers) { + EXPECT_EQ( + "static SomeType type = { aaaaaaaaaaaaaaaaaaaa, /* comment */\n" + " aaaaaaaaaaaaaaaaaaaa /* comment */,\n" + " /* comment */ aaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaa, // comment\n" + " aaaaaaaaaaaaaaaaaaaa };", + format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa , /* comment */\n" + " aaaaaaaaaaaaaaaaaaaa /* comment */ ,\n" + " /* comment */ aaaaaaaaaaaaaaaaaaaa ,\n" + " aaaaaaaaaaaaaaaaaaaa , // comment\n" + " aaaaaaaaaaaaaaaaaaaa };")); + verifyFormat("static SomeType type = { aaaaaaaaaaa, // comment for aa...\n" + " bbbbbbbbbbb, ccccccccccc };"); + verifyFormat("static SomeType type = { aaaaaaaaaaa,\n" + " // comment for bb....\n" + " bbbbbbbbbbb, ccccccccccc };"); + verifyGoogleFormat( + "static SomeType type = { aaaaaaaaaaa, // comment for aa...\n" + " bbbbbbbbbbb, ccccccccccc };"); + verifyGoogleFormat("static SomeType type = { aaaaaaaaaaa,\n" + " // comment for bb....\n" + " bbbbbbbbbbb, ccccccccccc };"); + + verifyFormat("S s = { { a, b, c }, // Group #1\n" + " { d, e, f }, // Group #2\n" + " { g, h, i } }; // Group #3"); + verifyFormat("S s = { { // Group #1\n" + " a, b, c },\n" + " { // Group #2\n" + " d, e, f },\n" + " { // Group #3\n" + " g, h, i } };"); + + EXPECT_EQ("S s = {\n" + " // Some comment\n" + " a,\n" + "\n" + " // Comment after empty line\n" + " b\n" + "}", + format("S s = {\n" + " // Some comment\n" + " a,\n" + " \n" + " // Comment after empty line\n" + " b\n" + "}")); + EXPECT_EQ("S s = { a, b };", format("S s = {\n" + " a,\n" + "\n" + " b\n" + "};")); + verifyFormat("const uint8_t aaaaaaaaaaaaaaaaaaaaaa[0] = {\n" + " 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n" + " 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n" + " 0x00, 0x00, 0x00, 0x00 // comment\n" + "};"); +} + +//===----------------------------------------------------------------------===// +// Tests for classes, namespaces, etc. +//===----------------------------------------------------------------------===// + +TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { + verifyFormat("class A {\n};"); +} + +TEST_F(FormatTest, UnderstandsAccessSpecifiers) { + verifyFormat("class A {\n" + "public:\n" + "protected:\n" + "private:\n" + " void f() {}\n" + "};"); + verifyGoogleFormat("class A {\n" + " public:\n" + " protected:\n" + " private:\n" + " void f() {}\n" + "};"); +} + +TEST_F(FormatTest, SeparatesLogicalBlocks) { + EXPECT_EQ("class A {\n" + "public:\n" + " void f();\n" + "\n" + "private:\n" + " void g() {}\n" + " // test\n" + "protected:\n" + " int h;\n" + "};", + format("class A {\n" + "public:\n" + "void f();\n" + "private:\n" + "void g() {}\n" + "// test\n" + "protected:\n" + "int h;\n" + "};")); +} + +TEST_F(FormatTest, FormatsDerivedClass) { + verifyFormat("class A : public B {\n};"); + verifyFormat("class A : public ::B {\n};"); + + verifyFormat( + "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" + " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {\n" + "};\n"); + verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA :\n" + " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" + " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {\n" + "};\n"); + verifyFormat( + "class A : public B, public C, public D, public E, public F, public G {\n" + "};"); + verifyFormat("class AAAAAAAAAAAA : public B,\n" + " public C,\n" + " public D,\n" + " public E,\n" + " public F,\n" + " public G {\n" + "};"); +} + +TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { + verifyFormat("class A {\n} a, b;"); + verifyFormat("struct A {\n} a, b;"); + verifyFormat("union A {\n} a;"); +} + +TEST_F(FormatTest, FormatsEnum) { + verifyFormat("enum {\n" + " Zero,\n" + " One = 1,\n" + " Two = One + 1,\n" + " Three = (One + Two),\n" + " Four = (Zero && (One ^ Two)) | (One << Two),\n" + " Five = (One, Two, Three, Four, 5)\n" + "};"); + verifyFormat("enum Enum {\n" + "};"); + verifyFormat("enum {\n" + "};"); + verifyFormat("enum X E {\n} d;"); + verifyFormat("enum __attribute__((...)) E {\n} d;"); + verifyFormat("enum __declspec__((...)) E {\n} d;"); + verifyFormat("enum X f() {\n a();\n return 42;\n}"); +} + +TEST_F(FormatTest, FormatsBitfields) { + verifyFormat("struct Bitfields {\n" + " unsigned sClass : 8;\n" + " unsigned ValueKind : 2;\n" + "};"); +} + +TEST_F(FormatTest, FormatsNamespaces) { + verifyFormat("namespace some_namespace {\n" + "class A {\n};\n" + "void f() { f(); }\n" + "}"); + verifyFormat("namespace {\n" + "class A {\n};\n" + "void f() { f(); }\n" + "}"); + verifyFormat("inline namespace X {\n" + "class A {\n};\n" + "void f() { f(); }\n" + "}"); + verifyFormat("using namespace some_namespace;\n" + "class A {\n};\n" + "void f() { f(); }"); + + // This code is more common than we thought; if we + // layout this correctly the semicolon will go into + // its own line, which is undesireable. + verifyFormat("namespace {\n};"); + verifyFormat("namespace {\n" + "class A {\n" + "};\n" + "};"); +} + +TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); } + +TEST_F(FormatTest, FormatsInlineASM) { + verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); + verifyFormat( + "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" + " \"cpuid\\n\\t\"\n" + " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" + " : \"=a\" (*rEAX), \"=S\" (*rEBX), \"=c\" (*rECX), \"=d\" (*rEDX)\n" + " : \"a\"(value));"); +} + +TEST_F(FormatTest, FormatTryCatch) { + // FIXME: Handle try-catch explicitly in the UnwrappedLineParser, then we'll + // also not create single-line-blocks. + verifyFormat("try {\n" + " throw a * b;\n" + "}\n" + "catch (int a) {\n" + " // Do nothing.\n" + "}\n" + "catch (...) {\n" + " exit(42);\n" + "}"); + + // Function-level try statements. + verifyFormat("int f() try { return 4; }\n" + "catch (...) {\n" + " return 5;\n" + "}"); + verifyFormat("class A {\n" + " int a;\n" + " A() try : a(0) {}\n" + " catch (...) {\n" + " throw;\n" + " }\n" + "};\n"); +} + +TEST_F(FormatTest, FormatObjCTryCatch) { + verifyFormat("@try {\n" + " f();\n" + "}\n" + "@catch (NSException e) {\n" + " @throw;\n" + "}\n" + "@finally {\n" + " exit(42);\n" + "}"); +} + +TEST_F(FormatTest, StaticInitializers) { + verifyFormat("static SomeClass SC = { 1, 'a' };"); + + // FIXME: Format like enums if the static initializer does not fit on a line. + verifyFormat( + "static SomeClass WithALoooooooooooooooooooongName = {\n" + " 100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" + "};"); + + verifyFormat( + "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n" + " looooooooooooooooooooooooooooooooooongname,\n" + " looooooooooooooooooooooooooooooong };"); + // Allow bin-packing in static initializers as this would often lead to + // terrible results, e.g.: + verifyGoogleFormat( + "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n" + " looooooooooooooooooooooooooooooooooongname,\n" + " looooooooooooooooooooooooooooooong };"); +} + +TEST_F(FormatTest, NestedStaticInitializers) { + verifyFormat("static A x = { { {} } };\n"); + verifyFormat("static A x = { { { init1, init2, init3, init4 },\n" + " { init1, init2, init3, init4 } } };"); + + verifyFormat("somes Status::global_reps[3] = {\n" + " { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n" + " { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n" + " { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n" + "};"); + verifyGoogleFormat("somes Status::global_reps[3] = {\n" + " { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n" + " { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n" + " { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n" + "};"); + verifyFormat( + "CGRect cg_rect = { { rect.fLeft, rect.fTop },\n" + " { rect.fRight - rect.fLeft, rect.fBottom - rect.fTop" + " } };"); + + verifyFormat( + "SomeArrayOfSomeType a = { { { 1, 2, 3 }, { 1, 2, 3 },\n" + " { 111111111111111111111111111111,\n" + " 222222222222222222222222222222,\n" + " 333333333333333333333333333333 },\n" + " { 1, 2, 3 }, { 1, 2, 3 } } };"); + verifyFormat( + "SomeArrayOfSomeType a = { { { 1, 2, 3 } }, { { 1, 2, 3 } },\n" + " { { 111111111111111111111111111111,\n" + " 222222222222222222222222222222,\n" + " 333333333333333333333333333333 } },\n" + " { { 1, 2, 3 } }, { { 1, 2, 3 } } };"); + + // FIXME: We might at some point want to handle this similar to parameter + // lists, where we have an option to put each on a single line. + verifyFormat( + "struct {\n" + " unsigned bit;\n" + " const char *const name;\n" + "} kBitsToOs[] = { { kOsMac, \"Mac\" }, { kOsWin, \"Windows\" },\n" + " { kOsLinux, \"Linux\" }, { kOsCrOS, \"Chrome OS\" } };"); +} + +TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { + verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" + " \\\n" + " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); +} + +TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { + verifyFormat( + "virtual void\n" + "write(ELFWriter *writerrr, OwningPtr<FileOutputBuffer> &buffer) = 0;"); +} + +TEST_F(FormatTest, LayoutUnknownPPDirective) { + EXPECT_EQ("#123 \"A string literal\"", + format(" # 123 \"A string literal\"")); + EXPECT_EQ("#;", format("#;")); + verifyFormat("#\n;\n;\n;"); +} + +TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { + EXPECT_EQ("#line 42 \"test\"\n", + format("# \\\n line \\\n 42 \\\n \"test\"\n")); + EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", + getLLVMStyleWithColumns(12))); +} + +TEST_F(FormatTest, EndOfFileEndsPPDirective) { + EXPECT_EQ("#line 42 \"test\"", + format("# \\\n line \\\n 42 \\\n \"test\"")); + EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); +} + +TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { + verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); + verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); + verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); + // FIXME: We never break before the macro name. + verifyFormat("#define AA(\\\n B)", getLLVMStyleWithColumns(12)); + + verifyFormat("#define A A\n#define A A"); + verifyFormat("#define A(X) A\n#define A A"); + + verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); + verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); +} + +TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { + EXPECT_EQ("// somecomment\n" + "#include \"a.h\"\n" + "#define A( \\\n" + " A, B)\n" + "#include \"b.h\"\n" + "// somecomment\n", + format(" // somecomment\n" + " #include \"a.h\"\n" + "#define A(A,\\\n" + " B)\n" + " #include \"b.h\"\n" + " // somecomment\n", + getLLVMStyleWithColumns(13))); +} + +TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } + +TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { + EXPECT_EQ("#define A \\\n" + " c; \\\n" + " e;\n" + "f;", + format("#define A c; e;\n" + "f;", + getLLVMStyleWithColumns(14))); +} + +TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } + +TEST_F(FormatTest, LayoutSingleUnwrappedLineInMacro) { + EXPECT_EQ("# define A\\\n b;", + format("# define A b;", 11, 2, getLLVMStyleWithColumns(11))); +} + +TEST_F(FormatTest, MacroDefinitionInsideStatement) { + EXPECT_EQ("int x,\n" + "#define A\n" + " y;", + format("int x,\n#define A\ny;")); +} + +TEST_F(FormatTest, HashInMacroDefinition) { + verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); + verifyFormat("#define A \\\n" + " { \\\n" + " f(#c);\\\n" + " }", + getLLVMStyleWithColumns(11)); + + verifyFormat("#define A(X) \\\n" + " void function##X()", + getLLVMStyleWithColumns(22)); + + verifyFormat("#define A(a, b, c) \\\n" + " void a##b##c()", + getLLVMStyleWithColumns(22)); + + verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); +} + +TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { + verifyFormat("#define A (1)"); +} + +TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { + EXPECT_EQ("#define A b;", format("#define A \\\n" + " \\\n" + " b;", + getLLVMStyleWithColumns(25))); + EXPECT_EQ("#define A \\\n" + " \\\n" + " a; \\\n" + " b;", + format("#define A \\\n" + " \\\n" + " a; \\\n" + " b;", + getLLVMStyleWithColumns(11))); + EXPECT_EQ("#define A \\\n" + " a; \\\n" + " \\\n" + " b;", + format("#define A \\\n" + " a; \\\n" + " \\\n" + " b;", + getLLVMStyleWithColumns(11))); +} + +TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { + verifyFormat("#define A :"); + + // FIXME: Improve formatting of case labels in macros. + verifyFormat("#define SOMECASES \\\n" + " case 1: \\\n" + " case 2\n", + getLLVMStyleWithColumns(20)); + + verifyFormat("#define A template <typename T>"); + verifyFormat("#define STR(x) #x\n" + "f(STR(this_is_a_string_literal{));"); +} + +TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) { + EXPECT_EQ("{\n {\n#define A\n }\n}", format("{{\n#define A\n}}")); +} + +TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { + verifyFormat("{\n { a #c; }\n}"); +} + +TEST_F(FormatTest, FormatUnbalancedStructuralElements) { + EXPECT_EQ("#define A \\\n { \\\n {\nint i;", + format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); + EXPECT_EQ("#define A \\\n } \\\n }\nint i;", + format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); +} + +TEST_F(FormatTest, EscapedNewlineAtStartOfTokenInMacroDefinition) { + EXPECT_EQ( + "#define A \\\n int i; \\\n int j;", + format("#define A \\\nint i;\\\n int j;", getLLVMStyleWithColumns(11))); +} + +TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { + verifyFormat("#define A \\\n" + " int v( \\\n" + " a); \\\n" + " int i;", + getLLVMStyleWithColumns(11)); +} + +TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { + EXPECT_EQ( + "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" + " \\\n" + " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" + "\n" + "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" + " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", + format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" + "\\\n" + "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" + " \n" + " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" + " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); +} + +TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { + EXPECT_EQ("int\n" + "#define A\n" + "a;", + format("int\n#define A\na;")); + verifyFormat("functionCallTo(\n" + " someOtherFunction(\n" + " withSomeParameters, whichInSequence,\n" + " areLongerThanALine(andAnotherCall,\n" + "#define A B\n" + " withMoreParamters,\n" + " whichStronglyInfluenceTheLayout),\n" + " andMoreParameters),\n" + " trailing);", + getLLVMStyleWithColumns(69)); +} + +TEST_F(FormatTest, LayoutBlockInsideParens) { + EXPECT_EQ("functionCall({\n" + " int i;\n" + "});", + format(" functionCall ( {int i;} );")); +} + +TEST_F(FormatTest, LayoutBlockInsideStatement) { + EXPECT_EQ("SOME_MACRO { int i; }\n" + "int i;", + format(" SOME_MACRO {int i;} int i;")); +} + +TEST_F(FormatTest, LayoutNestedBlocks) { + verifyFormat("void AddOsStrings(unsigned bitmask) {\n" + " struct s {\n" + " int i;\n" + " };\n" + " s kBitsToOs[] = { { 10 } };\n" + " for (int i = 0; i < 10; ++i)\n" + " return;\n" + "}"); +} + +TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { + EXPECT_EQ("{}", format("{}")); + + // Negative test for enum. + verifyFormat("enum E {\n};"); + + // Note that when there's a missing ';', we still join... + verifyFormat("enum E {}"); +} + +//===----------------------------------------------------------------------===// +// Line break tests. +//===----------------------------------------------------------------------===// + +TEST_F(FormatTest, FormatsFunctionDefinition) { + verifyFormat("void f(int a, int b, int c, int d, int e, int f, int g," + " int h, int j, int f,\n" + " int c, int ddddddddddddd) {}"); +} + +TEST_F(FormatTest, FormatsAwesomeMethodCall) { + verifyFormat( + "SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" + " parameter, parameter, parameter)),\n" + " SecondLongCall(parameter));"); +} + +TEST_F(FormatTest, PreventConfusingIndents) { + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaaaaaaaaaaaaa);"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[\n" + " aaaaaaaaaaaaaaaaaaaaaaaa[\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa],\n" + " aaaaaaaaaaaaaaaaaaaaaaaa];"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" + " aaaaaaaaaaaaaaaaaaaaaaaa<\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" + " aaaaaaaaaaaaaaaaaaaaaaaa>;"); + verifyFormat("int a = bbbb && ccc && fffff(\n" + "#define A Just forcing a new line\n" + " ddd);"); +} + +TEST_F(FormatTest, ConstructorInitializers) { + verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); + verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", + getLLVMStyleWithColumns(45)); + verifyFormat("Constructor()\n" + " : Inttializer(FitsOnTheLine) {}", + getLLVMStyleWithColumns(44)); + verifyFormat("Constructor()\n" + " : Inttializer(FitsOnTheLine) {}", + getLLVMStyleWithColumns(43)); + + verifyFormat( + "SomeClass::Constructor()\n" + " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); + + verifyFormat( + "SomeClass::Constructor()\n" + " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); + verifyFormat( + "SomeClass::Constructor()\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); + + verifyFormat("Constructor()\n" + " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaaaaaaaaaaaa() {}"); + + verifyFormat("Constructor()\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); + + verifyFormat("Constructor(int Parameter = 0)\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); + + // Here a line could be saved by splitting the second initializer onto two + // lines, but that is not desireable. + verifyFormat("Constructor()\n" + " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" + " aaaaaaaaaaa(aaaaaaaaaaa),\n" + " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); + + FormatStyle OnePerLine = getLLVMStyle(); + OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; + verifyFormat("SomeClass::Constructor()\n" + " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", + OnePerLine); + verifyFormat("SomeClass::Constructor()\n" + " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" + " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", + OnePerLine); + verifyFormat("MyClass::MyClass(int var)\n" + " : some_var_(var), // 4 space indent\n" + " some_other_var_(var + 1) { // lined up\n" + "}", + OnePerLine); + verifyFormat("Constructor()\n" + " : aaaaa(aaaaaa),\n" + " aaaaa(aaaaaa),\n" + " aaaaa(aaaaaa),\n" + " aaaaa(aaaaaa),\n" + " aaaaa(aaaaaa) {}", + OnePerLine); + + // This test takes VERY long when memoization is broken. + OnePerLine.BinPackParameters = false; + std::string input = "Constructor()\n" + " : aaaa(a,\n"; + for (unsigned i = 0, e = 80; i != e; ++i) { + input += " a,\n"; + } + input += " a) {}"; + verifyFormat(input, OnePerLine); +} + +TEST_F(FormatTest, BreaksAsHighAsPossible) { + verifyFormat( + "void f() {\n" + " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" + " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" + " f();\n" + "}"); + verifyFormat("if (Intervals[i].getRange().getFirst() <\n" + " Intervals[i - 1].getRange().getLast()) {\n}"); +} + +TEST_F(FormatTest, BreaksDesireably) { + verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" + " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" + " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); + verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" + "}"); + + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); + + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); + + verifyFormat( + "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" + " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); + + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" + " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + + verifyFormat( + "void f() {\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" + "}"); + verifyFormat( + "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); + verifyFormat( + "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); + verifyFormat( + "aaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + + // This test case breaks on an incorrect memoization, i.e. an optimization not + // taking into account the StopAt value. + verifyFormat( + "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" + " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" + " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + + verifyFormat("{\n {\n {\n" + " Annotation.SpaceRequiredBefore =\n" + " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" + " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" + " }\n }\n}"); +} + +TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { + FormatStyle NoBinPacking = getGoogleStyle(); + NoBinPacking.BinPackParameters = false; + verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", + NoBinPacking); + verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", + NoBinPacking); + verifyFormat( + "aaaaaaaa(aaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" + " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", + NoBinPacking); + verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" + " .aaaaaaaaaaaaaaaaaa();", + NoBinPacking); + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);", + NoBinPacking); + + verifyFormat( + "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaa,\n" + " aaaaaaaaaaaa);", + NoBinPacking); + verifyFormat( + "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" + " ddddddddddddddddddddddddddddd),\n" + " test);", + NoBinPacking); + + verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;", + NoBinPacking); + verifyFormat("a(\"a\"\n" + " \"a\",\n" + " a);"); + + NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; + verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" + " aaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", + NoBinPacking); + verifyFormat( + "void f() {\n" + " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" + " .aaaaaaa();\n" + "}", + NoBinPacking); +} + +TEST_F(FormatTest, FormatsBuilderPattern) { + verifyFormat( + "return llvm::StringSwitch<Reference::Kind>(name)\n" + " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" + " .StartsWith(\".eh_frame\", ORDER_EH_FRAME).StartsWith(\".init\", ORDER_INIT)\n" + " .StartsWith(\".fini\", ORDER_FINI).StartsWith(\".hash\", ORDER_HASH)\n" + " .Default(ORDER_TEXT);\n"); + + verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" + " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); + verifyFormat( + "aaaaaaa->aaaaaaa\n" + " ->aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" + " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" + " aaaaaaaaaaaaaa);"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa = aaaaaa->aaaaaaaaaaaa()\n" + " ->aaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" + " ->aaaaaaaaaaaaaaaaa();"); +} + +TEST_F(FormatTest, DoesNotBreakTrailingAnnotation) { + verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" + " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); + verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" + " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); + verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" + " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); + verifyFormat( + "void aaaaaaaaaaaaaaaaaa()\n" + " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa));"); + verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " __attribute__((unused));"); + + // FIXME: This is bad indentation, but generally hard to distinguish from a + // function declaration. + verifyFormat( + "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + "GUARDED_BY(aaaaaaaaaaaa);"); +} + +TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { + verifyFormat( + "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" + " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); + verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" + " ccccccccccccccccccccccccc) {\n}"); + verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" + " ccccccccccccccccccccccccc) {\n}"); + verifyFormat( + "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" + " ccccccccccccccccccccccccc) {\n}"); + verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" + " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" + " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" + " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); + verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" + " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" + " aaaaaaaaaaaaaaa != aa) {\n}"); +} + +TEST_F(FormatTest, BreaksAfterAssignments) { + verifyFormat( + "unsigned Cost =\n" + " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" + " SI->getPointerAddressSpaceee());\n"); + verifyFormat( + "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" + " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); + + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa()\n" + " .aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); +} + +TEST_F(FormatTest, AlignsAfterAssignments) { + verifyFormat( + "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa;"); + verifyFormat( + "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa;"); + verifyFormat( + "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa;"); + verifyFormat( + "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa);"); + verifyFormat("double LooooooooooooooooooooooooongResult =\n" + " aaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaa +\n" + " aaaaaaaaaaaaaaaaaaaaaaaa;"); +} + +TEST_F(FormatTest, AlignsAfterReturn) { + verifyFormat( + "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa;"); + verifyFormat( + "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa);"); + verifyFormat( + "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" + " aaaaaaaaaaaaaaaaaaaaaa();"); + verifyFormat( + "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" + " aaaaaaaaaaaaaaaaaaaaaa());"); +} + +TEST_F(FormatTest, BreaksConditionalExpressions) { + verifyFormat( + "aaaa(aaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + verifyFormat( + "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" + " : aaaaaaaaaaaaa);"); + verifyFormat( + "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaa);"); + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " : aaaaaaaaaaaaaaaa;"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " ? aaaaaaaaaaaaaaa\n" + " : aaaaaaaaaaaaaaa;"); + verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" + " aaaaaaaaa\n" + " ? b\n" + " : c);"); + verifyFormat( + "unsigned Indent =\n" + " format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n" + " ? IndentForLevel[TheLine.Level]\n" + " : TheLine * 2,\n" + " TheLine.InPPDirective, PreviousEndOfLineColumn);", + getLLVMStyleWithColumns(70)); + + FormatStyle NoBinPacking = getLLVMStyle(); + NoBinPacking.BinPackParameters = false; + verifyFormat( + "void f() {\n" + " g(aaa,\n" + " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " ? aaaaaaaaaaaaaaa\n" + " : aaaaaaaaaaaaaaa);\n" + "}", + NoBinPacking); +} + +TEST_F(FormatTest, DeclarationsOfMultipleVariables) { + verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" + " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); + verifyFormat("bool a = true, b = false;"); + + verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" + " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" + " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); + verifyFormat( + "bool aaaaaaaaaaaaaaaaaaaaa =\n" + " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" + " d = e && f;"); + verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" + " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); + verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" + " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); + verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" + " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); + // FIXME: If multiple variables are defined, the "*" needs to move to the new + // line. Also fix indent for breaking after the type, this looks bad. + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" + " *b = bbbbbbbbbbbbbbbbbbb;"); + + // Not ideal, but pointer-with-type does not allow much here. + verifyGoogleFormat( + "aaaaaaaaa* a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" + " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;"); +} + +TEST_F(FormatTest, ConditionalExpressionsInBrackets) { + verifyFormat("arr[foo ? bar : baz];"); + verifyFormat("f()[foo ? bar : baz];"); + verifyFormat("(a + b)[foo ? bar : baz];"); + verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); +} + +TEST_F(FormatTest, AlignsStringLiterals) { + verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" + " \"short literal\");"); + verifyFormat( + "looooooooooooooooooooooooongFunction(\n" + " \"short literal\"\n" + " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); + verifyFormat("someFunction(\"Always break between multi-line\"\n" + " \" string literals\",\n" + " and, other, parameters);"); + EXPECT_EQ("fun + \"1243\" /* comment */\n" + " \"5678\";", + format("fun + \"1243\" /* comment */\n" + " \"5678\";", + getLLVMStyleWithColumns(28))); + EXPECT_EQ( + "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" + " \"aaaaaaaaaaaaaaaaaaaaa\"\n" + " \"aaaaaaaaaaaaaaaa\";", + format("aaaaaa =" + "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " + "aaaaaaaaaaaaaaaaaaaaa\" " + "\"aaaaaaaaaaaaaaaa\";")); + verifyFormat("a = a + \"a\"\n" + " \"a\"\n" + " \"a\";"); + + verifyFormat( + "#define LL_FORMAT \"ll\"\n" + "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" + " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); +} + +TEST_F(FormatTest, AlignsPipes) { + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" + " << aaaaaaaaaaaaaaaaaaaa;"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); + verifyFormat( + "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" + " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" + " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); + verifyFormat( + "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" + " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); + + verifyFormat("return out << \"somepacket = {\\n\"\n" + " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" + " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" + " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" + " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" + " << \"}\";"); + + verifyFormat( + "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" + " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" + " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" + " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" + " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); + verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" + " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); + + verifyFormat( + "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); +} + +TEST_F(FormatTest, UnderstandsEquals) { + verifyFormat( + "aaaaaaaaaaaaaaaaa =\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); + verifyFormat( + "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); + verifyFormat( + "if (a) {\n" + " f();\n" + "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" + "}"); + + verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" + " 100000000 + 10000000) {\n}"); +} + +TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { + verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" + " .looooooooooooooooooooooooooooooooooooooongFunction();"); + + verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" + " ->looooooooooooooooooooooooooooooooooooooongFunction();"); + + verifyFormat( + "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" + " Parameter2);"); + + verifyFormat( + "ShortObject->shortFunction(\n" + " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" + " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); + + verifyFormat("loooooooooooooongFunction(\n" + " LoooooooooooooongObject->looooooooooooooooongFunction());"); + + verifyFormat( + "function(LoooooooooooooooooooooooooooooooooooongObject\n" + " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); + + verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" + " .WillRepeatedly(Return(SomeValue));"); + verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)]\n" + " .insert(ccccccccccccccccccccccc);"); + verifyFormat( + "aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" + " .aaaaaaaaaaaaaaa(\n" + " aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); + verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" + "}"); + + // Here, it is not necessary to wrap at "." or "->". + verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" + " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); + verifyFormat( + "aaaaaaaaaaa->aaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); + + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); + verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" + " aaaaaaaaa()->aaaaaa()->aaaaa());"); + verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" + " aaaaaaaaa()->aaaaaa()->aaaaa());"); + + // FIXME: Should we break before .a()? + verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).a();"); + + FormatStyle NoBinPacking = getLLVMStyle(); + NoBinPacking.BinPackParameters = false; + verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" + " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" + " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", + NoBinPacking); +} + +TEST_F(FormatTest, WrapsTemplateDeclarations) { + verifyFormat("template <typename T>\n" + "virtual void loooooooooooongFunction(int Param1, int Param2);"); + verifyFormat( + "template <typename T>\n" + "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); + verifyFormat("template <typename T>\n" + "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" + " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); + verifyFormat( + "template <typename T>\n" + "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" + " int Paaaaaaaaaaaaaaaaaaaaram2);"); + verifyFormat( + "template <typename T>\n" + "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + verifyFormat("template <typename T>\n" + "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " int aaaaaaaaaaaaaaaaaaaaaa);"); + verifyFormat( + "template <typename T1, typename T2 = char, typename T3 = char,\n" + " typename T4 = char>\n" + "void f();"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + + verifyFormat("a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" + " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));"); +} + +TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); + + // FIXME: Should we have an extra indent after the second break? + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); + + // FIXME: Look into whether we should indent 4 from the start or 4 from + // "bbbbb..." here instead of what we are doing now. + verifyFormat( + "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" + " cccccccccccccccccccccccccccccccccccccccccccccc());"); + + // Breaking at nested name specifiers is generally not desirable. + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaa);"); + + verifyFormat( + "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaaaaaaaaaaaaaaaaa);", + getLLVMStyleWithColumns(74)); + + verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); +} + +TEST_F(FormatTest, UnderstandsTemplateParameters) { + verifyFormat("A<int> a;"); + verifyFormat("A<A<A<int> > > a;"); + verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); + verifyFormat("bool x = a < 1 || 2 > a;"); + verifyFormat("bool x = 5 < f<int>();"); + verifyFormat("bool x = f<int>() > 5;"); + verifyFormat("bool x = 5 < a<int>::x;"); + verifyFormat("bool x = a < 4 ? a > 2 : false;"); + verifyFormat("bool x = f() ? a < 2 : a > 2;"); + + verifyGoogleFormat("A<A<int>> a;"); + verifyGoogleFormat("A<A<A<int>>> a;"); + verifyGoogleFormat("A<A<A<A<int>>>> a;"); + verifyGoogleFormat("A<A<int> > a;"); + verifyGoogleFormat("A<A<A<int> > > a;"); + verifyGoogleFormat("A<A<A<A<int> > > > a;"); + EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); + EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); + + verifyFormat("test >> a >> b;"); + verifyFormat("test << a >> b;"); + + verifyFormat("f<int>();"); + verifyFormat("template <typename T> void f() {}"); +} + +TEST_F(FormatTest, UnderstandsBinaryOperators) { + verifyFormat("COMPARE(a, ==, b);"); +} + +TEST_F(FormatTest, UnderstandsPointersToMembers) { + verifyFormat("int A::*x;"); + // FIXME: Recognize pointers to member functions. + //verifyFormat("int (S::*func)(void *);"); + verifyFormat("int(S::*func)(void *);"); + verifyFormat("(a->*f)();"); + verifyFormat("a->*x;"); + verifyFormat("(a.*f)();"); + verifyFormat("((*a).*f)();"); + verifyFormat("a.*x;"); +} + +TEST_F(FormatTest, UnderstandsUnaryOperators) { + verifyFormat("int a = -2;"); + verifyFormat("f(-1, -2, -3);"); + verifyFormat("a[-1] = 5;"); + verifyFormat("int a = 5 + -2;"); + verifyFormat("if (i == -1) {\n}"); + verifyFormat("if (i != -1) {\n}"); + verifyFormat("if (i > -1) {\n}"); + verifyFormat("if (i < -1) {\n}"); + verifyFormat("++(a->f());"); + verifyFormat("--(a->f());"); + verifyFormat("(a->f())++;"); + verifyFormat("a[42]++;"); + verifyFormat("if (!(a->f())) {\n}"); + + verifyFormat("a-- > b;"); + verifyFormat("b ? -a : c;"); + verifyFormat("n * sizeof char16;"); + verifyFormat("n * alignof char16;"); + verifyFormat("sizeof(char);"); + verifyFormat("alignof(char);"); + + verifyFormat("return -1;"); + verifyFormat("switch (a) {\n" + "case -1:\n" + " break;\n" + "}"); + verifyFormat("#define X -1"); + verifyFormat("#define X -kConstant"); + + verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { -5, +3 };"); + verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { +5, -3 };"); + + verifyFormat("int a = /* confusing comment */ -1;"); + // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. + verifyFormat("int a = i /* confusing comment */++;"); +} + +TEST_F(FormatTest, UndestandsOverloadedOperators) { + verifyFormat("bool operator<();"); + verifyFormat("bool operator>();"); + verifyFormat("bool operator=();"); + verifyFormat("bool operator==();"); + verifyFormat("bool operator!=();"); + verifyFormat("int operator+();"); + verifyFormat("int operator++();"); + verifyFormat("bool operator();"); + verifyFormat("bool operator()();"); + verifyFormat("bool operator[]();"); + verifyFormat("operator bool();"); + verifyFormat("operator int();"); + verifyFormat("operator void *();"); + verifyFormat("operator SomeType<int>();"); + verifyFormat("operator SomeType<int, int>();"); + verifyFormat("operator SomeType<SomeType<int> >();"); + verifyFormat("void *operator new(std::size_t size);"); + verifyFormat("void *operator new[](std::size_t size);"); + verifyFormat("void operator delete(void *ptr);"); + verifyFormat("void operator delete[](void *ptr);"); + + verifyFormat( + "ostream &operator<<(ostream &OutputStream,\n" + " SomeReallyLongType WithSomeReallyLongValue);"); + + verifyGoogleFormat("operator void*();"); + verifyGoogleFormat("operator SomeType<SomeType<int>>();"); +} + +TEST_F(FormatTest, UnderstandsNewAndDelete) { + verifyFormat("void f() {\n" + " A *a = new A;\n" + " A *a = new (placement) A;\n" + " delete a;\n" + " delete (A *)a;\n" + "}"); +} + +TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { + verifyFormat("int *f(int *a) {}"); + verifyFormat("int main(int argc, char **argv) {}"); + verifyFormat("Test::Test(int b) : a(b * b) {}"); + verifyIndependentOfContext("f(a, *a);"); + verifyFormat("void g() { f(*a); }"); + verifyIndependentOfContext("int a = b * 10;"); + verifyIndependentOfContext("int a = 10 * b;"); + verifyIndependentOfContext("int a = b * c;"); + verifyIndependentOfContext("int a += b * c;"); + verifyIndependentOfContext("int a -= b * c;"); + verifyIndependentOfContext("int a *= b * c;"); + verifyIndependentOfContext("int a /= b * c;"); + verifyIndependentOfContext("int a = *b;"); + verifyIndependentOfContext("int a = *b * c;"); + verifyIndependentOfContext("int a = b * *c;"); + verifyIndependentOfContext("return 10 * b;"); + verifyIndependentOfContext("return *b * *c;"); + verifyIndependentOfContext("return a & ~b;"); + verifyIndependentOfContext("f(b ? *c : *d);"); + verifyIndependentOfContext("int a = b ? *c : *d;"); + verifyIndependentOfContext("*b = a;"); + verifyIndependentOfContext("a * ~b;"); + verifyIndependentOfContext("a * !b;"); + verifyIndependentOfContext("a * +b;"); + verifyIndependentOfContext("a * -b;"); + verifyIndependentOfContext("a * ++b;"); + verifyIndependentOfContext("a * --b;"); + verifyIndependentOfContext("a[4] * b;"); + verifyIndependentOfContext("a[a * a] = 1;"); + verifyIndependentOfContext("f() * b;"); + verifyIndependentOfContext("a * [self dostuff];"); + verifyIndependentOfContext("int x = a * (a + b);"); + verifyIndependentOfContext("(a *)(a + b);"); + verifyIndependentOfContext("int *pa = (int *)&a;"); + verifyIndependentOfContext("return sizeof(int **);"); + verifyIndependentOfContext("return sizeof(int ******);"); + verifyIndependentOfContext("return (int **&)a;"); + verifyFormat("void f(Type (*parameter)[10]) {}"); + verifyGoogleFormat("return sizeof(int**);"); + verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); + verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); + // FIXME: The newline is wrong. + verifyFormat("auto a = [](int **&, int ***) {}\n;"); + + verifyIndependentOfContext("InvalidRegions[*R] = 0;"); + + verifyIndependentOfContext("A<int *> a;"); + verifyIndependentOfContext("A<int **> a;"); + verifyIndependentOfContext("A<int *, int *> a;"); + verifyIndependentOfContext( + "const char *const p = reinterpret_cast<const char *const>(q);"); + verifyIndependentOfContext("A<int **, int **> a;"); + verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); + verifyFormat("for (char **a = b; *a; ++a) {\n}"); + + verifyFormat( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); + + verifyGoogleFormat("int main(int argc, char** argv) {}"); + verifyGoogleFormat("A<int*> a;"); + verifyGoogleFormat("A<int**> a;"); + verifyGoogleFormat("A<int*, int*> a;"); + verifyGoogleFormat("A<int**, int**> a;"); + verifyGoogleFormat("f(b ? *c : *d);"); + verifyGoogleFormat("int a = b ? *c : *d;"); + verifyGoogleFormat("Type* t = **x;"); + verifyGoogleFormat("Type* t = *++*x;"); + verifyGoogleFormat("*++*x;"); + verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); + verifyGoogleFormat("Type* t = x++ * y;"); + verifyGoogleFormat( + "const char* const p = reinterpret_cast<const char* const>(q);"); + + verifyIndependentOfContext("a = *(x + y);"); + verifyIndependentOfContext("a = &(x + y);"); + verifyIndependentOfContext("*(x + y).call();"); + verifyIndependentOfContext("&(x + y)->call();"); + verifyFormat("void f() { &(*I).first; }"); + + verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); + verifyFormat( + "int *MyValues = {\n" + " *A, // Operator detection might be confused by the '{'\n" + " *BB // Operator detection might be confused by previous comment\n" + "};"); + + verifyIndependentOfContext("if (int *a = &b)"); + verifyIndependentOfContext("if (int &a = *b)"); + verifyIndependentOfContext("if (a & b[i])"); + verifyIndependentOfContext("if (a::b::c::d & b[i])"); + verifyIndependentOfContext("if (*b[i])"); + verifyIndependentOfContext("if (int *a = (&b))"); + verifyIndependentOfContext("while (int *a = &b)"); + verifyFormat("void f() {\n" + " for (const int &v : Values) {\n" + " }\n" + "}"); + verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); + verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); + + verifyIndependentOfContext("A = new SomeType *[Length];"); + verifyIndependentOfContext("A = new SomeType *[Length]();"); + verifyGoogleFormat("A = new SomeType* [Length]();"); + verifyGoogleFormat("A = new SomeType* [Length];"); +} + +TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { + EXPECT_EQ("int *a;\n" + "int *a;\n" + "int *a;", + format("int *a;\n" + "int* a;\n" + "int *a;", + getGoogleStyle())); + EXPECT_EQ("int* a;\n" + "int* a;\n" + "int* a;", + format("int* a;\n" + "int* a;\n" + "int *a;", + getGoogleStyle())); + EXPECT_EQ("int *a;\n" + "int *a;\n" + "int *a;", + format("int *a;\n" + "int * a;\n" + "int * a;", + getGoogleStyle())); +} + +TEST_F(FormatTest, UnderstandsRvalueReferences) { + verifyFormat("int f(int &&a) {}"); + verifyFormat("int f(int a, char &&b) {}"); + verifyFormat("void f() { int &&a = b; }"); + verifyGoogleFormat("int f(int a, char&& b) {}"); + verifyGoogleFormat("void f() { int&& a = b; }"); + + // FIXME: These require somewhat deeper changes in template arguments + // formatting. + // verifyIndependentOfContext("A<int &&> a;"); + // verifyIndependentOfContext("A<int &&, int &&> a;"); + // verifyGoogleFormat("A<int&&> a;"); + // verifyGoogleFormat("A<int&&, int&&> a;"); +} + +TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { + verifyFormat("void f() {\n" + " x[aaaaaaaaa -\n" + " b] = 23;\n" + "}", + getLLVMStyleWithColumns(15)); +} + +TEST_F(FormatTest, FormatsCasts) { + verifyFormat("Type *A = static_cast<Type *>(P);"); + verifyFormat("Type *A = (Type *)P;"); + verifyFormat("Type *A = (vector<Type *, int *>)P;"); + verifyFormat("int a = (int)(2.0f);"); + + // FIXME: These also need to be identified. + verifyFormat("int a = (int) 2.0f;"); + verifyFormat("int a = (int) * b;"); + + // These are not casts. + verifyFormat("void f(int *) {}"); + verifyFormat("f(foo)->b;"); + verifyFormat("f(foo).b;"); + verifyFormat("f(foo)(b);"); + verifyFormat("f(foo)[b];"); + verifyFormat("[](foo) { return 4; }(bar)];"); + verifyFormat("(*funptr)(foo)[4];"); + verifyFormat("funptrs[4](foo)[4];"); + verifyFormat("void f(int *);"); + verifyFormat("void f(int *) = 0;"); + verifyFormat("void f(SmallVector<int>) {}"); + verifyFormat("void f(SmallVector<int>);"); + verifyFormat("void f(SmallVector<int>) = 0;"); + verifyFormat("void f(int i = (kValue) * kMask) {}"); + verifyFormat("void f(int i = (kA * kB) & kMask) {}"); + verifyFormat("int a = sizeof(int) * b;"); + verifyFormat("int a = alignof(int) * b;"); + + // These are not casts, but at some point were confused with casts. + verifyFormat("virtual void foo(int *) override;"); + verifyFormat("virtual void foo(char &) const;"); + verifyFormat("virtual void foo(int *a, char *) const;"); + verifyFormat("int a = sizeof(int *) + b;"); + verifyFormat("int a = alignof(int *) + b;"); +} + +TEST_F(FormatTest, FormatsFunctionTypes) { + verifyFormat("A<bool()> a;"); + verifyFormat("A<SomeType()> a;"); + verifyFormat("A<void(*)(int, std::string)> a;"); + verifyFormat("A<void *(int)>;"); + verifyFormat("void *(*a)(int *, SomeType *);"); + + // FIXME: Inconsistent. + verifyFormat("int (*func)(void *);"); + verifyFormat("void f() { int(*func)(void *); }"); + + verifyGoogleFormat("A<void*(int*, SomeType*)>;"); + verifyGoogleFormat("void* (*a)(int);"); +} + +TEST_F(FormatTest, BreaksLongDeclarations) { + verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" + " int LoooooooooooooooooooongParam2) {}"); + verifyFormat( + "TypeSpecDecl *\n" + "TypeSpecDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,\n" + " IdentifierIn *II, Type *T) {}"); + verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" + "ReallyReallyLongFunctionName(\n" + " const std::string &SomeParameter,\n" + " const SomeType<string, SomeOtherTemplateParameter> &\n" + " ReallyReallyLongParameterName,\n" + " const SomeType<string, SomeOtherTemplateParameter> &\n" + " AnotherLongParameterName) {}"); + verifyFormat( + "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" + "aaaaaaaaaaaaaaaaaaaaaaa;"); + + verifyGoogleFormat( + "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" + " SourceLocation L) {}"); + verifyGoogleFormat( + "some_namespace::LongReturnType\n" + "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" + " int first_long_parameter, int second_parameter) {}"); + + verifyGoogleFormat("template <typename T>\n" + "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" + "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); + verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" + " int aaaaaaaaaaaaaaaaaaaaaaa);"); +} + +TEST_F(FormatTest, LineStartsWithSpecialCharacter) { + verifyFormat("(a)->b();"); + verifyFormat("--a;"); +} + +TEST_F(FormatTest, HandlesIncludeDirectives) { + verifyFormat("#include <string>\n" + "#include <a/b/c.h>\n" + "#include \"a/b/string\"\n" + "#include \"string.h\"\n" + "#include \"string.h\"\n" + "#include <a-a>\n" + "#include < path with space >\n" + "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"", + getLLVMStyleWithColumns(35)); + + verifyFormat("#import <string>"); + verifyFormat("#import <a/b/c.h>"); + verifyFormat("#import \"a/b/string\""); + verifyFormat("#import \"string.h\""); + verifyFormat("#import \"string.h\""); +} + +//===----------------------------------------------------------------------===// +// Error recovery tests. +//===----------------------------------------------------------------------===// + +TEST_F(FormatTest, IncompleteParameterLists) { + FormatStyle NoBinPacking = getLLVMStyle(); + NoBinPacking.BinPackParameters = false; + verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" + " double *min_x,\n" + " double *max_x,\n" + " double *min_y,\n" + " double *max_y,\n" + " double *min_z,\n" + " double *max_z, ) {}", + NoBinPacking); +} + +TEST_F(FormatTest, IncorrectCodeTrailingStuff) { + verifyFormat("void f() { return; }\n42"); + verifyFormat("void f() {\n" + " if (0)\n" + " return;\n" + "}\n" + "42"); + verifyFormat("void f() { return }\n42"); + verifyFormat("void f() {\n" + " if (0)\n" + " return\n" + "}\n" + "42"); +} + +TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { + EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); + EXPECT_EQ("void f() {\n" + " if (a)\n" + " return\n" + "}", + format("void f ( ) { if ( a ) return }")); + EXPECT_EQ("namespace N { void f() }", format("namespace N { void f() }")); + EXPECT_EQ("namespace N {\n" + "void f() {}\n" + "void g()\n" + "}", + format("namespace N { void f( ) { } void g( ) }")); +} + +TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { + verifyFormat("int aaaaaaaa =\n" + " // Overlylongcomment\n" + " b;", + getLLVMStyleWithColumns(20)); + verifyFormat("function(\n" + " ShortArgument,\n" + " LoooooooooooongArgument);\n", + getLLVMStyleWithColumns(20)); +} + +TEST_F(FormatTest, IncorrectAccessSpecifier) { + verifyFormat("public:"); + verifyFormat("class A {\n" + "public\n" + " void f() {}\n" + "};"); + verifyFormat("public\n" + "int qwerty;"); + verifyFormat("public\n" + "B {}"); + verifyFormat("public\n" + "{}"); + verifyFormat("public\n" + "B { int x; }"); +} + +TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { + verifyFormat("{"); + verifyFormat("#})"); +} + +TEST_F(FormatTest, IncorrectCodeDoNoWhile) { + verifyFormat("do {\n}"); + verifyFormat("do {\n}\n" + "f();"); + verifyFormat("do {\n}\n" + "wheeee(fun);"); + verifyFormat("do {\n" + " f();\n" + "}"); +} + +TEST_F(FormatTest, IncorrectCodeMissingParens) { + verifyFormat("if {\n foo;\n foo();\n}"); + verifyFormat("switch {\n foo;\n foo();\n}"); + verifyFormat("for {\n foo;\n foo();\n}"); + verifyFormat("while {\n foo;\n foo();\n}"); + verifyFormat("do {\n foo;\n foo();\n} while;"); +} + +TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { + verifyFormat("namespace {\n" + "class Foo { Foo ( }; } // comment"); +} + +TEST_F(FormatTest, IncorrectCodeErrorDetection) { + EXPECT_EQ("{\n{}\n", format("{\n{\n}\n")); + EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); + EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); + EXPECT_EQ("{\n {}\n }\n}\n", format("{\n {\n }\n }\n}\n")); + + EXPECT_EQ("{\n" + " {\n" + " breakme(\n" + " qwe);\n" + "}\n", + format("{\n" + " {\n" + " breakme(qwe);\n" + "}\n", + getLLVMStyleWithColumns(10))); +} + +TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { + verifyFormat("int x = {\n" + " avariable,\n" + " b(alongervariable)\n" + "};", + getLLVMStyleWithColumns(25)); +} + +TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { + verifyFormat("return (a)(b) { 1, 2, 3 };"); +} + +TEST_F(FormatTest, LayoutTokensFollowingBlockInParentheses) { + // FIXME: This is bad, find a better and more generic solution. + verifyFormat( + "Aaa({\n" + " int i;\n" + "},\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" + " ccccccccccccccccc));"); +} + +TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { + verifyFormat("void f() { return 42; }"); + verifyFormat("void f() {\n" + " // Comment\n" + "}"); + verifyFormat("{\n" + "#error {\n" + " int a;\n" + "}"); + verifyFormat("{\n" + " int a;\n" + "#error {\n" + "}"); + + verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); + verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); + + verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); + verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); +} + +TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { + // Elaborate type variable declarations. + verifyFormat("struct foo a = { bar };\nint n;"); + verifyFormat("class foo a = { bar };\nint n;"); + verifyFormat("union foo a = { bar };\nint n;"); + + // Elaborate types inside function definitions. + verifyFormat("struct foo f() {}\nint n;"); + verifyFormat("class foo f() {}\nint n;"); + verifyFormat("union foo f() {}\nint n;"); + + // Templates. + verifyFormat("template <class X> void f() {}\nint n;"); + verifyFormat("template <struct X> void f() {}\nint n;"); + verifyFormat("template <union X> void f() {}\nint n;"); + + // Actual definitions... + verifyFormat("struct {\n} n;"); + verifyFormat( + "template <template <class T, class Y>, class Z> class X {\n} n;"); + verifyFormat("union Z {\n int n;\n} x;"); + verifyFormat("class MACRO Z {\n} n;"); + verifyFormat("class MACRO(X) Z {\n} n;"); + verifyFormat("class __attribute__(X) Z {\n} n;"); + verifyFormat("class __declspec(X) Z {\n} n;"); + verifyFormat("class A##B##C {\n} n;"); + + // Redefinition from nested context: + verifyFormat("class A::B::C {\n} n;"); + + // Template definitions. + // FIXME: This is still incorrectly handled at the formatter side. + verifyFormat("template <> struct X < 15, i < 3 && 42 < 50 && 33<28> {\n};"); + + // FIXME: + // This now gets parsed incorrectly as class definition. + // verifyFormat("class A<int> f() {\n}\nint n;"); + + // Elaborate types where incorrectly parsing the structural element would + // break the indent. + verifyFormat("if (true)\n" + " class X x;\n" + "else\n" + " f();\n"); + + // This is simply incomplete. Formatting is not important, but must not crash. + verifyFormat("class A:"); +} + +TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { + verifyFormat("#error Leave all white!!!!! space* alone!\n"); + verifyFormat("#warning Leave all white!!!!! space* alone!\n"); + EXPECT_EQ("#error 1", format(" # error 1")); + EXPECT_EQ("#warning 1", format(" # warning 1")); +} + +TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { + FormatStyle AllowsMergedIf = getGoogleStyle(); + AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true; + verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); + verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); + verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); + EXPECT_EQ("if (true) return 42;", + format("if (true)\nreturn 42;", AllowsMergedIf)); + FormatStyle ShortMergedIf = AllowsMergedIf; + ShortMergedIf.ColumnLimit = 25; + verifyFormat("#define A \\\n" + " if (true) return 42;", + ShortMergedIf); + verifyFormat("#define A \\\n" + " f(); \\\n" + " if (true)\n" + "#define B", + ShortMergedIf); + verifyFormat("#define A \\\n" + " f(); \\\n" + " if (true)\n" + "g();", + ShortMergedIf); + verifyFormat("{\n" + "#ifdef A\n" + " // Comment\n" + " if (true) continue;\n" + "#endif\n" + " // Comment\n" + " if (true) continue;", + ShortMergedIf); +} + +TEST_F(FormatTest, BlockCommentsInControlLoops) { + verifyFormat("if (0) /* a comment in a strange place */ {\n" + " f();\n" + "}"); + verifyFormat("if (0) /* a comment in a strange place */ {\n" + " f();\n" + "} /* another comment */ else /* comment #3 */ {\n" + " g();\n" + "}"); + verifyFormat("while (0) /* a comment in a strange place */ {\n" + " f();\n" + "}"); + verifyFormat("for (;;) /* a comment in a strange place */ {\n" + " f();\n" + "}"); + verifyFormat("do /* a comment in a strange place */ {\n" + " f();\n" + "} /* another comment */ while (0);"); +} + +TEST_F(FormatTest, BlockComments) { + EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */", + format("/* *//* */ /* */\n/* *//* */ /* */")); + EXPECT_EQ("/* */ a /* */ b;", format(" /* */ a/* */ b;")); + EXPECT_EQ("#define A /*123*/\\\n" + " b\n" + "/* */\n" + "someCall(\n" + " parameter);", + format("#define A /*123*/ b\n" + "/* */\n" + "someCall(parameter);", + getLLVMStyleWithColumns(15))); + + EXPECT_EQ("#define A\n" + "/* */ someCall(\n" + " parameter);", + format("#define A\n" + "/* */someCall(parameter);", + getLLVMStyleWithColumns(15))); + + FormatStyle NoBinPacking = getLLVMStyle(); + NoBinPacking.BinPackParameters = false; + EXPECT_EQ("someFunction(1, /* comment 1 */\n" + " 2, /* comment 2 */\n" + " 3, /* comment 3 */\n" + " aaaa,\n" + " bbbb);", + format("someFunction (1, /* comment 1 */\n" + " 2, /* comment 2 */ \n" + " 3, /* comment 3 */\n" + "aaaa, bbbb );", + NoBinPacking)); + verifyFormat( + "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); + EXPECT_EQ( + "bool aaaaaaaaaaaaa = /* trailing comment */\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;", + format( + "bool aaaaaaaaaaaaa = /* trailing comment */\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" + " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;")); + EXPECT_EQ( + "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n" + "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n" + "int cccccccccccccccccccccccccccccc; /* comment */\n", + format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n" + "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n" + "int cccccccccccccccccccccccccccccc; /* comment */\n")); +} + +TEST_F(FormatTest, BlockCommentsInMacros) { + EXPECT_EQ("#define A \\\n" + " { \\\n" + " /* one line */ \\\n" + " someCall();", + format("#define A { \\\n" + " /* one line */ \\\n" + " someCall();", + getLLVMStyleWithColumns(20))); + EXPECT_EQ("#define A \\\n" + " { \\\n" + " /* previous */ \\\n" + " /* one line */ \\\n" + " someCall();", + format("#define A { \\\n" + " /* previous */ \\\n" + " /* one line */ \\\n" + " someCall();", + getLLVMStyleWithColumns(20))); +} + +TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) { + // FIXME: This is not what we want... + verifyFormat("{\n" + "// a" + "// b"); +} + +TEST_F(FormatTest, FormatStarDependingOnContext) { + verifyFormat("void f(int *a);"); + verifyFormat("void f() { f(fint * b); }"); + verifyFormat("class A {\n void f(int *a);\n};"); + verifyFormat("class A {\n int *a;\n};"); + verifyFormat("namespace a {\n" + "namespace b {\n" + "class A {\n" + " void f() {}\n" + " int *a;\n" + "};\n" + "}\n" + "}"); +} + +TEST_F(FormatTest, SpecialTokensAtEndOfLine) { + verifyFormat("while"); + verifyFormat("operator"); +} + +//===----------------------------------------------------------------------===// +// Objective-C tests. +//===----------------------------------------------------------------------===// + +TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { + verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); + EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", + format("-(NSUInteger)indexOfObject:(id)anObject;")); + EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); + EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); + EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", + format("-(NSInteger)Method3:(id)anObject;")); + EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", + format("-(NSInteger)Method4:(id)anObject;")); + EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", + format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); + EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", + format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); + EXPECT_EQ( + "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;", + format( + "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;")); + + // Very long objectiveC method declaration. + verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" + " inRange:(NSRange)range\n" + " outRange:(NSRange)out_range\n" + " outRange1:(NSRange)out_range1\n" + " outRange2:(NSRange)out_range2\n" + " outRange3:(NSRange)out_range3\n" + " outRange4:(NSRange)out_range4\n" + " outRange5:(NSRange)out_range5\n" + " outRange6:(NSRange)out_range6\n" + " outRange7:(NSRange)out_range7\n" + " outRange8:(NSRange)out_range8\n" + " outRange9:(NSRange)out_range9;"); + + verifyFormat("- (int)sum:(vector<int>)numbers;"); + verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); + // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC + // protocol lists (but not for template classes): + //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); + + verifyFormat("- (int(*)())foo:(int(*)())f;"); + verifyGoogleFormat("- (int(*)())foo:(int(*)())foo;"); + + // If there's no return type (very rare in practice!), LLVM and Google style + // agree. + verifyFormat("- foo;"); + verifyFormat("- foo:(int)f;"); + verifyGoogleFormat("- foo:(int)foo;"); +} + +TEST_F(FormatTest, FormatObjCBlocks) { + verifyFormat("int (^Block)(int, int);"); + verifyFormat("int (^Block1)(int, int) = ^(int i, int j)"); +} + +TEST_F(FormatTest, FormatObjCInterface) { + verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n" + "@public\n" + " int field1;\n" + "@protected\n" + " int field2;\n" + "@private\n" + " int field3;\n" + "@package\n" + " int field4;\n" + "}\n" + "+ (id)init;\n" + "@end"); + + verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n" + " @public\n" + " int field1;\n" + " @protected\n" + " int field2;\n" + " @private\n" + " int field3;\n" + " @package\n" + " int field4;\n" + "}\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface /* wait for it */ Foo\n" + "+ (id)init;\n" + "// Look, a comment!\n" + "- (int)answerWith:(int)i;\n" + "@end"); + + verifyFormat("@interface Foo\n" + "@end\n" + "@interface Bar\n" + "@end"); + + verifyFormat("@interface Foo : Bar\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n" + "+ (id)init;\n" + "@end"); + + verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo (HackStuff)\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo ()\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n" + "+ (id)init;\n" + "@end"); + + verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo {\n" + " int _i;\n" + "}\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo : Bar {\n" + " int _i;\n" + "}\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo : Bar <Baz, Quux> {\n" + " int _i;\n" + "}\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo (HackStuff) {\n" + " int _i;\n" + "}\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo () {\n" + " int _i;\n" + "}\n" + "+ (id)init;\n" + "@end"); + + verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n" + " int _i;\n" + "}\n" + "+ (id)init;\n" + "@end"); +} + +TEST_F(FormatTest, FormatObjCImplementation) { + verifyFormat("@implementation Foo : NSObject {\n" + "@public\n" + " int field1;\n" + "@protected\n" + " int field2;\n" + "@private\n" + " int field3;\n" + "@package\n" + " int field4;\n" + "}\n" + "+ (id)init {\n}\n" + "@end"); + + verifyGoogleFormat("@implementation Foo : NSObject {\n" + " @public\n" + " int field1;\n" + " @protected\n" + " int field2;\n" + " @private\n" + " int field3;\n" + " @package\n" + " int field4;\n" + "}\n" + "+ (id)init {\n}\n" + "@end"); + + verifyFormat("@implementation Foo\n" + "+ (id)init {\n" + " if (true)\n" + " return nil;\n" + "}\n" + "// Look, a comment!\n" + "- (int)answerWith:(int)i {\n" + " return i;\n" + "}\n" + "+ (int)answerWith:(int)i {\n" + " return i;\n" + "}\n" + "@end"); + + verifyFormat("@implementation Foo\n" + "@end\n" + "@implementation Bar\n" + "@end"); + + verifyFormat("@implementation Foo : Bar\n" + "+ (id)init {\n}\n" + "- (void)foo {\n}\n" + "@end"); + + verifyFormat("@implementation Foo {\n" + " int _i;\n" + "}\n" + "+ (id)init {\n}\n" + "@end"); + + verifyFormat("@implementation Foo : Bar {\n" + " int _i;\n" + "}\n" + "+ (id)init {\n}\n" + "@end"); + + verifyFormat("@implementation Foo (HackStuff)\n" + "+ (id)init {\n}\n" + "@end"); +} + +TEST_F(FormatTest, FormatObjCProtocol) { + verifyFormat("@protocol Foo\n" + "@property(weak) id delegate;\n" + "- (NSUInteger)numberOfThings;\n" + "@end"); + + verifyFormat("@protocol MyProtocol <NSObject>\n" + "- (NSUInteger)numberOfThings;\n" + "@end"); + + verifyGoogleFormat("@protocol MyProtocol<NSObject>\n" + "- (NSUInteger)numberOfThings;\n" + "@end"); + + verifyFormat("@protocol Foo;\n" + "@protocol Bar;\n"); + + verifyFormat("@protocol Foo\n" + "@end\n" + "@protocol Bar\n" + "@end"); + + verifyFormat("@protocol myProtocol\n" + "- (void)mandatoryWithInt:(int)i;\n" + "@optional\n" + "- (void)optional;\n" + "@required\n" + "- (void)required;\n" + "@optional\n" + "@property(assign) int madProp;\n" + "@end\n"); +} + +TEST_F(FormatTest, FormatObjCMethodDeclarations) { + verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n" + " rect:(NSRect)theRect\n" + " interval:(float)theInterval {\n" + "}"); + verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n" + " longKeyword:(NSRect)theRect\n" + " evenLongerKeyword:(float)theInterval\n" + " error:(NSError **)theError {\n" + "}"); +} + +TEST_F(FormatTest, FormatObjCMethodExpr) { + verifyFormat("[foo bar:baz];"); + verifyFormat("return [foo bar:baz];"); + verifyFormat("f([foo bar:baz]);"); + verifyFormat("f(2, [foo bar:baz]);"); + verifyFormat("f(2, a ? b : c);"); + verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];"); + + // Unary operators. + verifyFormat("int a = +[foo bar:baz];"); + verifyFormat("int a = -[foo bar:baz];"); + verifyFormat("int a = ![foo bar:baz];"); + verifyFormat("int a = ~[foo bar:baz];"); + verifyFormat("int a = ++[foo bar:baz];"); + verifyFormat("int a = --[foo bar:baz];"); + verifyFormat("int a = sizeof [foo bar:baz];"); + verifyFormat("int a = alignof [foo bar:baz];"); + verifyFormat("int a = &[foo bar:baz];"); + verifyFormat("int a = *[foo bar:baz];"); + // FIXME: Make casts work, without breaking f()[4]. + //verifyFormat("int a = (int)[foo bar:baz];"); + //verifyFormat("return (int)[foo bar:baz];"); + //verifyFormat("(void)[foo bar:baz];"); + verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];"); + + // Binary operators. + verifyFormat("[foo bar:baz], [foo bar:baz];"); + verifyFormat("[foo bar:baz] = [foo bar:baz];"); + verifyFormat("[foo bar:baz] *= [foo bar:baz];"); + verifyFormat("[foo bar:baz] /= [foo bar:baz];"); + verifyFormat("[foo bar:baz] %= [foo bar:baz];"); + verifyFormat("[foo bar:baz] += [foo bar:baz];"); + verifyFormat("[foo bar:baz] -= [foo bar:baz];"); + verifyFormat("[foo bar:baz] <<= [foo bar:baz];"); + verifyFormat("[foo bar:baz] >>= [foo bar:baz];"); + verifyFormat("[foo bar:baz] &= [foo bar:baz];"); + verifyFormat("[foo bar:baz] ^= [foo bar:baz];"); + verifyFormat("[foo bar:baz] |= [foo bar:baz];"); + verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];"); + verifyFormat("[foo bar:baz] || [foo bar:baz];"); + verifyFormat("[foo bar:baz] && [foo bar:baz];"); + verifyFormat("[foo bar:baz] | [foo bar:baz];"); + verifyFormat("[foo bar:baz] ^ [foo bar:baz];"); + verifyFormat("[foo bar:baz] & [foo bar:baz];"); + verifyFormat("[foo bar:baz] == [foo bar:baz];"); + verifyFormat("[foo bar:baz] != [foo bar:baz];"); + verifyFormat("[foo bar:baz] >= [foo bar:baz];"); + verifyFormat("[foo bar:baz] <= [foo bar:baz];"); + verifyFormat("[foo bar:baz] > [foo bar:baz];"); + verifyFormat("[foo bar:baz] < [foo bar:baz];"); + verifyFormat("[foo bar:baz] >> [foo bar:baz];"); + verifyFormat("[foo bar:baz] << [foo bar:baz];"); + verifyFormat("[foo bar:baz] - [foo bar:baz];"); + verifyFormat("[foo bar:baz] + [foo bar:baz];"); + verifyFormat("[foo bar:baz] * [foo bar:baz];"); + verifyFormat("[foo bar:baz] / [foo bar:baz];"); + verifyFormat("[foo bar:baz] % [foo bar:baz];"); + // Whew! + + verifyFormat("return in[42];"); + verifyFormat("for (id foo in [self getStuffFor:bla]) {\n" + "}"); + + verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];"); + verifyFormat("[self stuffWithInt:a ? b : c float:4.5];"); + verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];"); + verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];"); + verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]"); + verifyFormat("[button setAction:@selector(zoomOut:)];"); + verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];"); + + verifyFormat("arr[[self indexForFoo:a]];"); + verifyFormat("throw [self errorFor:a];"); + verifyFormat("@throw [self errorFor:a];"); + + // This tests that the formatter doesn't break after "backing" but before ":", + // which would be at 80 columns. + verifyFormat( + "void f() {\n" + " if ((self = [super initWithContentRect:contentRect\n" + " styleMask:styleMask\n" + " backing:NSBackingStoreBuffered\n" + " defer:YES]))"); + + verifyFormat( + "[foo checkThatBreakingAfterColonWorksOk:\n" + " [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];"); + + verifyFormat("[myObj short:arg1 // Force line break\n" + " longKeyword:arg2\n" + " evenLongerKeyword:arg3\n" + " error:arg4];"); + verifyFormat( + "void f() {\n" + " popup_window_.reset([[RenderWidgetPopupWindow alloc]\n" + " initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n" + " pos.width(), pos.height())\n" + " styleMask:NSBorderlessWindowMask\n" + " backing:NSBackingStoreBuffered\n" + " defer:NO]);\n" + "}"); + verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n" + " with:contentsNativeView];"); + + verifyFormat( + "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n" + " owner:nillllll];"); + + verifyFormat( + "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n" + " forType:kBookmarkButtonDragType];"); + + verifyFormat("[defaultCenter addObserver:self\n" + " selector:@selector(willEnterFullscreen)\n" + " name:kWillEnterFullscreenNotification\n" + " object:nil];"); + verifyFormat("[image_rep drawInRect:drawRect\n" + " fromRect:NSZeroRect\n" + " operation:NSCompositeCopy\n" + " fraction:1.0\n" + " respectFlipped:NO\n" + " hints:nil];"); + + verifyFormat( + "scoped_nsobject<NSTextField> message(\n" + " // The frame will be fixed up when |-setMessageText:| is called.\n" + " [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);"); +} + +TEST_F(FormatTest, ObjCAt) { + verifyFormat("@autoreleasepool"); + verifyFormat("@catch"); + verifyFormat("@class"); + verifyFormat("@compatibility_alias"); + verifyFormat("@defs"); + verifyFormat("@dynamic"); + verifyFormat("@encode"); + verifyFormat("@end"); + verifyFormat("@finally"); + verifyFormat("@implementation"); + verifyFormat("@import"); + verifyFormat("@interface"); + verifyFormat("@optional"); + verifyFormat("@package"); + verifyFormat("@private"); + verifyFormat("@property"); + verifyFormat("@protected"); + verifyFormat("@protocol"); + verifyFormat("@public"); + verifyFormat("@required"); + verifyFormat("@selector"); + verifyFormat("@synchronized"); + verifyFormat("@synthesize"); + verifyFormat("@throw"); + verifyFormat("@try"); + + EXPECT_EQ("@interface", format("@ interface")); + + // The precise formatting of this doesn't matter, nobody writes code like + // this. + verifyFormat("@ /*foo*/ interface"); +} + +TEST_F(FormatTest, ObjCSnippets) { + verifyFormat("@autoreleasepool {\n" + " foo();\n" + "}"); + verifyFormat("@class Foo, Bar;"); + verifyFormat("@compatibility_alias AliasName ExistingClass;"); + verifyFormat("@dynamic textColor;"); + verifyFormat("char *buf1 = @encode(int *);"); + verifyFormat("char *buf1 = @encode(typeof(4 * 5));"); + verifyFormat("char *buf1 = @encode(int **);"); + verifyFormat("Protocol *proto = @protocol(p1);"); + verifyFormat("SEL s = @selector(foo:);"); + verifyFormat("@synchronized(self) {\n" + " f();\n" + "}"); + + verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;"); + verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;"); + + verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;"); + verifyFormat("@property(assign, getter=isEditable) BOOL editable;"); + verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;"); +} + +TEST_F(FormatTest, ObjCLiterals) { + verifyFormat("@\"String\""); + verifyFormat("@1"); + verifyFormat("@+4.8"); + verifyFormat("@-4"); + verifyFormat("@1LL"); + verifyFormat("@.5"); + verifyFormat("@'c'"); + verifyFormat("@true"); + + verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);"); + verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);"); + verifyFormat("NSNumber *favoriteColor = @(Green);"); + verifyFormat("NSString *path = @(getenv(\"PATH\"));"); + + verifyFormat("@["); + verifyFormat("@[]"); + verifyFormat( + "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];"); + verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];"); + + verifyFormat("@{"); + verifyFormat("@{}"); + verifyFormat("@{ @\"one\" : @1 }"); + verifyFormat("return @{ @\"one\" : @1 };"); + verifyFormat("@{ @\"one\" : @1, }"); + verifyFormat("@{ @\"one\" : @{ @2 : @1 } }"); + verifyFormat("@{ @\"one\" : @{ @2 : @1 }, }"); + verifyFormat("@{ 1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2 }"); + verifyFormat("[self setDict:@{}"); + verifyFormat("[self setDict:@{ @1 : @2 }"); + verifyFormat("NSLog(@\"%@\", @{ @1 : @2, @2 : @3 }[@1]);"); + verifyFormat( + "NSDictionary *masses = @{ @\"H\" : @1.0078, @\"He\" : @4.0026 };"); + verifyFormat( + "NSDictionary *settings = @{ AVEncoderKey : @(AVAudioQualityMax) };"); + + // FIXME: Nested and multi-line array and dictionary literals need more work. + verifyFormat( + "NSDictionary *d = @{ @\"nam\" : NSUserNam(), @\"dte\" : [NSDate date],\n" + " @\"processInfo\" : [NSProcessInfo processInfo] };"); +} + +TEST_F(FormatTest, ReformatRegionAdjustsIndent) { + EXPECT_EQ("{\n" + "{\n" + "a;\n" + "b;\n" + "}\n" + "}", + format("{\n" + "{\n" + "a;\n" + " b;\n" + "}\n" + "}", + 13, 2, getLLVMStyle())); + EXPECT_EQ("{\n" + "{\n" + " a;\n" + "b;\n" + "}\n" + "}", + format("{\n" + "{\n" + " a;\n" + "b;\n" + "}\n" + "}", + 9, 2, getLLVMStyle())); + EXPECT_EQ("{\n" + "{\n" + "public:\n" + " b;\n" + "}\n" + "}", + format("{\n" + "{\n" + "public:\n" + " b;\n" + "}\n" + "}", + 17, 2, getLLVMStyle())); + EXPECT_EQ("{\n" + "{\n" + "a;\n" + "}\n" + "{\n" + " b;\n" + "}\n" + "}", + format("{\n" + "{\n" + "a;\n" + "}\n" + "{\n" + " b;\n" + "}\n" + "}", + 22, 2, getLLVMStyle())); + EXPECT_EQ(" {\n" + " a;\n" + " }", + format(" {\n" + "a;\n" + " }", + 4, 2, getLLVMStyle())); + EXPECT_EQ("void f() {}\n" + "void g() {}", + format("void f() {}\n" + "void g() {}", + 13, 0, getLLVMStyle())); + EXPECT_EQ("int a; // comment\n" + " // line 2\n" + "int b;", + format("int a; // comment\n" + " // line 2\n" + " int b;", + 35, 0, getLLVMStyle())); +} + +TEST_F(FormatTest, BreakStringLiterals) { + EXPECT_EQ("\"some text \"\n" + "\"other\";", + format("\"some text other\";", getLLVMStyleWithColumns(12))); + EXPECT_EQ( + "#define A \\\n" + " \"some \" \\\n" + " \"text \" \\\n" + " \"other\";", + format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); + EXPECT_EQ( + "#define A \\\n" + " \"so \" \\\n" + " \"text \" \\\n" + " \"other\";", + format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); + + EXPECT_EQ("\"some text\"", + format("\"some text\"", getLLVMStyleWithColumns(1))); + EXPECT_EQ("\"some text\"", + format("\"some text\"", getLLVMStyleWithColumns(11))); + EXPECT_EQ("\"some \"\n" + "\"text\"", + format("\"some text\"", getLLVMStyleWithColumns(10))); + EXPECT_EQ("\"some \"\n" + "\"text\"", + format("\"some text\"", getLLVMStyleWithColumns(7))); + EXPECT_EQ("\"some\"\n" + "\" text\"", + format("\"some text\"", getLLVMStyleWithColumns(6))); + EXPECT_EQ("\"some\"\n" + "\" tex\"\n" + "\" and\"", + format("\"some tex and\"", getLLVMStyleWithColumns(6))); + EXPECT_EQ("\"some\"\n" + "\"/tex\"\n" + "\"/and\"", + format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); + + EXPECT_EQ("variable =\n" + " \"long string \"\n" + " \"literal\";", + format("variable = \"long string literal\";", + getLLVMStyleWithColumns(20))); + + EXPECT_EQ("variable = f(\n" + " \"long string \"\n" + " \"literal\",\n" + " short,\n" + " loooooooooooooooooooong);", + format("variable = f(\"long string literal\", short, " + "loooooooooooooooooooong);", + getLLVMStyleWithColumns(20))); + EXPECT_EQ( + "f(\"one two\".split(\n" + " variable));", + format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); + EXPECT_EQ("f(\"one two three four five six \"\n" + " \"seven\".split(\n" + " really_looooong_variable));", + format("f(\"one two three four five six seven\"." + "split(really_looooong_variable));", + getLLVMStyleWithColumns(33))); + + EXPECT_EQ("f(\"some \"\n" + " \"text\",\n" + " other);", + format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); + + // Only break as a last resort. + verifyFormat( + "aaaaaaaaaaaaaaaaaaaa(\n" + " aaaaaaaaaaaaaaaaaaaa,\n" + " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); + + EXPECT_EQ( + "\"splitmea\"\n" + "\"trandomp\"\n" + "\"oint\"", + format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); + + EXPECT_EQ( + "\"split/\"\n" + "\"pathat/\"\n" + "\"slashes\"", + format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); +} + +TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { + EXPECT_EQ("\"\\a\"", + format("\"\\a\"", getLLVMStyleWithColumns(3))); + EXPECT_EQ("\"\\\"", + format("\"\\\"", getLLVMStyleWithColumns(2))); + EXPECT_EQ("\"test\"\n" + "\"\\n\"", + format("\"test\\n\"", getLLVMStyleWithColumns(7))); + EXPECT_EQ("\"tes\\\\\"\n" + "\"n\"", + format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); + EXPECT_EQ("\"\\\\\\\\\"\n" + "\"\\n\"", + format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); + EXPECT_EQ("\"\\uff01\"", + format("\"\\uff01\"", getLLVMStyleWithColumns(7))); + EXPECT_EQ("\"\\uff01\"\n" + "\"test\"", + format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); + EXPECT_EQ("\"\\Uff01ff02\"", + format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); + EXPECT_EQ("\"\\x000000000001\"\n" + "\"next\"", + format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); + EXPECT_EQ("\"\\x000000000001next\"", + format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); + EXPECT_EQ("\"\\x000000000001\"", + format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); + EXPECT_EQ("\"test\"\n" + "\"\\000000\"\n" + "\"000001\"", + format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); + EXPECT_EQ("\"test\\000\"\n" + "\"000000001\"", + format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); + EXPECT_EQ("R\"(\\x\\x00)\"\n", + format("R\"(\\x\\x00)\"\n", getLLVMStyleWithColumns(7))); +} + +} // end namespace tooling +} // end namespace clang diff --git a/unittests/Format/Makefile b/unittests/Format/Makefile new file mode 100644 index 0000000..e9d0cbb --- /dev/null +++ b/unittests/Format/Makefile @@ -0,0 +1,19 @@ +##===- 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 +USEDLIBS = clangFormat.a clangTooling.a clangFrontend.a clangSerialization.a \ + clangDriver.a clangParse.a clangRewriteCore.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/Frontend/CMakeLists.txt b/unittests/Frontend/CMakeLists.txt index 139cf42..c65a163 100644 --- a/unittests/Frontend/CMakeLists.txt +++ b/unittests/Frontend/CMakeLists.txt @@ -1,6 +1,7 @@ set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} asmparser + bitreader support mc ) diff --git a/unittests/Frontend/FrontendActionTest.cpp b/unittests/Frontend/FrontendActionTest.cpp index 84a6545..bcb340d 100644 --- a/unittests/Frontend/FrontendActionTest.cpp +++ b/unittests/Frontend/FrontendActionTest.cpp @@ -7,16 +7,14 @@ // //===----------------------------------------------------------------------===// -#include "clang/AST/RecursiveASTVisitor.h" -#include "clang/AST/ASTContext.h" +#include "clang/Frontend/FrontendAction.h" #include "clang/AST/ASTConsumer.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/RecursiveASTVisitor.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInvocation.h" -#include "clang/Frontend/FrontendAction.h" - #include "llvm/ADT/Triple.h" #include "llvm/Support/MemoryBuffer.h" - #include "gtest/gtest.h" using namespace llvm; @@ -62,7 +60,7 @@ TEST(ASTFrontendAction, Sanity) { invocation->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CompilerInstance compiler; compiler.setInvocation(invocation); - compiler.createDiagnostics(0, NULL); + compiler.createDiagnostics(); TestASTFrontendAction test_action; ASSERT_TRUE(compiler.ExecuteAction(test_action)); diff --git a/unittests/Frontend/Makefile b/unittests/Frontend/Makefile index 4b6f875..f61791b 100644 --- a/unittests/Frontend/Makefile +++ b/unittests/Frontend/Makefile @@ -10,7 +10,7 @@ CLANG_LEVEL = ../.. TESTNAME = Frontend include $(CLANG_LEVEL)/../../Makefile.config -LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser support mc +LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc USEDLIBS = clangFrontendTool.a clangFrontend.a clangDriver.a \ clangSerialization.a clangCodeGen.a clangParse.a clangSema.a \ clangStaticAnalyzerCheckers.a clangStaticAnalyzerCore.a \ diff --git a/unittests/Lex/CMakeLists.txt b/unittests/Lex/CMakeLists.txt index 03c8cd5..78838c0 100644 --- a/unittests/Lex/CMakeLists.txt +++ b/unittests/Lex/CMakeLists.txt @@ -1,7 +1,7 @@ add_clang_unittest(LexTests LexerTest.cpp - PreprocessingRecordTest.cpp PPCallbacksTest.cpp + PPConditionalDirectiveRecordTest.cpp ) target_link_libraries(LexTests diff --git a/unittests/Lex/LexerTest.cpp b/unittests/Lex/LexerTest.cpp index e95cd02..c9b1840 100644 --- a/unittests/Lex/LexerTest.cpp +++ b/unittests/Lex/LexerTest.cpp @@ -1,4 +1,4 @@ -//===- unittests/Basic/LexerTest.cpp ------ Lexer tests -------------------===// +//===- unittests/Lex/LexerTest.cpp ------ Lexer tests ---------------------===// // // The LLVM Compiler Infrastructure // @@ -7,20 +7,20 @@ // //===----------------------------------------------------------------------===// -#include "clang/Basic/SourceManager.h" -#include "clang/Basic/FileManager.h" +#include "clang/Lex/Lexer.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" +#include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" -#include "clang/Basic/TargetOptions.h" +#include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" -#include "clang/Lex/ModuleLoader.h" +#include "clang/Basic/TargetOptions.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" +#include "clang/Lex/ModuleLoader.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" #include "llvm/Config/config.h" - #include "gtest/gtest.h" using namespace llvm; @@ -39,7 +39,7 @@ protected: TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; - Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); + Target = TargetInfo::CreateTargetInfo(Diags, &*TargetOpts); } FileSystemOptions FileMgrOpts; @@ -53,11 +53,17 @@ protected: }; class VoidModuleLoader : public ModuleLoader { - virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, - Module::NameVisibilityKind Visibility, - bool IsInclusionDirective) { - return 0; + virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, + ModuleIdPath Path, + Module::NameVisibilityKind Visibility, + bool IsInclusionDirective) { + return ModuleLoadResult(); } + + virtual void makeModuleVisible(Module *Mod, + Module::NameVisibilityKind Visibility, + SourceLocation ImportLoc, + bool Complain) { } }; TEST_F(LexerTest, LexAPI) { diff --git a/unittests/Lex/PPCallbacksTest.cpp b/unittests/Lex/PPCallbacksTest.cpp index 6e7efa9..36bd5f9 100644 --- a/unittests/Lex/PPCallbacksTest.cpp +++ b/unittests/Lex/PPCallbacksTest.cpp @@ -7,6 +7,7 @@ // //===--------------------------------------------------------------===// +#include "clang/Lex/Preprocessor.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" @@ -16,12 +17,9 @@ #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/ModuleLoader.h" -#include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" - #include "llvm/ADT/SmallString.h" #include "llvm/Support/PathV2.h" - #include "gtest/gtest.h" using namespace llvm; @@ -32,11 +30,17 @@ namespace { // Stub out module loading. class VoidModuleLoader : public ModuleLoader { - virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, - Module::NameVisibilityKind Visibility, - bool IsInclusionDirective) { - return 0; + virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, + ModuleIdPath Path, + Module::NameVisibilityKind Visibility, + bool IsInclusionDirective) { + return ModuleLoadResult(); } + + virtual void makeModuleVisible(Module *Mod, + Module::NameVisibilityKind Visibility, + SourceLocation ImportLoc, + bool Complain) { } }; // Stub to collect data from InclusionDirective callbacks. @@ -84,7 +88,7 @@ protected: SourceMgr(Diags, FileMgr) { TargetOpts = new TargetOptions(); TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; - Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); + Target = TargetInfo::CreateTargetInfo(Diags, &*TargetOpts); } FileSystemOptions FileMgrOpts; @@ -107,7 +111,7 @@ protected: // Add header's parent path to search path. StringRef SearchPath = path::parent_path(HeaderPath); const DirectoryEntry *DE = FileMgr.getDirectory(SearchPath); - DirectoryLookup DL(DE, SrcMgr::C_User, true, false); + DirectoryLookup DL(DE, SrcMgr::C_User, false); HeaderInfo.AddSearchPath(DL, IsSystemHeader); } diff --git a/unittests/Lex/PreprocessingRecordTest.cpp b/unittests/Lex/PPConditionalDirectiveRecordTest.cpp index 815081a..082eced 100644 --- a/unittests/Lex/PreprocessingRecordTest.cpp +++ b/unittests/Lex/PPConditionalDirectiveRecordTest.cpp @@ -1,4 +1,4 @@ -//===- unittests/Lex/PreprocessingRecordTest.cpp - PreprocessingRecord tests =// +//===- unittests/Lex/PPConditionalDirectiveRecordTest.cpp-PP directive tests =// // // The LLVM Compiler Infrastructure // @@ -7,21 +7,20 @@ // //===----------------------------------------------------------------------===// -#include "clang/Basic/SourceManager.h" -#include "clang/Basic/FileManager.h" +#include "clang/Lex/PPConditionalDirectiveRecord.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" +#include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" -#include "clang/Basic/TargetOptions.h" +#include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" -#include "clang/Lex/ModuleLoader.h" +#include "clang/Basic/TargetOptions.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" +#include "clang/Lex/ModuleLoader.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" -#include "clang/Lex/PreprocessingRecord.h" #include "llvm/Config/config.h" - #include "gtest/gtest.h" using namespace llvm; @@ -30,9 +29,9 @@ using namespace clang; namespace { // The test fixture. -class PreprocessingRecordTest : public ::testing::Test { +class PPConditionalDirectiveRecordTest : public ::testing::Test { protected: - PreprocessingRecordTest() + PPConditionalDirectiveRecordTest() : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()), @@ -40,7 +39,7 @@ protected: TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; - Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); + Target = TargetInfo::CreateTargetInfo(Diags, &*TargetOpts); } FileSystemOptions FileMgrOpts; @@ -54,14 +53,20 @@ protected: }; class VoidModuleLoader : public ModuleLoader { - virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, - Module::NameVisibilityKind Visibility, - bool IsInclusionDirective) { - return 0; + virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, + ModuleIdPath Path, + Module::NameVisibilityKind Visibility, + bool IsInclusionDirective) { + return ModuleLoadResult(); } + + virtual void makeModuleVisible(Module *Mod, + Module::NameVisibilityKind Visibility, + SourceLocation ImportLoc, + bool Complain) { } }; -TEST_F(PreprocessingRecordTest, PPRecAPI) { +TEST_F(PPConditionalDirectiveRecordTest, PPRecAPI) { const char *source = "0 1\n" "#if 1\n" @@ -92,7 +97,9 @@ TEST_F(PreprocessingRecordTest, PPRecAPI) { /*IILookup =*/ 0, /*OwnsHeaderSearch =*/false, /*DelayInitialization =*/ false); - PP.createPreprocessingRecord(true); + PPConditionalDirectiveRecord * + PPRec = new PPConditionalDirectiveRecord(SourceMgr); + PP.addPPCallbacks(PPRec); PP.EnterMainSourceFile(); std::vector<Token> toks; @@ -107,37 +114,36 @@ TEST_F(PreprocessingRecordTest, PPRecAPI) { // Make sure we got the tokens that we expected. ASSERT_EQ(10U, toks.size()); - PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); - EXPECT_FALSE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[0].getLocation(), toks[1].getLocation()))); - EXPECT_TRUE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_TRUE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[0].getLocation(), toks[2].getLocation()))); - EXPECT_FALSE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[3].getLocation(), toks[4].getLocation()))); - EXPECT_TRUE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_TRUE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[1].getLocation(), toks[5].getLocation()))); - EXPECT_TRUE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_TRUE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[2].getLocation(), toks[6].getLocation()))); - EXPECT_FALSE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[2].getLocation(), toks[5].getLocation()))); - EXPECT_FALSE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[0].getLocation(), toks[6].getLocation()))); - EXPECT_TRUE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_TRUE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[2].getLocation(), toks[8].getLocation()))); - EXPECT_FALSE(PPRec.rangeIntersectsConditionalDirective( + EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective( SourceRange(toks[0].getLocation(), toks[9].getLocation()))); - EXPECT_TRUE(PPRec.areInDifferentConditionalDirectiveRegion( + EXPECT_TRUE(PPRec->areInDifferentConditionalDirectiveRegion( toks[0].getLocation(), toks[2].getLocation())); - EXPECT_FALSE(PPRec.areInDifferentConditionalDirectiveRegion( + EXPECT_FALSE(PPRec->areInDifferentConditionalDirectiveRegion( toks[3].getLocation(), toks[4].getLocation())); - EXPECT_TRUE(PPRec.areInDifferentConditionalDirectiveRegion( + EXPECT_TRUE(PPRec->areInDifferentConditionalDirectiveRegion( toks[1].getLocation(), toks[5].getLocation())); - EXPECT_TRUE(PPRec.areInDifferentConditionalDirectiveRegion( + EXPECT_TRUE(PPRec->areInDifferentConditionalDirectiveRegion( toks[2].getLocation(), toks[0].getLocation())); - EXPECT_FALSE(PPRec.areInDifferentConditionalDirectiveRegion( + EXPECT_FALSE(PPRec->areInDifferentConditionalDirectiveRegion( toks[4].getLocation(), toks[3].getLocation())); - EXPECT_TRUE(PPRec.areInDifferentConditionalDirectiveRegion( + EXPECT_TRUE(PPRec->areInDifferentConditionalDirectiveRegion( toks[5].getLocation(), toks[1].getLocation())); } diff --git a/unittests/Makefile b/unittests/Makefile index f74820b..e01a6ac 100644 --- a/unittests/Makefile +++ b/unittests/Makefile @@ -14,7 +14,21 @@ ifndef CLANG_LEVEL IS_UNITTEST_LEVEL := 1 CLANG_LEVEL := .. -PARALLEL_DIRS = ASTMatchers Basic AST Frontend Lex Tooling +PARALLEL_DIRS = Basic Lex + +include $(CLANG_LEVEL)/../..//Makefile.config + +ifeq ($(ENABLE_CLANG_REWRITER),1) +PARALLEL_DIRS += Format +endif + +ifeq ($(ENABLE_CLANG_REWRITER),1) +PARALLEL_DIRS += ASTMatchers AST Tooling +endif + +ifeq ($(ENABLE_CLANG_STATIC_ANALYZER),1) +PARALLEL_DIRS += Frontend +endif endif # CLANG_LEVEL diff --git a/unittests/Tooling/CMakeLists.txt b/unittests/Tooling/CMakeLists.txt index bd7317f..245c059 100644 --- a/unittests/Tooling/CMakeLists.txt +++ b/unittests/Tooling/CMakeLists.txt @@ -1,6 +1,7 @@ set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} asmparser + bitreader support mc ) diff --git a/unittests/Tooling/CompilationDatabaseTest.cpp b/unittests/Tooling/CompilationDatabaseTest.cpp index 5ed4240..c453b05 100644 --- a/unittests/Tooling/CompilationDatabaseTest.cpp +++ b/unittests/Tooling/CompilationDatabaseTest.cpp @@ -42,7 +42,7 @@ TEST(JSONCompilationDatabase, ErrsOnInvalidFormat) { static std::vector<std::string> getAllFiles(StringRef JSONDatabase, std::string &ErrorMessage) { - llvm::OwningPtr<CompilationDatabase> Database( + OwningPtr<CompilationDatabase> Database( JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage)); if (!Database) { ADD_FAILURE() << ErrorMessage; @@ -51,6 +51,17 @@ static std::vector<std::string> getAllFiles(StringRef JSONDatabase, return Database->getAllFiles(); } +static std::vector<CompileCommand> getAllCompileCommands(StringRef JSONDatabase, + std::string &ErrorMessage) { + OwningPtr<CompilationDatabase> Database( + JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage)); + if (!Database) { + ADD_FAILURE() << ErrorMessage; + return std::vector<CompileCommand>(); + } + return Database->getAllCompileCommands(); +} + TEST(JSONCompilationDatabase, GetAllFiles) { std::string ErrorMessage; EXPECT_EQ(std::vector<std::string>(), @@ -72,10 +83,39 @@ TEST(JSONCompilationDatabase, GetAllFiles) { ErrorMessage)) << ErrorMessage; } +TEST(JSONCompilationDatabase, GetAllCompileCommands) { + std::string ErrorMessage; + EXPECT_EQ(0u, + getAllCompileCommands("[]", ErrorMessage).size()) << ErrorMessage; + + StringRef Directory1("//net/dir1"); + StringRef FileName1("file1"); + StringRef Command1("command1"); + StringRef Directory2("//net/dir2"); + StringRef FileName2("file1"); + StringRef Command2("command1"); + + std::vector<CompileCommand> Commands = getAllCompileCommands( + ("[{\"directory\":\"" + Directory1 + "\"," + + "\"command\":\"" + Command1 + "\"," + "\"file\":\"" + FileName1 + "\"}," + " {\"directory\":\"" + Directory2 + "\"," + + "\"command\":\"" + Command2 + "\"," + "\"file\":\"" + FileName2 + "\"}]").str(), + ErrorMessage); + EXPECT_EQ(2U, Commands.size()) << ErrorMessage; + EXPECT_EQ(Directory1, Commands[0].Directory) << ErrorMessage; + ASSERT_EQ(1u, Commands[0].CommandLine.size()); + EXPECT_EQ(Command1, Commands[0].CommandLine[0]) << ErrorMessage; + EXPECT_EQ(Directory2, Commands[1].Directory) << ErrorMessage; + ASSERT_EQ(1u, Commands[1].CommandLine.size()); + EXPECT_EQ(Command2, Commands[1].CommandLine[0]) << ErrorMessage; +} + static CompileCommand findCompileArgsInJsonDatabase(StringRef FileName, StringRef JSONDatabase, std::string &ErrorMessage) { - llvm::OwningPtr<CompilationDatabase> Database( + OwningPtr<CompilationDatabase> Database( JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage)); if (!Database) return CompileCommand(); @@ -351,6 +391,12 @@ TEST(unescapeJsonCommandLine, ParsesQuotedStringWithoutClosingQuote) { EXPECT_EQ("", Empty[0]); } +TEST(unescapeJsonCommandLine, ParsesSingleQuotedString) { + std::vector<std::string> Args = unescapeJsonCommandLine("a'\\\\b \\\"c\\\"'"); + ASSERT_EQ(1ul, Args.size()); + EXPECT_EQ("a\\b \"c\"", Args[0]); +} + TEST(FixedCompilationDatabase, ReturnsFixedCommandLine) { std::vector<std::string> CommandLine; CommandLine.push_back("one"); @@ -376,9 +422,18 @@ TEST(FixedCompilationDatabase, GetAllFiles) { EXPECT_EQ(0ul, Database.getAllFiles().size()); } +TEST(FixedCompilationDatabase, GetAllCompileCommands) { + std::vector<std::string> CommandLine; + CommandLine.push_back("one"); + CommandLine.push_back("two"); + FixedCompilationDatabase Database(".", CommandLine); + + EXPECT_EQ(0ul, Database.getAllCompileCommands().size()); +} + TEST(ParseFixedCompilationDatabase, ReturnsNullOnEmptyArgumentList) { int Argc = 0; - llvm::OwningPtr<FixedCompilationDatabase> Database( + OwningPtr<FixedCompilationDatabase> Database( FixedCompilationDatabase::loadFromCommandLine(Argc, NULL)); EXPECT_FALSE(Database); EXPECT_EQ(0, Argc); @@ -387,7 +442,7 @@ TEST(ParseFixedCompilationDatabase, ReturnsNullOnEmptyArgumentList) { TEST(ParseFixedCompilationDatabase, ReturnsNullWithoutDoubleDash) { int Argc = 2; const char *Argv[] = { "1", "2" }; - llvm::OwningPtr<FixedCompilationDatabase> Database( + OwningPtr<FixedCompilationDatabase> Database( FixedCompilationDatabase::loadFromCommandLine(Argc, Argv)); EXPECT_FALSE(Database); EXPECT_EQ(2, Argc); @@ -396,7 +451,7 @@ TEST(ParseFixedCompilationDatabase, ReturnsNullWithoutDoubleDash) { TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) { int Argc = 5; const char *Argv[] = { "1", "2", "--\0no-constant-folding", "3", "4" }; - llvm::OwningPtr<FixedCompilationDatabase> Database( + OwningPtr<FixedCompilationDatabase> Database( FixedCompilationDatabase::loadFromCommandLine(Argc, Argv)); ASSERT_TRUE(Database); std::vector<CompileCommand> Result = @@ -415,7 +470,7 @@ TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) { TEST(ParseFixedCompilationDatabase, ReturnsEmptyCommandLine) { int Argc = 3; const char *Argv[] = { "1", "2", "--\0no-constant-folding" }; - llvm::OwningPtr<FixedCompilationDatabase> Database( + OwningPtr<FixedCompilationDatabase> Database( FixedCompilationDatabase::loadFromCommandLine(Argc, Argv)); ASSERT_TRUE(Database); std::vector<CompileCommand> Result = diff --git a/unittests/Tooling/Makefile b/unittests/Tooling/Makefile index 5ed99fc..06fdf88 100644 --- a/unittests/Tooling/Makefile +++ b/unittests/Tooling/Makefile @@ -10,7 +10,7 @@ CLANG_LEVEL = ../.. TESTNAME = Tooling include $(CLANG_LEVEL)/../../Makefile.config -LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser support mc +LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc USEDLIBS = clangTooling.a clangFrontend.a clangSerialization.a clangDriver.a \ clangParse.a clangRewriteCore.a clangRewriteFrontend.a \ clangSema.a clangAnalysis.a clangEdit.a \ diff --git a/unittests/Tooling/RecursiveASTVisitorTest.cpp b/unittests/Tooling/RecursiveASTVisitorTest.cpp index a68a869..81be190 100644 --- a/unittests/Tooling/RecursiveASTVisitorTest.cpp +++ b/unittests/Tooling/RecursiveASTVisitorTest.cpp @@ -50,10 +50,11 @@ class NamedDeclVisitor public: bool VisitNamedDecl(NamedDecl *Decl) { std::string NameWithTemplateArgs; - Decl->getNameForDiagnostic(NameWithTemplateArgs, + llvm::raw_string_ostream OS(NameWithTemplateArgs); + Decl->getNameForDiagnostic(OS, Decl->getASTContext().getPrintingPolicy(), true); - Match(NameWithTemplateArgs, Decl->getLocation()); + Match(OS.str(), Decl->getLocation()); return true; } }; diff --git a/unittests/Tooling/RefactoringCallbacksTest.cpp b/unittests/Tooling/RefactoringCallbacksTest.cpp index 4e30cfd..9e086d8 100644 --- a/unittests/Tooling/RefactoringCallbacksTest.cpp +++ b/unittests/Tooling/RefactoringCallbacksTest.cpp @@ -1,4 +1,4 @@ -//===- unittest/ASTMatchers/RefactoringCallbacksTest.cpp ------------------===// +//===- unittest/Tooling/RefactoringCallbacksTest.cpp ----------------------===// // // The LLVM Compiler Infrastructure // @@ -7,10 +7,10 @@ // //===----------------------------------------------------------------------===// -#include "clang/ASTMatchers/ASTMatchers.h" -#include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Tooling/RefactoringCallbacks.h" #include "RewriterTestContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "gtest/gtest.h" namespace clang { diff --git a/unittests/Tooling/RefactoringTest.cpp b/unittests/Tooling/RefactoringTest.cpp index ff278bf..3e0d728 100644 --- a/unittests/Tooling/RefactoringTest.cpp +++ b/unittests/Tooling/RefactoringTest.cpp @@ -8,12 +8,11 @@ //===----------------------------------------------------------------------===// #include "RewriterTestContext.h" -#include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" +#include "clang/AST/ASTContext.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/RecursiveASTVisitor.h" -#include "clang/Tooling/Refactoring.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/FileManager.h" @@ -23,6 +22,7 @@ #include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Rewrite/Core/Rewriter.h" +#include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Tooling.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Path.h" @@ -166,7 +166,7 @@ class FlushRewrittenFilesTest : public ::testing::Test { } FileID createFile(llvm::StringRef Name, llvm::StringRef Content) { - llvm::SmallString<1024> Path(TemporaryDirectory.str()); + SmallString<1024> Path(TemporaryDirectory.str()); llvm::sys::path::append(Path, Name); std::string ErrorInfo; llvm::raw_fd_ostream OutStream(Path.c_str(), @@ -180,7 +180,7 @@ class FlushRewrittenFilesTest : public ::testing::Test { } std::string getFileContentFromDisk(llvm::StringRef Name) { - llvm::SmallString<1024> Path(TemporaryDirectory.str()); + SmallString<1024> Path(TemporaryDirectory.str()); llvm::sys::path::append(Path, Name); // We need to read directly from the FileManager without relaying through // a FileEntry, as otherwise we'd read through an already opened file diff --git a/unittests/Tooling/RewriterTestContext.h b/unittests/Tooling/RewriterTestContext.h index d790ac1..13c4202 100644 --- a/unittests/Tooling/RewriterTestContext.h +++ b/unittests/Tooling/RewriterTestContext.h @@ -36,7 +36,7 @@ class RewriterTestContext { public: RewriterTestContext() : DiagOpts(new DiagnosticOptions()), - Diagnostics(llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), + Diagnostics(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts), DiagnosticPrinter(llvm::outs(), &*DiagOpts), Files((FileSystemOptions())), @@ -72,7 +72,7 @@ class RewriterTestContext { llvm::raw_fd_ostream Closer(FD, /*shouldClose=*/true); TemporaryDirectory = llvm::sys::path::parent_path(TemporaryDirectory); } - llvm::SmallString<1024> Path(TemporaryDirectory); + SmallString<1024> Path(TemporaryDirectory); llvm::sys::path::append(Path, Name); std::string ErrorInfo; llvm::raw_fd_ostream OutStream(Path.c_str(), @@ -101,7 +101,7 @@ class RewriterTestContext { } std::string getFileContentFromDisk(StringRef Name) { - llvm::SmallString<1024> Path(TemporaryDirectory.str()); + SmallString<1024> Path(TemporaryDirectory.str()); llvm::sys::path::append(Path, Name); // We need to read directly from the FileManager without relaying through // a FileEntry, as otherwise we'd read through an already opened file @@ -111,7 +111,7 @@ class RewriterTestContext { return Files.getBufferForFile(Path, NULL)->getBuffer(); } - llvm::IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts; + IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts; DiagnosticsEngine Diagnostics; TextDiagnosticPrinter DiagnosticPrinter; FileManager Files; diff --git a/unittests/Tooling/TestVisitor.h b/unittests/Tooling/TestVisitor.h index 8333c24..ce3246a 100644 --- a/unittests/Tooling/TestVisitor.h +++ b/unittests/Tooling/TestVisitor.h @@ -15,15 +15,14 @@ #ifndef LLVM_CLANG_TEST_VISITOR_H #define LLVM_CLANG_TEST_VISITOR_H -#include <vector> - -#include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" +#include "clang/AST/ASTContext.h" #include "clang/AST/RecursiveASTVisitor.h" -#include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/CompilerInstance.h" +#include "clang/Frontend/FrontendAction.h" #include "clang/Tooling/Tooling.h" #include "gtest/gtest.h" +#include <vector> namespace clang { diff --git a/unittests/Tooling/ToolingTest.cpp b/unittests/Tooling/ToolingTest.cpp index d40c613..a9319f2 100644 --- a/unittests/Tooling/ToolingTest.cpp +++ b/unittests/Tooling/ToolingTest.cpp @@ -10,6 +10,7 @@ #include "clang/AST/ASTConsumer.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" +#include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CompilationDatabase.h" @@ -97,9 +98,9 @@ TEST(runToolOnCode, FindsClassDecl) { } TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) { - llvm::OwningPtr<FrontendActionFactory> Factory( - newFrontendActionFactory<SyntaxOnlyAction>()); - llvm::OwningPtr<FrontendAction> Action(Factory->create()); + OwningPtr<FrontendActionFactory> Factory( + newFrontendActionFactory<SyntaxOnlyAction>()); + OwningPtr<FrontendAction> Action(Factory->create()); EXPECT_TRUE(Action.get() != NULL); } @@ -111,9 +112,9 @@ struct IndependentFrontendActionCreator { TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) { IndependentFrontendActionCreator Creator; - llvm::OwningPtr<FrontendActionFactory> Factory( - newFrontendActionFactory(&Creator)); - llvm::OwningPtr<FrontendAction> Action(Factory->create()); + OwningPtr<FrontendActionFactory> Factory( + newFrontendActionFactory(&Creator)); + OwningPtr<FrontendAction> Action(Factory->create()); EXPECT_TRUE(Action.get() != NULL); } @@ -162,5 +163,28 @@ TEST(newFrontendActionFactory, InjectsEndOfSourceFileCallback) { } #endif +struct SkipBodyConsumer : public clang::ASTConsumer { + /// Skip the 'skipMe' function. + virtual bool shouldSkipFunctionBody(Decl *D) { + FunctionDecl *F = dyn_cast<FunctionDecl>(D); + return F && F->getNameAsString() == "skipMe"; + } +}; + +struct SkipBodyAction : public clang::ASTFrontendAction { + virtual ASTConsumer *CreateASTConsumer(CompilerInstance &Compiler, + StringRef) { + Compiler.getFrontendOpts().SkipFunctionBodies = true; + return new SkipBodyConsumer; + } +}; + +TEST(runToolOnCode, TestSkipFunctionBody) { + EXPECT_TRUE(runToolOnCode(new SkipBodyAction, + "int skipMe() { an_error_here }")); + EXPECT_FALSE(runToolOnCode(new SkipBodyAction, + "int skipMeNot() { an_error_here }")); +} + } // end namespace tooling } // end namespace clang |