1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Format/Format.h" 10 11 #include "../Tooling/ReplacementTest.h" 12 #include "FormatTestUtils.h" 13 14 #include "llvm/Support/Debug.h" 15 #include "llvm/Support/MemoryBuffer.h" 16 #include "gtest/gtest.h" 17 18 #define DEBUG_TYPE "format-test" 19 20 using clang::tooling::ReplacementTest; 21 using clang::tooling::toReplacements; 22 using testing::ScopedTrace; 23 24 namespace clang { 25 namespace format { 26 namespace { 27 28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); } 29 30 class FormatTest : public ::testing::Test { 31 protected: 32 enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck }; 33 34 std::string format(llvm::StringRef Code, 35 const FormatStyle &Style = getLLVMStyle(), 36 StatusCheck CheckComplete = SC_ExpectComplete) { 37 LLVM_DEBUG(llvm::errs() << "---\n"); 38 LLVM_DEBUG(llvm::errs() << Code << "\n\n"); 39 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size())); 40 FormattingAttemptStatus Status; 41 tooling::Replacements Replaces = 42 reformat(Style, Code, Ranges, "<stdin>", &Status); 43 if (CheckComplete != SC_DoNotCheck) { 44 bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete; 45 EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete) 46 << Code << "\n\n"; 47 } 48 ReplacementCount = Replaces.size(); 49 auto Result = applyAllReplacements(Code, Replaces); 50 EXPECT_TRUE(static_cast<bool>(Result)); 51 LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); 52 return *Result; 53 } 54 55 FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) { 56 Style.ColumnLimit = ColumnLimit; 57 return Style; 58 } 59 60 FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) { 61 return getStyleWithColumns(getLLVMStyle(), ColumnLimit); 62 } 63 64 FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) { 65 return getStyleWithColumns(getGoogleStyle(), ColumnLimit); 66 } 67 68 void _verifyFormat(const char *File, int Line, llvm::StringRef Expected, 69 llvm::StringRef Code, 70 const FormatStyle &Style = getLLVMStyle()) { 71 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 72 EXPECT_EQ(Expected.str(), format(Expected, Style)) 73 << "Expected code is not stable"; 74 EXPECT_EQ(Expected.str(), format(Code, Style)); 75 if (Style.Language == FormatStyle::LK_Cpp) { 76 // Objective-C++ is a superset of C++, so everything checked for C++ 77 // needs to be checked for Objective-C++ as well. 78 FormatStyle ObjCStyle = Style; 79 ObjCStyle.Language = FormatStyle::LK_ObjC; 80 EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle)); 81 } 82 } 83 84 void _verifyFormat(const char *File, int Line, llvm::StringRef Code, 85 const FormatStyle &Style = getLLVMStyle()) { 86 _verifyFormat(File, Line, Code, test::messUp(Code), Style); 87 } 88 89 void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code, 90 const FormatStyle &Style = getLLVMStyle()) { 91 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 92 EXPECT_EQ(Code.str(), 93 format(test::messUp(Code), Style, SC_ExpectIncomplete)); 94 } 95 96 void _verifyIndependentOfContext(const char *File, int Line, 97 llvm::StringRef Text, 98 const FormatStyle &Style = getLLVMStyle()) { 99 _verifyFormat(File, Line, Text, Style); 100 _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(), 101 Style); 102 } 103 104 /// \brief Verify that clang-format does not crash on the given input. 105 void verifyNoCrash(llvm::StringRef Code, 106 const FormatStyle &Style = getLLVMStyle()) { 107 format(Code, Style, SC_DoNotCheck); 108 } 109 110 int ReplacementCount; 111 }; 112 113 #define verifyIndependentOfContext(...) \ 114 _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__) 115 #define verifyIncompleteFormat(...) \ 116 _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__) 117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__) 118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle()) 119 120 TEST_F(FormatTest, MessUp) { 121 EXPECT_EQ("1 2 3", test::messUp("1 2 3")); 122 EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n")); 123 EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc")); 124 EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc")); 125 EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne")); 126 } 127 128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) { 129 EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language); 130 } 131 132 TEST_F(FormatTest, LLVMStyleOverride) { 133 EXPECT_EQ(FormatStyle::LK_Proto, 134 getLLVMStyle(FormatStyle::LK_Proto).Language); 135 } 136 137 //===----------------------------------------------------------------------===// 138 // Basic function tests. 139 //===----------------------------------------------------------------------===// 140 141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { 142 EXPECT_EQ(";", format(";")); 143 } 144 145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) { 146 EXPECT_EQ("int i;", format(" int i;")); 147 EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;")); 148 EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); 149 EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); 150 } 151 152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { 153 EXPECT_EQ("int i;", format("int\ni;")); 154 } 155 156 TEST_F(FormatTest, FormatsNestedBlockStatements) { 157 EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); 158 } 159 160 TEST_F(FormatTest, FormatsNestedCall) { 161 verifyFormat("Method(f1, f2(f3));"); 162 verifyFormat("Method(f1(f2, f3()));"); 163 verifyFormat("Method(f1(f2, (f3())));"); 164 } 165 166 TEST_F(FormatTest, NestedNameSpecifiers) { 167 verifyFormat("vector<::Type> v;"); 168 verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); 169 verifyFormat("static constexpr bool Bar = decltype(bar())::value;"); 170 verifyFormat("static constexpr bool Bar = typeof(bar())::value;"); 171 verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;"); 172 verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;"); 173 verifyFormat("bool a = 2 < ::SomeFunction();"); 174 verifyFormat("ALWAYS_INLINE ::std::string getName();"); 175 verifyFormat("some::string getName();"); 176 } 177 178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { 179 EXPECT_EQ("if (a) {\n" 180 " f();\n" 181 "}", 182 format("if(a){f();}")); 183 EXPECT_EQ(4, ReplacementCount); 184 EXPECT_EQ("if (a) {\n" 185 " f();\n" 186 "}", 187 format("if (a) {\n" 188 " f();\n" 189 "}")); 190 EXPECT_EQ(0, ReplacementCount); 191 EXPECT_EQ("/*\r\n" 192 "\r\n" 193 "*/\r\n", 194 format("/*\r\n" 195 "\r\n" 196 "*/\r\n")); 197 EXPECT_EQ(0, ReplacementCount); 198 } 199 200 TEST_F(FormatTest, RemovesEmptyLines) { 201 EXPECT_EQ("class C {\n" 202 " int i;\n" 203 "};", 204 format("class C {\n" 205 " int i;\n" 206 "\n" 207 "};")); 208 209 // Don't remove empty lines at the start of namespaces or extern "C" blocks. 210 EXPECT_EQ("namespace N {\n" 211 "\n" 212 "int i;\n" 213 "}", 214 format("namespace N {\n" 215 "\n" 216 "int i;\n" 217 "}", 218 getGoogleStyle())); 219 EXPECT_EQ("/* something */ namespace N {\n" 220 "\n" 221 "int i;\n" 222 "}", 223 format("/* something */ namespace N {\n" 224 "\n" 225 "int i;\n" 226 "}", 227 getGoogleStyle())); 228 EXPECT_EQ("inline namespace N {\n" 229 "\n" 230 "int i;\n" 231 "}", 232 format("inline namespace N {\n" 233 "\n" 234 "int i;\n" 235 "}", 236 getGoogleStyle())); 237 EXPECT_EQ("/* something */ inline namespace N {\n" 238 "\n" 239 "int i;\n" 240 "}", 241 format("/* something */ inline namespace N {\n" 242 "\n" 243 "int i;\n" 244 "}", 245 getGoogleStyle())); 246 EXPECT_EQ("export namespace N {\n" 247 "\n" 248 "int i;\n" 249 "}", 250 format("export namespace N {\n" 251 "\n" 252 "int i;\n" 253 "}", 254 getGoogleStyle())); 255 EXPECT_EQ("extern /**/ \"C\" /**/ {\n" 256 "\n" 257 "int i;\n" 258 "}", 259 format("extern /**/ \"C\" /**/ {\n" 260 "\n" 261 "int i;\n" 262 "}", 263 getGoogleStyle())); 264 265 auto CustomStyle = getLLVMStyle(); 266 CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom; 267 CustomStyle.BraceWrapping.AfterNamespace = true; 268 CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false; 269 EXPECT_EQ("namespace N\n" 270 "{\n" 271 "\n" 272 "int i;\n" 273 "}", 274 format("namespace N\n" 275 "{\n" 276 "\n" 277 "\n" 278 "int i;\n" 279 "}", 280 CustomStyle)); 281 EXPECT_EQ("/* something */ namespace N\n" 282 "{\n" 283 "\n" 284 "int i;\n" 285 "}", 286 format("/* something */ namespace N {\n" 287 "\n" 288 "\n" 289 "int i;\n" 290 "}", 291 CustomStyle)); 292 EXPECT_EQ("inline namespace N\n" 293 "{\n" 294 "\n" 295 "int i;\n" 296 "}", 297 format("inline namespace N\n" 298 "{\n" 299 "\n" 300 "\n" 301 "int i;\n" 302 "}", 303 CustomStyle)); 304 EXPECT_EQ("/* something */ inline namespace N\n" 305 "{\n" 306 "\n" 307 "int i;\n" 308 "}", 309 format("/* something */ inline namespace N\n" 310 "{\n" 311 "\n" 312 "int i;\n" 313 "}", 314 CustomStyle)); 315 EXPECT_EQ("export namespace N\n" 316 "{\n" 317 "\n" 318 "int i;\n" 319 "}", 320 format("export namespace N\n" 321 "{\n" 322 "\n" 323 "int i;\n" 324 "}", 325 CustomStyle)); 326 EXPECT_EQ("namespace a\n" 327 "{\n" 328 "namespace b\n" 329 "{\n" 330 "\n" 331 "class AA {};\n" 332 "\n" 333 "} // namespace b\n" 334 "} // namespace a\n", 335 format("namespace a\n" 336 "{\n" 337 "namespace b\n" 338 "{\n" 339 "\n" 340 "\n" 341 "class AA {};\n" 342 "\n" 343 "\n" 344 "}\n" 345 "}\n", 346 CustomStyle)); 347 EXPECT_EQ("namespace A /* comment */\n" 348 "{\n" 349 "class B {}\n" 350 "} // namespace A", 351 format("namespace A /* comment */ { class B {} }", CustomStyle)); 352 EXPECT_EQ("namespace A\n" 353 "{ /* comment */\n" 354 "class B {}\n" 355 "} // namespace A", 356 format("namespace A {/* comment */ class B {} }", CustomStyle)); 357 EXPECT_EQ("namespace A\n" 358 "{ /* comment */\n" 359 "\n" 360 "class B {}\n" 361 "\n" 362 "" 363 "} // namespace A", 364 format("namespace A { /* comment */\n" 365 "\n" 366 "\n" 367 "class B {}\n" 368 "\n" 369 "\n" 370 "}", 371 CustomStyle)); 372 EXPECT_EQ("namespace A /* comment */\n" 373 "{\n" 374 "\n" 375 "class B {}\n" 376 "\n" 377 "} // namespace A", 378 format("namespace A/* comment */ {\n" 379 "\n" 380 "\n" 381 "class B {}\n" 382 "\n" 383 "\n" 384 "}", 385 CustomStyle)); 386 387 // ...but do keep inlining and removing empty lines for non-block extern "C" 388 // functions. 389 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); 390 EXPECT_EQ("extern \"C\" int f() {\n" 391 " int i = 42;\n" 392 " return i;\n" 393 "}", 394 format("extern \"C\" int f() {\n" 395 "\n" 396 " int i = 42;\n" 397 " return i;\n" 398 "}", 399 getGoogleStyle())); 400 401 // Remove empty lines at the beginning and end of blocks. 402 EXPECT_EQ("void f() {\n" 403 "\n" 404 " if (a) {\n" 405 "\n" 406 " f();\n" 407 " }\n" 408 "}", 409 format("void f() {\n" 410 "\n" 411 " if (a) {\n" 412 "\n" 413 " f();\n" 414 "\n" 415 " }\n" 416 "\n" 417 "}", 418 getLLVMStyle())); 419 EXPECT_EQ("void f() {\n" 420 " if (a) {\n" 421 " f();\n" 422 " }\n" 423 "}", 424 format("void f() {\n" 425 "\n" 426 " if (a) {\n" 427 "\n" 428 " f();\n" 429 "\n" 430 " }\n" 431 "\n" 432 "}", 433 getGoogleStyle())); 434 435 // Don't remove empty lines in more complex control statements. 436 EXPECT_EQ("void f() {\n" 437 " if (a) {\n" 438 " f();\n" 439 "\n" 440 " } else if (b) {\n" 441 " f();\n" 442 " }\n" 443 "}", 444 format("void f() {\n" 445 " if (a) {\n" 446 " f();\n" 447 "\n" 448 " } else if (b) {\n" 449 " f();\n" 450 "\n" 451 " }\n" 452 "\n" 453 "}")); 454 455 // Don't remove empty lines before namespace endings. 456 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 457 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 458 EXPECT_EQ("namespace {\n" 459 "int i;\n" 460 "\n" 461 "}", 462 format("namespace {\n" 463 "int i;\n" 464 "\n" 465 "}", 466 LLVMWithNoNamespaceFix)); 467 EXPECT_EQ("namespace {\n" 468 "int i;\n" 469 "}", 470 format("namespace {\n" 471 "int i;\n" 472 "}", 473 LLVMWithNoNamespaceFix)); 474 EXPECT_EQ("namespace {\n" 475 "int i;\n" 476 "\n" 477 "};", 478 format("namespace {\n" 479 "int i;\n" 480 "\n" 481 "};", 482 LLVMWithNoNamespaceFix)); 483 EXPECT_EQ("namespace {\n" 484 "int i;\n" 485 "};", 486 format("namespace {\n" 487 "int i;\n" 488 "};", 489 LLVMWithNoNamespaceFix)); 490 EXPECT_EQ("namespace {\n" 491 "int i;\n" 492 "\n" 493 "}", 494 format("namespace {\n" 495 "int i;\n" 496 "\n" 497 "}")); 498 EXPECT_EQ("namespace {\n" 499 "int i;\n" 500 "\n" 501 "} // namespace", 502 format("namespace {\n" 503 "int i;\n" 504 "\n" 505 "} // namespace")); 506 507 FormatStyle Style = getLLVMStyle(); 508 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 509 Style.MaxEmptyLinesToKeep = 2; 510 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 511 Style.BraceWrapping.AfterClass = true; 512 Style.BraceWrapping.AfterFunction = true; 513 Style.KeepEmptyLinesAtTheStartOfBlocks = false; 514 515 EXPECT_EQ("class Foo\n" 516 "{\n" 517 " Foo() {}\n" 518 "\n" 519 " void funk() {}\n" 520 "};", 521 format("class Foo\n" 522 "{\n" 523 " Foo()\n" 524 " {\n" 525 " }\n" 526 "\n" 527 " void funk() {}\n" 528 "};", 529 Style)); 530 } 531 532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { 533 verifyFormat("x = (a) and (b);"); 534 verifyFormat("x = (a) or (b);"); 535 verifyFormat("x = (a) bitand (b);"); 536 verifyFormat("x = (a) bitor (b);"); 537 verifyFormat("x = (a) not_eq (b);"); 538 verifyFormat("x = (a) and_eq (b);"); 539 verifyFormat("x = (a) or_eq (b);"); 540 verifyFormat("x = (a) xor (b);"); 541 } 542 543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { 544 verifyFormat("x = compl(a);"); 545 verifyFormat("x = not(a);"); 546 verifyFormat("x = bitand(a);"); 547 // Unary operator must not be merged with the next identifier 548 verifyFormat("x = compl a;"); 549 verifyFormat("x = not a;"); 550 verifyFormat("x = bitand a;"); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // Tests for control statements. 555 //===----------------------------------------------------------------------===// 556 557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { 558 verifyFormat("if (true)\n f();\ng();"); 559 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); 560 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); 561 verifyFormat("if constexpr (true)\n" 562 " f();\ng();"); 563 verifyFormat("if CONSTEXPR (true)\n" 564 " f();\ng();"); 565 verifyFormat("if constexpr (a)\n" 566 " if constexpr (b)\n" 567 " if constexpr (c)\n" 568 " g();\n" 569 "h();"); 570 verifyFormat("if CONSTEXPR (a)\n" 571 " if CONSTEXPR (b)\n" 572 " if CONSTEXPR (c)\n" 573 " g();\n" 574 "h();"); 575 verifyFormat("if constexpr (a)\n" 576 " if constexpr (b) {\n" 577 " f();\n" 578 " }\n" 579 "g();"); 580 verifyFormat("if CONSTEXPR (a)\n" 581 " if CONSTEXPR (b) {\n" 582 " f();\n" 583 " }\n" 584 "g();"); 585 586 verifyFormat("if (a)\n" 587 " g();"); 588 verifyFormat("if (a) {\n" 589 " g()\n" 590 "};"); 591 verifyFormat("if (a)\n" 592 " g();\n" 593 "else\n" 594 " g();"); 595 verifyFormat("if (a) {\n" 596 " g();\n" 597 "} else\n" 598 " g();"); 599 verifyFormat("if (a)\n" 600 " g();\n" 601 "else {\n" 602 " g();\n" 603 "}"); 604 verifyFormat("if (a) {\n" 605 " g();\n" 606 "} else {\n" 607 " g();\n" 608 "}"); 609 verifyFormat("if (a)\n" 610 " g();\n" 611 "else if (b)\n" 612 " g();\n" 613 "else\n" 614 " g();"); 615 verifyFormat("if (a) {\n" 616 " g();\n" 617 "} else if (b)\n" 618 " g();\n" 619 "else\n" 620 " g();"); 621 verifyFormat("if (a)\n" 622 " g();\n" 623 "else if (b) {\n" 624 " g();\n" 625 "} else\n" 626 " g();"); 627 verifyFormat("if (a)\n" 628 " g();\n" 629 "else if (b)\n" 630 " g();\n" 631 "else {\n" 632 " g();\n" 633 "}"); 634 verifyFormat("if (a)\n" 635 " g();\n" 636 "else if (b) {\n" 637 " g();\n" 638 "} else {\n" 639 " g();\n" 640 "}"); 641 verifyFormat("if (a) {\n" 642 " g();\n" 643 "} else if (b) {\n" 644 " g();\n" 645 "} else {\n" 646 " g();\n" 647 "}"); 648 649 FormatStyle AllowsMergedIf = getLLVMStyle(); 650 AllowsMergedIf.IfMacros.push_back("MYIF"); 651 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 652 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 653 FormatStyle::SIS_WithoutElse; 654 verifyFormat("if (a)\n" 655 " // comment\n" 656 " f();", 657 AllowsMergedIf); 658 verifyFormat("{\n" 659 " if (a)\n" 660 " label:\n" 661 " f();\n" 662 "}", 663 AllowsMergedIf); 664 verifyFormat("#define A \\\n" 665 " if (a) \\\n" 666 " label: \\\n" 667 " f()", 668 AllowsMergedIf); 669 verifyFormat("if (a)\n" 670 " ;", 671 AllowsMergedIf); 672 verifyFormat("if (a)\n" 673 " if (b) return;", 674 AllowsMergedIf); 675 676 verifyFormat("if (a) // Can't merge this\n" 677 " f();\n", 678 AllowsMergedIf); 679 verifyFormat("if (a) /* still don't merge */\n" 680 " f();", 681 AllowsMergedIf); 682 verifyFormat("if (a) { // Never merge this\n" 683 " f();\n" 684 "}", 685 AllowsMergedIf); 686 verifyFormat("if (a) { /* Never merge this */\n" 687 " f();\n" 688 "}", 689 AllowsMergedIf); 690 verifyFormat("MYIF (a)\n" 691 " // comment\n" 692 " f();", 693 AllowsMergedIf); 694 verifyFormat("{\n" 695 " MYIF (a)\n" 696 " label:\n" 697 " f();\n" 698 "}", 699 AllowsMergedIf); 700 verifyFormat("#define A \\\n" 701 " MYIF (a) \\\n" 702 " label: \\\n" 703 " f()", 704 AllowsMergedIf); 705 verifyFormat("MYIF (a)\n" 706 " ;", 707 AllowsMergedIf); 708 verifyFormat("MYIF (a)\n" 709 " MYIF (b) return;", 710 AllowsMergedIf); 711 712 verifyFormat("MYIF (a) // Can't merge this\n" 713 " f();\n", 714 AllowsMergedIf); 715 verifyFormat("MYIF (a) /* still don't merge */\n" 716 " f();", 717 AllowsMergedIf); 718 verifyFormat("MYIF (a) { // Never merge this\n" 719 " f();\n" 720 "}", 721 AllowsMergedIf); 722 verifyFormat("MYIF (a) { /* Never merge this */\n" 723 " f();\n" 724 "}", 725 AllowsMergedIf); 726 727 AllowsMergedIf.ColumnLimit = 14; 728 // Where line-lengths matter, a 2-letter synonym that maintains line length. 729 // Not IF to avoid any confusion that IF is somehow special. 730 AllowsMergedIf.IfMacros.push_back("FI"); 731 verifyFormat("if (a) return;", AllowsMergedIf); 732 verifyFormat("if (aaaaaaaaa)\n" 733 " return;", 734 AllowsMergedIf); 735 verifyFormat("FI (a) return;", AllowsMergedIf); 736 verifyFormat("FI (aaaaaaaaa)\n" 737 " return;", 738 AllowsMergedIf); 739 740 AllowsMergedIf.ColumnLimit = 13; 741 verifyFormat("if (a)\n return;", AllowsMergedIf); 742 verifyFormat("FI (a)\n return;", AllowsMergedIf); 743 744 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 745 AllowsMergedIfElse.IfMacros.push_back("MYIF"); 746 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 747 FormatStyle::SIS_AllIfsAndElse; 748 verifyFormat("if (a)\n" 749 " // comment\n" 750 " f();\n" 751 "else\n" 752 " // comment\n" 753 " f();", 754 AllowsMergedIfElse); 755 verifyFormat("{\n" 756 " if (a)\n" 757 " label:\n" 758 " f();\n" 759 " else\n" 760 " label:\n" 761 " f();\n" 762 "}", 763 AllowsMergedIfElse); 764 verifyFormat("if (a)\n" 765 " ;\n" 766 "else\n" 767 " ;", 768 AllowsMergedIfElse); 769 verifyFormat("if (a) {\n" 770 "} else {\n" 771 "}", 772 AllowsMergedIfElse); 773 verifyFormat("if (a) return;\n" 774 "else if (b) return;\n" 775 "else return;", 776 AllowsMergedIfElse); 777 verifyFormat("if (a) {\n" 778 "} else return;", 779 AllowsMergedIfElse); 780 verifyFormat("if (a) {\n" 781 "} else if (b) return;\n" 782 "else return;", 783 AllowsMergedIfElse); 784 verifyFormat("if (a) return;\n" 785 "else if (b) {\n" 786 "} else return;", 787 AllowsMergedIfElse); 788 verifyFormat("if (a)\n" 789 " if (b) return;\n" 790 " else return;", 791 AllowsMergedIfElse); 792 verifyFormat("if constexpr (a)\n" 793 " if constexpr (b) return;\n" 794 " else if constexpr (c) return;\n" 795 " else return;", 796 AllowsMergedIfElse); 797 verifyFormat("MYIF (a)\n" 798 " // comment\n" 799 " f();\n" 800 "else\n" 801 " // comment\n" 802 " f();", 803 AllowsMergedIfElse); 804 verifyFormat("{\n" 805 " MYIF (a)\n" 806 " label:\n" 807 " f();\n" 808 " else\n" 809 " label:\n" 810 " f();\n" 811 "}", 812 AllowsMergedIfElse); 813 verifyFormat("MYIF (a)\n" 814 " ;\n" 815 "else\n" 816 " ;", 817 AllowsMergedIfElse); 818 verifyFormat("MYIF (a) {\n" 819 "} else {\n" 820 "}", 821 AllowsMergedIfElse); 822 verifyFormat("MYIF (a) return;\n" 823 "else MYIF (b) return;\n" 824 "else return;", 825 AllowsMergedIfElse); 826 verifyFormat("MYIF (a) {\n" 827 "} else return;", 828 AllowsMergedIfElse); 829 verifyFormat("MYIF (a) {\n" 830 "} else MYIF (b) return;\n" 831 "else return;", 832 AllowsMergedIfElse); 833 verifyFormat("MYIF (a) return;\n" 834 "else MYIF (b) {\n" 835 "} else return;", 836 AllowsMergedIfElse); 837 verifyFormat("MYIF (a)\n" 838 " MYIF (b) return;\n" 839 " else return;", 840 AllowsMergedIfElse); 841 verifyFormat("MYIF constexpr (a)\n" 842 " MYIF constexpr (b) return;\n" 843 " else MYIF constexpr (c) return;\n" 844 " else return;", 845 AllowsMergedIfElse); 846 } 847 848 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 849 FormatStyle AllowsMergedIf = getLLVMStyle(); 850 AllowsMergedIf.IfMacros.push_back("MYIF"); 851 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 852 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 853 FormatStyle::SIS_WithoutElse; 854 verifyFormat("if (a)\n" 855 " f();\n" 856 "else {\n" 857 " g();\n" 858 "}", 859 AllowsMergedIf); 860 verifyFormat("if (a)\n" 861 " f();\n" 862 "else\n" 863 " g();\n", 864 AllowsMergedIf); 865 866 verifyFormat("if (a) g();", AllowsMergedIf); 867 verifyFormat("if (a) {\n" 868 " g()\n" 869 "};", 870 AllowsMergedIf); 871 verifyFormat("if (a)\n" 872 " g();\n" 873 "else\n" 874 " g();", 875 AllowsMergedIf); 876 verifyFormat("if (a) {\n" 877 " g();\n" 878 "} else\n" 879 " g();", 880 AllowsMergedIf); 881 verifyFormat("if (a)\n" 882 " g();\n" 883 "else {\n" 884 " g();\n" 885 "}", 886 AllowsMergedIf); 887 verifyFormat("if (a) {\n" 888 " g();\n" 889 "} else {\n" 890 " g();\n" 891 "}", 892 AllowsMergedIf); 893 verifyFormat("if (a)\n" 894 " g();\n" 895 "else if (b)\n" 896 " g();\n" 897 "else\n" 898 " g();", 899 AllowsMergedIf); 900 verifyFormat("if (a) {\n" 901 " g();\n" 902 "} else if (b)\n" 903 " g();\n" 904 "else\n" 905 " g();", 906 AllowsMergedIf); 907 verifyFormat("if (a)\n" 908 " g();\n" 909 "else if (b) {\n" 910 " g();\n" 911 "} else\n" 912 " g();", 913 AllowsMergedIf); 914 verifyFormat("if (a)\n" 915 " g();\n" 916 "else if (b)\n" 917 " g();\n" 918 "else {\n" 919 " g();\n" 920 "}", 921 AllowsMergedIf); 922 verifyFormat("if (a)\n" 923 " g();\n" 924 "else if (b) {\n" 925 " g();\n" 926 "} else {\n" 927 " g();\n" 928 "}", 929 AllowsMergedIf); 930 verifyFormat("if (a) {\n" 931 " g();\n" 932 "} else if (b) {\n" 933 " g();\n" 934 "} else {\n" 935 " g();\n" 936 "}", 937 AllowsMergedIf); 938 verifyFormat("MYIF (a)\n" 939 " f();\n" 940 "else {\n" 941 " g();\n" 942 "}", 943 AllowsMergedIf); 944 verifyFormat("MYIF (a)\n" 945 " f();\n" 946 "else\n" 947 " g();\n", 948 AllowsMergedIf); 949 950 verifyFormat("MYIF (a) g();", AllowsMergedIf); 951 verifyFormat("MYIF (a) {\n" 952 " g()\n" 953 "};", 954 AllowsMergedIf); 955 verifyFormat("MYIF (a)\n" 956 " g();\n" 957 "else\n" 958 " g();", 959 AllowsMergedIf); 960 verifyFormat("MYIF (a) {\n" 961 " g();\n" 962 "} else\n" 963 " g();", 964 AllowsMergedIf); 965 verifyFormat("MYIF (a)\n" 966 " g();\n" 967 "else {\n" 968 " g();\n" 969 "}", 970 AllowsMergedIf); 971 verifyFormat("MYIF (a) {\n" 972 " g();\n" 973 "} else {\n" 974 " g();\n" 975 "}", 976 AllowsMergedIf); 977 verifyFormat("MYIF (a)\n" 978 " g();\n" 979 "else MYIF (b)\n" 980 " g();\n" 981 "else\n" 982 " g();", 983 AllowsMergedIf); 984 verifyFormat("MYIF (a)\n" 985 " g();\n" 986 "else if (b)\n" 987 " g();\n" 988 "else\n" 989 " g();", 990 AllowsMergedIf); 991 verifyFormat("MYIF (a) {\n" 992 " g();\n" 993 "} else MYIF (b)\n" 994 " g();\n" 995 "else\n" 996 " g();", 997 AllowsMergedIf); 998 verifyFormat("MYIF (a) {\n" 999 " g();\n" 1000 "} else if (b)\n" 1001 " g();\n" 1002 "else\n" 1003 " g();", 1004 AllowsMergedIf); 1005 verifyFormat("MYIF (a)\n" 1006 " g();\n" 1007 "else MYIF (b) {\n" 1008 " g();\n" 1009 "} else\n" 1010 " g();", 1011 AllowsMergedIf); 1012 verifyFormat("MYIF (a)\n" 1013 " g();\n" 1014 "else if (b) {\n" 1015 " g();\n" 1016 "} else\n" 1017 " g();", 1018 AllowsMergedIf); 1019 verifyFormat("MYIF (a)\n" 1020 " g();\n" 1021 "else MYIF (b)\n" 1022 " g();\n" 1023 "else {\n" 1024 " g();\n" 1025 "}", 1026 AllowsMergedIf); 1027 verifyFormat("MYIF (a)\n" 1028 " g();\n" 1029 "else if (b)\n" 1030 " g();\n" 1031 "else {\n" 1032 " g();\n" 1033 "}", 1034 AllowsMergedIf); 1035 verifyFormat("MYIF (a)\n" 1036 " g();\n" 1037 "else MYIF (b) {\n" 1038 " g();\n" 1039 "} else {\n" 1040 " g();\n" 1041 "}", 1042 AllowsMergedIf); 1043 verifyFormat("MYIF (a)\n" 1044 " g();\n" 1045 "else if (b) {\n" 1046 " g();\n" 1047 "} else {\n" 1048 " g();\n" 1049 "}", 1050 AllowsMergedIf); 1051 verifyFormat("MYIF (a) {\n" 1052 " g();\n" 1053 "} else MYIF (b) {\n" 1054 " g();\n" 1055 "} else {\n" 1056 " g();\n" 1057 "}", 1058 AllowsMergedIf); 1059 verifyFormat("MYIF (a) {\n" 1060 " g();\n" 1061 "} else if (b) {\n" 1062 " g();\n" 1063 "} else {\n" 1064 " g();\n" 1065 "}", 1066 AllowsMergedIf); 1067 1068 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1069 FormatStyle::SIS_OnlyFirstIf; 1070 1071 verifyFormat("if (a) f();\n" 1072 "else {\n" 1073 " g();\n" 1074 "}", 1075 AllowsMergedIf); 1076 verifyFormat("if (a) f();\n" 1077 "else {\n" 1078 " if (a) f();\n" 1079 " else {\n" 1080 " g();\n" 1081 " }\n" 1082 " g();\n" 1083 "}", 1084 AllowsMergedIf); 1085 1086 verifyFormat("if (a) g();", AllowsMergedIf); 1087 verifyFormat("if (a) {\n" 1088 " g()\n" 1089 "};", 1090 AllowsMergedIf); 1091 verifyFormat("if (a) g();\n" 1092 "else\n" 1093 " g();", 1094 AllowsMergedIf); 1095 verifyFormat("if (a) {\n" 1096 " g();\n" 1097 "} else\n" 1098 " g();", 1099 AllowsMergedIf); 1100 verifyFormat("if (a) g();\n" 1101 "else {\n" 1102 " g();\n" 1103 "}", 1104 AllowsMergedIf); 1105 verifyFormat("if (a) {\n" 1106 " g();\n" 1107 "} else {\n" 1108 " g();\n" 1109 "}", 1110 AllowsMergedIf); 1111 verifyFormat("if (a) g();\n" 1112 "else if (b)\n" 1113 " g();\n" 1114 "else\n" 1115 " g();", 1116 AllowsMergedIf); 1117 verifyFormat("if (a) {\n" 1118 " g();\n" 1119 "} else if (b)\n" 1120 " g();\n" 1121 "else\n" 1122 " g();", 1123 AllowsMergedIf); 1124 verifyFormat("if (a) g();\n" 1125 "else if (b) {\n" 1126 " g();\n" 1127 "} else\n" 1128 " g();", 1129 AllowsMergedIf); 1130 verifyFormat("if (a) g();\n" 1131 "else if (b)\n" 1132 " g();\n" 1133 "else {\n" 1134 " g();\n" 1135 "}", 1136 AllowsMergedIf); 1137 verifyFormat("if (a) g();\n" 1138 "else if (b) {\n" 1139 " g();\n" 1140 "} else {\n" 1141 " g();\n" 1142 "}", 1143 AllowsMergedIf); 1144 verifyFormat("if (a) {\n" 1145 " g();\n" 1146 "} else if (b) {\n" 1147 " g();\n" 1148 "} else {\n" 1149 " g();\n" 1150 "}", 1151 AllowsMergedIf); 1152 verifyFormat("MYIF (a) f();\n" 1153 "else {\n" 1154 " g();\n" 1155 "}", 1156 AllowsMergedIf); 1157 verifyFormat("MYIF (a) f();\n" 1158 "else {\n" 1159 " if (a) f();\n" 1160 " else {\n" 1161 " g();\n" 1162 " }\n" 1163 " g();\n" 1164 "}", 1165 AllowsMergedIf); 1166 1167 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1168 verifyFormat("MYIF (a) {\n" 1169 " g()\n" 1170 "};", 1171 AllowsMergedIf); 1172 verifyFormat("MYIF (a) g();\n" 1173 "else\n" 1174 " g();", 1175 AllowsMergedIf); 1176 verifyFormat("MYIF (a) {\n" 1177 " g();\n" 1178 "} else\n" 1179 " g();", 1180 AllowsMergedIf); 1181 verifyFormat("MYIF (a) g();\n" 1182 "else {\n" 1183 " g();\n" 1184 "}", 1185 AllowsMergedIf); 1186 verifyFormat("MYIF (a) {\n" 1187 " g();\n" 1188 "} else {\n" 1189 " g();\n" 1190 "}", 1191 AllowsMergedIf); 1192 verifyFormat("MYIF (a) g();\n" 1193 "else MYIF (b)\n" 1194 " g();\n" 1195 "else\n" 1196 " g();", 1197 AllowsMergedIf); 1198 verifyFormat("MYIF (a) g();\n" 1199 "else if (b)\n" 1200 " g();\n" 1201 "else\n" 1202 " g();", 1203 AllowsMergedIf); 1204 verifyFormat("MYIF (a) {\n" 1205 " g();\n" 1206 "} else MYIF (b)\n" 1207 " g();\n" 1208 "else\n" 1209 " g();", 1210 AllowsMergedIf); 1211 verifyFormat("MYIF (a) {\n" 1212 " g();\n" 1213 "} else if (b)\n" 1214 " g();\n" 1215 "else\n" 1216 " g();", 1217 AllowsMergedIf); 1218 verifyFormat("MYIF (a) g();\n" 1219 "else MYIF (b) {\n" 1220 " g();\n" 1221 "} else\n" 1222 " g();", 1223 AllowsMergedIf); 1224 verifyFormat("MYIF (a) g();\n" 1225 "else if (b) {\n" 1226 " g();\n" 1227 "} else\n" 1228 " g();", 1229 AllowsMergedIf); 1230 verifyFormat("MYIF (a) g();\n" 1231 "else MYIF (b)\n" 1232 " g();\n" 1233 "else {\n" 1234 " g();\n" 1235 "}", 1236 AllowsMergedIf); 1237 verifyFormat("MYIF (a) g();\n" 1238 "else if (b)\n" 1239 " g();\n" 1240 "else {\n" 1241 " g();\n" 1242 "}", 1243 AllowsMergedIf); 1244 verifyFormat("MYIF (a) g();\n" 1245 "else MYIF (b) {\n" 1246 " g();\n" 1247 "} else {\n" 1248 " g();\n" 1249 "}", 1250 AllowsMergedIf); 1251 verifyFormat("MYIF (a) g();\n" 1252 "else if (b) {\n" 1253 " g();\n" 1254 "} else {\n" 1255 " g();\n" 1256 "}", 1257 AllowsMergedIf); 1258 verifyFormat("MYIF (a) {\n" 1259 " g();\n" 1260 "} else MYIF (b) {\n" 1261 " g();\n" 1262 "} else {\n" 1263 " g();\n" 1264 "}", 1265 AllowsMergedIf); 1266 verifyFormat("MYIF (a) {\n" 1267 " g();\n" 1268 "} else if (b) {\n" 1269 " g();\n" 1270 "} else {\n" 1271 " g();\n" 1272 "}", 1273 AllowsMergedIf); 1274 1275 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1276 FormatStyle::SIS_AllIfsAndElse; 1277 1278 verifyFormat("if (a) f();\n" 1279 "else {\n" 1280 " g();\n" 1281 "}", 1282 AllowsMergedIf); 1283 verifyFormat("if (a) f();\n" 1284 "else {\n" 1285 " if (a) f();\n" 1286 " else {\n" 1287 " g();\n" 1288 " }\n" 1289 " g();\n" 1290 "}", 1291 AllowsMergedIf); 1292 1293 verifyFormat("if (a) g();", AllowsMergedIf); 1294 verifyFormat("if (a) {\n" 1295 " g()\n" 1296 "};", 1297 AllowsMergedIf); 1298 verifyFormat("if (a) g();\n" 1299 "else g();", 1300 AllowsMergedIf); 1301 verifyFormat("if (a) {\n" 1302 " g();\n" 1303 "} else g();", 1304 AllowsMergedIf); 1305 verifyFormat("if (a) g();\n" 1306 "else {\n" 1307 " g();\n" 1308 "}", 1309 AllowsMergedIf); 1310 verifyFormat("if (a) {\n" 1311 " g();\n" 1312 "} else {\n" 1313 " g();\n" 1314 "}", 1315 AllowsMergedIf); 1316 verifyFormat("if (a) g();\n" 1317 "else if (b) g();\n" 1318 "else g();", 1319 AllowsMergedIf); 1320 verifyFormat("if (a) {\n" 1321 " g();\n" 1322 "} else if (b) g();\n" 1323 "else g();", 1324 AllowsMergedIf); 1325 verifyFormat("if (a) g();\n" 1326 "else if (b) {\n" 1327 " g();\n" 1328 "} else g();", 1329 AllowsMergedIf); 1330 verifyFormat("if (a) g();\n" 1331 "else if (b) g();\n" 1332 "else {\n" 1333 " g();\n" 1334 "}", 1335 AllowsMergedIf); 1336 verifyFormat("if (a) g();\n" 1337 "else if (b) {\n" 1338 " g();\n" 1339 "} else {\n" 1340 " g();\n" 1341 "}", 1342 AllowsMergedIf); 1343 verifyFormat("if (a) {\n" 1344 " g();\n" 1345 "} else if (b) {\n" 1346 " g();\n" 1347 "} else {\n" 1348 " g();\n" 1349 "}", 1350 AllowsMergedIf); 1351 verifyFormat("MYIF (a) f();\n" 1352 "else {\n" 1353 " g();\n" 1354 "}", 1355 AllowsMergedIf); 1356 verifyFormat("MYIF (a) f();\n" 1357 "else {\n" 1358 " if (a) f();\n" 1359 " else {\n" 1360 " g();\n" 1361 " }\n" 1362 " g();\n" 1363 "}", 1364 AllowsMergedIf); 1365 1366 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1367 verifyFormat("MYIF (a) {\n" 1368 " g()\n" 1369 "};", 1370 AllowsMergedIf); 1371 verifyFormat("MYIF (a) g();\n" 1372 "else g();", 1373 AllowsMergedIf); 1374 verifyFormat("MYIF (a) {\n" 1375 " g();\n" 1376 "} else g();", 1377 AllowsMergedIf); 1378 verifyFormat("MYIF (a) g();\n" 1379 "else {\n" 1380 " g();\n" 1381 "}", 1382 AllowsMergedIf); 1383 verifyFormat("MYIF (a) {\n" 1384 " g();\n" 1385 "} else {\n" 1386 " g();\n" 1387 "}", 1388 AllowsMergedIf); 1389 verifyFormat("MYIF (a) g();\n" 1390 "else MYIF (b) g();\n" 1391 "else g();", 1392 AllowsMergedIf); 1393 verifyFormat("MYIF (a) g();\n" 1394 "else if (b) g();\n" 1395 "else g();", 1396 AllowsMergedIf); 1397 verifyFormat("MYIF (a) {\n" 1398 " g();\n" 1399 "} else MYIF (b) g();\n" 1400 "else g();", 1401 AllowsMergedIf); 1402 verifyFormat("MYIF (a) {\n" 1403 " g();\n" 1404 "} else if (b) g();\n" 1405 "else g();", 1406 AllowsMergedIf); 1407 verifyFormat("MYIF (a) g();\n" 1408 "else MYIF (b) {\n" 1409 " g();\n" 1410 "} else g();", 1411 AllowsMergedIf); 1412 verifyFormat("MYIF (a) g();\n" 1413 "else if (b) {\n" 1414 " g();\n" 1415 "} else g();", 1416 AllowsMergedIf); 1417 verifyFormat("MYIF (a) g();\n" 1418 "else MYIF (b) g();\n" 1419 "else {\n" 1420 " g();\n" 1421 "}", 1422 AllowsMergedIf); 1423 verifyFormat("MYIF (a) g();\n" 1424 "else if (b) g();\n" 1425 "else {\n" 1426 " g();\n" 1427 "}", 1428 AllowsMergedIf); 1429 verifyFormat("MYIF (a) g();\n" 1430 "else MYIF (b) {\n" 1431 " g();\n" 1432 "} else {\n" 1433 " g();\n" 1434 "}", 1435 AllowsMergedIf); 1436 verifyFormat("MYIF (a) g();\n" 1437 "else if (b) {\n" 1438 " g();\n" 1439 "} else {\n" 1440 " g();\n" 1441 "}", 1442 AllowsMergedIf); 1443 verifyFormat("MYIF (a) {\n" 1444 " g();\n" 1445 "} else MYIF (b) {\n" 1446 " g();\n" 1447 "} else {\n" 1448 " g();\n" 1449 "}", 1450 AllowsMergedIf); 1451 verifyFormat("MYIF (a) {\n" 1452 " g();\n" 1453 "} else if (b) {\n" 1454 " g();\n" 1455 "} else {\n" 1456 " g();\n" 1457 "}", 1458 AllowsMergedIf); 1459 } 1460 1461 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 1462 FormatStyle AllowsMergedLoops = getLLVMStyle(); 1463 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 1464 verifyFormat("while (true) continue;", AllowsMergedLoops); 1465 verifyFormat("for (;;) continue;", AllowsMergedLoops); 1466 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 1467 verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops); 1468 verifyFormat("while (true)\n" 1469 " ;", 1470 AllowsMergedLoops); 1471 verifyFormat("for (;;)\n" 1472 " ;", 1473 AllowsMergedLoops); 1474 verifyFormat("for (;;)\n" 1475 " for (;;) continue;", 1476 AllowsMergedLoops); 1477 verifyFormat("for (;;)\n" 1478 " while (true) continue;", 1479 AllowsMergedLoops); 1480 verifyFormat("while (true)\n" 1481 " for (;;) continue;", 1482 AllowsMergedLoops); 1483 verifyFormat("BOOST_FOREACH (int &v, vec)\n" 1484 " for (;;) continue;", 1485 AllowsMergedLoops); 1486 verifyFormat("for (;;)\n" 1487 " BOOST_FOREACH (int &v, vec) continue;", 1488 AllowsMergedLoops); 1489 verifyFormat("for (;;) // Can't merge this\n" 1490 " continue;", 1491 AllowsMergedLoops); 1492 verifyFormat("for (;;) /* still don't merge */\n" 1493 " continue;", 1494 AllowsMergedLoops); 1495 verifyFormat("do a++;\n" 1496 "while (true);", 1497 AllowsMergedLoops); 1498 verifyFormat("do /* Don't merge */\n" 1499 " a++;\n" 1500 "while (true);", 1501 AllowsMergedLoops); 1502 verifyFormat("do // Don't merge\n" 1503 " a++;\n" 1504 "while (true);", 1505 AllowsMergedLoops); 1506 verifyFormat("do\n" 1507 " // Don't merge\n" 1508 " a++;\n" 1509 "while (true);", 1510 AllowsMergedLoops); 1511 // Without braces labels are interpreted differently. 1512 verifyFormat("{\n" 1513 " do\n" 1514 " label:\n" 1515 " a++;\n" 1516 " while (true);\n" 1517 "}", 1518 AllowsMergedLoops); 1519 } 1520 1521 TEST_F(FormatTest, FormatShortBracedStatements) { 1522 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1523 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1524 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1525 // Not IF to avoid any confusion that IF is somehow special. 1526 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1527 AllowSimpleBracedStatements.ColumnLimit = 40; 1528 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1529 FormatStyle::SBS_Always; 1530 1531 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1532 FormatStyle::SIS_WithoutElse; 1533 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1534 1535 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1536 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1537 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1538 1539 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1540 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1541 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1542 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1543 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1544 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1545 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1546 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1547 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1548 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1549 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1550 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1551 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1552 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1553 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1554 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1555 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1556 AllowSimpleBracedStatements); 1557 verifyFormat("if (true) {\n" 1558 " ffffffffffffffffffffffff();\n" 1559 "}", 1560 AllowSimpleBracedStatements); 1561 verifyFormat("if (true) {\n" 1562 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1563 "}", 1564 AllowSimpleBracedStatements); 1565 verifyFormat("if (true) { //\n" 1566 " f();\n" 1567 "}", 1568 AllowSimpleBracedStatements); 1569 verifyFormat("if (true) {\n" 1570 " f();\n" 1571 " f();\n" 1572 "}", 1573 AllowSimpleBracedStatements); 1574 verifyFormat("if (true) {\n" 1575 " f();\n" 1576 "} else {\n" 1577 " f();\n" 1578 "}", 1579 AllowSimpleBracedStatements); 1580 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1581 AllowSimpleBracedStatements); 1582 verifyFormat("MYIF (true) {\n" 1583 " ffffffffffffffffffffffff();\n" 1584 "}", 1585 AllowSimpleBracedStatements); 1586 verifyFormat("MYIF (true) {\n" 1587 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1588 "}", 1589 AllowSimpleBracedStatements); 1590 verifyFormat("MYIF (true) { //\n" 1591 " f();\n" 1592 "}", 1593 AllowSimpleBracedStatements); 1594 verifyFormat("MYIF (true) {\n" 1595 " f();\n" 1596 " f();\n" 1597 "}", 1598 AllowSimpleBracedStatements); 1599 verifyFormat("MYIF (true) {\n" 1600 " f();\n" 1601 "} else {\n" 1602 " f();\n" 1603 "}", 1604 AllowSimpleBracedStatements); 1605 1606 verifyFormat("struct A2 {\n" 1607 " int X;\n" 1608 "};", 1609 AllowSimpleBracedStatements); 1610 verifyFormat("typedef struct A2 {\n" 1611 " int X;\n" 1612 "} A2_t;", 1613 AllowSimpleBracedStatements); 1614 verifyFormat("template <int> struct A2 {\n" 1615 " struct B {};\n" 1616 "};", 1617 AllowSimpleBracedStatements); 1618 1619 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1620 FormatStyle::SIS_Never; 1621 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1622 verifyFormat("if (true) {\n" 1623 " f();\n" 1624 "}", 1625 AllowSimpleBracedStatements); 1626 verifyFormat("if (true) {\n" 1627 " f();\n" 1628 "} else {\n" 1629 " f();\n" 1630 "}", 1631 AllowSimpleBracedStatements); 1632 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1633 verifyFormat("MYIF (true) {\n" 1634 " f();\n" 1635 "}", 1636 AllowSimpleBracedStatements); 1637 verifyFormat("MYIF (true) {\n" 1638 " f();\n" 1639 "} else {\n" 1640 " f();\n" 1641 "}", 1642 AllowSimpleBracedStatements); 1643 1644 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1645 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1646 verifyFormat("while (true) {\n" 1647 " f();\n" 1648 "}", 1649 AllowSimpleBracedStatements); 1650 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1651 verifyFormat("for (;;) {\n" 1652 " f();\n" 1653 "}", 1654 AllowSimpleBracedStatements); 1655 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1656 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1657 " f();\n" 1658 "}", 1659 AllowSimpleBracedStatements); 1660 1661 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1662 FormatStyle::SIS_WithoutElse; 1663 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1664 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1665 FormatStyle::BWACS_Always; 1666 1667 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1668 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1669 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1670 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1671 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1672 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1673 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1674 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1675 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1676 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1677 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1678 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1679 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1680 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1681 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1682 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1683 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1684 AllowSimpleBracedStatements); 1685 verifyFormat("if (true)\n" 1686 "{\n" 1687 " ffffffffffffffffffffffff();\n" 1688 "}", 1689 AllowSimpleBracedStatements); 1690 verifyFormat("if (true)\n" 1691 "{\n" 1692 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1693 "}", 1694 AllowSimpleBracedStatements); 1695 verifyFormat("if (true)\n" 1696 "{ //\n" 1697 " f();\n" 1698 "}", 1699 AllowSimpleBracedStatements); 1700 verifyFormat("if (true)\n" 1701 "{\n" 1702 " f();\n" 1703 " f();\n" 1704 "}", 1705 AllowSimpleBracedStatements); 1706 verifyFormat("if (true)\n" 1707 "{\n" 1708 " f();\n" 1709 "} else\n" 1710 "{\n" 1711 " f();\n" 1712 "}", 1713 AllowSimpleBracedStatements); 1714 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1715 AllowSimpleBracedStatements); 1716 verifyFormat("MYIF (true)\n" 1717 "{\n" 1718 " ffffffffffffffffffffffff();\n" 1719 "}", 1720 AllowSimpleBracedStatements); 1721 verifyFormat("MYIF (true)\n" 1722 "{\n" 1723 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1724 "}", 1725 AllowSimpleBracedStatements); 1726 verifyFormat("MYIF (true)\n" 1727 "{ //\n" 1728 " f();\n" 1729 "}", 1730 AllowSimpleBracedStatements); 1731 verifyFormat("MYIF (true)\n" 1732 "{\n" 1733 " f();\n" 1734 " f();\n" 1735 "}", 1736 AllowSimpleBracedStatements); 1737 verifyFormat("MYIF (true)\n" 1738 "{\n" 1739 " f();\n" 1740 "} else\n" 1741 "{\n" 1742 " f();\n" 1743 "}", 1744 AllowSimpleBracedStatements); 1745 1746 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1747 FormatStyle::SIS_Never; 1748 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1749 verifyFormat("if (true)\n" 1750 "{\n" 1751 " f();\n" 1752 "}", 1753 AllowSimpleBracedStatements); 1754 verifyFormat("if (true)\n" 1755 "{\n" 1756 " f();\n" 1757 "} else\n" 1758 "{\n" 1759 " f();\n" 1760 "}", 1761 AllowSimpleBracedStatements); 1762 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1763 verifyFormat("MYIF (true)\n" 1764 "{\n" 1765 " f();\n" 1766 "}", 1767 AllowSimpleBracedStatements); 1768 verifyFormat("MYIF (true)\n" 1769 "{\n" 1770 " f();\n" 1771 "} else\n" 1772 "{\n" 1773 " f();\n" 1774 "}", 1775 AllowSimpleBracedStatements); 1776 1777 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1778 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1779 verifyFormat("while (true)\n" 1780 "{\n" 1781 " f();\n" 1782 "}", 1783 AllowSimpleBracedStatements); 1784 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1785 verifyFormat("for (;;)\n" 1786 "{\n" 1787 " f();\n" 1788 "}", 1789 AllowSimpleBracedStatements); 1790 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1791 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1792 "{\n" 1793 " f();\n" 1794 "}", 1795 AllowSimpleBracedStatements); 1796 } 1797 1798 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1799 FormatStyle Style = getLLVMStyleWithColumns(60); 1800 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1801 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1802 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1803 EXPECT_EQ("#define A \\\n" 1804 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1805 " { \\\n" 1806 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1807 " }\n" 1808 "X;", 1809 format("#define A \\\n" 1810 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1811 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1812 " }\n" 1813 "X;", 1814 Style)); 1815 } 1816 1817 TEST_F(FormatTest, ParseIfElse) { 1818 verifyFormat("if (true)\n" 1819 " if (true)\n" 1820 " if (true)\n" 1821 " f();\n" 1822 " else\n" 1823 " g();\n" 1824 " else\n" 1825 " h();\n" 1826 "else\n" 1827 " i();"); 1828 verifyFormat("if (true)\n" 1829 " if (true)\n" 1830 " if (true) {\n" 1831 " if (true)\n" 1832 " f();\n" 1833 " } else {\n" 1834 " g();\n" 1835 " }\n" 1836 " else\n" 1837 " h();\n" 1838 "else {\n" 1839 " i();\n" 1840 "}"); 1841 verifyFormat("if (true)\n" 1842 " if constexpr (true)\n" 1843 " if (true) {\n" 1844 " if constexpr (true)\n" 1845 " f();\n" 1846 " } else {\n" 1847 " g();\n" 1848 " }\n" 1849 " else\n" 1850 " h();\n" 1851 "else {\n" 1852 " i();\n" 1853 "}"); 1854 verifyFormat("if (true)\n" 1855 " if CONSTEXPR (true)\n" 1856 " if (true) {\n" 1857 " if CONSTEXPR (true)\n" 1858 " f();\n" 1859 " } else {\n" 1860 " g();\n" 1861 " }\n" 1862 " else\n" 1863 " h();\n" 1864 "else {\n" 1865 " i();\n" 1866 "}"); 1867 verifyFormat("void f() {\n" 1868 " if (a) {\n" 1869 " } else {\n" 1870 " }\n" 1871 "}"); 1872 } 1873 1874 TEST_F(FormatTest, ElseIf) { 1875 verifyFormat("if (a) {\n} else if (b) {\n}"); 1876 verifyFormat("if (a)\n" 1877 " f();\n" 1878 "else if (b)\n" 1879 " g();\n" 1880 "else\n" 1881 " h();"); 1882 verifyFormat("if (a)\n" 1883 " f();\n" 1884 "else // comment\n" 1885 " if (b) {\n" 1886 " g();\n" 1887 " h();\n" 1888 " }"); 1889 verifyFormat("if constexpr (a)\n" 1890 " f();\n" 1891 "else if constexpr (b)\n" 1892 " g();\n" 1893 "else\n" 1894 " h();"); 1895 verifyFormat("if CONSTEXPR (a)\n" 1896 " f();\n" 1897 "else if CONSTEXPR (b)\n" 1898 " g();\n" 1899 "else\n" 1900 " h();"); 1901 verifyFormat("if (a) {\n" 1902 " f();\n" 1903 "}\n" 1904 "// or else ..\n" 1905 "else {\n" 1906 " g()\n" 1907 "}"); 1908 1909 verifyFormat("if (a) {\n" 1910 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1911 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1912 "}"); 1913 verifyFormat("if (a) {\n" 1914 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1915 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1916 "}"); 1917 verifyFormat("if (a) {\n" 1918 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1919 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1920 "}"); 1921 verifyFormat("if (a) {\n" 1922 "} else if (\n" 1923 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1924 "}", 1925 getLLVMStyleWithColumns(62)); 1926 verifyFormat("if (a) {\n" 1927 "} else if constexpr (\n" 1928 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1929 "}", 1930 getLLVMStyleWithColumns(62)); 1931 verifyFormat("if (a) {\n" 1932 "} else if CONSTEXPR (\n" 1933 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1934 "}", 1935 getLLVMStyleWithColumns(62)); 1936 } 1937 1938 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 1939 FormatStyle Style = getLLVMStyle(); 1940 // Check first the default LLVM style 1941 // Style.PointerAlignment = FormatStyle::PAS_Right; 1942 // Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 1943 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 1944 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 1945 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 1946 verifyFormat("int *f1(int &a) const &;", Style); 1947 verifyFormat("int *f1(int &a) const & = 0;", Style); 1948 verifyFormat("int *a = f1();", Style); 1949 verifyFormat("int &b = f2();", Style); 1950 verifyFormat("int &&c = f3();", Style); 1951 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1952 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1953 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1954 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 1955 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1956 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1957 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1958 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 1959 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 1960 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 1961 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 1962 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 1963 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 1964 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 1965 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 1966 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 1967 1968 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 1969 verifyFormat("Const unsigned int *c;\n" 1970 "const unsigned int *d;\n" 1971 "Const unsigned int &e;\n" 1972 "const unsigned int &f;\n" 1973 "const unsigned &&g;\n" 1974 "Const unsigned h;", 1975 Style); 1976 1977 Style.PointerAlignment = FormatStyle::PAS_Left; 1978 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 1979 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 1980 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 1981 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 1982 verifyFormat("int* f1(int& a) const& = 0;", Style); 1983 verifyFormat("int* a = f1();", Style); 1984 verifyFormat("int& b = f2();", Style); 1985 verifyFormat("int&& c = f3();", Style); 1986 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 1987 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 1988 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 1989 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 1990 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 1991 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 1992 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 1993 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 1994 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 1995 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 1996 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 1997 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 1998 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 1999 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2000 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2001 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2002 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2003 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2004 2005 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2006 verifyFormat("Const unsigned int* c;\n" 2007 "const unsigned int* d;\n" 2008 "Const unsigned int& e;\n" 2009 "const unsigned int& f;\n" 2010 "const unsigned&& g;\n" 2011 "Const unsigned h;", 2012 Style); 2013 2014 Style.PointerAlignment = FormatStyle::PAS_Right; 2015 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2016 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2017 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2018 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2019 verifyFormat("int *a = f1();", Style); 2020 verifyFormat("int& b = f2();", Style); 2021 verifyFormat("int&& c = f3();", Style); 2022 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2023 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2024 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2025 2026 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2027 verifyFormat("Const unsigned int *c;\n" 2028 "const unsigned int *d;\n" 2029 "Const unsigned int& e;\n" 2030 "const unsigned int& f;\n" 2031 "const unsigned g;\n" 2032 "Const unsigned h;", 2033 Style); 2034 2035 Style.PointerAlignment = FormatStyle::PAS_Left; 2036 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2037 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2038 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2039 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2040 verifyFormat("int* a = f1();", Style); 2041 verifyFormat("int & b = f2();", Style); 2042 verifyFormat("int && c = f3();", Style); 2043 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2044 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2045 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2046 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2047 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2048 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2049 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2050 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2051 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2052 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2053 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2054 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2055 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2056 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2057 2058 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2059 verifyFormat("Const unsigned int* c;\n" 2060 "const unsigned int* d;\n" 2061 "Const unsigned int & e;\n" 2062 "const unsigned int & f;\n" 2063 "const unsigned && g;\n" 2064 "Const unsigned h;", 2065 Style); 2066 2067 Style.PointerAlignment = FormatStyle::PAS_Middle; 2068 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2069 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2070 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2071 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2072 verifyFormat("int * a = f1();", Style); 2073 verifyFormat("int &b = f2();", Style); 2074 verifyFormat("int &&c = f3();", Style); 2075 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2076 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2077 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2078 2079 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2080 // specifically handled 2081 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2082 } 2083 2084 TEST_F(FormatTest, FormatsForLoop) { 2085 verifyFormat( 2086 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2087 " ++VeryVeryLongLoopVariable)\n" 2088 " ;"); 2089 verifyFormat("for (;;)\n" 2090 " f();"); 2091 verifyFormat("for (;;) {\n}"); 2092 verifyFormat("for (;;) {\n" 2093 " f();\n" 2094 "}"); 2095 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2096 2097 verifyFormat( 2098 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2099 " E = UnwrappedLines.end();\n" 2100 " I != E; ++I) {\n}"); 2101 2102 verifyFormat( 2103 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2104 " ++IIIII) {\n}"); 2105 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2106 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2107 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2108 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2109 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2110 " E = FD->getDeclsInPrototypeScope().end();\n" 2111 " I != E; ++I) {\n}"); 2112 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2113 " I = Container.begin(),\n" 2114 " E = Container.end();\n" 2115 " I != E; ++I) {\n}", 2116 getLLVMStyleWithColumns(76)); 2117 2118 verifyFormat( 2119 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2120 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2121 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2122 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2123 " ++aaaaaaaaaaa) {\n}"); 2124 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2125 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2126 " ++i) {\n}"); 2127 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2128 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2129 "}"); 2130 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2131 " aaaaaaaaaa);\n" 2132 " iter; ++iter) {\n" 2133 "}"); 2134 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2136 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2137 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2138 2139 // These should not be formatted as Objective-C for-in loops. 2140 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2141 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2142 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2143 verifyFormat( 2144 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2145 2146 FormatStyle NoBinPacking = getLLVMStyle(); 2147 NoBinPacking.BinPackParameters = false; 2148 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2149 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2150 " aaaaaaaaaaaaaaaa,\n" 2151 " aaaaaaaaaaaaaaaa,\n" 2152 " aaaaaaaaaaaaaaaa);\n" 2153 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2154 "}", 2155 NoBinPacking); 2156 verifyFormat( 2157 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2158 " E = UnwrappedLines.end();\n" 2159 " I != E;\n" 2160 " ++I) {\n}", 2161 NoBinPacking); 2162 2163 FormatStyle AlignLeft = getLLVMStyle(); 2164 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2165 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2166 } 2167 2168 TEST_F(FormatTest, RangeBasedForLoops) { 2169 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2170 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2171 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2172 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2173 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2174 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2175 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2176 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2177 } 2178 2179 TEST_F(FormatTest, ForEachLoops) { 2180 FormatStyle Style = getLLVMStyle(); 2181 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2182 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2183 verifyFormat("void f() {\n" 2184 " for (;;) {\n" 2185 " }\n" 2186 " foreach (Item *item, itemlist) {\n" 2187 " }\n" 2188 " Q_FOREACH (Item *item, itemlist) {\n" 2189 " }\n" 2190 " BOOST_FOREACH (Item *item, itemlist) {\n" 2191 " }\n" 2192 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2193 "}", 2194 Style); 2195 verifyFormat("void f() {\n" 2196 " for (;;)\n" 2197 " int j = 1;\n" 2198 " Q_FOREACH (int v, vec)\n" 2199 " v *= 2;\n" 2200 " for (;;) {\n" 2201 " int j = 1;\n" 2202 " }\n" 2203 " Q_FOREACH (int v, vec) {\n" 2204 " v *= 2;\n" 2205 " }\n" 2206 "}", 2207 Style); 2208 2209 FormatStyle ShortBlocks = getLLVMStyle(); 2210 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2211 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2212 verifyFormat("void f() {\n" 2213 " for (;;)\n" 2214 " int j = 1;\n" 2215 " Q_FOREACH (int &v, vec)\n" 2216 " v *= 2;\n" 2217 " for (;;) {\n" 2218 " int j = 1;\n" 2219 " }\n" 2220 " Q_FOREACH (int &v, vec) {\n" 2221 " int j = 1;\n" 2222 " }\n" 2223 "}", 2224 ShortBlocks); 2225 2226 FormatStyle ShortLoops = getLLVMStyle(); 2227 ShortLoops.AllowShortLoopsOnASingleLine = true; 2228 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2229 verifyFormat("void f() {\n" 2230 " for (;;) int j = 1;\n" 2231 " Q_FOREACH (int &v, vec) int j = 1;\n" 2232 " for (;;) {\n" 2233 " int j = 1;\n" 2234 " }\n" 2235 " Q_FOREACH (int &v, vec) {\n" 2236 " int j = 1;\n" 2237 " }\n" 2238 "}", 2239 ShortLoops); 2240 2241 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2242 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2243 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2244 verifyFormat("void f() {\n" 2245 " for (;;) int j = 1;\n" 2246 " Q_FOREACH (int &v, vec) int j = 1;\n" 2247 " for (;;) { int j = 1; }\n" 2248 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2249 "}", 2250 ShortBlocksAndLoops); 2251 2252 Style.SpaceBeforeParens = 2253 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2254 verifyFormat("void f() {\n" 2255 " for (;;) {\n" 2256 " }\n" 2257 " foreach(Item *item, itemlist) {\n" 2258 " }\n" 2259 " Q_FOREACH(Item *item, itemlist) {\n" 2260 " }\n" 2261 " BOOST_FOREACH(Item *item, itemlist) {\n" 2262 " }\n" 2263 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2264 "}", 2265 Style); 2266 2267 // As function-like macros. 2268 verifyFormat("#define foreach(x, y)\n" 2269 "#define Q_FOREACH(x, y)\n" 2270 "#define BOOST_FOREACH(x, y)\n" 2271 "#define UNKNOWN_FOREACH(x, y)\n"); 2272 2273 // Not as function-like macros. 2274 verifyFormat("#define foreach (x, y)\n" 2275 "#define Q_FOREACH (x, y)\n" 2276 "#define BOOST_FOREACH (x, y)\n" 2277 "#define UNKNOWN_FOREACH (x, y)\n"); 2278 2279 // handle microsoft non standard extension 2280 verifyFormat("for each (char c in x->MyStringProperty)"); 2281 } 2282 2283 TEST_F(FormatTest, FormatsWhileLoop) { 2284 verifyFormat("while (true) {\n}"); 2285 verifyFormat("while (true)\n" 2286 " f();"); 2287 verifyFormat("while () {\n}"); 2288 verifyFormat("while () {\n" 2289 " f();\n" 2290 "}"); 2291 } 2292 2293 TEST_F(FormatTest, FormatsDoWhile) { 2294 verifyFormat("do {\n" 2295 " do_something();\n" 2296 "} while (something());"); 2297 verifyFormat("do\n" 2298 " do_something();\n" 2299 "while (something());"); 2300 } 2301 2302 TEST_F(FormatTest, FormatsSwitchStatement) { 2303 verifyFormat("switch (x) {\n" 2304 "case 1:\n" 2305 " f();\n" 2306 " break;\n" 2307 "case kFoo:\n" 2308 "case ns::kBar:\n" 2309 "case kBaz:\n" 2310 " break;\n" 2311 "default:\n" 2312 " g();\n" 2313 " break;\n" 2314 "}"); 2315 verifyFormat("switch (x) {\n" 2316 "case 1: {\n" 2317 " f();\n" 2318 " break;\n" 2319 "}\n" 2320 "case 2: {\n" 2321 " break;\n" 2322 "}\n" 2323 "}"); 2324 verifyFormat("switch (x) {\n" 2325 "case 1: {\n" 2326 " f();\n" 2327 " {\n" 2328 " g();\n" 2329 " h();\n" 2330 " }\n" 2331 " break;\n" 2332 "}\n" 2333 "}"); 2334 verifyFormat("switch (x) {\n" 2335 "case 1: {\n" 2336 " f();\n" 2337 " if (foo) {\n" 2338 " g();\n" 2339 " h();\n" 2340 " }\n" 2341 " break;\n" 2342 "}\n" 2343 "}"); 2344 verifyFormat("switch (x) {\n" 2345 "case 1: {\n" 2346 " f();\n" 2347 " g();\n" 2348 "} break;\n" 2349 "}"); 2350 verifyFormat("switch (test)\n" 2351 " ;"); 2352 verifyFormat("switch (x) {\n" 2353 "default: {\n" 2354 " // Do nothing.\n" 2355 "}\n" 2356 "}"); 2357 verifyFormat("switch (x) {\n" 2358 "// comment\n" 2359 "// if 1, do f()\n" 2360 "case 1:\n" 2361 " f();\n" 2362 "}"); 2363 verifyFormat("switch (x) {\n" 2364 "case 1:\n" 2365 " // Do amazing stuff\n" 2366 " {\n" 2367 " f();\n" 2368 " g();\n" 2369 " }\n" 2370 " break;\n" 2371 "}"); 2372 verifyFormat("#define A \\\n" 2373 " switch (x) { \\\n" 2374 " case a: \\\n" 2375 " foo = b; \\\n" 2376 " }", 2377 getLLVMStyleWithColumns(20)); 2378 verifyFormat("#define OPERATION_CASE(name) \\\n" 2379 " case OP_name: \\\n" 2380 " return operations::Operation##name\n", 2381 getLLVMStyleWithColumns(40)); 2382 verifyFormat("switch (x) {\n" 2383 "case 1:;\n" 2384 "default:;\n" 2385 " int i;\n" 2386 "}"); 2387 2388 verifyGoogleFormat("switch (x) {\n" 2389 " case 1:\n" 2390 " f();\n" 2391 " break;\n" 2392 " case kFoo:\n" 2393 " case ns::kBar:\n" 2394 " case kBaz:\n" 2395 " break;\n" 2396 " default:\n" 2397 " g();\n" 2398 " break;\n" 2399 "}"); 2400 verifyGoogleFormat("switch (x) {\n" 2401 " case 1: {\n" 2402 " f();\n" 2403 " break;\n" 2404 " }\n" 2405 "}"); 2406 verifyGoogleFormat("switch (test)\n" 2407 " ;"); 2408 2409 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2410 " case OP_name: \\\n" 2411 " return operations::Operation##name\n"); 2412 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2413 " // Get the correction operation class.\n" 2414 " switch (OpCode) {\n" 2415 " CASE(Add);\n" 2416 " CASE(Subtract);\n" 2417 " default:\n" 2418 " return operations::Unknown;\n" 2419 " }\n" 2420 "#undef OPERATION_CASE\n" 2421 "}"); 2422 verifyFormat("DEBUG({\n" 2423 " switch (x) {\n" 2424 " case A:\n" 2425 " f();\n" 2426 " break;\n" 2427 " // fallthrough\n" 2428 " case B:\n" 2429 " g();\n" 2430 " break;\n" 2431 " }\n" 2432 "});"); 2433 EXPECT_EQ("DEBUG({\n" 2434 " switch (x) {\n" 2435 " case A:\n" 2436 " f();\n" 2437 " break;\n" 2438 " // On B:\n" 2439 " case B:\n" 2440 " g();\n" 2441 " break;\n" 2442 " }\n" 2443 "});", 2444 format("DEBUG({\n" 2445 " switch (x) {\n" 2446 " case A:\n" 2447 " f();\n" 2448 " break;\n" 2449 " // On B:\n" 2450 " case B:\n" 2451 " g();\n" 2452 " break;\n" 2453 " }\n" 2454 "});", 2455 getLLVMStyle())); 2456 EXPECT_EQ("switch (n) {\n" 2457 "case 0: {\n" 2458 " return false;\n" 2459 "}\n" 2460 "default: {\n" 2461 " return true;\n" 2462 "}\n" 2463 "}", 2464 format("switch (n)\n" 2465 "{\n" 2466 "case 0: {\n" 2467 " return false;\n" 2468 "}\n" 2469 "default: {\n" 2470 " return true;\n" 2471 "}\n" 2472 "}", 2473 getLLVMStyle())); 2474 verifyFormat("switch (a) {\n" 2475 "case (b):\n" 2476 " return;\n" 2477 "}"); 2478 2479 verifyFormat("switch (a) {\n" 2480 "case some_namespace::\n" 2481 " some_constant:\n" 2482 " return;\n" 2483 "}", 2484 getLLVMStyleWithColumns(34)); 2485 2486 FormatStyle Style = getLLVMStyle(); 2487 Style.IndentCaseLabels = true; 2488 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2489 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2490 Style.BraceWrapping.AfterCaseLabel = true; 2491 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2492 EXPECT_EQ("switch (n)\n" 2493 "{\n" 2494 " case 0:\n" 2495 " {\n" 2496 " return false;\n" 2497 " }\n" 2498 " default:\n" 2499 " {\n" 2500 " return true;\n" 2501 " }\n" 2502 "}", 2503 format("switch (n) {\n" 2504 " case 0: {\n" 2505 " return false;\n" 2506 " }\n" 2507 " default: {\n" 2508 " return true;\n" 2509 " }\n" 2510 "}", 2511 Style)); 2512 Style.BraceWrapping.AfterCaseLabel = false; 2513 EXPECT_EQ("switch (n)\n" 2514 "{\n" 2515 " case 0: {\n" 2516 " return false;\n" 2517 " }\n" 2518 " default: {\n" 2519 " return true;\n" 2520 " }\n" 2521 "}", 2522 format("switch (n) {\n" 2523 " case 0:\n" 2524 " {\n" 2525 " return false;\n" 2526 " }\n" 2527 " default:\n" 2528 " {\n" 2529 " return true;\n" 2530 " }\n" 2531 "}", 2532 Style)); 2533 Style.IndentCaseLabels = false; 2534 Style.IndentCaseBlocks = true; 2535 EXPECT_EQ("switch (n)\n" 2536 "{\n" 2537 "case 0:\n" 2538 " {\n" 2539 " return false;\n" 2540 " }\n" 2541 "case 1:\n" 2542 " break;\n" 2543 "default:\n" 2544 " {\n" 2545 " return true;\n" 2546 " }\n" 2547 "}", 2548 format("switch (n) {\n" 2549 "case 0: {\n" 2550 " return false;\n" 2551 "}\n" 2552 "case 1:\n" 2553 " break;\n" 2554 "default: {\n" 2555 " return true;\n" 2556 "}\n" 2557 "}", 2558 Style)); 2559 Style.IndentCaseLabels = true; 2560 Style.IndentCaseBlocks = true; 2561 EXPECT_EQ("switch (n)\n" 2562 "{\n" 2563 " case 0:\n" 2564 " {\n" 2565 " return false;\n" 2566 " }\n" 2567 " case 1:\n" 2568 " break;\n" 2569 " default:\n" 2570 " {\n" 2571 " return true;\n" 2572 " }\n" 2573 "}", 2574 format("switch (n) {\n" 2575 "case 0: {\n" 2576 " return false;\n" 2577 "}\n" 2578 "case 1:\n" 2579 " break;\n" 2580 "default: {\n" 2581 " return true;\n" 2582 "}\n" 2583 "}", 2584 Style)); 2585 } 2586 2587 TEST_F(FormatTest, CaseRanges) { 2588 verifyFormat("switch (x) {\n" 2589 "case 'A' ... 'Z':\n" 2590 "case 1 ... 5:\n" 2591 "case a ... b:\n" 2592 " break;\n" 2593 "}"); 2594 } 2595 2596 TEST_F(FormatTest, ShortEnums) { 2597 FormatStyle Style = getLLVMStyle(); 2598 Style.AllowShortEnumsOnASingleLine = true; 2599 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2600 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2601 Style.AllowShortEnumsOnASingleLine = false; 2602 verifyFormat("enum {\n" 2603 " A,\n" 2604 " B,\n" 2605 " C\n" 2606 "} ShortEnum1, ShortEnum2;", 2607 Style); 2608 verifyFormat("typedef enum {\n" 2609 " A,\n" 2610 " B,\n" 2611 " C\n" 2612 "} ShortEnum1, ShortEnum2;", 2613 Style); 2614 verifyFormat("enum {\n" 2615 " A,\n" 2616 "} ShortEnum1, ShortEnum2;", 2617 Style); 2618 verifyFormat("typedef enum {\n" 2619 " A,\n" 2620 "} ShortEnum1, ShortEnum2;", 2621 Style); 2622 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2623 Style.BraceWrapping.AfterEnum = true; 2624 verifyFormat("enum\n" 2625 "{\n" 2626 " A,\n" 2627 " B,\n" 2628 " C\n" 2629 "} ShortEnum1, ShortEnum2;", 2630 Style); 2631 verifyFormat("typedef enum\n" 2632 "{\n" 2633 " A,\n" 2634 " B,\n" 2635 " C\n" 2636 "} ShortEnum1, ShortEnum2;", 2637 Style); 2638 } 2639 2640 TEST_F(FormatTest, ShortCaseLabels) { 2641 FormatStyle Style = getLLVMStyle(); 2642 Style.AllowShortCaseLabelsOnASingleLine = true; 2643 verifyFormat("switch (a) {\n" 2644 "case 1: x = 1; break;\n" 2645 "case 2: return;\n" 2646 "case 3:\n" 2647 "case 4:\n" 2648 "case 5: return;\n" 2649 "case 6: // comment\n" 2650 " return;\n" 2651 "case 7:\n" 2652 " // comment\n" 2653 " return;\n" 2654 "case 8:\n" 2655 " x = 8; // comment\n" 2656 " break;\n" 2657 "default: y = 1; break;\n" 2658 "}", 2659 Style); 2660 verifyFormat("switch (a) {\n" 2661 "case 0: return; // comment\n" 2662 "case 1: break; // comment\n" 2663 "case 2: return;\n" 2664 "// comment\n" 2665 "case 3: return;\n" 2666 "// comment 1\n" 2667 "// comment 2\n" 2668 "// comment 3\n" 2669 "case 4: break; /* comment */\n" 2670 "case 5:\n" 2671 " // comment\n" 2672 " break;\n" 2673 "case 6: /* comment */ x = 1; break;\n" 2674 "case 7: x = /* comment */ 1; break;\n" 2675 "case 8:\n" 2676 " x = 1; /* comment */\n" 2677 " break;\n" 2678 "case 9:\n" 2679 " break; // comment line 1\n" 2680 " // comment line 2\n" 2681 "}", 2682 Style); 2683 EXPECT_EQ("switch (a) {\n" 2684 "case 1:\n" 2685 " x = 8;\n" 2686 " // fall through\n" 2687 "case 2: x = 8;\n" 2688 "// comment\n" 2689 "case 3:\n" 2690 " return; /* comment line 1\n" 2691 " * comment line 2 */\n" 2692 "case 4: i = 8;\n" 2693 "// something else\n" 2694 "#if FOO\n" 2695 "case 5: break;\n" 2696 "#endif\n" 2697 "}", 2698 format("switch (a) {\n" 2699 "case 1: x = 8;\n" 2700 " // fall through\n" 2701 "case 2:\n" 2702 " x = 8;\n" 2703 "// comment\n" 2704 "case 3:\n" 2705 " return; /* comment line 1\n" 2706 " * comment line 2 */\n" 2707 "case 4:\n" 2708 " i = 8;\n" 2709 "// something else\n" 2710 "#if FOO\n" 2711 "case 5: break;\n" 2712 "#endif\n" 2713 "}", 2714 Style)); 2715 EXPECT_EQ("switch (a) {\n" 2716 "case 0:\n" 2717 " return; // long long long long long long long long long long " 2718 "long long comment\n" 2719 " // line\n" 2720 "}", 2721 format("switch (a) {\n" 2722 "case 0: return; // long long long long long long long long " 2723 "long long long long comment line\n" 2724 "}", 2725 Style)); 2726 EXPECT_EQ("switch (a) {\n" 2727 "case 0:\n" 2728 " return; /* long long long long long long long long long long " 2729 "long long comment\n" 2730 " line */\n" 2731 "}", 2732 format("switch (a) {\n" 2733 "case 0: return; /* long long long long long long long long " 2734 "long long long long comment line */\n" 2735 "}", 2736 Style)); 2737 verifyFormat("switch (a) {\n" 2738 "#if FOO\n" 2739 "case 0: return 0;\n" 2740 "#endif\n" 2741 "}", 2742 Style); 2743 verifyFormat("switch (a) {\n" 2744 "case 1: {\n" 2745 "}\n" 2746 "case 2: {\n" 2747 " return;\n" 2748 "}\n" 2749 "case 3: {\n" 2750 " x = 1;\n" 2751 " return;\n" 2752 "}\n" 2753 "case 4:\n" 2754 " if (x)\n" 2755 " return;\n" 2756 "}", 2757 Style); 2758 Style.ColumnLimit = 21; 2759 verifyFormat("switch (a) {\n" 2760 "case 1: x = 1; break;\n" 2761 "case 2: return;\n" 2762 "case 3:\n" 2763 "case 4:\n" 2764 "case 5: return;\n" 2765 "default:\n" 2766 " y = 1;\n" 2767 " break;\n" 2768 "}", 2769 Style); 2770 Style.ColumnLimit = 80; 2771 Style.AllowShortCaseLabelsOnASingleLine = false; 2772 Style.IndentCaseLabels = true; 2773 EXPECT_EQ("switch (n) {\n" 2774 " default /*comments*/:\n" 2775 " return true;\n" 2776 " case 0:\n" 2777 " return false;\n" 2778 "}", 2779 format("switch (n) {\n" 2780 "default/*comments*/:\n" 2781 " return true;\n" 2782 "case 0:\n" 2783 " return false;\n" 2784 "}", 2785 Style)); 2786 Style.AllowShortCaseLabelsOnASingleLine = true; 2787 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2788 Style.BraceWrapping.AfterCaseLabel = true; 2789 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2790 EXPECT_EQ("switch (n)\n" 2791 "{\n" 2792 " case 0:\n" 2793 " {\n" 2794 " return false;\n" 2795 " }\n" 2796 " default:\n" 2797 " {\n" 2798 " return true;\n" 2799 " }\n" 2800 "}", 2801 format("switch (n) {\n" 2802 " case 0: {\n" 2803 " return false;\n" 2804 " }\n" 2805 " default:\n" 2806 " {\n" 2807 " return true;\n" 2808 " }\n" 2809 "}", 2810 Style)); 2811 } 2812 2813 TEST_F(FormatTest, FormatsLabels) { 2814 verifyFormat("void f() {\n" 2815 " some_code();\n" 2816 "test_label:\n" 2817 " some_other_code();\n" 2818 " {\n" 2819 " some_more_code();\n" 2820 " another_label:\n" 2821 " some_more_code();\n" 2822 " }\n" 2823 "}"); 2824 verifyFormat("{\n" 2825 " some_code();\n" 2826 "test_label:\n" 2827 " some_other_code();\n" 2828 "}"); 2829 verifyFormat("{\n" 2830 " some_code();\n" 2831 "test_label:;\n" 2832 " int i = 0;\n" 2833 "}"); 2834 FormatStyle Style = getLLVMStyle(); 2835 Style.IndentGotoLabels = false; 2836 verifyFormat("void f() {\n" 2837 " some_code();\n" 2838 "test_label:\n" 2839 " some_other_code();\n" 2840 " {\n" 2841 " some_more_code();\n" 2842 "another_label:\n" 2843 " some_more_code();\n" 2844 " }\n" 2845 "}", 2846 Style); 2847 verifyFormat("{\n" 2848 " some_code();\n" 2849 "test_label:\n" 2850 " some_other_code();\n" 2851 "}", 2852 Style); 2853 verifyFormat("{\n" 2854 " some_code();\n" 2855 "test_label:;\n" 2856 " int i = 0;\n" 2857 "}"); 2858 } 2859 2860 TEST_F(FormatTest, MultiLineControlStatements) { 2861 FormatStyle Style = getLLVMStyleWithColumns(20); 2862 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2863 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2864 // Short lines should keep opening brace on same line. 2865 EXPECT_EQ("if (foo) {\n" 2866 " bar();\n" 2867 "}", 2868 format("if(foo){bar();}", Style)); 2869 EXPECT_EQ("if (foo) {\n" 2870 " bar();\n" 2871 "} else {\n" 2872 " baz();\n" 2873 "}", 2874 format("if(foo){bar();}else{baz();}", Style)); 2875 EXPECT_EQ("if (foo && bar) {\n" 2876 " baz();\n" 2877 "}", 2878 format("if(foo&&bar){baz();}", Style)); 2879 EXPECT_EQ("if (foo) {\n" 2880 " bar();\n" 2881 "} else if (baz) {\n" 2882 " quux();\n" 2883 "}", 2884 format("if(foo){bar();}else if(baz){quux();}", Style)); 2885 EXPECT_EQ( 2886 "if (foo) {\n" 2887 " bar();\n" 2888 "} else if (baz) {\n" 2889 " quux();\n" 2890 "} else {\n" 2891 " foobar();\n" 2892 "}", 2893 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 2894 EXPECT_EQ("for (;;) {\n" 2895 " foo();\n" 2896 "}", 2897 format("for(;;){foo();}")); 2898 EXPECT_EQ("while (1) {\n" 2899 " foo();\n" 2900 "}", 2901 format("while(1){foo();}", Style)); 2902 EXPECT_EQ("switch (foo) {\n" 2903 "case bar:\n" 2904 " return;\n" 2905 "}", 2906 format("switch(foo){case bar:return;}", Style)); 2907 EXPECT_EQ("try {\n" 2908 " foo();\n" 2909 "} catch (...) {\n" 2910 " bar();\n" 2911 "}", 2912 format("try{foo();}catch(...){bar();}", Style)); 2913 EXPECT_EQ("do {\n" 2914 " foo();\n" 2915 "} while (bar &&\n" 2916 " baz);", 2917 format("do{foo();}while(bar&&baz);", Style)); 2918 // Long lines should put opening brace on new line. 2919 EXPECT_EQ("if (foo && bar &&\n" 2920 " baz)\n" 2921 "{\n" 2922 " quux();\n" 2923 "}", 2924 format("if(foo&&bar&&baz){quux();}", Style)); 2925 EXPECT_EQ("if (foo && bar &&\n" 2926 " baz)\n" 2927 "{\n" 2928 " quux();\n" 2929 "}", 2930 format("if (foo && bar &&\n" 2931 " baz) {\n" 2932 " quux();\n" 2933 "}", 2934 Style)); 2935 EXPECT_EQ("if (foo) {\n" 2936 " bar();\n" 2937 "} else if (baz ||\n" 2938 " quux)\n" 2939 "{\n" 2940 " foobar();\n" 2941 "}", 2942 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 2943 EXPECT_EQ( 2944 "if (foo) {\n" 2945 " bar();\n" 2946 "} else if (baz ||\n" 2947 " quux)\n" 2948 "{\n" 2949 " foobar();\n" 2950 "} else {\n" 2951 " barbaz();\n" 2952 "}", 2953 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 2954 Style)); 2955 EXPECT_EQ("for (int i = 0;\n" 2956 " i < 10; ++i)\n" 2957 "{\n" 2958 " foo();\n" 2959 "}", 2960 format("for(int i=0;i<10;++i){foo();}", Style)); 2961 EXPECT_EQ("foreach (int i,\n" 2962 " list)\n" 2963 "{\n" 2964 " foo();\n" 2965 "}", 2966 format("foreach(int i, list){foo();}", Style)); 2967 Style.ColumnLimit = 2968 40; // to concentrate at brace wrapping, not line wrap due to column limit 2969 EXPECT_EQ("foreach (int i, list) {\n" 2970 " foo();\n" 2971 "}", 2972 format("foreach(int i, list){foo();}", Style)); 2973 Style.ColumnLimit = 2974 20; // to concentrate at brace wrapping, not line wrap due to column limit 2975 EXPECT_EQ("while (foo || bar ||\n" 2976 " baz)\n" 2977 "{\n" 2978 " quux();\n" 2979 "}", 2980 format("while(foo||bar||baz){quux();}", Style)); 2981 EXPECT_EQ("switch (\n" 2982 " foo = barbaz)\n" 2983 "{\n" 2984 "case quux:\n" 2985 " return;\n" 2986 "}", 2987 format("switch(foo=barbaz){case quux:return;}", Style)); 2988 EXPECT_EQ("try {\n" 2989 " foo();\n" 2990 "} catch (\n" 2991 " Exception &bar)\n" 2992 "{\n" 2993 " baz();\n" 2994 "}", 2995 format("try{foo();}catch(Exception&bar){baz();}", Style)); 2996 Style.ColumnLimit = 2997 40; // to concentrate at brace wrapping, not line wrap due to column limit 2998 EXPECT_EQ("try {\n" 2999 " foo();\n" 3000 "} catch (Exception &bar) {\n" 3001 " baz();\n" 3002 "}", 3003 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3004 Style.ColumnLimit = 3005 20; // to concentrate at brace wrapping, not line wrap due to column limit 3006 3007 Style.BraceWrapping.BeforeElse = true; 3008 EXPECT_EQ( 3009 "if (foo) {\n" 3010 " bar();\n" 3011 "}\n" 3012 "else if (baz ||\n" 3013 " quux)\n" 3014 "{\n" 3015 " foobar();\n" 3016 "}\n" 3017 "else {\n" 3018 " barbaz();\n" 3019 "}", 3020 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3021 Style)); 3022 3023 Style.BraceWrapping.BeforeCatch = true; 3024 EXPECT_EQ("try {\n" 3025 " foo();\n" 3026 "}\n" 3027 "catch (...) {\n" 3028 " baz();\n" 3029 "}", 3030 format("try{foo();}catch(...){baz();}", Style)); 3031 3032 Style.BraceWrapping.AfterFunction = true; 3033 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3034 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3035 Style.ColumnLimit = 80; 3036 verifyFormat("void shortfunction() { bar(); }", Style); 3037 3038 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3039 verifyFormat("void shortfunction()\n" 3040 "{\n" 3041 " bar();\n" 3042 "}", 3043 Style); 3044 } 3045 3046 TEST_F(FormatTest, BeforeWhile) { 3047 FormatStyle Style = getLLVMStyle(); 3048 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3049 3050 verifyFormat("do {\n" 3051 " foo();\n" 3052 "} while (1);", 3053 Style); 3054 Style.BraceWrapping.BeforeWhile = true; 3055 verifyFormat("do {\n" 3056 " foo();\n" 3057 "}\n" 3058 "while (1);", 3059 Style); 3060 } 3061 3062 //===----------------------------------------------------------------------===// 3063 // Tests for classes, namespaces, etc. 3064 //===----------------------------------------------------------------------===// 3065 3066 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3067 verifyFormat("class A {};"); 3068 } 3069 3070 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3071 verifyFormat("class A {\n" 3072 "public:\n" 3073 "public: // comment\n" 3074 "protected:\n" 3075 "private:\n" 3076 " void f() {}\n" 3077 "};"); 3078 verifyFormat("export class A {\n" 3079 "public:\n" 3080 "public: // comment\n" 3081 "protected:\n" 3082 "private:\n" 3083 " void f() {}\n" 3084 "};"); 3085 verifyGoogleFormat("class A {\n" 3086 " public:\n" 3087 " protected:\n" 3088 " private:\n" 3089 " void f() {}\n" 3090 "};"); 3091 verifyGoogleFormat("export class A {\n" 3092 " public:\n" 3093 " protected:\n" 3094 " private:\n" 3095 " void f() {}\n" 3096 "};"); 3097 verifyFormat("class A {\n" 3098 "public slots:\n" 3099 " void f1() {}\n" 3100 "public Q_SLOTS:\n" 3101 " void f2() {}\n" 3102 "protected slots:\n" 3103 " void f3() {}\n" 3104 "protected Q_SLOTS:\n" 3105 " void f4() {}\n" 3106 "private slots:\n" 3107 " void f5() {}\n" 3108 "private Q_SLOTS:\n" 3109 " void f6() {}\n" 3110 "signals:\n" 3111 " void g1();\n" 3112 "Q_SIGNALS:\n" 3113 " void g2();\n" 3114 "};"); 3115 3116 // Don't interpret 'signals' the wrong way. 3117 verifyFormat("signals.set();"); 3118 verifyFormat("for (Signals signals : f()) {\n}"); 3119 verifyFormat("{\n" 3120 " signals.set(); // This needs indentation.\n" 3121 "}"); 3122 verifyFormat("void f() {\n" 3123 "label:\n" 3124 " signals.baz();\n" 3125 "}"); 3126 } 3127 3128 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3129 EXPECT_EQ("class A {\n" 3130 "public:\n" 3131 " void f();\n" 3132 "\n" 3133 "private:\n" 3134 " void g() {}\n" 3135 " // test\n" 3136 "protected:\n" 3137 " int h;\n" 3138 "};", 3139 format("class A {\n" 3140 "public:\n" 3141 "void f();\n" 3142 "private:\n" 3143 "void g() {}\n" 3144 "// test\n" 3145 "protected:\n" 3146 "int h;\n" 3147 "};")); 3148 EXPECT_EQ("class A {\n" 3149 "protected:\n" 3150 "public:\n" 3151 " void f();\n" 3152 "};", 3153 format("class A {\n" 3154 "protected:\n" 3155 "\n" 3156 "public:\n" 3157 "\n" 3158 " void f();\n" 3159 "};")); 3160 3161 // Even ensure proper spacing inside macros. 3162 EXPECT_EQ("#define B \\\n" 3163 " class A { \\\n" 3164 " protected: \\\n" 3165 " public: \\\n" 3166 " void f(); \\\n" 3167 " };", 3168 format("#define B \\\n" 3169 " class A { \\\n" 3170 " protected: \\\n" 3171 " \\\n" 3172 " public: \\\n" 3173 " \\\n" 3174 " void f(); \\\n" 3175 " };", 3176 getGoogleStyle())); 3177 // But don't remove empty lines after macros ending in access specifiers. 3178 EXPECT_EQ("#define A private:\n" 3179 "\n" 3180 "int i;", 3181 format("#define A private:\n" 3182 "\n" 3183 "int i;")); 3184 } 3185 3186 TEST_F(FormatTest, FormatsClasses) { 3187 verifyFormat("class A : public B {};"); 3188 verifyFormat("class A : public ::B {};"); 3189 3190 verifyFormat( 3191 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3192 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3193 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3194 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3195 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3196 verifyFormat( 3197 "class A : public B, public C, public D, public E, public F {};"); 3198 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3199 " public C,\n" 3200 " public D,\n" 3201 " public E,\n" 3202 " public F,\n" 3203 " public G {};"); 3204 3205 verifyFormat("class\n" 3206 " ReallyReallyLongClassName {\n" 3207 " int i;\n" 3208 "};", 3209 getLLVMStyleWithColumns(32)); 3210 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3211 " aaaaaaaaaaaaaaaa> {};"); 3212 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3213 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3214 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3215 verifyFormat("template <class R, class C>\n" 3216 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3217 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3218 verifyFormat("class ::A::B {};"); 3219 } 3220 3221 TEST_F(FormatTest, BreakInheritanceStyle) { 3222 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3223 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3224 FormatStyle::BILS_BeforeComma; 3225 verifyFormat("class MyClass : public X {};", 3226 StyleWithInheritanceBreakBeforeComma); 3227 verifyFormat("class MyClass\n" 3228 " : public X\n" 3229 " , public Y {};", 3230 StyleWithInheritanceBreakBeforeComma); 3231 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3232 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3233 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3234 StyleWithInheritanceBreakBeforeComma); 3235 verifyFormat("struct aaaaaaaaaaaaa\n" 3236 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3237 " aaaaaaaaaaaaaaaa> {};", 3238 StyleWithInheritanceBreakBeforeComma); 3239 3240 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3241 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3242 FormatStyle::BILS_AfterColon; 3243 verifyFormat("class MyClass : public X {};", 3244 StyleWithInheritanceBreakAfterColon); 3245 verifyFormat("class MyClass : public X, public Y {};", 3246 StyleWithInheritanceBreakAfterColon); 3247 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3248 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3249 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3250 StyleWithInheritanceBreakAfterColon); 3251 verifyFormat("struct aaaaaaaaaaaaa :\n" 3252 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3253 " aaaaaaaaaaaaaaaa> {};", 3254 StyleWithInheritanceBreakAfterColon); 3255 3256 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3257 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3258 FormatStyle::BILS_AfterComma; 3259 verifyFormat("class MyClass : public X {};", 3260 StyleWithInheritanceBreakAfterComma); 3261 verifyFormat("class MyClass : public X,\n" 3262 " public Y {};", 3263 StyleWithInheritanceBreakAfterComma); 3264 verifyFormat( 3265 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3266 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3267 "{};", 3268 StyleWithInheritanceBreakAfterComma); 3269 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3270 " aaaaaaaaaaaaaaaa> {};", 3271 StyleWithInheritanceBreakAfterComma); 3272 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3273 " : public OnceBreak,\n" 3274 " public AlwaysBreak,\n" 3275 " EvenBasesFitInOneLine {};", 3276 StyleWithInheritanceBreakAfterComma); 3277 } 3278 3279 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { 3280 verifyFormat("class A {\n} a, b;"); 3281 verifyFormat("struct A {\n} a, b;"); 3282 verifyFormat("union A {\n} a;"); 3283 } 3284 3285 TEST_F(FormatTest, FormatsEnum) { 3286 verifyFormat("enum {\n" 3287 " Zero,\n" 3288 " One = 1,\n" 3289 " Two = One + 1,\n" 3290 " Three = (One + Two),\n" 3291 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3292 " Five = (One, Two, Three, Four, 5)\n" 3293 "};"); 3294 verifyGoogleFormat("enum {\n" 3295 " Zero,\n" 3296 " One = 1,\n" 3297 " Two = One + 1,\n" 3298 " Three = (One + Two),\n" 3299 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3300 " Five = (One, Two, Three, Four, 5)\n" 3301 "};"); 3302 verifyFormat("enum Enum {};"); 3303 verifyFormat("enum {};"); 3304 verifyFormat("enum X E {} d;"); 3305 verifyFormat("enum __attribute__((...)) E {} d;"); 3306 verifyFormat("enum __declspec__((...)) E {} d;"); 3307 verifyFormat("enum {\n" 3308 " Bar = Foo<int, int>::value\n" 3309 "};", 3310 getLLVMStyleWithColumns(30)); 3311 3312 verifyFormat("enum ShortEnum { A, B, C };"); 3313 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3314 3315 EXPECT_EQ("enum KeepEmptyLines {\n" 3316 " ONE,\n" 3317 "\n" 3318 " TWO,\n" 3319 "\n" 3320 " THREE\n" 3321 "}", 3322 format("enum KeepEmptyLines {\n" 3323 " ONE,\n" 3324 "\n" 3325 " TWO,\n" 3326 "\n" 3327 "\n" 3328 " THREE\n" 3329 "}")); 3330 verifyFormat("enum E { // comment\n" 3331 " ONE,\n" 3332 " TWO\n" 3333 "};\n" 3334 "int i;"); 3335 3336 FormatStyle EightIndent = getLLVMStyle(); 3337 EightIndent.IndentWidth = 8; 3338 verifyFormat("enum {\n" 3339 " VOID,\n" 3340 " CHAR,\n" 3341 " SHORT,\n" 3342 " INT,\n" 3343 " LONG,\n" 3344 " SIGNED,\n" 3345 " UNSIGNED,\n" 3346 " BOOL,\n" 3347 " FLOAT,\n" 3348 " DOUBLE,\n" 3349 " COMPLEX\n" 3350 "};", 3351 EightIndent); 3352 3353 // Not enums. 3354 verifyFormat("enum X f() {\n" 3355 " a();\n" 3356 " return 42;\n" 3357 "}"); 3358 verifyFormat("enum X Type::f() {\n" 3359 " a();\n" 3360 " return 42;\n" 3361 "}"); 3362 verifyFormat("enum ::X f() {\n" 3363 " a();\n" 3364 " return 42;\n" 3365 "}"); 3366 verifyFormat("enum ns::X f() {\n" 3367 " a();\n" 3368 " return 42;\n" 3369 "}"); 3370 } 3371 3372 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3373 verifyFormat("enum Type {\n" 3374 " One = 0; // These semicolons should be commas.\n" 3375 " Two = 1;\n" 3376 "};"); 3377 verifyFormat("namespace n {\n" 3378 "enum Type {\n" 3379 " One,\n" 3380 " Two, // missing };\n" 3381 " int i;\n" 3382 "}\n" 3383 "void g() {}"); 3384 } 3385 3386 TEST_F(FormatTest, FormatsEnumStruct) { 3387 verifyFormat("enum struct {\n" 3388 " Zero,\n" 3389 " One = 1,\n" 3390 " Two = One + 1,\n" 3391 " Three = (One + Two),\n" 3392 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3393 " Five = (One, Two, Three, Four, 5)\n" 3394 "};"); 3395 verifyFormat("enum struct Enum {};"); 3396 verifyFormat("enum struct {};"); 3397 verifyFormat("enum struct X E {} d;"); 3398 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3399 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3400 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3401 } 3402 3403 TEST_F(FormatTest, FormatsEnumClass) { 3404 verifyFormat("enum class {\n" 3405 " Zero,\n" 3406 " One = 1,\n" 3407 " Two = One + 1,\n" 3408 " Three = (One + Two),\n" 3409 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3410 " Five = (One, Two, Three, Four, 5)\n" 3411 "};"); 3412 verifyFormat("enum class Enum {};"); 3413 verifyFormat("enum class {};"); 3414 verifyFormat("enum class X E {} d;"); 3415 verifyFormat("enum class __attribute__((...)) E {} d;"); 3416 verifyFormat("enum class __declspec__((...)) E {} d;"); 3417 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3418 } 3419 3420 TEST_F(FormatTest, FormatsEnumTypes) { 3421 verifyFormat("enum X : int {\n" 3422 " A, // Force multiple lines.\n" 3423 " B\n" 3424 "};"); 3425 verifyFormat("enum X : int { A, B };"); 3426 verifyFormat("enum X : std::uint32_t { A, B };"); 3427 } 3428 3429 TEST_F(FormatTest, FormatsTypedefEnum) { 3430 FormatStyle Style = getLLVMStyleWithColumns(40); 3431 verifyFormat("typedef enum {} EmptyEnum;"); 3432 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3433 verifyFormat("typedef enum {\n" 3434 " ZERO = 0,\n" 3435 " ONE = 1,\n" 3436 " TWO = 2,\n" 3437 " THREE = 3\n" 3438 "} LongEnum;", 3439 Style); 3440 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3441 Style.BraceWrapping.AfterEnum = true; 3442 verifyFormat("typedef enum {} EmptyEnum;"); 3443 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3444 verifyFormat("typedef enum\n" 3445 "{\n" 3446 " ZERO = 0,\n" 3447 " ONE = 1,\n" 3448 " TWO = 2,\n" 3449 " THREE = 3\n" 3450 "} LongEnum;", 3451 Style); 3452 } 3453 3454 TEST_F(FormatTest, FormatsNSEnums) { 3455 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3456 verifyGoogleFormat( 3457 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3458 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3459 " // Information about someDecentlyLongValue.\n" 3460 " someDecentlyLongValue,\n" 3461 " // Information about anotherDecentlyLongValue.\n" 3462 " anotherDecentlyLongValue,\n" 3463 " // Information about aThirdDecentlyLongValue.\n" 3464 " aThirdDecentlyLongValue\n" 3465 "};"); 3466 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3467 " // Information about someDecentlyLongValue.\n" 3468 " someDecentlyLongValue,\n" 3469 " // Information about anotherDecentlyLongValue.\n" 3470 " anotherDecentlyLongValue,\n" 3471 " // Information about aThirdDecentlyLongValue.\n" 3472 " aThirdDecentlyLongValue\n" 3473 "};"); 3474 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3475 " a = 1,\n" 3476 " b = 2,\n" 3477 " c = 3,\n" 3478 "};"); 3479 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3480 " a = 1,\n" 3481 " b = 2,\n" 3482 " c = 3,\n" 3483 "};"); 3484 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3485 " a = 1,\n" 3486 " b = 2,\n" 3487 " c = 3,\n" 3488 "};"); 3489 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3490 " a = 1,\n" 3491 " b = 2,\n" 3492 " c = 3,\n" 3493 "};"); 3494 } 3495 3496 TEST_F(FormatTest, FormatsBitfields) { 3497 verifyFormat("struct Bitfields {\n" 3498 " unsigned sClass : 8;\n" 3499 " unsigned ValueKind : 2;\n" 3500 "};"); 3501 verifyFormat("struct A {\n" 3502 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3503 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3504 "};"); 3505 verifyFormat("struct MyStruct {\n" 3506 " uchar data;\n" 3507 " uchar : 8;\n" 3508 " uchar : 8;\n" 3509 " uchar other;\n" 3510 "};"); 3511 FormatStyle Style = getLLVMStyle(); 3512 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3513 verifyFormat("struct Bitfields {\n" 3514 " unsigned sClass:8;\n" 3515 " unsigned ValueKind:2;\n" 3516 " uchar other;\n" 3517 "};", 3518 Style); 3519 verifyFormat("struct A {\n" 3520 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3521 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3522 "};", 3523 Style); 3524 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3525 verifyFormat("struct Bitfields {\n" 3526 " unsigned sClass :8;\n" 3527 " unsigned ValueKind :2;\n" 3528 " uchar other;\n" 3529 "};", 3530 Style); 3531 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3532 verifyFormat("struct Bitfields {\n" 3533 " unsigned sClass: 8;\n" 3534 " unsigned ValueKind: 2;\n" 3535 " uchar other;\n" 3536 "};", 3537 Style); 3538 } 3539 3540 TEST_F(FormatTest, FormatsNamespaces) { 3541 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3542 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3543 3544 verifyFormat("namespace some_namespace {\n" 3545 "class A {};\n" 3546 "void f() { f(); }\n" 3547 "}", 3548 LLVMWithNoNamespaceFix); 3549 verifyFormat("namespace N::inline D {\n" 3550 "class A {};\n" 3551 "void f() { f(); }\n" 3552 "}", 3553 LLVMWithNoNamespaceFix); 3554 verifyFormat("namespace N::inline D::E {\n" 3555 "class A {};\n" 3556 "void f() { f(); }\n" 3557 "}", 3558 LLVMWithNoNamespaceFix); 3559 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3560 "class A {};\n" 3561 "void f() { f(); }\n" 3562 "}", 3563 LLVMWithNoNamespaceFix); 3564 verifyFormat("/* something */ namespace some_namespace {\n" 3565 "class A {};\n" 3566 "void f() { f(); }\n" 3567 "}", 3568 LLVMWithNoNamespaceFix); 3569 verifyFormat("namespace {\n" 3570 "class A {};\n" 3571 "void f() { f(); }\n" 3572 "}", 3573 LLVMWithNoNamespaceFix); 3574 verifyFormat("/* something */ namespace {\n" 3575 "class A {};\n" 3576 "void f() { f(); }\n" 3577 "}", 3578 LLVMWithNoNamespaceFix); 3579 verifyFormat("inline namespace X {\n" 3580 "class A {};\n" 3581 "void f() { f(); }\n" 3582 "}", 3583 LLVMWithNoNamespaceFix); 3584 verifyFormat("/* something */ inline namespace X {\n" 3585 "class A {};\n" 3586 "void f() { f(); }\n" 3587 "}", 3588 LLVMWithNoNamespaceFix); 3589 verifyFormat("export namespace X {\n" 3590 "class A {};\n" 3591 "void f() { f(); }\n" 3592 "}", 3593 LLVMWithNoNamespaceFix); 3594 verifyFormat("using namespace some_namespace;\n" 3595 "class A {};\n" 3596 "void f() { f(); }", 3597 LLVMWithNoNamespaceFix); 3598 3599 // This code is more common than we thought; if we 3600 // layout this correctly the semicolon will go into 3601 // its own line, which is undesirable. 3602 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3603 verifyFormat("namespace {\n" 3604 "class A {};\n" 3605 "};", 3606 LLVMWithNoNamespaceFix); 3607 3608 verifyFormat("namespace {\n" 3609 "int SomeVariable = 0; // comment\n" 3610 "} // namespace", 3611 LLVMWithNoNamespaceFix); 3612 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3613 "#define HEADER_GUARD\n" 3614 "namespace my_namespace {\n" 3615 "int i;\n" 3616 "} // my_namespace\n" 3617 "#endif // HEADER_GUARD", 3618 format("#ifndef HEADER_GUARD\n" 3619 " #define HEADER_GUARD\n" 3620 " namespace my_namespace {\n" 3621 "int i;\n" 3622 "} // my_namespace\n" 3623 "#endif // HEADER_GUARD", 3624 LLVMWithNoNamespaceFix)); 3625 3626 EXPECT_EQ("namespace A::B {\n" 3627 "class C {};\n" 3628 "}", 3629 format("namespace A::B {\n" 3630 "class C {};\n" 3631 "}", 3632 LLVMWithNoNamespaceFix)); 3633 3634 FormatStyle Style = getLLVMStyle(); 3635 Style.NamespaceIndentation = FormatStyle::NI_All; 3636 EXPECT_EQ("namespace out {\n" 3637 " int i;\n" 3638 " namespace in {\n" 3639 " int i;\n" 3640 " } // namespace in\n" 3641 "} // namespace out", 3642 format("namespace out {\n" 3643 "int i;\n" 3644 "namespace in {\n" 3645 "int i;\n" 3646 "} // namespace in\n" 3647 "} // namespace out", 3648 Style)); 3649 3650 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3651 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3652 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3653 FormatStyle::SFS_Inline; 3654 verifyFormat("namespace {\n" 3655 " void f() {\n" 3656 " return;\n" 3657 " }\n" 3658 "} // namespace\n", 3659 ShortInlineFunctions); 3660 verifyFormat("namespace {\n" 3661 " int some_int;\n" 3662 " void f() {\n" 3663 " return;\n" 3664 " }\n" 3665 "} // namespace\n", 3666 ShortInlineFunctions); 3667 verifyFormat("namespace interface {\n" 3668 " void f() {\n" 3669 " return;\n" 3670 " }\n" 3671 "} // namespace interface\n", 3672 ShortInlineFunctions); 3673 verifyFormat("namespace {\n" 3674 " class X {\n" 3675 " void f() { return; }\n" 3676 " };\n" 3677 "} // namespace\n", 3678 ShortInlineFunctions); 3679 verifyFormat("namespace {\n" 3680 " struct X {\n" 3681 " void f() { return; }\n" 3682 " };\n" 3683 "} // namespace\n", 3684 ShortInlineFunctions); 3685 verifyFormat("namespace {\n" 3686 " union X {\n" 3687 " void f() { return; }\n" 3688 " };\n" 3689 "} // namespace\n", 3690 ShortInlineFunctions); 3691 verifyFormat("extern \"C\" {\n" 3692 "void f() {\n" 3693 " return;\n" 3694 "}\n" 3695 "} // namespace\n", 3696 ShortInlineFunctions); 3697 verifyFormat("namespace {\n" 3698 " class X {\n" 3699 " void f() { return; }\n" 3700 " } x;\n" 3701 "} // namespace\n", 3702 ShortInlineFunctions); 3703 verifyFormat("namespace {\n" 3704 " [[nodiscard]] class X {\n" 3705 " void f() { return; }\n" 3706 " };\n" 3707 "} // namespace\n", 3708 ShortInlineFunctions); 3709 verifyFormat("namespace {\n" 3710 " static class X {\n" 3711 " void f() { return; }\n" 3712 " } x;\n" 3713 "} // namespace\n", 3714 ShortInlineFunctions); 3715 verifyFormat("namespace {\n" 3716 " constexpr class X {\n" 3717 " void f() { return; }\n" 3718 " } x;\n" 3719 "} // namespace\n", 3720 ShortInlineFunctions); 3721 3722 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 3723 verifyFormat("extern \"C\" {\n" 3724 " void f() {\n" 3725 " return;\n" 3726 " }\n" 3727 "} // namespace\n", 3728 ShortInlineFunctions); 3729 3730 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3731 EXPECT_EQ("namespace out {\n" 3732 "int i;\n" 3733 "namespace in {\n" 3734 " int i;\n" 3735 "} // namespace in\n" 3736 "} // namespace out", 3737 format("namespace out {\n" 3738 "int i;\n" 3739 "namespace in {\n" 3740 "int i;\n" 3741 "} // namespace in\n" 3742 "} // namespace out", 3743 Style)); 3744 3745 Style.NamespaceIndentation = FormatStyle::NI_None; 3746 verifyFormat("template <class T>\n" 3747 "concept a_concept = X<>;\n" 3748 "namespace B {\n" 3749 "struct b_struct {};\n" 3750 "} // namespace B\n", 3751 Style); 3752 verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n" 3753 "namespace ns {\n" 3754 "void foo() {}\n" 3755 "} // namespace ns\n", 3756 Style); 3757 } 3758 3759 TEST_F(FormatTest, NamespaceMacros) { 3760 FormatStyle Style = getLLVMStyle(); 3761 Style.NamespaceMacros.push_back("TESTSUITE"); 3762 3763 verifyFormat("TESTSUITE(A) {\n" 3764 "int foo();\n" 3765 "} // TESTSUITE(A)", 3766 Style); 3767 3768 verifyFormat("TESTSUITE(A, B) {\n" 3769 "int foo();\n" 3770 "} // TESTSUITE(A)", 3771 Style); 3772 3773 // Properly indent according to NamespaceIndentation style 3774 Style.NamespaceIndentation = FormatStyle::NI_All; 3775 verifyFormat("TESTSUITE(A) {\n" 3776 " int foo();\n" 3777 "} // TESTSUITE(A)", 3778 Style); 3779 verifyFormat("TESTSUITE(A) {\n" 3780 " namespace B {\n" 3781 " int foo();\n" 3782 " } // namespace B\n" 3783 "} // TESTSUITE(A)", 3784 Style); 3785 verifyFormat("namespace A {\n" 3786 " TESTSUITE(B) {\n" 3787 " int foo();\n" 3788 " } // TESTSUITE(B)\n" 3789 "} // namespace A", 3790 Style); 3791 3792 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3793 verifyFormat("TESTSUITE(A) {\n" 3794 "TESTSUITE(B) {\n" 3795 " int foo();\n" 3796 "} // TESTSUITE(B)\n" 3797 "} // TESTSUITE(A)", 3798 Style); 3799 verifyFormat("TESTSUITE(A) {\n" 3800 "namespace B {\n" 3801 " int foo();\n" 3802 "} // namespace B\n" 3803 "} // TESTSUITE(A)", 3804 Style); 3805 verifyFormat("namespace A {\n" 3806 "TESTSUITE(B) {\n" 3807 " int foo();\n" 3808 "} // TESTSUITE(B)\n" 3809 "} // namespace A", 3810 Style); 3811 3812 // Properly merge namespace-macros blocks in CompactNamespaces mode 3813 Style.NamespaceIndentation = FormatStyle::NI_None; 3814 Style.CompactNamespaces = true; 3815 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 3816 "}} // TESTSUITE(A::B)", 3817 Style); 3818 3819 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3820 "}} // TESTSUITE(out::in)", 3821 format("TESTSUITE(out) {\n" 3822 "TESTSUITE(in) {\n" 3823 "} // TESTSUITE(in)\n" 3824 "} // TESTSUITE(out)", 3825 Style)); 3826 3827 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3828 "}} // TESTSUITE(out::in)", 3829 format("TESTSUITE(out) {\n" 3830 "TESTSUITE(in) {\n" 3831 "} // TESTSUITE(in)\n" 3832 "} // TESTSUITE(out)", 3833 Style)); 3834 3835 // Do not merge different namespaces/macros 3836 EXPECT_EQ("namespace out {\n" 3837 "TESTSUITE(in) {\n" 3838 "} // TESTSUITE(in)\n" 3839 "} // namespace out", 3840 format("namespace out {\n" 3841 "TESTSUITE(in) {\n" 3842 "} // TESTSUITE(in)\n" 3843 "} // namespace out", 3844 Style)); 3845 EXPECT_EQ("TESTSUITE(out) {\n" 3846 "namespace in {\n" 3847 "} // namespace in\n" 3848 "} // TESTSUITE(out)", 3849 format("TESTSUITE(out) {\n" 3850 "namespace in {\n" 3851 "} // namespace in\n" 3852 "} // TESTSUITE(out)", 3853 Style)); 3854 Style.NamespaceMacros.push_back("FOOBAR"); 3855 EXPECT_EQ("TESTSUITE(out) {\n" 3856 "FOOBAR(in) {\n" 3857 "} // FOOBAR(in)\n" 3858 "} // TESTSUITE(out)", 3859 format("TESTSUITE(out) {\n" 3860 "FOOBAR(in) {\n" 3861 "} // FOOBAR(in)\n" 3862 "} // TESTSUITE(out)", 3863 Style)); 3864 } 3865 3866 TEST_F(FormatTest, FormatsCompactNamespaces) { 3867 FormatStyle Style = getLLVMStyle(); 3868 Style.CompactNamespaces = true; 3869 Style.NamespaceMacros.push_back("TESTSUITE"); 3870 3871 verifyFormat("namespace A { namespace B {\n" 3872 "}} // namespace A::B", 3873 Style); 3874 3875 EXPECT_EQ("namespace out { namespace in {\n" 3876 "}} // namespace out::in", 3877 format("namespace out {\n" 3878 "namespace in {\n" 3879 "} // namespace in\n" 3880 "} // namespace out", 3881 Style)); 3882 3883 // Only namespaces which have both consecutive opening and end get compacted 3884 EXPECT_EQ("namespace out {\n" 3885 "namespace in1 {\n" 3886 "} // namespace in1\n" 3887 "namespace in2 {\n" 3888 "} // namespace in2\n" 3889 "} // namespace out", 3890 format("namespace out {\n" 3891 "namespace in1 {\n" 3892 "} // namespace in1\n" 3893 "namespace in2 {\n" 3894 "} // namespace in2\n" 3895 "} // namespace out", 3896 Style)); 3897 3898 EXPECT_EQ("namespace out {\n" 3899 "int i;\n" 3900 "namespace in {\n" 3901 "int j;\n" 3902 "} // namespace in\n" 3903 "int k;\n" 3904 "} // namespace out", 3905 format("namespace out { int i;\n" 3906 "namespace in { int j; } // namespace in\n" 3907 "int k; } // namespace out", 3908 Style)); 3909 3910 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 3911 "}}} // namespace A::B::C\n", 3912 format("namespace A { namespace B {\n" 3913 "namespace C {\n" 3914 "}} // namespace B::C\n" 3915 "} // namespace A\n", 3916 Style)); 3917 3918 Style.ColumnLimit = 40; 3919 EXPECT_EQ("namespace aaaaaaaaaa {\n" 3920 "namespace bbbbbbbbbb {\n" 3921 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 3922 format("namespace aaaaaaaaaa {\n" 3923 "namespace bbbbbbbbbb {\n" 3924 "} // namespace bbbbbbbbbb\n" 3925 "} // namespace aaaaaaaaaa", 3926 Style)); 3927 3928 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 3929 "namespace cccccc {\n" 3930 "}}} // namespace aaaaaa::bbbbbb::cccccc", 3931 format("namespace aaaaaa {\n" 3932 "namespace bbbbbb {\n" 3933 "namespace cccccc {\n" 3934 "} // namespace cccccc\n" 3935 "} // namespace bbbbbb\n" 3936 "} // namespace aaaaaa", 3937 Style)); 3938 Style.ColumnLimit = 80; 3939 3940 // Extra semicolon after 'inner' closing brace prevents merging 3941 EXPECT_EQ("namespace out { namespace in {\n" 3942 "}; } // namespace out::in", 3943 format("namespace out {\n" 3944 "namespace in {\n" 3945 "}; // namespace in\n" 3946 "} // namespace out", 3947 Style)); 3948 3949 // Extra semicolon after 'outer' closing brace is conserved 3950 EXPECT_EQ("namespace out { namespace in {\n" 3951 "}}; // namespace out::in", 3952 format("namespace out {\n" 3953 "namespace in {\n" 3954 "} // namespace in\n" 3955 "}; // namespace out", 3956 Style)); 3957 3958 Style.NamespaceIndentation = FormatStyle::NI_All; 3959 EXPECT_EQ("namespace out { namespace in {\n" 3960 " int i;\n" 3961 "}} // namespace out::in", 3962 format("namespace out {\n" 3963 "namespace in {\n" 3964 "int i;\n" 3965 "} // namespace in\n" 3966 "} // namespace out", 3967 Style)); 3968 EXPECT_EQ("namespace out { namespace mid {\n" 3969 " namespace in {\n" 3970 " int j;\n" 3971 " } // namespace in\n" 3972 " int k;\n" 3973 "}} // namespace out::mid", 3974 format("namespace out { namespace mid {\n" 3975 "namespace in { int j; } // namespace in\n" 3976 "int k; }} // namespace out::mid", 3977 Style)); 3978 3979 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3980 EXPECT_EQ("namespace out { namespace in {\n" 3981 " int i;\n" 3982 "}} // namespace out::in", 3983 format("namespace out {\n" 3984 "namespace in {\n" 3985 "int i;\n" 3986 "} // namespace in\n" 3987 "} // namespace out", 3988 Style)); 3989 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 3990 " int i;\n" 3991 "}}} // namespace out::mid::in", 3992 format("namespace out {\n" 3993 "namespace mid {\n" 3994 "namespace in {\n" 3995 "int i;\n" 3996 "} // namespace in\n" 3997 "} // namespace mid\n" 3998 "} // namespace out", 3999 Style)); 4000 4001 Style.CompactNamespaces = true; 4002 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4003 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4004 Style.BraceWrapping.BeforeLambdaBody = true; 4005 verifyFormat("namespace out { namespace in {\n" 4006 "}} // namespace out::in", 4007 Style); 4008 EXPECT_EQ("namespace out { namespace in {\n" 4009 "}} // namespace out::in", 4010 format("namespace out {\n" 4011 "namespace in {\n" 4012 "} // namespace in\n" 4013 "} // namespace out", 4014 Style)); 4015 } 4016 4017 TEST_F(FormatTest, FormatsExternC) { 4018 verifyFormat("extern \"C\" {\nint a;"); 4019 verifyFormat("extern \"C\" {}"); 4020 verifyFormat("extern \"C\" {\n" 4021 "int foo();\n" 4022 "}"); 4023 verifyFormat("extern \"C\" int foo() {}"); 4024 verifyFormat("extern \"C\" int foo();"); 4025 verifyFormat("extern \"C\" int foo() {\n" 4026 " int i = 42;\n" 4027 " return i;\n" 4028 "}"); 4029 4030 FormatStyle Style = getLLVMStyle(); 4031 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4032 Style.BraceWrapping.AfterFunction = true; 4033 verifyFormat("extern \"C\" int foo() {}", Style); 4034 verifyFormat("extern \"C\" int foo();", Style); 4035 verifyFormat("extern \"C\" int foo()\n" 4036 "{\n" 4037 " int i = 42;\n" 4038 " return i;\n" 4039 "}", 4040 Style); 4041 4042 Style.BraceWrapping.AfterExternBlock = true; 4043 Style.BraceWrapping.SplitEmptyRecord = false; 4044 verifyFormat("extern \"C\"\n" 4045 "{}", 4046 Style); 4047 verifyFormat("extern \"C\"\n" 4048 "{\n" 4049 " int foo();\n" 4050 "}", 4051 Style); 4052 } 4053 4054 TEST_F(FormatTest, IndentExternBlockStyle) { 4055 FormatStyle Style = getLLVMStyle(); 4056 Style.IndentWidth = 2; 4057 4058 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4059 verifyFormat("extern \"C\" { /*9*/\n" 4060 "}", 4061 Style); 4062 verifyFormat("extern \"C\" {\n" 4063 " int foo10();\n" 4064 "}", 4065 Style); 4066 4067 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4068 verifyFormat("extern \"C\" { /*11*/\n" 4069 "}", 4070 Style); 4071 verifyFormat("extern \"C\" {\n" 4072 "int foo12();\n" 4073 "}", 4074 Style); 4075 4076 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4077 Style.BraceWrapping.AfterExternBlock = true; 4078 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4079 verifyFormat("extern \"C\"\n" 4080 "{ /*13*/\n" 4081 "}", 4082 Style); 4083 verifyFormat("extern \"C\"\n{\n" 4084 " int foo14();\n" 4085 "}", 4086 Style); 4087 4088 Style.BraceWrapping.AfterExternBlock = false; 4089 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4090 verifyFormat("extern \"C\" { /*15*/\n" 4091 "}", 4092 Style); 4093 verifyFormat("extern \"C\" {\n" 4094 "int foo16();\n" 4095 "}", 4096 Style); 4097 4098 Style.BraceWrapping.AfterExternBlock = true; 4099 verifyFormat("extern \"C\"\n" 4100 "{ /*13*/\n" 4101 "}", 4102 Style); 4103 verifyFormat("extern \"C\"\n" 4104 "{\n" 4105 "int foo14();\n" 4106 "}", 4107 Style); 4108 4109 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4110 verifyFormat("extern \"C\"\n" 4111 "{ /*13*/\n" 4112 "}", 4113 Style); 4114 verifyFormat("extern \"C\"\n" 4115 "{\n" 4116 " int foo14();\n" 4117 "}", 4118 Style); 4119 } 4120 4121 TEST_F(FormatTest, FormatsInlineASM) { 4122 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4123 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4124 verifyFormat( 4125 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4126 " \"cpuid\\n\\t\"\n" 4127 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4128 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4129 " : \"a\"(value));"); 4130 EXPECT_EQ( 4131 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4132 " __asm {\n" 4133 " mov edx,[that] // vtable in edx\n" 4134 " mov eax,methodIndex\n" 4135 " call [edx][eax*4] // stdcall\n" 4136 " }\n" 4137 "}", 4138 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4139 " __asm {\n" 4140 " mov edx,[that] // vtable in edx\n" 4141 " mov eax,methodIndex\n" 4142 " call [edx][eax*4] // stdcall\n" 4143 " }\n" 4144 "}")); 4145 EXPECT_EQ("_asm {\n" 4146 " xor eax, eax;\n" 4147 " cpuid;\n" 4148 "}", 4149 format("_asm {\n" 4150 " xor eax, eax;\n" 4151 " cpuid;\n" 4152 "}")); 4153 verifyFormat("void function() {\n" 4154 " // comment\n" 4155 " asm(\"\");\n" 4156 "}"); 4157 EXPECT_EQ("__asm {\n" 4158 "}\n" 4159 "int i;", 4160 format("__asm {\n" 4161 "}\n" 4162 "int i;")); 4163 } 4164 4165 TEST_F(FormatTest, FormatTryCatch) { 4166 verifyFormat("try {\n" 4167 " throw a * b;\n" 4168 "} catch (int a) {\n" 4169 " // Do nothing.\n" 4170 "} catch (...) {\n" 4171 " exit(42);\n" 4172 "}"); 4173 4174 // Function-level try statements. 4175 verifyFormat("int f() try { return 4; } catch (...) {\n" 4176 " return 5;\n" 4177 "}"); 4178 verifyFormat("class A {\n" 4179 " int a;\n" 4180 " A() try : a(0) {\n" 4181 " } catch (...) {\n" 4182 " throw;\n" 4183 " }\n" 4184 "};\n"); 4185 verifyFormat("class A {\n" 4186 " int a;\n" 4187 " A() try : a(0), b{1} {\n" 4188 " } catch (...) {\n" 4189 " throw;\n" 4190 " }\n" 4191 "};\n"); 4192 verifyFormat("class A {\n" 4193 " int a;\n" 4194 " A() try : a(0), b{1}, c{2} {\n" 4195 " } catch (...) {\n" 4196 " throw;\n" 4197 " }\n" 4198 "};\n"); 4199 verifyFormat("class A {\n" 4200 " int a;\n" 4201 " A() try : a(0), b{1}, c{2} {\n" 4202 " { // New scope.\n" 4203 " }\n" 4204 " } catch (...) {\n" 4205 " throw;\n" 4206 " }\n" 4207 "};\n"); 4208 4209 // Incomplete try-catch blocks. 4210 verifyIncompleteFormat("try {} catch ("); 4211 } 4212 4213 TEST_F(FormatTest, FormatTryAsAVariable) { 4214 verifyFormat("int try;"); 4215 verifyFormat("int try, size;"); 4216 verifyFormat("try = foo();"); 4217 verifyFormat("if (try < size) {\n return true;\n}"); 4218 4219 verifyFormat("int catch;"); 4220 verifyFormat("int catch, size;"); 4221 verifyFormat("catch = foo();"); 4222 verifyFormat("if (catch < size) {\n return true;\n}"); 4223 4224 FormatStyle Style = getLLVMStyle(); 4225 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4226 Style.BraceWrapping.AfterFunction = true; 4227 Style.BraceWrapping.BeforeCatch = true; 4228 verifyFormat("try {\n" 4229 " int bar = 1;\n" 4230 "}\n" 4231 "catch (...) {\n" 4232 " int bar = 1;\n" 4233 "}", 4234 Style); 4235 verifyFormat("#if NO_EX\n" 4236 "try\n" 4237 "#endif\n" 4238 "{\n" 4239 "}\n" 4240 "#if NO_EX\n" 4241 "catch (...) {\n" 4242 "}", 4243 Style); 4244 verifyFormat("try /* abc */ {\n" 4245 " int bar = 1;\n" 4246 "}\n" 4247 "catch (...) {\n" 4248 " int bar = 1;\n" 4249 "}", 4250 Style); 4251 verifyFormat("try\n" 4252 "// abc\n" 4253 "{\n" 4254 " int bar = 1;\n" 4255 "}\n" 4256 "catch (...) {\n" 4257 " int bar = 1;\n" 4258 "}", 4259 Style); 4260 } 4261 4262 TEST_F(FormatTest, FormatSEHTryCatch) { 4263 verifyFormat("__try {\n" 4264 " int a = b * c;\n" 4265 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4266 " // Do nothing.\n" 4267 "}"); 4268 4269 verifyFormat("__try {\n" 4270 " int a = b * c;\n" 4271 "} __finally {\n" 4272 " // Do nothing.\n" 4273 "}"); 4274 4275 verifyFormat("DEBUG({\n" 4276 " __try {\n" 4277 " } __finally {\n" 4278 " }\n" 4279 "});\n"); 4280 } 4281 4282 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4283 verifyFormat("try {\n" 4284 " f();\n" 4285 "} catch {\n" 4286 " g();\n" 4287 "}"); 4288 verifyFormat("try {\n" 4289 " f();\n" 4290 "} catch (A a) MACRO(x) {\n" 4291 " g();\n" 4292 "} catch (B b) MACRO(x) {\n" 4293 " g();\n" 4294 "}"); 4295 } 4296 4297 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4298 FormatStyle Style = getLLVMStyle(); 4299 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4300 FormatStyle::BS_WebKit}) { 4301 Style.BreakBeforeBraces = BraceStyle; 4302 verifyFormat("try {\n" 4303 " // something\n" 4304 "} catch (...) {\n" 4305 " // something\n" 4306 "}", 4307 Style); 4308 } 4309 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4310 verifyFormat("try {\n" 4311 " // something\n" 4312 "}\n" 4313 "catch (...) {\n" 4314 " // something\n" 4315 "}", 4316 Style); 4317 verifyFormat("__try {\n" 4318 " // something\n" 4319 "}\n" 4320 "__finally {\n" 4321 " // something\n" 4322 "}", 4323 Style); 4324 verifyFormat("@try {\n" 4325 " // something\n" 4326 "}\n" 4327 "@finally {\n" 4328 " // something\n" 4329 "}", 4330 Style); 4331 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4332 verifyFormat("try\n" 4333 "{\n" 4334 " // something\n" 4335 "}\n" 4336 "catch (...)\n" 4337 "{\n" 4338 " // something\n" 4339 "}", 4340 Style); 4341 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4342 verifyFormat("try\n" 4343 " {\n" 4344 " // something white\n" 4345 " }\n" 4346 "catch (...)\n" 4347 " {\n" 4348 " // something white\n" 4349 " }", 4350 Style); 4351 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4352 verifyFormat("try\n" 4353 " {\n" 4354 " // something\n" 4355 " }\n" 4356 "catch (...)\n" 4357 " {\n" 4358 " // something\n" 4359 " }", 4360 Style); 4361 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4362 Style.BraceWrapping.BeforeCatch = true; 4363 verifyFormat("try {\n" 4364 " // something\n" 4365 "}\n" 4366 "catch (...) {\n" 4367 " // something\n" 4368 "}", 4369 Style); 4370 } 4371 4372 TEST_F(FormatTest, StaticInitializers) { 4373 verifyFormat("static SomeClass SC = {1, 'a'};"); 4374 4375 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4376 " 100000000, " 4377 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4378 4379 // Here, everything other than the "}" would fit on a line. 4380 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4381 " 10000000000000000000000000};"); 4382 EXPECT_EQ("S s = {a,\n" 4383 "\n" 4384 " b};", 4385 format("S s = {\n" 4386 " a,\n" 4387 "\n" 4388 " b\n" 4389 "};")); 4390 4391 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4392 // line. However, the formatting looks a bit off and this probably doesn't 4393 // happen often in practice. 4394 verifyFormat("static int Variable[1] = {\n" 4395 " {1000000000000000000000000000000000000}};", 4396 getLLVMStyleWithColumns(40)); 4397 } 4398 4399 TEST_F(FormatTest, DesignatedInitializers) { 4400 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4401 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4402 " .bbbbbbbbbb = 2,\n" 4403 " .cccccccccc = 3,\n" 4404 " .dddddddddd = 4,\n" 4405 " .eeeeeeeeee = 5};"); 4406 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4407 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4408 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4409 " .ccccccccccccccccccccccccccc = 3,\n" 4410 " .ddddddddddddddddddddddddddd = 4,\n" 4411 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4412 4413 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4414 4415 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4416 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4417 " [2] = bbbbbbbbbb,\n" 4418 " [3] = cccccccccc,\n" 4419 " [4] = dddddddddd,\n" 4420 " [5] = eeeeeeeeee};"); 4421 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4422 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4423 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4424 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4425 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4426 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4427 } 4428 4429 TEST_F(FormatTest, NestedStaticInitializers) { 4430 verifyFormat("static A x = {{{}}};\n"); 4431 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4432 " {init1, init2, init3, init4}}};", 4433 getLLVMStyleWithColumns(50)); 4434 4435 verifyFormat("somes Status::global_reps[3] = {\n" 4436 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4437 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4438 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4439 getLLVMStyleWithColumns(60)); 4440 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4441 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4442 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4443 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4444 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4445 " {rect.fRight - rect.fLeft, rect.fBottom - " 4446 "rect.fTop}};"); 4447 4448 verifyFormat( 4449 "SomeArrayOfSomeType a = {\n" 4450 " {{1, 2, 3},\n" 4451 " {1, 2, 3},\n" 4452 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4453 " 333333333333333333333333333333},\n" 4454 " {1, 2, 3},\n" 4455 " {1, 2, 3}}};"); 4456 verifyFormat( 4457 "SomeArrayOfSomeType a = {\n" 4458 " {{1, 2, 3}},\n" 4459 " {{1, 2, 3}},\n" 4460 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4461 " 333333333333333333333333333333}},\n" 4462 " {{1, 2, 3}},\n" 4463 " {{1, 2, 3}}};"); 4464 4465 verifyFormat("struct {\n" 4466 " unsigned bit;\n" 4467 " const char *const name;\n" 4468 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4469 " {kOsWin, \"Windows\"},\n" 4470 " {kOsLinux, \"Linux\"},\n" 4471 " {kOsCrOS, \"Chrome OS\"}};"); 4472 verifyFormat("struct {\n" 4473 " unsigned bit;\n" 4474 " const char *const name;\n" 4475 "} kBitsToOs[] = {\n" 4476 " {kOsMac, \"Mac\"},\n" 4477 " {kOsWin, \"Windows\"},\n" 4478 " {kOsLinux, \"Linux\"},\n" 4479 " {kOsCrOS, \"Chrome OS\"},\n" 4480 "};"); 4481 } 4482 4483 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4484 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4485 " \\\n" 4486 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4487 } 4488 4489 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4490 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4491 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4492 4493 // Do break defaulted and deleted functions. 4494 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4495 " default;", 4496 getLLVMStyleWithColumns(40)); 4497 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4498 " delete;", 4499 getLLVMStyleWithColumns(40)); 4500 } 4501 4502 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4503 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4504 getLLVMStyleWithColumns(40)); 4505 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4506 getLLVMStyleWithColumns(40)); 4507 EXPECT_EQ("#define Q \\\n" 4508 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4509 " \"aaaaaaaa.cpp\"", 4510 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4511 getLLVMStyleWithColumns(40))); 4512 } 4513 4514 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4515 EXPECT_EQ("# 123 \"A string literal\"", 4516 format(" # 123 \"A string literal\"")); 4517 } 4518 4519 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4520 EXPECT_EQ("#;", format("#;")); 4521 verifyFormat("#\n;\n;\n;"); 4522 } 4523 4524 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4525 EXPECT_EQ("#line 42 \"test\"\n", 4526 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4527 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4528 getLLVMStyleWithColumns(12))); 4529 } 4530 4531 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4532 EXPECT_EQ("#line 42 \"test\"", 4533 format("# \\\n line \\\n 42 \\\n \"test\"")); 4534 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4535 } 4536 4537 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4538 verifyFormat("#define A \\x20"); 4539 verifyFormat("#define A \\ x20"); 4540 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4541 verifyFormat("#define A ''"); 4542 verifyFormat("#define A ''qqq"); 4543 verifyFormat("#define A `qqq"); 4544 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4545 EXPECT_EQ("const char *c = STRINGIFY(\n" 4546 "\\na : b);", 4547 format("const char * c = STRINGIFY(\n" 4548 "\\na : b);")); 4549 4550 verifyFormat("a\r\\"); 4551 verifyFormat("a\v\\"); 4552 verifyFormat("a\f\\"); 4553 } 4554 4555 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4556 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4557 style.IndentWidth = 4; 4558 style.PPIndentWidth = 1; 4559 4560 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4561 verifyFormat("#ifdef __linux__\n" 4562 "void foo() {\n" 4563 " int x = 0;\n" 4564 "}\n" 4565 "#define FOO\n" 4566 "#endif\n" 4567 "void bar() {\n" 4568 " int y = 0;\n" 4569 "}\n", 4570 style); 4571 4572 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4573 verifyFormat("#ifdef __linux__\n" 4574 "void foo() {\n" 4575 " int x = 0;\n" 4576 "}\n" 4577 "# define FOO foo\n" 4578 "#endif\n" 4579 "void bar() {\n" 4580 " int y = 0;\n" 4581 "}\n", 4582 style); 4583 4584 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4585 verifyFormat("#ifdef __linux__\n" 4586 "void foo() {\n" 4587 " int x = 0;\n" 4588 "}\n" 4589 " #define FOO foo\n" 4590 "#endif\n" 4591 "void bar() {\n" 4592 " int y = 0;\n" 4593 "}\n", 4594 style); 4595 } 4596 4597 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4598 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4599 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4600 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4601 // FIXME: We never break before the macro name. 4602 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4603 4604 verifyFormat("#define A A\n#define A A"); 4605 verifyFormat("#define A(X) A\n#define A A"); 4606 4607 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4608 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4609 } 4610 4611 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4612 EXPECT_EQ("// somecomment\n" 4613 "#include \"a.h\"\n" 4614 "#define A( \\\n" 4615 " A, B)\n" 4616 "#include \"b.h\"\n" 4617 "// somecomment\n", 4618 format(" // somecomment\n" 4619 " #include \"a.h\"\n" 4620 "#define A(A,\\\n" 4621 " B)\n" 4622 " #include \"b.h\"\n" 4623 " // somecomment\n", 4624 getLLVMStyleWithColumns(13))); 4625 } 4626 4627 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4628 4629 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4630 EXPECT_EQ("#define A \\\n" 4631 " c; \\\n" 4632 " e;\n" 4633 "f;", 4634 format("#define A c; e;\n" 4635 "f;", 4636 getLLVMStyleWithColumns(14))); 4637 } 4638 4639 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4640 4641 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4642 EXPECT_EQ("int x,\n" 4643 "#define A\n" 4644 " y;", 4645 format("int x,\n#define A\ny;")); 4646 } 4647 4648 TEST_F(FormatTest, HashInMacroDefinition) { 4649 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4650 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4651 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4652 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4653 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4654 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4655 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4656 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4657 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4658 verifyFormat("#define A \\\n" 4659 " { \\\n" 4660 " f(#c); \\\n" 4661 " }", 4662 getLLVMStyleWithColumns(11)); 4663 4664 verifyFormat("#define A(X) \\\n" 4665 " void function##X()", 4666 getLLVMStyleWithColumns(22)); 4667 4668 verifyFormat("#define A(a, b, c) \\\n" 4669 " void a##b##c()", 4670 getLLVMStyleWithColumns(22)); 4671 4672 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4673 } 4674 4675 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4676 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4677 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4678 4679 FormatStyle Style = getLLVMStyle(); 4680 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4681 verifyFormat("#define true ((foo)1)", Style); 4682 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4683 verifyFormat("#define false((foo)0)", Style); 4684 } 4685 4686 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4687 EXPECT_EQ("#define A b;", format("#define A \\\n" 4688 " \\\n" 4689 " b;", 4690 getLLVMStyleWithColumns(25))); 4691 EXPECT_EQ("#define A \\\n" 4692 " \\\n" 4693 " a; \\\n" 4694 " b;", 4695 format("#define A \\\n" 4696 " \\\n" 4697 " a; \\\n" 4698 " b;", 4699 getLLVMStyleWithColumns(11))); 4700 EXPECT_EQ("#define A \\\n" 4701 " a; \\\n" 4702 " \\\n" 4703 " b;", 4704 format("#define A \\\n" 4705 " a; \\\n" 4706 " \\\n" 4707 " b;", 4708 getLLVMStyleWithColumns(11))); 4709 } 4710 4711 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 4712 verifyIncompleteFormat("#define A :"); 4713 verifyFormat("#define SOMECASES \\\n" 4714 " case 1: \\\n" 4715 " case 2\n", 4716 getLLVMStyleWithColumns(20)); 4717 verifyFormat("#define MACRO(a) \\\n" 4718 " if (a) \\\n" 4719 " f(); \\\n" 4720 " else \\\n" 4721 " g()", 4722 getLLVMStyleWithColumns(18)); 4723 verifyFormat("#define A template <typename T>"); 4724 verifyIncompleteFormat("#define STR(x) #x\n" 4725 "f(STR(this_is_a_string_literal{));"); 4726 verifyFormat("#pragma omp threadprivate( \\\n" 4727 " y)), // expected-warning", 4728 getLLVMStyleWithColumns(28)); 4729 verifyFormat("#d, = };"); 4730 verifyFormat("#if \"a"); 4731 verifyIncompleteFormat("({\n" 4732 "#define b \\\n" 4733 " } \\\n" 4734 " a\n" 4735 "a", 4736 getLLVMStyleWithColumns(15)); 4737 verifyFormat("#define A \\\n" 4738 " { \\\n" 4739 " {\n" 4740 "#define B \\\n" 4741 " } \\\n" 4742 " }", 4743 getLLVMStyleWithColumns(15)); 4744 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 4745 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 4746 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 4747 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 4748 } 4749 4750 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 4751 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 4752 EXPECT_EQ("class A : public QObject {\n" 4753 " Q_OBJECT\n" 4754 "\n" 4755 " A() {}\n" 4756 "};", 4757 format("class A : public QObject {\n" 4758 " Q_OBJECT\n" 4759 "\n" 4760 " A() {\n}\n" 4761 "} ;")); 4762 EXPECT_EQ("MACRO\n" 4763 "/*static*/ int i;", 4764 format("MACRO\n" 4765 " /*static*/ int i;")); 4766 EXPECT_EQ("SOME_MACRO\n" 4767 "namespace {\n" 4768 "void f();\n" 4769 "} // namespace", 4770 format("SOME_MACRO\n" 4771 " namespace {\n" 4772 "void f( );\n" 4773 "} // namespace")); 4774 // Only if the identifier contains at least 5 characters. 4775 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 4776 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 4777 // Only if everything is upper case. 4778 EXPECT_EQ("class A : public QObject {\n" 4779 " Q_Object A() {}\n" 4780 "};", 4781 format("class A : public QObject {\n" 4782 " Q_Object\n" 4783 " A() {\n}\n" 4784 "} ;")); 4785 4786 // Only if the next line can actually start an unwrapped line. 4787 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 4788 format("SOME_WEIRD_LOG_MACRO\n" 4789 "<< SomeThing;")); 4790 4791 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 4792 "(n, buffers))\n", 4793 getChromiumStyle(FormatStyle::LK_Cpp)); 4794 4795 // See PR41483 4796 EXPECT_EQ("/**/ FOO(a)\n" 4797 "FOO(b)", 4798 format("/**/ FOO(a)\n" 4799 "FOO(b)")); 4800 } 4801 4802 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 4803 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4804 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4805 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4806 "class X {};\n" 4807 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4808 "int *createScopDetectionPass() { return 0; }", 4809 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4810 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4811 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4812 " class X {};\n" 4813 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4814 " int *createScopDetectionPass() { return 0; }")); 4815 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 4816 // braces, so that inner block is indented one level more. 4817 EXPECT_EQ("int q() {\n" 4818 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4819 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4820 " IPC_END_MESSAGE_MAP()\n" 4821 "}", 4822 format("int q() {\n" 4823 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4824 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4825 " IPC_END_MESSAGE_MAP()\n" 4826 "}")); 4827 4828 // Same inside macros. 4829 EXPECT_EQ("#define LIST(L) \\\n" 4830 " L(A) \\\n" 4831 " L(B) \\\n" 4832 " L(C)", 4833 format("#define LIST(L) \\\n" 4834 " L(A) \\\n" 4835 " L(B) \\\n" 4836 " L(C)", 4837 getGoogleStyle())); 4838 4839 // These must not be recognized as macros. 4840 EXPECT_EQ("int q() {\n" 4841 " f(x);\n" 4842 " f(x) {}\n" 4843 " f(x)->g();\n" 4844 " f(x)->*g();\n" 4845 " f(x).g();\n" 4846 " f(x) = x;\n" 4847 " f(x) += x;\n" 4848 " f(x) -= x;\n" 4849 " f(x) *= x;\n" 4850 " f(x) /= x;\n" 4851 " f(x) %= x;\n" 4852 " f(x) &= x;\n" 4853 " f(x) |= x;\n" 4854 " f(x) ^= x;\n" 4855 " f(x) >>= x;\n" 4856 " f(x) <<= x;\n" 4857 " f(x)[y].z();\n" 4858 " LOG(INFO) << x;\n" 4859 " ifstream(x) >> x;\n" 4860 "}\n", 4861 format("int q() {\n" 4862 " f(x)\n;\n" 4863 " f(x)\n {}\n" 4864 " f(x)\n->g();\n" 4865 " f(x)\n->*g();\n" 4866 " f(x)\n.g();\n" 4867 " f(x)\n = x;\n" 4868 " f(x)\n += x;\n" 4869 " f(x)\n -= x;\n" 4870 " f(x)\n *= x;\n" 4871 " f(x)\n /= x;\n" 4872 " f(x)\n %= x;\n" 4873 " f(x)\n &= x;\n" 4874 " f(x)\n |= x;\n" 4875 " f(x)\n ^= x;\n" 4876 " f(x)\n >>= x;\n" 4877 " f(x)\n <<= x;\n" 4878 " f(x)\n[y].z();\n" 4879 " LOG(INFO)\n << x;\n" 4880 " ifstream(x)\n >> x;\n" 4881 "}\n")); 4882 EXPECT_EQ("int q() {\n" 4883 " F(x)\n" 4884 " if (1) {\n" 4885 " }\n" 4886 " F(x)\n" 4887 " while (1) {\n" 4888 " }\n" 4889 " F(x)\n" 4890 " G(x);\n" 4891 " F(x)\n" 4892 " try {\n" 4893 " Q();\n" 4894 " } catch (...) {\n" 4895 " }\n" 4896 "}\n", 4897 format("int q() {\n" 4898 "F(x)\n" 4899 "if (1) {}\n" 4900 "F(x)\n" 4901 "while (1) {}\n" 4902 "F(x)\n" 4903 "G(x);\n" 4904 "F(x)\n" 4905 "try { Q(); } catch (...) {}\n" 4906 "}\n")); 4907 EXPECT_EQ("class A {\n" 4908 " A() : t(0) {}\n" 4909 " A(int i) noexcept() : {}\n" 4910 " A(X x)\n" // FIXME: function-level try blocks are broken. 4911 " try : t(0) {\n" 4912 " } catch (...) {\n" 4913 " }\n" 4914 "};", 4915 format("class A {\n" 4916 " A()\n : t(0) {}\n" 4917 " A(int i)\n noexcept() : {}\n" 4918 " A(X x)\n" 4919 " try : t(0) {} catch (...) {}\n" 4920 "};")); 4921 FormatStyle Style = getLLVMStyle(); 4922 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4923 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 4924 Style.BraceWrapping.AfterFunction = true; 4925 EXPECT_EQ("void f()\n" 4926 "try\n" 4927 "{\n" 4928 "}", 4929 format("void f() try {\n" 4930 "}", 4931 Style)); 4932 EXPECT_EQ("class SomeClass {\n" 4933 "public:\n" 4934 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4935 "};", 4936 format("class SomeClass {\n" 4937 "public:\n" 4938 " SomeClass()\n" 4939 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4940 "};")); 4941 EXPECT_EQ("class SomeClass {\n" 4942 "public:\n" 4943 " SomeClass()\n" 4944 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4945 "};", 4946 format("class SomeClass {\n" 4947 "public:\n" 4948 " SomeClass()\n" 4949 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4950 "};", 4951 getLLVMStyleWithColumns(40))); 4952 4953 verifyFormat("MACRO(>)"); 4954 4955 // Some macros contain an implicit semicolon. 4956 Style = getLLVMStyle(); 4957 Style.StatementMacros.push_back("FOO"); 4958 verifyFormat("FOO(a) int b = 0;"); 4959 verifyFormat("FOO(a)\n" 4960 "int b = 0;", 4961 Style); 4962 verifyFormat("FOO(a);\n" 4963 "int b = 0;", 4964 Style); 4965 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 4966 "int b = 0;", 4967 Style); 4968 verifyFormat("FOO()\n" 4969 "int b = 0;", 4970 Style); 4971 verifyFormat("FOO\n" 4972 "int b = 0;", 4973 Style); 4974 verifyFormat("void f() {\n" 4975 " FOO(a)\n" 4976 " return a;\n" 4977 "}", 4978 Style); 4979 verifyFormat("FOO(a)\n" 4980 "FOO(b)", 4981 Style); 4982 verifyFormat("int a = 0;\n" 4983 "FOO(b)\n" 4984 "int c = 0;", 4985 Style); 4986 verifyFormat("int a = 0;\n" 4987 "int x = FOO(a)\n" 4988 "int b = 0;", 4989 Style); 4990 verifyFormat("void foo(int a) { FOO(a) }\n" 4991 "uint32_t bar() {}", 4992 Style); 4993 } 4994 4995 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 4996 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 4997 4998 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 4999 ZeroColumn); 5000 } 5001 5002 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5003 verifyFormat("#define A \\\n" 5004 " f({ \\\n" 5005 " g(); \\\n" 5006 " });", 5007 getLLVMStyleWithColumns(11)); 5008 } 5009 5010 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5011 FormatStyle Style = getLLVMStyleWithColumns(40); 5012 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5013 verifyFormat("#ifdef _WIN32\n" 5014 "#define A 0\n" 5015 "#ifdef VAR2\n" 5016 "#define B 1\n" 5017 "#include <someheader.h>\n" 5018 "#define MACRO \\\n" 5019 " some_very_long_func_aaaaaaaaaa();\n" 5020 "#endif\n" 5021 "#else\n" 5022 "#define A 1\n" 5023 "#endif", 5024 Style); 5025 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5026 verifyFormat("#ifdef _WIN32\n" 5027 "# define A 0\n" 5028 "# ifdef VAR2\n" 5029 "# define B 1\n" 5030 "# include <someheader.h>\n" 5031 "# define MACRO \\\n" 5032 " some_very_long_func_aaaaaaaaaa();\n" 5033 "# endif\n" 5034 "#else\n" 5035 "# define A 1\n" 5036 "#endif", 5037 Style); 5038 verifyFormat("#if A\n" 5039 "# define MACRO \\\n" 5040 " void a(int x) { \\\n" 5041 " b(); \\\n" 5042 " c(); \\\n" 5043 " d(); \\\n" 5044 " e(); \\\n" 5045 " f(); \\\n" 5046 " }\n" 5047 "#endif", 5048 Style); 5049 // Comments before include guard. 5050 verifyFormat("// file comment\n" 5051 "// file comment\n" 5052 "#ifndef HEADER_H\n" 5053 "#define HEADER_H\n" 5054 "code();\n" 5055 "#endif", 5056 Style); 5057 // Test with include guards. 5058 verifyFormat("#ifndef HEADER_H\n" 5059 "#define HEADER_H\n" 5060 "code();\n" 5061 "#endif", 5062 Style); 5063 // Include guards must have a #define with the same variable immediately 5064 // after #ifndef. 5065 verifyFormat("#ifndef NOT_GUARD\n" 5066 "# define FOO\n" 5067 "code();\n" 5068 "#endif", 5069 Style); 5070 5071 // Include guards must cover the entire file. 5072 verifyFormat("code();\n" 5073 "code();\n" 5074 "#ifndef NOT_GUARD\n" 5075 "# define NOT_GUARD\n" 5076 "code();\n" 5077 "#endif", 5078 Style); 5079 verifyFormat("#ifndef NOT_GUARD\n" 5080 "# define NOT_GUARD\n" 5081 "code();\n" 5082 "#endif\n" 5083 "code();", 5084 Style); 5085 // Test with trailing blank lines. 5086 verifyFormat("#ifndef HEADER_H\n" 5087 "#define HEADER_H\n" 5088 "code();\n" 5089 "#endif\n", 5090 Style); 5091 // Include guards don't have #else. 5092 verifyFormat("#ifndef NOT_GUARD\n" 5093 "# define NOT_GUARD\n" 5094 "code();\n" 5095 "#else\n" 5096 "#endif", 5097 Style); 5098 verifyFormat("#ifndef NOT_GUARD\n" 5099 "# define NOT_GUARD\n" 5100 "code();\n" 5101 "#elif FOO\n" 5102 "#endif", 5103 Style); 5104 // Non-identifier #define after potential include guard. 5105 verifyFormat("#ifndef FOO\n" 5106 "# define 1\n" 5107 "#endif\n", 5108 Style); 5109 // #if closes past last non-preprocessor line. 5110 verifyFormat("#ifndef FOO\n" 5111 "#define FOO\n" 5112 "#if 1\n" 5113 "int i;\n" 5114 "# define A 0\n" 5115 "#endif\n" 5116 "#endif\n", 5117 Style); 5118 // Don't crash if there is an #elif directive without a condition. 5119 verifyFormat("#if 1\n" 5120 "int x;\n" 5121 "#elif\n" 5122 "int y;\n" 5123 "#else\n" 5124 "int z;\n" 5125 "#endif", 5126 Style); 5127 // FIXME: This doesn't handle the case where there's code between the 5128 // #ifndef and #define but all other conditions hold. This is because when 5129 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5130 // previous code line yet, so we can't detect it. 5131 EXPECT_EQ("#ifndef NOT_GUARD\n" 5132 "code();\n" 5133 "#define NOT_GUARD\n" 5134 "code();\n" 5135 "#endif", 5136 format("#ifndef NOT_GUARD\n" 5137 "code();\n" 5138 "# define NOT_GUARD\n" 5139 "code();\n" 5140 "#endif", 5141 Style)); 5142 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5143 // be outside an include guard. Examples are #pragma once and 5144 // #pragma GCC diagnostic, or anything else that does not change the meaning 5145 // of the file if it's included multiple times. 5146 EXPECT_EQ("#ifdef WIN32\n" 5147 "# pragma once\n" 5148 "#endif\n" 5149 "#ifndef HEADER_H\n" 5150 "# define HEADER_H\n" 5151 "code();\n" 5152 "#endif", 5153 format("#ifdef WIN32\n" 5154 "# pragma once\n" 5155 "#endif\n" 5156 "#ifndef HEADER_H\n" 5157 "#define HEADER_H\n" 5158 "code();\n" 5159 "#endif", 5160 Style)); 5161 // FIXME: This does not detect when there is a single non-preprocessor line 5162 // in front of an include-guard-like structure where other conditions hold 5163 // because ScopedLineState hides the line. 5164 EXPECT_EQ("code();\n" 5165 "#ifndef HEADER_H\n" 5166 "#define HEADER_H\n" 5167 "code();\n" 5168 "#endif", 5169 format("code();\n" 5170 "#ifndef HEADER_H\n" 5171 "# define HEADER_H\n" 5172 "code();\n" 5173 "#endif", 5174 Style)); 5175 // Keep comments aligned with #, otherwise indent comments normally. These 5176 // tests cannot use verifyFormat because messUp manipulates leading 5177 // whitespace. 5178 { 5179 const char *Expected = "" 5180 "void f() {\n" 5181 "#if 1\n" 5182 "// Preprocessor aligned.\n" 5183 "# define A 0\n" 5184 " // Code. Separated by blank line.\n" 5185 "\n" 5186 "# define B 0\n" 5187 " // Code. Not aligned with #\n" 5188 "# define C 0\n" 5189 "#endif"; 5190 const char *ToFormat = "" 5191 "void f() {\n" 5192 "#if 1\n" 5193 "// Preprocessor aligned.\n" 5194 "# define A 0\n" 5195 "// Code. Separated by blank line.\n" 5196 "\n" 5197 "# define B 0\n" 5198 " // Code. Not aligned with #\n" 5199 "# define C 0\n" 5200 "#endif"; 5201 EXPECT_EQ(Expected, format(ToFormat, Style)); 5202 EXPECT_EQ(Expected, format(Expected, Style)); 5203 } 5204 // Keep block quotes aligned. 5205 { 5206 const char *Expected = "" 5207 "void f() {\n" 5208 "#if 1\n" 5209 "/* Preprocessor aligned. */\n" 5210 "# define A 0\n" 5211 " /* Code. Separated by blank line. */\n" 5212 "\n" 5213 "# define B 0\n" 5214 " /* Code. Not aligned with # */\n" 5215 "# define C 0\n" 5216 "#endif"; 5217 const char *ToFormat = "" 5218 "void f() {\n" 5219 "#if 1\n" 5220 "/* Preprocessor aligned. */\n" 5221 "# define A 0\n" 5222 "/* Code. Separated by blank line. */\n" 5223 "\n" 5224 "# define B 0\n" 5225 " /* Code. Not aligned with # */\n" 5226 "# define C 0\n" 5227 "#endif"; 5228 EXPECT_EQ(Expected, format(ToFormat, Style)); 5229 EXPECT_EQ(Expected, format(Expected, Style)); 5230 } 5231 // Keep comments aligned with un-indented directives. 5232 { 5233 const char *Expected = "" 5234 "void f() {\n" 5235 "// Preprocessor aligned.\n" 5236 "#define A 0\n" 5237 " // Code. Separated by blank line.\n" 5238 "\n" 5239 "#define B 0\n" 5240 " // Code. Not aligned with #\n" 5241 "#define C 0\n"; 5242 const char *ToFormat = "" 5243 "void f() {\n" 5244 "// Preprocessor aligned.\n" 5245 "#define A 0\n" 5246 "// Code. Separated by blank line.\n" 5247 "\n" 5248 "#define B 0\n" 5249 " // Code. Not aligned with #\n" 5250 "#define C 0\n"; 5251 EXPECT_EQ(Expected, format(ToFormat, Style)); 5252 EXPECT_EQ(Expected, format(Expected, Style)); 5253 } 5254 // Test AfterHash with tabs. 5255 { 5256 FormatStyle Tabbed = Style; 5257 Tabbed.UseTab = FormatStyle::UT_Always; 5258 Tabbed.IndentWidth = 8; 5259 Tabbed.TabWidth = 8; 5260 verifyFormat("#ifdef _WIN32\n" 5261 "#\tdefine A 0\n" 5262 "#\tifdef VAR2\n" 5263 "#\t\tdefine B 1\n" 5264 "#\t\tinclude <someheader.h>\n" 5265 "#\t\tdefine MACRO \\\n" 5266 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5267 "#\tendif\n" 5268 "#else\n" 5269 "#\tdefine A 1\n" 5270 "#endif", 5271 Tabbed); 5272 } 5273 5274 // Regression test: Multiline-macro inside include guards. 5275 verifyFormat("#ifndef HEADER_H\n" 5276 "#define HEADER_H\n" 5277 "#define A() \\\n" 5278 " int i; \\\n" 5279 " int j;\n" 5280 "#endif // HEADER_H", 5281 getLLVMStyleWithColumns(20)); 5282 5283 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5284 // Basic before hash indent tests 5285 verifyFormat("#ifdef _WIN32\n" 5286 " #define A 0\n" 5287 " #ifdef VAR2\n" 5288 " #define B 1\n" 5289 " #include <someheader.h>\n" 5290 " #define MACRO \\\n" 5291 " some_very_long_func_aaaaaaaaaa();\n" 5292 " #endif\n" 5293 "#else\n" 5294 " #define A 1\n" 5295 "#endif", 5296 Style); 5297 verifyFormat("#if A\n" 5298 " #define MACRO \\\n" 5299 " void a(int x) { \\\n" 5300 " b(); \\\n" 5301 " c(); \\\n" 5302 " d(); \\\n" 5303 " e(); \\\n" 5304 " f(); \\\n" 5305 " }\n" 5306 "#endif", 5307 Style); 5308 // Keep comments aligned with indented directives. These 5309 // tests cannot use verifyFormat because messUp manipulates leading 5310 // whitespace. 5311 { 5312 const char *Expected = "void f() {\n" 5313 "// Aligned to preprocessor.\n" 5314 "#if 1\n" 5315 " // Aligned to code.\n" 5316 " int a;\n" 5317 " #if 1\n" 5318 " // Aligned to preprocessor.\n" 5319 " #define A 0\n" 5320 " // Aligned to code.\n" 5321 " int b;\n" 5322 " #endif\n" 5323 "#endif\n" 5324 "}"; 5325 const char *ToFormat = "void f() {\n" 5326 "// Aligned to preprocessor.\n" 5327 "#if 1\n" 5328 "// Aligned to code.\n" 5329 "int a;\n" 5330 "#if 1\n" 5331 "// Aligned to preprocessor.\n" 5332 "#define A 0\n" 5333 "// Aligned to code.\n" 5334 "int b;\n" 5335 "#endif\n" 5336 "#endif\n" 5337 "}"; 5338 EXPECT_EQ(Expected, format(ToFormat, Style)); 5339 EXPECT_EQ(Expected, format(Expected, Style)); 5340 } 5341 { 5342 const char *Expected = "void f() {\n" 5343 "/* Aligned to preprocessor. */\n" 5344 "#if 1\n" 5345 " /* Aligned to code. */\n" 5346 " int a;\n" 5347 " #if 1\n" 5348 " /* Aligned to preprocessor. */\n" 5349 " #define A 0\n" 5350 " /* Aligned to code. */\n" 5351 " int b;\n" 5352 " #endif\n" 5353 "#endif\n" 5354 "}"; 5355 const char *ToFormat = "void f() {\n" 5356 "/* Aligned to preprocessor. */\n" 5357 "#if 1\n" 5358 "/* Aligned to code. */\n" 5359 "int a;\n" 5360 "#if 1\n" 5361 "/* Aligned to preprocessor. */\n" 5362 "#define A 0\n" 5363 "/* Aligned to code. */\n" 5364 "int b;\n" 5365 "#endif\n" 5366 "#endif\n" 5367 "}"; 5368 EXPECT_EQ(Expected, format(ToFormat, Style)); 5369 EXPECT_EQ(Expected, format(Expected, Style)); 5370 } 5371 5372 // Test single comment before preprocessor 5373 verifyFormat("// Comment\n" 5374 "\n" 5375 "#if 1\n" 5376 "#endif", 5377 Style); 5378 } 5379 5380 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5381 verifyFormat("{\n { a #c; }\n}"); 5382 } 5383 5384 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5385 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5386 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5387 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5388 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5389 } 5390 5391 TEST_F(FormatTest, EscapedNewlines) { 5392 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5393 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5394 format("#define A \\\nint i;\\\n int j;", Narrow)); 5395 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5396 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5397 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5398 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5399 5400 FormatStyle AlignLeft = getLLVMStyle(); 5401 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5402 EXPECT_EQ("#define MACRO(x) \\\n" 5403 "private: \\\n" 5404 " int x(int a);\n", 5405 format("#define MACRO(x) \\\n" 5406 "private: \\\n" 5407 " int x(int a);\n", 5408 AlignLeft)); 5409 5410 // CRLF line endings 5411 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5412 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5413 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5414 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5415 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5416 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5417 EXPECT_EQ("#define MACRO(x) \\\r\n" 5418 "private: \\\r\n" 5419 " int x(int a);\r\n", 5420 format("#define MACRO(x) \\\r\n" 5421 "private: \\\r\n" 5422 " int x(int a);\r\n", 5423 AlignLeft)); 5424 5425 FormatStyle DontAlign = getLLVMStyle(); 5426 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5427 DontAlign.MaxEmptyLinesToKeep = 3; 5428 // FIXME: can't use verifyFormat here because the newline before 5429 // "public:" is not inserted the first time it's reformatted 5430 EXPECT_EQ("#define A \\\n" 5431 " class Foo { \\\n" 5432 " void bar(); \\\n" 5433 "\\\n" 5434 "\\\n" 5435 "\\\n" 5436 " public: \\\n" 5437 " void baz(); \\\n" 5438 " };", 5439 format("#define A \\\n" 5440 " class Foo { \\\n" 5441 " void bar(); \\\n" 5442 "\\\n" 5443 "\\\n" 5444 "\\\n" 5445 " public: \\\n" 5446 " void baz(); \\\n" 5447 " };", 5448 DontAlign)); 5449 } 5450 5451 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5452 verifyFormat("#define A \\\n" 5453 " int v( \\\n" 5454 " a); \\\n" 5455 " int i;", 5456 getLLVMStyleWithColumns(11)); 5457 } 5458 5459 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5460 EXPECT_EQ( 5461 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5462 " \\\n" 5463 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5464 "\n" 5465 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5466 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5467 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5468 "\\\n" 5469 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5470 " \n" 5471 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5472 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5473 } 5474 5475 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5476 EXPECT_EQ("int\n" 5477 "#define A\n" 5478 " a;", 5479 format("int\n#define A\na;")); 5480 verifyFormat("functionCallTo(\n" 5481 " someOtherFunction(\n" 5482 " withSomeParameters, whichInSequence,\n" 5483 " areLongerThanALine(andAnotherCall,\n" 5484 "#define A B\n" 5485 " withMoreParamters,\n" 5486 " whichStronglyInfluenceTheLayout),\n" 5487 " andMoreParameters),\n" 5488 " trailing);", 5489 getLLVMStyleWithColumns(69)); 5490 verifyFormat("Foo::Foo()\n" 5491 "#ifdef BAR\n" 5492 " : baz(0)\n" 5493 "#endif\n" 5494 "{\n" 5495 "}"); 5496 verifyFormat("void f() {\n" 5497 " if (true)\n" 5498 "#ifdef A\n" 5499 " f(42);\n" 5500 " x();\n" 5501 "#else\n" 5502 " g();\n" 5503 " x();\n" 5504 "#endif\n" 5505 "}"); 5506 verifyFormat("void f(param1, param2,\n" 5507 " param3,\n" 5508 "#ifdef A\n" 5509 " param4(param5,\n" 5510 "#ifdef A1\n" 5511 " param6,\n" 5512 "#ifdef A2\n" 5513 " param7),\n" 5514 "#else\n" 5515 " param8),\n" 5516 " param9,\n" 5517 "#endif\n" 5518 " param10,\n" 5519 "#endif\n" 5520 " param11)\n" 5521 "#else\n" 5522 " param12)\n" 5523 "#endif\n" 5524 "{\n" 5525 " x();\n" 5526 "}", 5527 getLLVMStyleWithColumns(28)); 5528 verifyFormat("#if 1\n" 5529 "int i;"); 5530 verifyFormat("#if 1\n" 5531 "#endif\n" 5532 "#if 1\n" 5533 "#else\n" 5534 "#endif\n"); 5535 verifyFormat("DEBUG({\n" 5536 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5537 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5538 "});\n" 5539 "#if a\n" 5540 "#else\n" 5541 "#endif"); 5542 5543 verifyIncompleteFormat("void f(\n" 5544 "#if A\n" 5545 ");\n" 5546 "#else\n" 5547 "#endif"); 5548 } 5549 5550 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5551 verifyFormat("#endif\n" 5552 "#if B"); 5553 } 5554 5555 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5556 FormatStyle SingleLine = getLLVMStyle(); 5557 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5558 verifyFormat("#if 0\n" 5559 "#elif 1\n" 5560 "#endif\n" 5561 "void foo() {\n" 5562 " if (test) foo2();\n" 5563 "}", 5564 SingleLine); 5565 } 5566 5567 TEST_F(FormatTest, LayoutBlockInsideParens) { 5568 verifyFormat("functionCall({ int i; });"); 5569 verifyFormat("functionCall({\n" 5570 " int i;\n" 5571 " int j;\n" 5572 "});"); 5573 verifyFormat("functionCall(\n" 5574 " {\n" 5575 " int i;\n" 5576 " int j;\n" 5577 " },\n" 5578 " aaaa, bbbb, cccc);"); 5579 verifyFormat("functionA(functionB({\n" 5580 " int i;\n" 5581 " int j;\n" 5582 " }),\n" 5583 " aaaa, bbbb, cccc);"); 5584 verifyFormat("functionCall(\n" 5585 " {\n" 5586 " int i;\n" 5587 " int j;\n" 5588 " },\n" 5589 " aaaa, bbbb, // comment\n" 5590 " cccc);"); 5591 verifyFormat("functionA(functionB({\n" 5592 " int i;\n" 5593 " int j;\n" 5594 " }),\n" 5595 " aaaa, bbbb, // comment\n" 5596 " cccc);"); 5597 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5598 verifyFormat("functionCall(aaaa, bbbb, {\n" 5599 " int i;\n" 5600 " int j;\n" 5601 "});"); 5602 verifyFormat( 5603 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5604 " {\n" 5605 " int i; // break\n" 5606 " },\n" 5607 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5608 " ccccccccccccccccc));"); 5609 verifyFormat("DEBUG({\n" 5610 " if (a)\n" 5611 " f();\n" 5612 "});"); 5613 } 5614 5615 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5616 EXPECT_EQ("SOME_MACRO { int i; }\n" 5617 "int i;", 5618 format(" SOME_MACRO {int i;} int i;")); 5619 } 5620 5621 TEST_F(FormatTest, LayoutNestedBlocks) { 5622 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5623 " struct s {\n" 5624 " int i;\n" 5625 " };\n" 5626 " s kBitsToOs[] = {{10}};\n" 5627 " for (int i = 0; i < 10; ++i)\n" 5628 " return;\n" 5629 "}"); 5630 verifyFormat("call(parameter, {\n" 5631 " something();\n" 5632 " // Comment using all columns.\n" 5633 " somethingelse();\n" 5634 "});", 5635 getLLVMStyleWithColumns(40)); 5636 verifyFormat("DEBUG( //\n" 5637 " { f(); }, a);"); 5638 verifyFormat("DEBUG( //\n" 5639 " {\n" 5640 " f(); //\n" 5641 " },\n" 5642 " a);"); 5643 5644 EXPECT_EQ("call(parameter, {\n" 5645 " something();\n" 5646 " // Comment too\n" 5647 " // looooooooooong.\n" 5648 " somethingElse();\n" 5649 "});", 5650 format("call(parameter, {\n" 5651 " something();\n" 5652 " // Comment too looooooooooong.\n" 5653 " somethingElse();\n" 5654 "});", 5655 getLLVMStyleWithColumns(29))); 5656 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5657 EXPECT_EQ("DEBUG({ // comment\n" 5658 " int i;\n" 5659 "});", 5660 format("DEBUG({ // comment\n" 5661 "int i;\n" 5662 "});")); 5663 EXPECT_EQ("DEBUG({\n" 5664 " int i;\n" 5665 "\n" 5666 " // comment\n" 5667 " int j;\n" 5668 "});", 5669 format("DEBUG({\n" 5670 " int i;\n" 5671 "\n" 5672 " // comment\n" 5673 " int j;\n" 5674 "});")); 5675 5676 verifyFormat("DEBUG({\n" 5677 " if (a)\n" 5678 " return;\n" 5679 "});"); 5680 verifyGoogleFormat("DEBUG({\n" 5681 " if (a) return;\n" 5682 "});"); 5683 FormatStyle Style = getGoogleStyle(); 5684 Style.ColumnLimit = 45; 5685 verifyFormat("Debug(\n" 5686 " aaaaa,\n" 5687 " {\n" 5688 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5689 " },\n" 5690 " a);", 5691 Style); 5692 5693 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5694 5695 verifyNoCrash("^{v^{a}}"); 5696 } 5697 5698 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 5699 EXPECT_EQ("#define MACRO() \\\n" 5700 " Debug(aaa, /* force line break */ \\\n" 5701 " { \\\n" 5702 " int i; \\\n" 5703 " int j; \\\n" 5704 " })", 5705 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 5706 " { int i; int j; })", 5707 getGoogleStyle())); 5708 5709 EXPECT_EQ("#define A \\\n" 5710 " [] { \\\n" 5711 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5712 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 5713 " }", 5714 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5715 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 5716 getGoogleStyle())); 5717 } 5718 5719 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 5720 EXPECT_EQ("{}", format("{}")); 5721 verifyFormat("enum E {};"); 5722 verifyFormat("enum E {}"); 5723 FormatStyle Style = getLLVMStyle(); 5724 Style.SpaceInEmptyBlock = true; 5725 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 5726 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 5727 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 5728 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5729 Style.BraceWrapping.BeforeElse = false; 5730 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5731 verifyFormat("if (a)\n" 5732 "{\n" 5733 "} else if (b)\n" 5734 "{\n" 5735 "} else\n" 5736 "{ }", 5737 Style); 5738 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 5739 verifyFormat("if (a) {\n" 5740 "} else if (b) {\n" 5741 "} else {\n" 5742 "}", 5743 Style); 5744 Style.BraceWrapping.BeforeElse = true; 5745 verifyFormat("if (a) { }\n" 5746 "else if (b) { }\n" 5747 "else { }", 5748 Style); 5749 } 5750 5751 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 5752 FormatStyle Style = getLLVMStyle(); 5753 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 5754 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 5755 verifyFormat("FOO_BEGIN\n" 5756 " FOO_ENTRY\n" 5757 "FOO_END", 5758 Style); 5759 verifyFormat("FOO_BEGIN\n" 5760 " NESTED_FOO_BEGIN\n" 5761 " NESTED_FOO_ENTRY\n" 5762 " NESTED_FOO_END\n" 5763 "FOO_END", 5764 Style); 5765 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 5766 " int x;\n" 5767 " x = 1;\n" 5768 "FOO_END(Baz)", 5769 Style); 5770 } 5771 5772 //===----------------------------------------------------------------------===// 5773 // Line break tests. 5774 //===----------------------------------------------------------------------===// 5775 5776 TEST_F(FormatTest, PreventConfusingIndents) { 5777 verifyFormat( 5778 "void f() {\n" 5779 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 5780 " parameter, parameter, parameter)),\n" 5781 " SecondLongCall(parameter));\n" 5782 "}"); 5783 verifyFormat( 5784 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5785 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5786 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5787 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 5788 verifyFormat( 5789 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5790 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 5791 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 5792 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 5793 verifyFormat( 5794 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 5795 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 5796 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 5797 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 5798 verifyFormat("int a = bbbb && ccc &&\n" 5799 " fffff(\n" 5800 "#define A Just forcing a new line\n" 5801 " ddd);"); 5802 } 5803 5804 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 5805 verifyFormat( 5806 "bool aaaaaaa =\n" 5807 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 5808 " bbbbbbbb();"); 5809 verifyFormat( 5810 "bool aaaaaaa =\n" 5811 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 5812 " bbbbbbbb();"); 5813 5814 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5815 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 5816 " ccccccccc == ddddddddddd;"); 5817 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5818 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 5819 " ccccccccc == ddddddddddd;"); 5820 verifyFormat( 5821 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 5822 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 5823 " ccccccccc == ddddddddddd;"); 5824 5825 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5826 " aaaaaa) &&\n" 5827 " bbbbbb && cccccc;"); 5828 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5829 " aaaaaa) >>\n" 5830 " bbbbbb;"); 5831 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 5832 " SourceMgr.getSpellingColumnNumber(\n" 5833 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 5834 " 1);"); 5835 5836 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5837 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 5838 " cccccc) {\n}"); 5839 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5840 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5841 " cccccc) {\n}"); 5842 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5843 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5844 " cccccc) {\n}"); 5845 verifyFormat("b = a &&\n" 5846 " // Comment\n" 5847 " b.c && d;"); 5848 5849 // If the LHS of a comparison is not a binary expression itself, the 5850 // additional linebreak confuses many people. 5851 verifyFormat( 5852 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5853 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 5854 "}"); 5855 verifyFormat( 5856 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5857 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5858 "}"); 5859 verifyFormat( 5860 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 5861 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5862 "}"); 5863 verifyFormat( 5864 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5865 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 5866 "}"); 5867 // Even explicit parentheses stress the precedence enough to make the 5868 // additional break unnecessary. 5869 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5870 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5871 "}"); 5872 // This cases is borderline, but with the indentation it is still readable. 5873 verifyFormat( 5874 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5875 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5876 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 5877 "}", 5878 getLLVMStyleWithColumns(75)); 5879 5880 // If the LHS is a binary expression, we should still use the additional break 5881 // as otherwise the formatting hides the operator precedence. 5882 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5883 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5884 " 5) {\n" 5885 "}"); 5886 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5887 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 5888 " 5) {\n" 5889 "}"); 5890 5891 FormatStyle OnePerLine = getLLVMStyle(); 5892 OnePerLine.BinPackParameters = false; 5893 verifyFormat( 5894 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5895 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5896 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 5897 OnePerLine); 5898 5899 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 5900 " .aaa(aaaaaaaaaaaaa) *\n" 5901 " aaaaaaa +\n" 5902 " aaaaaaa;", 5903 getLLVMStyleWithColumns(40)); 5904 } 5905 5906 TEST_F(FormatTest, ExpressionIndentation) { 5907 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5908 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5910 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5911 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 5912 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 5913 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5914 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 5915 " ccccccccccccccccccccccccccccccccccccccccc;"); 5916 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5917 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5918 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5919 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5920 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5921 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5922 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5923 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5924 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5925 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5926 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5927 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5928 verifyFormat("if () {\n" 5929 "} else if (aaaaa && bbbbb > // break\n" 5930 " ccccc) {\n" 5931 "}"); 5932 verifyFormat("if () {\n" 5933 "} else if constexpr (aaaaa && bbbbb > // break\n" 5934 " ccccc) {\n" 5935 "}"); 5936 verifyFormat("if () {\n" 5937 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 5938 " ccccc) {\n" 5939 "}"); 5940 verifyFormat("if () {\n" 5941 "} else if (aaaaa &&\n" 5942 " bbbbb > // break\n" 5943 " ccccc &&\n" 5944 " ddddd) {\n" 5945 "}"); 5946 5947 // Presence of a trailing comment used to change indentation of b. 5948 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 5949 " b;\n" 5950 "return aaaaaaaaaaaaaaaaaaa +\n" 5951 " b; //", 5952 getLLVMStyleWithColumns(30)); 5953 } 5954 5955 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 5956 // Not sure what the best system is here. Like this, the LHS can be found 5957 // immediately above an operator (everything with the same or a higher 5958 // indent). The RHS is aligned right of the operator and so compasses 5959 // everything until something with the same indent as the operator is found. 5960 // FIXME: Is this a good system? 5961 FormatStyle Style = getLLVMStyle(); 5962 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 5963 verifyFormat( 5964 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5965 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5966 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5967 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5968 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5969 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5970 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5971 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5972 " > ccccccccccccccccccccccccccccccccccccccccc;", 5973 Style); 5974 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5975 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5976 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5977 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5978 Style); 5979 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5980 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5981 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5982 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5983 Style); 5984 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5985 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5986 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5987 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5988 Style); 5989 verifyFormat("if () {\n" 5990 "} else if (aaaaa\n" 5991 " && bbbbb // break\n" 5992 " > ccccc) {\n" 5993 "}", 5994 Style); 5995 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5996 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 5997 Style); 5998 verifyFormat("return (a)\n" 5999 " // comment\n" 6000 " + b;", 6001 Style); 6002 verifyFormat( 6003 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6004 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6005 " + cc;", 6006 Style); 6007 6008 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6009 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6010 Style); 6011 6012 // Forced by comments. 6013 verifyFormat( 6014 "unsigned ContentSize =\n" 6015 " sizeof(int16_t) // DWARF ARange version number\n" 6016 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6017 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6018 " + sizeof(int8_t); // Segment Size (in bytes)"); 6019 6020 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6021 " == boost::fusion::at_c<1>(iiii).second;", 6022 Style); 6023 6024 Style.ColumnLimit = 60; 6025 verifyFormat("zzzzzzzzzz\n" 6026 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6027 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6028 Style); 6029 6030 Style.ColumnLimit = 80; 6031 Style.IndentWidth = 4; 6032 Style.TabWidth = 4; 6033 Style.UseTab = FormatStyle::UT_Always; 6034 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6035 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6036 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6037 "\t&& (someOtherLongishConditionPart1\n" 6038 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6039 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6040 "(someOtherLongishConditionPart1 || " 6041 "someOtherEvenLongerNestedConditionPart2);", 6042 Style)); 6043 } 6044 6045 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6046 FormatStyle Style = getLLVMStyle(); 6047 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6048 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6049 6050 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6051 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6052 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6053 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6054 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6055 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6056 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6057 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6058 " > ccccccccccccccccccccccccccccccccccccccccc;", 6059 Style); 6060 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6061 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6062 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6063 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6064 Style); 6065 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6066 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6067 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6068 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6069 Style); 6070 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6071 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6072 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6073 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6074 Style); 6075 verifyFormat("if () {\n" 6076 "} else if (aaaaa\n" 6077 " && bbbbb // break\n" 6078 " > ccccc) {\n" 6079 "}", 6080 Style); 6081 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6082 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6083 Style); 6084 verifyFormat("return (a)\n" 6085 " // comment\n" 6086 " + b;", 6087 Style); 6088 verifyFormat( 6089 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6090 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6091 " + cc;", 6092 Style); 6093 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6094 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6095 " : 3333333333333333;", 6096 Style); 6097 verifyFormat( 6098 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6099 " : ccccccccccccccc ? dddddddddddddddddd\n" 6100 " : eeeeeeeeeeeeeeeeee)\n" 6101 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6102 " : 3333333333333333;", 6103 Style); 6104 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6105 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6106 Style); 6107 6108 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6109 " == boost::fusion::at_c<1>(iiii).second;", 6110 Style); 6111 6112 Style.ColumnLimit = 60; 6113 verifyFormat("zzzzzzzzzzzzz\n" 6114 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6115 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6116 Style); 6117 6118 // Forced by comments. 6119 Style.ColumnLimit = 80; 6120 verifyFormat( 6121 "unsigned ContentSize\n" 6122 " = sizeof(int16_t) // DWARF ARange version number\n" 6123 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6124 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6125 " + sizeof(int8_t); // Segment Size (in bytes)", 6126 Style); 6127 6128 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6129 verifyFormat( 6130 "unsigned ContentSize =\n" 6131 " sizeof(int16_t) // DWARF ARange version number\n" 6132 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6133 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6134 " + sizeof(int8_t); // Segment Size (in bytes)", 6135 Style); 6136 6137 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6138 verifyFormat( 6139 "unsigned ContentSize =\n" 6140 " sizeof(int16_t) // DWARF ARange version number\n" 6141 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6142 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6143 " + sizeof(int8_t); // Segment Size (in bytes)", 6144 Style); 6145 } 6146 6147 TEST_F(FormatTest, EnforcedOperatorWraps) { 6148 // Here we'd like to wrap after the || operators, but a comment is forcing an 6149 // earlier wrap. 6150 verifyFormat("bool x = aaaaa //\n" 6151 " || bbbbb\n" 6152 " //\n" 6153 " || cccc;"); 6154 } 6155 6156 TEST_F(FormatTest, NoOperandAlignment) { 6157 FormatStyle Style = getLLVMStyle(); 6158 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6159 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6161 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6162 Style); 6163 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6164 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6165 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6166 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6167 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6168 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6169 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6170 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6171 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6172 " > ccccccccccccccccccccccccccccccccccccccccc;", 6173 Style); 6174 6175 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6176 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6177 " + cc;", 6178 Style); 6179 verifyFormat("int a = aa\n" 6180 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6181 " * cccccccccccccccccccccccccccccccccccc;\n", 6182 Style); 6183 6184 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6185 verifyFormat("return (a > b\n" 6186 " // comment1\n" 6187 " // comment2\n" 6188 " || c);", 6189 Style); 6190 } 6191 6192 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6193 FormatStyle Style = getLLVMStyle(); 6194 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6195 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6196 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6197 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6198 Style); 6199 } 6200 6201 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6202 FormatStyle Style = getLLVMStyleWithColumns(40); 6203 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6204 Style.BinPackArguments = false; 6205 verifyFormat("void test() {\n" 6206 " someFunction(\n" 6207 " this + argument + is + quite\n" 6208 " + long + so + it + gets + wrapped\n" 6209 " + but + remains + bin - packed);\n" 6210 "}", 6211 Style); 6212 verifyFormat("void test() {\n" 6213 " someFunction(arg1,\n" 6214 " this + argument + is\n" 6215 " + quite + long + so\n" 6216 " + it + gets + wrapped\n" 6217 " + but + remains + bin\n" 6218 " - packed,\n" 6219 " arg3);\n" 6220 "}", 6221 Style); 6222 verifyFormat("void test() {\n" 6223 " someFunction(\n" 6224 " arg1,\n" 6225 " this + argument + has\n" 6226 " + anotherFunc(nested,\n" 6227 " calls + whose\n" 6228 " + arguments\n" 6229 " + are + also\n" 6230 " + wrapped,\n" 6231 " in + addition)\n" 6232 " + to + being + bin - packed,\n" 6233 " arg3);\n" 6234 "}", 6235 Style); 6236 6237 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6238 verifyFormat("void test() {\n" 6239 " someFunction(\n" 6240 " arg1,\n" 6241 " this + argument + has +\n" 6242 " anotherFunc(nested,\n" 6243 " calls + whose +\n" 6244 " arguments +\n" 6245 " are + also +\n" 6246 " wrapped,\n" 6247 " in + addition) +\n" 6248 " to + being + bin - packed,\n" 6249 " arg3);\n" 6250 "}", 6251 Style); 6252 } 6253 6254 TEST_F(FormatTest, ConstructorInitializers) { 6255 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6256 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6257 getLLVMStyleWithColumns(45)); 6258 verifyFormat("Constructor()\n" 6259 " : Inttializer(FitsOnTheLine) {}", 6260 getLLVMStyleWithColumns(44)); 6261 verifyFormat("Constructor()\n" 6262 " : Inttializer(FitsOnTheLine) {}", 6263 getLLVMStyleWithColumns(43)); 6264 6265 verifyFormat("template <typename T>\n" 6266 "Constructor() : Initializer(FitsOnTheLine) {}", 6267 getLLVMStyleWithColumns(45)); 6268 6269 verifyFormat( 6270 "SomeClass::Constructor()\n" 6271 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6272 6273 verifyFormat( 6274 "SomeClass::Constructor()\n" 6275 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6276 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6277 verifyFormat( 6278 "SomeClass::Constructor()\n" 6279 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6280 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6281 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6282 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6283 " : aaaaaaaaaa(aaaaaa) {}"); 6284 6285 verifyFormat("Constructor()\n" 6286 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6287 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6288 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6289 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6290 6291 verifyFormat("Constructor()\n" 6292 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6293 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6294 6295 verifyFormat("Constructor(int Parameter = 0)\n" 6296 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6297 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6298 verifyFormat("Constructor()\n" 6299 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6300 "}", 6301 getLLVMStyleWithColumns(60)); 6302 verifyFormat("Constructor()\n" 6303 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6304 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6305 6306 // Here a line could be saved by splitting the second initializer onto two 6307 // lines, but that is not desirable. 6308 verifyFormat("Constructor()\n" 6309 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6310 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6311 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6312 6313 FormatStyle OnePerLine = getLLVMStyle(); 6314 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6315 verifyFormat("MyClass::MyClass()\n" 6316 " : a(a),\n" 6317 " b(b),\n" 6318 " c(c) {}", 6319 OnePerLine); 6320 verifyFormat("MyClass::MyClass()\n" 6321 " : a(a), // comment\n" 6322 " b(b),\n" 6323 " c(c) {}", 6324 OnePerLine); 6325 verifyFormat("MyClass::MyClass(int a)\n" 6326 " : b(a), // comment\n" 6327 " c(a + 1) { // lined up\n" 6328 "}", 6329 OnePerLine); 6330 verifyFormat("Constructor()\n" 6331 " : a(b, b, b) {}", 6332 OnePerLine); 6333 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6334 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6335 verifyFormat("SomeClass::Constructor()\n" 6336 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6337 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6338 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6339 OnePerLine); 6340 verifyFormat("SomeClass::Constructor()\n" 6341 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6342 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6343 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6344 OnePerLine); 6345 verifyFormat("MyClass::MyClass(int var)\n" 6346 " : some_var_(var), // 4 space indent\n" 6347 " some_other_var_(var + 1) { // lined up\n" 6348 "}", 6349 OnePerLine); 6350 verifyFormat("Constructor()\n" 6351 " : aaaaa(aaaaaa),\n" 6352 " aaaaa(aaaaaa),\n" 6353 " aaaaa(aaaaaa),\n" 6354 " aaaaa(aaaaaa),\n" 6355 " aaaaa(aaaaaa) {}", 6356 OnePerLine); 6357 verifyFormat("Constructor()\n" 6358 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6359 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6360 OnePerLine); 6361 OnePerLine.BinPackParameters = false; 6362 verifyFormat( 6363 "Constructor()\n" 6364 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6365 " aaaaaaaaaaa().aaa(),\n" 6366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6367 OnePerLine); 6368 OnePerLine.ColumnLimit = 60; 6369 verifyFormat("Constructor()\n" 6370 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6371 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6372 OnePerLine); 6373 6374 EXPECT_EQ("Constructor()\n" 6375 " : // Comment forcing unwanted break.\n" 6376 " aaaa(aaaa) {}", 6377 format("Constructor() :\n" 6378 " // Comment forcing unwanted break.\n" 6379 " aaaa(aaaa) {}")); 6380 } 6381 6382 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6383 FormatStyle Style = getLLVMStyleWithColumns(60); 6384 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6385 Style.BinPackParameters = false; 6386 6387 for (int i = 0; i < 4; ++i) { 6388 // Test all combinations of parameters that should not have an effect. 6389 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6390 Style.AllowAllArgumentsOnNextLine = i & 2; 6391 6392 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6393 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6394 verifyFormat("Constructor()\n" 6395 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6396 Style); 6397 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6398 6399 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6400 verifyFormat("Constructor()\n" 6401 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6402 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6403 Style); 6404 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6405 6406 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6407 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6408 verifyFormat("Constructor()\n" 6409 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6410 Style); 6411 6412 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6413 verifyFormat("Constructor()\n" 6414 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6415 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6416 Style); 6417 6418 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6419 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6420 verifyFormat("Constructor() :\n" 6421 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6422 Style); 6423 6424 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6425 verifyFormat("Constructor() :\n" 6426 " aaaaaaaaaaaaaaaaaa(a),\n" 6427 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6428 Style); 6429 } 6430 6431 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6432 // AllowAllConstructorInitializersOnNextLine in all 6433 // BreakConstructorInitializers modes 6434 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6435 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6436 verifyFormat("SomeClassWithALongName::Constructor(\n" 6437 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6438 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6439 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6440 Style); 6441 6442 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6443 verifyFormat("SomeClassWithALongName::Constructor(\n" 6444 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6445 " int bbbbbbbbbbbbb,\n" 6446 " int cccccccccccccccc)\n" 6447 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6448 Style); 6449 6450 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6451 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6452 verifyFormat("SomeClassWithALongName::Constructor(\n" 6453 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6454 " int bbbbbbbbbbbbb)\n" 6455 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6456 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6457 Style); 6458 6459 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6460 6461 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6462 verifyFormat("SomeClassWithALongName::Constructor(\n" 6463 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6464 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6465 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6466 Style); 6467 6468 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6469 verifyFormat("SomeClassWithALongName::Constructor(\n" 6470 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6471 " int bbbbbbbbbbbbb,\n" 6472 " int cccccccccccccccc)\n" 6473 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6474 Style); 6475 6476 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6477 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6478 verifyFormat("SomeClassWithALongName::Constructor(\n" 6479 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6480 " int bbbbbbbbbbbbb)\n" 6481 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6482 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6483 Style); 6484 6485 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6486 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6487 verifyFormat("SomeClassWithALongName::Constructor(\n" 6488 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6489 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6490 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6491 Style); 6492 6493 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6494 verifyFormat("SomeClassWithALongName::Constructor(\n" 6495 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6496 " int bbbbbbbbbbbbb,\n" 6497 " int cccccccccccccccc) :\n" 6498 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6499 Style); 6500 6501 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6502 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6503 verifyFormat("SomeClassWithALongName::Constructor(\n" 6504 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6505 " int bbbbbbbbbbbbb) :\n" 6506 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6507 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6508 Style); 6509 } 6510 6511 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6512 FormatStyle Style = getLLVMStyleWithColumns(60); 6513 Style.BinPackArguments = false; 6514 for (int i = 0; i < 4; ++i) { 6515 // Test all combinations of parameters that should not have an effect. 6516 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6517 Style.PackConstructorInitializers = 6518 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6519 6520 Style.AllowAllArgumentsOnNextLine = true; 6521 verifyFormat("void foo() {\n" 6522 " FunctionCallWithReallyLongName(\n" 6523 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6524 "}", 6525 Style); 6526 Style.AllowAllArgumentsOnNextLine = false; 6527 verifyFormat("void foo() {\n" 6528 " FunctionCallWithReallyLongName(\n" 6529 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6530 " bbbbbbbbbbbb);\n" 6531 "}", 6532 Style); 6533 6534 Style.AllowAllArgumentsOnNextLine = true; 6535 verifyFormat("void foo() {\n" 6536 " auto VariableWithReallyLongName = {\n" 6537 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6538 "}", 6539 Style); 6540 Style.AllowAllArgumentsOnNextLine = false; 6541 verifyFormat("void foo() {\n" 6542 " auto VariableWithReallyLongName = {\n" 6543 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6544 " bbbbbbbbbbbb};\n" 6545 "}", 6546 Style); 6547 } 6548 6549 // This parameter should not affect declarations. 6550 Style.BinPackParameters = false; 6551 Style.AllowAllArgumentsOnNextLine = false; 6552 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6553 verifyFormat("void FunctionCallWithReallyLongName(\n" 6554 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6555 Style); 6556 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6557 verifyFormat("void FunctionCallWithReallyLongName(\n" 6558 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6559 " int bbbbbbbbbbbb);", 6560 Style); 6561 } 6562 6563 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6564 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6565 // and BAS_Align. 6566 FormatStyle Style = getLLVMStyleWithColumns(35); 6567 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6568 "void functionDecl(int A, int B, int C);"; 6569 Style.AllowAllArgumentsOnNextLine = false; 6570 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6571 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6572 " paramC);\n" 6573 "void functionDecl(int A, int B,\n" 6574 " int C);"), 6575 format(Input, Style)); 6576 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6577 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6578 " paramC);\n" 6579 "void functionDecl(int A, int B,\n" 6580 " int C);"), 6581 format(Input, Style)); 6582 // However, BAS_AlwaysBreak should take precedence over 6583 // AllowAllArgumentsOnNextLine. 6584 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6585 EXPECT_EQ(StringRef("functionCall(\n" 6586 " paramA, paramB, paramC);\n" 6587 "void functionDecl(\n" 6588 " int A, int B, int C);"), 6589 format(Input, Style)); 6590 6591 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6592 // first argument. 6593 Style.AllowAllArgumentsOnNextLine = true; 6594 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6595 EXPECT_EQ(StringRef("functionCall(\n" 6596 " paramA, paramB, paramC);\n" 6597 "void functionDecl(\n" 6598 " int A, int B, int C);"), 6599 format(Input, Style)); 6600 // It wouldn't fit on one line with aligned parameters so this setting 6601 // doesn't change anything for BAS_Align. 6602 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6603 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6604 " paramC);\n" 6605 "void functionDecl(int A, int B,\n" 6606 " int C);"), 6607 format(Input, Style)); 6608 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6609 EXPECT_EQ(StringRef("functionCall(\n" 6610 " paramA, paramB, paramC);\n" 6611 "void functionDecl(\n" 6612 " int A, int B, int C);"), 6613 format(Input, Style)); 6614 } 6615 6616 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6617 FormatStyle Style = getLLVMStyle(); 6618 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6619 6620 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6621 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6622 getStyleWithColumns(Style, 45)); 6623 verifyFormat("Constructor() :\n" 6624 " Initializer(FitsOnTheLine) {}", 6625 getStyleWithColumns(Style, 44)); 6626 verifyFormat("Constructor() :\n" 6627 " Initializer(FitsOnTheLine) {}", 6628 getStyleWithColumns(Style, 43)); 6629 6630 verifyFormat("template <typename T>\n" 6631 "Constructor() : Initializer(FitsOnTheLine) {}", 6632 getStyleWithColumns(Style, 50)); 6633 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6634 verifyFormat( 6635 "SomeClass::Constructor() :\n" 6636 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6637 Style); 6638 6639 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6640 verifyFormat( 6641 "SomeClass::Constructor() :\n" 6642 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6643 Style); 6644 6645 verifyFormat( 6646 "SomeClass::Constructor() :\n" 6647 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6648 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6649 Style); 6650 verifyFormat( 6651 "SomeClass::Constructor() :\n" 6652 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6653 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6654 Style); 6655 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6656 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6657 " aaaaaaaaaa(aaaaaa) {}", 6658 Style); 6659 6660 verifyFormat("Constructor() :\n" 6661 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6662 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6663 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6664 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 6665 Style); 6666 6667 verifyFormat("Constructor() :\n" 6668 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6669 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6670 Style); 6671 6672 verifyFormat("Constructor(int Parameter = 0) :\n" 6673 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6674 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 6675 Style); 6676 verifyFormat("Constructor() :\n" 6677 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6678 "}", 6679 getStyleWithColumns(Style, 60)); 6680 verifyFormat("Constructor() :\n" 6681 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6682 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 6683 Style); 6684 6685 // Here a line could be saved by splitting the second initializer onto two 6686 // lines, but that is not desirable. 6687 verifyFormat("Constructor() :\n" 6688 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6689 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6690 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6691 Style); 6692 6693 FormatStyle OnePerLine = Style; 6694 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6695 verifyFormat("SomeClass::Constructor() :\n" 6696 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6697 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6698 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6699 OnePerLine); 6700 verifyFormat("SomeClass::Constructor() :\n" 6701 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6702 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6703 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6704 OnePerLine); 6705 verifyFormat("MyClass::MyClass(int var) :\n" 6706 " some_var_(var), // 4 space indent\n" 6707 " some_other_var_(var + 1) { // lined up\n" 6708 "}", 6709 OnePerLine); 6710 verifyFormat("Constructor() :\n" 6711 " aaaaa(aaaaaa),\n" 6712 " aaaaa(aaaaaa),\n" 6713 " aaaaa(aaaaaa),\n" 6714 " aaaaa(aaaaaa),\n" 6715 " aaaaa(aaaaaa) {}", 6716 OnePerLine); 6717 verifyFormat("Constructor() :\n" 6718 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6719 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6720 OnePerLine); 6721 OnePerLine.BinPackParameters = false; 6722 verifyFormat("Constructor() :\n" 6723 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6724 " aaaaaaaaaaa().aaa(),\n" 6725 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6726 OnePerLine); 6727 OnePerLine.ColumnLimit = 60; 6728 verifyFormat("Constructor() :\n" 6729 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6730 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6731 OnePerLine); 6732 6733 EXPECT_EQ("Constructor() :\n" 6734 " // Comment forcing unwanted break.\n" 6735 " aaaa(aaaa) {}", 6736 format("Constructor() :\n" 6737 " // Comment forcing unwanted break.\n" 6738 " aaaa(aaaa) {}", 6739 Style)); 6740 6741 Style.ColumnLimit = 0; 6742 verifyFormat("SomeClass::Constructor() :\n" 6743 " a(a) {}", 6744 Style); 6745 verifyFormat("SomeClass::Constructor() noexcept :\n" 6746 " a(a) {}", 6747 Style); 6748 verifyFormat("SomeClass::Constructor() :\n" 6749 " a(a), b(b), c(c) {}", 6750 Style); 6751 verifyFormat("SomeClass::Constructor() :\n" 6752 " a(a) {\n" 6753 " foo();\n" 6754 " bar();\n" 6755 "}", 6756 Style); 6757 6758 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 6759 verifyFormat("SomeClass::Constructor() :\n" 6760 " a(a), b(b), c(c) {\n" 6761 "}", 6762 Style); 6763 verifyFormat("SomeClass::Constructor() :\n" 6764 " a(a) {\n" 6765 "}", 6766 Style); 6767 6768 Style.ColumnLimit = 80; 6769 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 6770 Style.ConstructorInitializerIndentWidth = 2; 6771 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 6772 verifyFormat("SomeClass::Constructor() :\n" 6773 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6774 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 6775 Style); 6776 6777 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 6778 // well 6779 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 6780 verifyFormat( 6781 "class SomeClass\n" 6782 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6783 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6784 Style); 6785 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 6786 verifyFormat( 6787 "class SomeClass\n" 6788 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6789 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6790 Style); 6791 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 6792 verifyFormat( 6793 "class SomeClass :\n" 6794 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6795 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6796 Style); 6797 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 6798 verifyFormat( 6799 "class SomeClass\n" 6800 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6801 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6802 Style); 6803 } 6804 6805 #ifndef EXPENSIVE_CHECKS 6806 // Expensive checks enables libstdc++ checking which includes validating the 6807 // state of ranges used in std::priority_queue - this blows out the 6808 // runtime/scalability of the function and makes this test unacceptably slow. 6809 TEST_F(FormatTest, MemoizationTests) { 6810 // This breaks if the memoization lookup does not take \c Indent and 6811 // \c LastSpace into account. 6812 verifyFormat( 6813 "extern CFRunLoopTimerRef\n" 6814 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 6815 " CFTimeInterval interval, CFOptionFlags flags,\n" 6816 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 6817 " CFRunLoopTimerContext *context) {}"); 6818 6819 // Deep nesting somewhat works around our memoization. 6820 verifyFormat( 6821 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6822 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6823 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6824 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6825 " aaaaa())))))))))))))))))))))))))))))))))))))));", 6826 getLLVMStyleWithColumns(65)); 6827 verifyFormat( 6828 "aaaaa(\n" 6829 " aaaaa,\n" 6830 " aaaaa(\n" 6831 " aaaaa,\n" 6832 " aaaaa(\n" 6833 " aaaaa,\n" 6834 " aaaaa(\n" 6835 " aaaaa,\n" 6836 " aaaaa(\n" 6837 " aaaaa,\n" 6838 " aaaaa(\n" 6839 " aaaaa,\n" 6840 " aaaaa(\n" 6841 " aaaaa,\n" 6842 " aaaaa(\n" 6843 " aaaaa,\n" 6844 " aaaaa(\n" 6845 " aaaaa,\n" 6846 " aaaaa(\n" 6847 " aaaaa,\n" 6848 " aaaaa(\n" 6849 " aaaaa,\n" 6850 " aaaaa(\n" 6851 " aaaaa,\n" 6852 " aaaaa))))))))))));", 6853 getLLVMStyleWithColumns(65)); 6854 verifyFormat( 6855 "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n" 6856 " a),\n" 6857 " a),\n" 6858 " a),\n" 6859 " a),\n" 6860 " a),\n" 6861 " a),\n" 6862 " a),\n" 6863 " a),\n" 6864 " a),\n" 6865 " a),\n" 6866 " a),\n" 6867 " a),\n" 6868 " a),\n" 6869 " a),\n" 6870 " a),\n" 6871 " a),\n" 6872 " a)", 6873 getLLVMStyleWithColumns(65)); 6874 6875 // This test takes VERY long when memoization is broken. 6876 FormatStyle OnePerLine = getLLVMStyle(); 6877 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6878 OnePerLine.BinPackParameters = false; 6879 std::string input = "Constructor()\n" 6880 " : aaaa(a,\n"; 6881 for (unsigned i = 0, e = 80; i != e; ++i) { 6882 input += " a,\n"; 6883 } 6884 input += " a) {}"; 6885 verifyFormat(input, OnePerLine); 6886 } 6887 #endif 6888 6889 TEST_F(FormatTest, BreaksAsHighAsPossible) { 6890 verifyFormat( 6891 "void f() {\n" 6892 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 6893 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 6894 " f();\n" 6895 "}"); 6896 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 6897 " Intervals[i - 1].getRange().getLast()) {\n}"); 6898 } 6899 6900 TEST_F(FormatTest, BreaksFunctionDeclarations) { 6901 // Principially, we break function declarations in a certain order: 6902 // 1) break amongst arguments. 6903 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 6904 " Cccccccccccccc cccccccccccccc);"); 6905 verifyFormat("template <class TemplateIt>\n" 6906 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 6907 " TemplateIt *stop) {}"); 6908 6909 // 2) break after return type. 6910 verifyFormat( 6911 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6912 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 6913 getGoogleStyle()); 6914 6915 // 3) break after (. 6916 verifyFormat( 6917 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 6918 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 6919 getGoogleStyle()); 6920 6921 // 4) break before after nested name specifiers. 6922 verifyFormat( 6923 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6924 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 6925 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 6926 getGoogleStyle()); 6927 6928 // However, there are exceptions, if a sufficient amount of lines can be 6929 // saved. 6930 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 6931 // more adjusting. 6932 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 6933 " Cccccccccccccc cccccccccc,\n" 6934 " Cccccccccccccc cccccccccc,\n" 6935 " Cccccccccccccc cccccccccc,\n" 6936 " Cccccccccccccc cccccccccc);"); 6937 verifyFormat( 6938 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6939 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6940 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6941 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 6942 getGoogleStyle()); 6943 verifyFormat( 6944 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 6945 " Cccccccccccccc cccccccccc,\n" 6946 " Cccccccccccccc cccccccccc,\n" 6947 " Cccccccccccccc cccccccccc,\n" 6948 " Cccccccccccccc cccccccccc,\n" 6949 " Cccccccccccccc cccccccccc,\n" 6950 " Cccccccccccccc cccccccccc);"); 6951 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 6952 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6953 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6954 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6955 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 6956 6957 // Break after multi-line parameters. 6958 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6959 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6960 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6961 " bbbb bbbb);"); 6962 verifyFormat("void SomeLoooooooooooongFunction(\n" 6963 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 6964 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6965 " int bbbbbbbbbbbbb);"); 6966 6967 // Treat overloaded operators like other functions. 6968 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6969 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 6970 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6971 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 6972 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6973 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 6974 verifyGoogleFormat( 6975 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 6976 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 6977 verifyGoogleFormat( 6978 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 6979 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 6980 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6981 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 6982 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 6983 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 6984 verifyGoogleFormat( 6985 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 6986 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6987 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 6988 verifyGoogleFormat("template <typename T>\n" 6989 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6990 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 6991 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 6992 6993 FormatStyle Style = getLLVMStyle(); 6994 Style.PointerAlignment = FormatStyle::PAS_Left; 6995 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6996 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 6997 Style); 6998 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 6999 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7000 Style); 7001 } 7002 7003 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7004 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7005 // Prefer keeping `::` followed by `operator` together. 7006 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7007 "ccccccccc::operator++() {\n" 7008 " stuff();\n" 7009 "}", 7010 format("const aaaa::bbbbbbb\n" 7011 "&ccccccccc::operator++() { stuff(); }", 7012 getLLVMStyleWithColumns(40))); 7013 } 7014 7015 TEST_F(FormatTest, TrailingReturnType) { 7016 verifyFormat("auto foo() -> int;\n"); 7017 // correct trailing return type spacing 7018 verifyFormat("auto operator->() -> int;\n"); 7019 verifyFormat("auto operator++(int) -> int;\n"); 7020 7021 verifyFormat("struct S {\n" 7022 " auto bar() const -> int;\n" 7023 "};"); 7024 verifyFormat("template <size_t Order, typename T>\n" 7025 "auto load_img(const std::string &filename)\n" 7026 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7027 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7028 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7029 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7030 verifyFormat("template <typename T>\n" 7031 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7032 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7033 7034 // Not trailing return types. 7035 verifyFormat("void f() { auto a = b->c(); }"); 7036 verifyFormat("auto a = p->foo();"); 7037 verifyFormat("int a = p->foo();"); 7038 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7039 } 7040 7041 TEST_F(FormatTest, DeductionGuides) { 7042 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7043 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7044 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7045 verifyFormat( 7046 "template <class... T>\n" 7047 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7048 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7049 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7050 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7051 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7052 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7053 verifyFormat("template <class T> x() -> x<1>;"); 7054 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7055 7056 // Ensure not deduction guides. 7057 verifyFormat("c()->f<int>();"); 7058 verifyFormat("x()->foo<1>;"); 7059 verifyFormat("x = p->foo<3>();"); 7060 verifyFormat("x()->x<1>();"); 7061 verifyFormat("x()->x<1>;"); 7062 } 7063 7064 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7065 // Avoid breaking before trailing 'const' or other trailing annotations, if 7066 // they are not function-like. 7067 FormatStyle Style = getGoogleStyleWithColumns(47); 7068 verifyFormat("void someLongFunction(\n" 7069 " int someLoooooooooooooongParameter) const {\n}", 7070 getLLVMStyleWithColumns(47)); 7071 verifyFormat("LoooooongReturnType\n" 7072 "someLoooooooongFunction() const {}", 7073 getLLVMStyleWithColumns(47)); 7074 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7075 " const {}", 7076 Style); 7077 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7078 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7079 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7080 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7081 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7082 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7083 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7084 " aaaaaaaaaaa aaaaa) const override;"); 7085 verifyGoogleFormat( 7086 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7087 " const override;"); 7088 7089 // Even if the first parameter has to be wrapped. 7090 verifyFormat("void someLongFunction(\n" 7091 " int someLongParameter) const {}", 7092 getLLVMStyleWithColumns(46)); 7093 verifyFormat("void someLongFunction(\n" 7094 " int someLongParameter) const {}", 7095 Style); 7096 verifyFormat("void someLongFunction(\n" 7097 " int someLongParameter) override {}", 7098 Style); 7099 verifyFormat("void someLongFunction(\n" 7100 " int someLongParameter) OVERRIDE {}", 7101 Style); 7102 verifyFormat("void someLongFunction(\n" 7103 " int someLongParameter) final {}", 7104 Style); 7105 verifyFormat("void someLongFunction(\n" 7106 " int someLongParameter) FINAL {}", 7107 Style); 7108 verifyFormat("void someLongFunction(\n" 7109 " int parameter) const override {}", 7110 Style); 7111 7112 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7113 verifyFormat("void someLongFunction(\n" 7114 " int someLongParameter) const\n" 7115 "{\n" 7116 "}", 7117 Style); 7118 7119 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7120 verifyFormat("void someLongFunction(\n" 7121 " int someLongParameter) const\n" 7122 " {\n" 7123 " }", 7124 Style); 7125 7126 // Unless these are unknown annotations. 7127 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7128 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7129 " LONG_AND_UGLY_ANNOTATION;"); 7130 7131 // Breaking before function-like trailing annotations is fine to keep them 7132 // close to their arguments. 7133 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7134 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7135 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7136 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7137 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7138 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7139 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7140 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7141 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7142 7143 verifyFormat( 7144 "void aaaaaaaaaaaaaaaaaa()\n" 7145 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7146 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7147 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7148 " __attribute__((unused));"); 7149 verifyGoogleFormat( 7150 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7151 " GUARDED_BY(aaaaaaaaaaaa);"); 7152 verifyGoogleFormat( 7153 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7154 " GUARDED_BY(aaaaaaaaaaaa);"); 7155 verifyGoogleFormat( 7156 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7157 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7158 verifyGoogleFormat( 7159 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7160 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7161 } 7162 7163 TEST_F(FormatTest, FunctionAnnotations) { 7164 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7165 "int OldFunction(const string ¶meter) {}"); 7166 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7167 "string OldFunction(const string ¶meter) {}"); 7168 verifyFormat("template <typename T>\n" 7169 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7170 "string OldFunction(const string ¶meter) {}"); 7171 7172 // Not function annotations. 7173 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7174 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7175 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7176 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7177 verifyFormat("MACRO(abc).function() // wrap\n" 7178 " << abc;"); 7179 verifyFormat("MACRO(abc)->function() // wrap\n" 7180 " << abc;"); 7181 verifyFormat("MACRO(abc)::function() // wrap\n" 7182 " << abc;"); 7183 } 7184 7185 TEST_F(FormatTest, BreaksDesireably) { 7186 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7187 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7188 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7189 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7190 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7191 "}"); 7192 7193 verifyFormat( 7194 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7195 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7196 7197 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7200 7201 verifyFormat( 7202 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7203 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7204 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7205 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7207 7208 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7209 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7210 7211 verifyFormat( 7212 "void f() {\n" 7213 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7214 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7215 "}"); 7216 verifyFormat( 7217 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7218 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7219 verifyFormat( 7220 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7222 verifyFormat( 7223 "aaaaaa(aaa,\n" 7224 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7225 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7226 " aaaa);"); 7227 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7229 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7230 7231 // Indent consistently independent of call expression and unary operator. 7232 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7233 " dddddddddddddddddddddddddddddd));"); 7234 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7235 " dddddddddddddddddddddddddddddd));"); 7236 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7237 " dddddddddddddddddddddddddddddd));"); 7238 7239 // This test case breaks on an incorrect memoization, i.e. an optimization not 7240 // taking into account the StopAt value. 7241 verifyFormat( 7242 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7243 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7244 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7245 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7246 7247 verifyFormat("{\n {\n {\n" 7248 " Annotation.SpaceRequiredBefore =\n" 7249 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7250 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7251 " }\n }\n}"); 7252 7253 // Break on an outer level if there was a break on an inner level. 7254 EXPECT_EQ("f(g(h(a, // comment\n" 7255 " b, c),\n" 7256 " d, e),\n" 7257 " x, y);", 7258 format("f(g(h(a, // comment\n" 7259 " b, c), d, e), x, y);")); 7260 7261 // Prefer breaking similar line breaks. 7262 verifyFormat( 7263 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7264 " NSTrackingMouseEnteredAndExited |\n" 7265 " NSTrackingActiveAlways;"); 7266 } 7267 7268 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7269 FormatStyle NoBinPacking = getGoogleStyle(); 7270 NoBinPacking.BinPackParameters = false; 7271 NoBinPacking.BinPackArguments = true; 7272 verifyFormat("void f() {\n" 7273 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7274 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7275 "}", 7276 NoBinPacking); 7277 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7278 " int aaaaaaaaaaaaaaaaaaaa,\n" 7279 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7280 NoBinPacking); 7281 7282 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7283 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7284 " vector<int> bbbbbbbbbbbbbbb);", 7285 NoBinPacking); 7286 // FIXME: This behavior difference is probably not wanted. However, currently 7287 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7288 // template arguments from BreakBeforeParameter being set because of the 7289 // one-per-line formatting. 7290 verifyFormat( 7291 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7292 " aaaaaaaaaa> aaaaaaaaaa);", 7293 NoBinPacking); 7294 verifyFormat( 7295 "void fffffffffff(\n" 7296 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7297 " aaaaaaaaaa);"); 7298 } 7299 7300 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7301 FormatStyle NoBinPacking = getGoogleStyle(); 7302 NoBinPacking.BinPackParameters = false; 7303 NoBinPacking.BinPackArguments = false; 7304 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7305 " aaaaaaaaaaaaaaaaaaaa,\n" 7306 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7307 NoBinPacking); 7308 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7309 " aaaaaaaaaaaaa,\n" 7310 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7311 NoBinPacking); 7312 verifyFormat( 7313 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7314 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7316 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7317 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7318 NoBinPacking); 7319 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7320 " .aaaaaaaaaaaaaaaaaa();", 7321 NoBinPacking); 7322 verifyFormat("void f() {\n" 7323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7324 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7325 "}", 7326 NoBinPacking); 7327 7328 verifyFormat( 7329 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7330 " aaaaaaaaaaaa,\n" 7331 " aaaaaaaaaaaa);", 7332 NoBinPacking); 7333 verifyFormat( 7334 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7335 " ddddddddddddddddddddddddddddd),\n" 7336 " test);", 7337 NoBinPacking); 7338 7339 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7340 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7341 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7342 " aaaaaaaaaaaaaaaaaa;", 7343 NoBinPacking); 7344 verifyFormat("a(\"a\"\n" 7345 " \"a\",\n" 7346 " a);"); 7347 7348 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7349 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7350 " aaaaaaaaa,\n" 7351 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7352 NoBinPacking); 7353 verifyFormat( 7354 "void f() {\n" 7355 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7356 " .aaaaaaa();\n" 7357 "}", 7358 NoBinPacking); 7359 verifyFormat( 7360 "template <class SomeType, class SomeOtherType>\n" 7361 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7362 NoBinPacking); 7363 } 7364 7365 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7366 FormatStyle Style = getLLVMStyleWithColumns(15); 7367 Style.ExperimentalAutoDetectBinPacking = true; 7368 EXPECT_EQ("aaa(aaaa,\n" 7369 " aaaa,\n" 7370 " aaaa);\n" 7371 "aaa(aaaa,\n" 7372 " aaaa,\n" 7373 " aaaa);", 7374 format("aaa(aaaa,\n" // one-per-line 7375 " aaaa,\n" 7376 " aaaa );\n" 7377 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7378 Style)); 7379 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7380 " aaaa);\n" 7381 "aaa(aaaa, aaaa,\n" 7382 " aaaa);", 7383 format("aaa(aaaa, aaaa,\n" // bin-packed 7384 " aaaa );\n" 7385 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7386 Style)); 7387 } 7388 7389 TEST_F(FormatTest, FormatsBuilderPattern) { 7390 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7391 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7392 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7393 " .StartsWith(\".init\", ORDER_INIT)\n" 7394 " .StartsWith(\".fini\", ORDER_FINI)\n" 7395 " .StartsWith(\".hash\", ORDER_HASH)\n" 7396 " .Default(ORDER_TEXT);\n"); 7397 7398 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7399 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7400 verifyFormat("aaaaaaa->aaaaaaa\n" 7401 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7402 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7403 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7404 verifyFormat( 7405 "aaaaaaa->aaaaaaa\n" 7406 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7407 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7408 verifyFormat( 7409 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7410 " aaaaaaaaaaaaaa);"); 7411 verifyFormat( 7412 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7413 " aaaaaa->aaaaaaaaaaaa()\n" 7414 " ->aaaaaaaaaaaaaaaa(\n" 7415 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7416 " ->aaaaaaaaaaaaaaaaa();"); 7417 verifyGoogleFormat( 7418 "void f() {\n" 7419 " someo->Add((new util::filetools::Handler(dir))\n" 7420 " ->OnEvent1(NewPermanentCallback(\n" 7421 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7422 " ->OnEvent2(NewPermanentCallback(\n" 7423 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7424 " ->OnEvent3(NewPermanentCallback(\n" 7425 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7426 " ->OnEvent5(NewPermanentCallback(\n" 7427 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7428 " ->OnEvent6(NewPermanentCallback(\n" 7429 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7430 "}"); 7431 7432 verifyFormat( 7433 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7434 verifyFormat("aaaaaaaaaaaaaaa()\n" 7435 " .aaaaaaaaaaaaaaa()\n" 7436 " .aaaaaaaaaaaaaaa()\n" 7437 " .aaaaaaaaaaaaaaa()\n" 7438 " .aaaaaaaaaaaaaaa();"); 7439 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7440 " .aaaaaaaaaaaaaaa()\n" 7441 " .aaaaaaaaaaaaaaa()\n" 7442 " .aaaaaaaaaaaaaaa();"); 7443 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7444 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7445 " .aaaaaaaaaaaaaaa();"); 7446 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7447 " ->aaaaaaaaaaaaaae(0)\n" 7448 " ->aaaaaaaaaaaaaaa();"); 7449 7450 // Don't linewrap after very short segments. 7451 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7452 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7453 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7454 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7455 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7456 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7457 verifyFormat("aaa()\n" 7458 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7459 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7460 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7461 7462 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7463 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7464 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7465 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7466 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7467 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7468 7469 // Prefer not to break after empty parentheses. 7470 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7471 " First->LastNewlineOffset);"); 7472 7473 // Prefer not to create "hanging" indents. 7474 verifyFormat( 7475 "return !soooooooooooooome_map\n" 7476 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7477 " .second;"); 7478 verifyFormat( 7479 "return aaaaaaaaaaaaaaaa\n" 7480 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7481 " .aaaa(aaaaaaaaaaaaaa);"); 7482 // No hanging indent here. 7483 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7484 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7485 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7486 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7487 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7488 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7489 getLLVMStyleWithColumns(60)); 7490 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7491 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7492 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7493 getLLVMStyleWithColumns(59)); 7494 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7495 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7496 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7497 7498 // Dont break if only closing statements before member call 7499 verifyFormat("test() {\n" 7500 " ([]() -> {\n" 7501 " int b = 32;\n" 7502 " return 3;\n" 7503 " }).foo();\n" 7504 "}"); 7505 verifyFormat("test() {\n" 7506 " (\n" 7507 " []() -> {\n" 7508 " int b = 32;\n" 7509 " return 3;\n" 7510 " },\n" 7511 " foo, bar)\n" 7512 " .foo();\n" 7513 "}"); 7514 verifyFormat("test() {\n" 7515 " ([]() -> {\n" 7516 " int b = 32;\n" 7517 " return 3;\n" 7518 " })\n" 7519 " .foo()\n" 7520 " .bar();\n" 7521 "}"); 7522 verifyFormat("test() {\n" 7523 " ([]() -> {\n" 7524 " int b = 32;\n" 7525 " return 3;\n" 7526 " })\n" 7527 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7528 " \"bbbb\");\n" 7529 "}", 7530 getLLVMStyleWithColumns(30)); 7531 } 7532 7533 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7534 verifyFormat( 7535 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7536 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7537 verifyFormat( 7538 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7539 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7540 7541 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7542 " ccccccccccccccccccccccccc) {\n}"); 7543 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7544 " ccccccccccccccccccccccccc) {\n}"); 7545 7546 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7547 " ccccccccccccccccccccccccc) {\n}"); 7548 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7549 " ccccccccccccccccccccccccc) {\n}"); 7550 7551 verifyFormat( 7552 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7553 " ccccccccccccccccccccccccc) {\n}"); 7554 verifyFormat( 7555 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7556 " ccccccccccccccccccccccccc) {\n}"); 7557 7558 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7559 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7560 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7561 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7562 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7563 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7564 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7565 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7566 7567 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7568 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7569 " aaaaaaaaaaaaaaa != aa) {\n}"); 7570 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7571 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7572 " aaaaaaaaaaaaaaa != aa) {\n}"); 7573 } 7574 7575 TEST_F(FormatTest, BreaksAfterAssignments) { 7576 verifyFormat( 7577 "unsigned Cost =\n" 7578 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7579 " SI->getPointerAddressSpaceee());\n"); 7580 verifyFormat( 7581 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7582 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7583 7584 verifyFormat( 7585 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7586 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7587 verifyFormat("unsigned OriginalStartColumn =\n" 7588 " SourceMgr.getSpellingColumnNumber(\n" 7589 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7590 " 1;"); 7591 } 7592 7593 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7594 FormatStyle Style = getLLVMStyle(); 7595 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7596 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7597 Style); 7598 7599 Style.PenaltyBreakAssignment = 20; 7600 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7601 " cccccccccccccccccccccccccc;", 7602 Style); 7603 } 7604 7605 TEST_F(FormatTest, AlignsAfterAssignments) { 7606 verifyFormat( 7607 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7608 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7609 verifyFormat( 7610 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7611 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7612 verifyFormat( 7613 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7614 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7615 verifyFormat( 7616 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7617 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7618 verifyFormat( 7619 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7620 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7621 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7622 } 7623 7624 TEST_F(FormatTest, AlignsAfterReturn) { 7625 verifyFormat( 7626 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7627 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7628 verifyFormat( 7629 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7630 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7631 verifyFormat( 7632 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7633 " aaaaaaaaaaaaaaaaaaaaaa();"); 7634 verifyFormat( 7635 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7636 " aaaaaaaaaaaaaaaaaaaaaa());"); 7637 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7638 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7639 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7640 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7641 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7642 verifyFormat("return\n" 7643 " // true if code is one of a or b.\n" 7644 " code == a || code == b;"); 7645 } 7646 7647 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7648 verifyFormat( 7649 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7650 " aaaaaaaaa aaaaaaa) {}"); 7651 verifyFormat( 7652 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7653 " aaaaaaaaaaa aaaaaaaaa);"); 7654 verifyFormat( 7655 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7656 " aaaaaaaaaaaaaaaaaaaaa));"); 7657 FormatStyle Style = getLLVMStyle(); 7658 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7659 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7660 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 7661 Style); 7662 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7663 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 7664 Style); 7665 verifyFormat("SomeLongVariableName->someFunction(\n" 7666 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 7667 Style); 7668 verifyFormat( 7669 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7670 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7671 Style); 7672 verifyFormat( 7673 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7674 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7675 Style); 7676 verifyFormat( 7677 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7678 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7679 Style); 7680 7681 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 7682 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 7683 " b));", 7684 Style); 7685 7686 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7687 Style.BinPackArguments = false; 7688 Style.BinPackParameters = false; 7689 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7690 " aaaaaaaaaaa aaaaaaaa,\n" 7691 " aaaaaaaaa aaaaaaa,\n" 7692 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7693 Style); 7694 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7695 " aaaaaaaaaaa aaaaaaaaa,\n" 7696 " aaaaaaaaaaa aaaaaaaaa,\n" 7697 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7698 Style); 7699 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 7700 " aaaaaaaaaaaaaaa,\n" 7701 " aaaaaaaaaaaaaaaaaaaaa,\n" 7702 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7703 Style); 7704 verifyFormat( 7705 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 7706 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7707 Style); 7708 verifyFormat( 7709 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 7710 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7711 Style); 7712 verifyFormat( 7713 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7714 " aaaaaaaaaaaaaaaaaaaaa(\n" 7715 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 7716 " aaaaaaaaaaaaaaaa);", 7717 Style); 7718 verifyFormat( 7719 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7720 " aaaaaaaaaaaaaaaaaaaaa(\n" 7721 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 7722 " aaaaaaaaaaaaaaaa);", 7723 Style); 7724 } 7725 7726 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 7727 FormatStyle Style = getLLVMStyleWithColumns(40); 7728 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7729 " bbbbbbbbbbbbbbbbbbbbbb);", 7730 Style); 7731 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7732 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7733 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7734 " bbbbbbbbbbbbbbbbbbbbbb);", 7735 Style); 7736 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7737 Style.AlignOperands = FormatStyle::OAS_Align; 7738 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7739 " bbbbbbbbbbbbbbbbbbbbbb);", 7740 Style); 7741 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7742 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7743 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7744 " bbbbbbbbbbbbbbbbbbbbbb);", 7745 Style); 7746 } 7747 7748 TEST_F(FormatTest, BreaksConditionalExpressions) { 7749 verifyFormat( 7750 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7751 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7752 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7753 verifyFormat( 7754 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 7755 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7756 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7757 verifyFormat( 7758 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7759 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7760 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 7761 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7762 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7763 verifyFormat( 7764 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 7765 " : aaaaaaaaaaaaa);"); 7766 verifyFormat( 7767 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7768 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7769 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7770 " aaaaaaaaaaaaa);"); 7771 verifyFormat( 7772 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7773 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7774 " aaaaaaaaaaaaa);"); 7775 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7776 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7777 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7778 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7779 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7780 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7781 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7782 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7783 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7784 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7785 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7786 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7787 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7788 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7789 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7790 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7791 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7792 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7793 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7794 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7795 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 7796 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7797 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7798 " : aaaaaaaaaaaaaaaa;"); 7799 verifyFormat( 7800 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7801 " ? aaaaaaaaaaaaaaa\n" 7802 " : aaaaaaaaaaaaaaa;"); 7803 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 7804 " aaaaaaaaa\n" 7805 " ? b\n" 7806 " : c);"); 7807 verifyFormat("return aaaa == bbbb\n" 7808 " // comment\n" 7809 " ? aaaa\n" 7810 " : bbbb;"); 7811 verifyFormat("unsigned Indent =\n" 7812 " format(TheLine.First,\n" 7813 " IndentForLevel[TheLine.Level] >= 0\n" 7814 " ? IndentForLevel[TheLine.Level]\n" 7815 " : TheLine * 2,\n" 7816 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 7817 getLLVMStyleWithColumns(60)); 7818 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7819 " ? aaaaaaaaaaaaaaa\n" 7820 " : bbbbbbbbbbbbbbb //\n" 7821 " ? ccccccccccccccc\n" 7822 " : ddddddddddddddd;"); 7823 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7824 " ? aaaaaaaaaaaaaaa\n" 7825 " : (bbbbbbbbbbbbbbb //\n" 7826 " ? ccccccccccccccc\n" 7827 " : ddddddddddddddd);"); 7828 verifyFormat( 7829 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7830 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7831 " aaaaaaaaaaaaaaaaaaaaa +\n" 7832 " aaaaaaaaaaaaaaaaaaaaa\n" 7833 " : aaaaaaaaaa;"); 7834 verifyFormat( 7835 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7836 " : aaaaaaaaaaaaaaaaaaaaaa\n" 7837 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7838 7839 FormatStyle NoBinPacking = getLLVMStyle(); 7840 NoBinPacking.BinPackArguments = false; 7841 verifyFormat( 7842 "void f() {\n" 7843 " g(aaa,\n" 7844 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7845 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7846 " ? aaaaaaaaaaaaaaa\n" 7847 " : aaaaaaaaaaaaaaa);\n" 7848 "}", 7849 NoBinPacking); 7850 verifyFormat( 7851 "void f() {\n" 7852 " g(aaa,\n" 7853 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7855 " ?: aaaaaaaaaaaaaaa);\n" 7856 "}", 7857 NoBinPacking); 7858 7859 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 7860 " // comment.\n" 7861 " ccccccccccccccccccccccccccccccccccccccc\n" 7862 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7863 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 7864 7865 // Assignments in conditional expressions. Apparently not uncommon :-(. 7866 verifyFormat("return a != b\n" 7867 " // comment\n" 7868 " ? a = b\n" 7869 " : a = b;"); 7870 verifyFormat("return a != b\n" 7871 " // comment\n" 7872 " ? a = a != b\n" 7873 " // comment\n" 7874 " ? a = b\n" 7875 " : a\n" 7876 " : a;\n"); 7877 verifyFormat("return a != b\n" 7878 " // comment\n" 7879 " ? a\n" 7880 " : a = a != b\n" 7881 " // comment\n" 7882 " ? a = b\n" 7883 " : a;"); 7884 7885 // Chained conditionals 7886 FormatStyle Style = getLLVMStyleWithColumns(70); 7887 Style.AlignOperands = FormatStyle::OAS_Align; 7888 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7889 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7890 " : 3333333333333333;", 7891 Style); 7892 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7893 " : bbbbbbbbbb ? 2222222222222222\n" 7894 " : 3333333333333333;", 7895 Style); 7896 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 7897 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 7898 " : 3333333333333333;", 7899 Style); 7900 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7901 " : bbbbbbbbbbbbbb ? 222222\n" 7902 " : 333333;", 7903 Style); 7904 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7905 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7906 " : cccccccccccccc ? 3333333333333333\n" 7907 " : 4444444444444444;", 7908 Style); 7909 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 7910 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7911 " : 3333333333333333;", 7912 Style); 7913 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7914 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7915 " : (aaa ? bbb : ccc);", 7916 Style); 7917 verifyFormat( 7918 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7919 " : cccccccccccccccccc)\n" 7920 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7921 " : 3333333333333333;", 7922 Style); 7923 verifyFormat( 7924 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7925 " : cccccccccccccccccc)\n" 7926 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7927 " : 3333333333333333;", 7928 Style); 7929 verifyFormat( 7930 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7931 " : dddddddddddddddddd)\n" 7932 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7933 " : 3333333333333333;", 7934 Style); 7935 verifyFormat( 7936 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7937 " : dddddddddddddddddd)\n" 7938 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7939 " : 3333333333333333;", 7940 Style); 7941 verifyFormat( 7942 "return aaaaaaaaa ? 1111111111111111\n" 7943 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7944 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7945 " : dddddddddddddddddd)\n", 7946 Style); 7947 verifyFormat( 7948 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7949 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7950 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7951 " : cccccccccccccccccc);", 7952 Style); 7953 verifyFormat( 7954 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7955 " : ccccccccccccccc ? dddddddddddddddddd\n" 7956 " : eeeeeeeeeeeeeeeeee)\n" 7957 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7958 " : 3333333333333333;", 7959 Style); 7960 verifyFormat( 7961 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7962 " : ccccccccccccccc ? dddddddddddddddddd\n" 7963 " : eeeeeeeeeeeeeeeeee)\n" 7964 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7965 " : 3333333333333333;", 7966 Style); 7967 verifyFormat( 7968 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7969 " : cccccccccccc ? dddddddddddddddddd\n" 7970 " : eeeeeeeeeeeeeeeeee)\n" 7971 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7972 " : 3333333333333333;", 7973 Style); 7974 verifyFormat( 7975 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7976 " : cccccccccccccccccc\n" 7977 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7978 " : 3333333333333333;", 7979 Style); 7980 verifyFormat( 7981 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7982 " : cccccccccccccccc ? dddddddddddddddddd\n" 7983 " : eeeeeeeeeeeeeeeeee\n" 7984 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7985 " : 3333333333333333;", 7986 Style); 7987 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 7988 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7989 " : cccccccccccccccccc ? dddddddddddddddddd\n" 7990 " : eeeeeeeeeeeeeeeeee)\n" 7991 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 7992 " : 3333333333333333;", 7993 Style); 7994 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 7995 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7996 " : cccccccccccccccc ? dddddddddddddddddd\n" 7997 " : eeeeeeeeeeeeeeeeee\n" 7998 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 7999 " : 3333333333333333;", 8000 Style); 8001 8002 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8003 Style.BreakBeforeTernaryOperators = false; 8004 // FIXME: Aligning the question marks is weird given DontAlign. 8005 // Consider disabling this alignment in this case. Also check whether this 8006 // will render the adjustment from https://reviews.llvm.org/D82199 8007 // unnecessary. 8008 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8009 " bbbb ? cccccccccccccccccc :\n" 8010 " ddddd;\n", 8011 Style); 8012 8013 EXPECT_EQ( 8014 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8015 " /*\n" 8016 " */\n" 8017 " function() {\n" 8018 " try {\n" 8019 " return JJJJJJJJJJJJJJ(\n" 8020 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8021 " }\n" 8022 " } :\n" 8023 " function() {};", 8024 format( 8025 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8026 " /*\n" 8027 " */\n" 8028 " function() {\n" 8029 " try {\n" 8030 " return JJJJJJJJJJJJJJ(\n" 8031 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8032 " }\n" 8033 " } :\n" 8034 " function() {};", 8035 getGoogleStyle(FormatStyle::LK_JavaScript))); 8036 } 8037 8038 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8039 FormatStyle Style = getLLVMStyleWithColumns(70); 8040 Style.BreakBeforeTernaryOperators = false; 8041 verifyFormat( 8042 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8043 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8044 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8045 Style); 8046 verifyFormat( 8047 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8048 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8049 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8050 Style); 8051 verifyFormat( 8052 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8053 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8054 Style); 8055 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8056 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8057 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8058 Style); 8059 verifyFormat( 8060 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8061 " aaaaaaaaaaaaa);", 8062 Style); 8063 verifyFormat( 8064 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8065 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8066 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8067 " aaaaaaaaaaaaa);", 8068 Style); 8069 verifyFormat( 8070 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8071 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8072 " aaaaaaaaaaaaa);", 8073 Style); 8074 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8075 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8076 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8077 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8078 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8079 Style); 8080 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8081 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8082 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8083 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8084 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8085 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8086 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8087 Style); 8088 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8089 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8090 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8091 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8092 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8093 Style); 8094 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8095 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8096 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8097 Style); 8098 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8099 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8100 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8101 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8102 Style); 8103 verifyFormat( 8104 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8105 " aaaaaaaaaaaaaaa :\n" 8106 " aaaaaaaaaaaaaaa;", 8107 Style); 8108 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8109 " aaaaaaaaa ?\n" 8110 " b :\n" 8111 " c);", 8112 Style); 8113 verifyFormat("unsigned Indent =\n" 8114 " format(TheLine.First,\n" 8115 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8116 " IndentForLevel[TheLine.Level] :\n" 8117 " TheLine * 2,\n" 8118 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8119 Style); 8120 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8121 " aaaaaaaaaaaaaaa :\n" 8122 " bbbbbbbbbbbbbbb ? //\n" 8123 " ccccccccccccccc :\n" 8124 " ddddddddddddddd;", 8125 Style); 8126 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8127 " aaaaaaaaaaaaaaa :\n" 8128 " (bbbbbbbbbbbbbbb ? //\n" 8129 " ccccccccccccccc :\n" 8130 " ddddddddddddddd);", 8131 Style); 8132 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8133 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8134 " ccccccccccccccccccccccccccc;", 8135 Style); 8136 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8137 " aaaaa :\n" 8138 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8139 Style); 8140 8141 // Chained conditionals 8142 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8143 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8144 " 3333333333333333;", 8145 Style); 8146 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8147 " bbbbbbbbbb ? 2222222222222222 :\n" 8148 " 3333333333333333;", 8149 Style); 8150 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8151 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8152 " 3333333333333333;", 8153 Style); 8154 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8155 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8156 " 333333;", 8157 Style); 8158 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8159 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8160 " cccccccccccccccc ? 3333333333333333 :\n" 8161 " 4444444444444444;", 8162 Style); 8163 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8164 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8165 " 3333333333333333;", 8166 Style); 8167 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8168 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8169 " (aaa ? bbb : ccc);", 8170 Style); 8171 verifyFormat( 8172 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8173 " cccccccccccccccccc) :\n" 8174 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8175 " 3333333333333333;", 8176 Style); 8177 verifyFormat( 8178 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8179 " cccccccccccccccccc) :\n" 8180 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8181 " 3333333333333333;", 8182 Style); 8183 verifyFormat( 8184 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8185 " dddddddddddddddddd) :\n" 8186 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8187 " 3333333333333333;", 8188 Style); 8189 verifyFormat( 8190 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8191 " dddddddddddddddddd) :\n" 8192 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8193 " 3333333333333333;", 8194 Style); 8195 verifyFormat( 8196 "return aaaaaaaaa ? 1111111111111111 :\n" 8197 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8198 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8199 " dddddddddddddddddd)\n", 8200 Style); 8201 verifyFormat( 8202 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8203 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8204 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8205 " cccccccccccccccccc);", 8206 Style); 8207 verifyFormat( 8208 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8209 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8210 " eeeeeeeeeeeeeeeeee) :\n" 8211 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8212 " 3333333333333333;", 8213 Style); 8214 verifyFormat( 8215 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8216 " ccccccccccccc ? dddddddddddddddddd :\n" 8217 " eeeeeeeeeeeeeeeeee) :\n" 8218 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8219 " 3333333333333333;", 8220 Style); 8221 verifyFormat( 8222 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8223 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8224 " eeeeeeeeeeeeeeeeee) :\n" 8225 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8226 " 3333333333333333;", 8227 Style); 8228 verifyFormat( 8229 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8230 " cccccccccccccccccc :\n" 8231 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8232 " 3333333333333333;", 8233 Style); 8234 verifyFormat( 8235 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8236 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8237 " eeeeeeeeeeeeeeeeee :\n" 8238 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8239 " 3333333333333333;", 8240 Style); 8241 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8242 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8243 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8244 " eeeeeeeeeeeeeeeeee) :\n" 8245 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8246 " 3333333333333333;", 8247 Style); 8248 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8249 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8250 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8251 " eeeeeeeeeeeeeeeeee :\n" 8252 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8253 " 3333333333333333;", 8254 Style); 8255 } 8256 8257 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8258 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8259 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8260 verifyFormat("bool a = true, b = false;"); 8261 8262 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8263 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8264 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8265 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8266 verifyFormat( 8267 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8268 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8269 " d = e && f;"); 8270 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8271 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8272 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8273 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8274 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8275 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8276 8277 FormatStyle Style = getGoogleStyle(); 8278 Style.PointerAlignment = FormatStyle::PAS_Left; 8279 Style.DerivePointerAlignment = false; 8280 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8281 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8282 " *b = bbbbbbbbbbbbbbbbbbb;", 8283 Style); 8284 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8285 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8286 Style); 8287 verifyFormat("vector<int*> a, b;", Style); 8288 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8289 } 8290 8291 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8292 verifyFormat("arr[foo ? bar : baz];"); 8293 verifyFormat("f()[foo ? bar : baz];"); 8294 verifyFormat("(a + b)[foo ? bar : baz];"); 8295 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8296 } 8297 8298 TEST_F(FormatTest, AlignsStringLiterals) { 8299 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8300 " \"short literal\");"); 8301 verifyFormat( 8302 "looooooooooooooooooooooooongFunction(\n" 8303 " \"short literal\"\n" 8304 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8305 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8306 " \" string literals\",\n" 8307 " and, other, parameters);"); 8308 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8309 " \"5678\";", 8310 format("fun + \"1243\" /* comment */\n" 8311 " \"5678\";", 8312 getLLVMStyleWithColumns(28))); 8313 EXPECT_EQ( 8314 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8315 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8316 " \"aaaaaaaaaaaaaaaa\";", 8317 format("aaaaaa =" 8318 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8319 "aaaaaaaaaaaaaaaaaaaaa\" " 8320 "\"aaaaaaaaaaaaaaaa\";")); 8321 verifyFormat("a = a + \"a\"\n" 8322 " \"a\"\n" 8323 " \"a\";"); 8324 verifyFormat("f(\"a\", \"b\"\n" 8325 " \"c\");"); 8326 8327 verifyFormat( 8328 "#define LL_FORMAT \"ll\"\n" 8329 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8330 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8331 8332 verifyFormat("#define A(X) \\\n" 8333 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8334 " \"ccccc\"", 8335 getLLVMStyleWithColumns(23)); 8336 verifyFormat("#define A \"def\"\n" 8337 "f(\"abc\" A \"ghi\"\n" 8338 " \"jkl\");"); 8339 8340 verifyFormat("f(L\"a\"\n" 8341 " L\"b\");"); 8342 verifyFormat("#define A(X) \\\n" 8343 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8344 " L\"ccccc\"", 8345 getLLVMStyleWithColumns(25)); 8346 8347 verifyFormat("f(@\"a\"\n" 8348 " @\"b\");"); 8349 verifyFormat("NSString s = @\"a\"\n" 8350 " @\"b\"\n" 8351 " @\"c\";"); 8352 verifyFormat("NSString s = @\"a\"\n" 8353 " \"b\"\n" 8354 " \"c\";"); 8355 } 8356 8357 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8358 FormatStyle Style = getLLVMStyle(); 8359 // No declarations or definitions should be moved to own line. 8360 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8361 verifyFormat("class A {\n" 8362 " int f() { return 1; }\n" 8363 " int g();\n" 8364 "};\n" 8365 "int f() { return 1; }\n" 8366 "int g();\n", 8367 Style); 8368 8369 // All declarations and definitions should have the return type moved to its 8370 // own line. 8371 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8372 Style.TypenameMacros = {"LIST"}; 8373 verifyFormat("SomeType\n" 8374 "funcdecl(LIST(uint64_t));", 8375 Style); 8376 verifyFormat("class E {\n" 8377 " int\n" 8378 " f() {\n" 8379 " return 1;\n" 8380 " }\n" 8381 " int\n" 8382 " g();\n" 8383 "};\n" 8384 "int\n" 8385 "f() {\n" 8386 " return 1;\n" 8387 "}\n" 8388 "int\n" 8389 "g();\n", 8390 Style); 8391 8392 // Top-level definitions, and no kinds of declarations should have the 8393 // return type moved to its own line. 8394 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8395 verifyFormat("class B {\n" 8396 " int f() { return 1; }\n" 8397 " int g();\n" 8398 "};\n" 8399 "int\n" 8400 "f() {\n" 8401 " return 1;\n" 8402 "}\n" 8403 "int g();\n", 8404 Style); 8405 8406 // Top-level definitions and declarations should have the return type moved 8407 // to its own line. 8408 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8409 verifyFormat("class C {\n" 8410 " int f() { return 1; }\n" 8411 " int g();\n" 8412 "};\n" 8413 "int\n" 8414 "f() {\n" 8415 " return 1;\n" 8416 "}\n" 8417 "int\n" 8418 "g();\n", 8419 Style); 8420 8421 // All definitions should have the return type moved to its own line, but no 8422 // kinds of declarations. 8423 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8424 verifyFormat("class D {\n" 8425 " int\n" 8426 " f() {\n" 8427 " return 1;\n" 8428 " }\n" 8429 " int g();\n" 8430 "};\n" 8431 "int\n" 8432 "f() {\n" 8433 " return 1;\n" 8434 "}\n" 8435 "int g();\n", 8436 Style); 8437 verifyFormat("const char *\n" 8438 "f(void) {\n" // Break here. 8439 " return \"\";\n" 8440 "}\n" 8441 "const char *bar(void);\n", // No break here. 8442 Style); 8443 verifyFormat("template <class T>\n" 8444 "T *\n" 8445 "f(T &c) {\n" // Break here. 8446 " return NULL;\n" 8447 "}\n" 8448 "template <class T> T *f(T &c);\n", // No break here. 8449 Style); 8450 verifyFormat("class C {\n" 8451 " int\n" 8452 " operator+() {\n" 8453 " return 1;\n" 8454 " }\n" 8455 " int\n" 8456 " operator()() {\n" 8457 " return 1;\n" 8458 " }\n" 8459 "};\n", 8460 Style); 8461 verifyFormat("void\n" 8462 "A::operator()() {}\n" 8463 "void\n" 8464 "A::operator>>() {}\n" 8465 "void\n" 8466 "A::operator+() {}\n" 8467 "void\n" 8468 "A::operator*() {}\n" 8469 "void\n" 8470 "A::operator->() {}\n" 8471 "void\n" 8472 "A::operator void *() {}\n" 8473 "void\n" 8474 "A::operator void &() {}\n" 8475 "void\n" 8476 "A::operator void &&() {}\n" 8477 "void\n" 8478 "A::operator char *() {}\n" 8479 "void\n" 8480 "A::operator[]() {}\n" 8481 "void\n" 8482 "A::operator!() {}\n" 8483 "void\n" 8484 "A::operator**() {}\n" 8485 "void\n" 8486 "A::operator<Foo> *() {}\n" 8487 "void\n" 8488 "A::operator<Foo> **() {}\n" 8489 "void\n" 8490 "A::operator<Foo> &() {}\n" 8491 "void\n" 8492 "A::operator void **() {}\n", 8493 Style); 8494 verifyFormat("constexpr auto\n" 8495 "operator()() const -> reference {}\n" 8496 "constexpr auto\n" 8497 "operator>>() const -> reference {}\n" 8498 "constexpr auto\n" 8499 "operator+() const -> reference {}\n" 8500 "constexpr auto\n" 8501 "operator*() const -> reference {}\n" 8502 "constexpr auto\n" 8503 "operator->() const -> reference {}\n" 8504 "constexpr auto\n" 8505 "operator++() const -> reference {}\n" 8506 "constexpr auto\n" 8507 "operator void *() const -> reference {}\n" 8508 "constexpr auto\n" 8509 "operator void **() const -> reference {}\n" 8510 "constexpr auto\n" 8511 "operator void *() const -> reference {}\n" 8512 "constexpr auto\n" 8513 "operator void &() const -> reference {}\n" 8514 "constexpr auto\n" 8515 "operator void &&() const -> reference {}\n" 8516 "constexpr auto\n" 8517 "operator char *() const -> reference {}\n" 8518 "constexpr auto\n" 8519 "operator!() const -> reference {}\n" 8520 "constexpr auto\n" 8521 "operator[]() const -> reference {}\n", 8522 Style); 8523 verifyFormat("void *operator new(std::size_t s);", // No break here. 8524 Style); 8525 verifyFormat("void *\n" 8526 "operator new(std::size_t s) {}", 8527 Style); 8528 verifyFormat("void *\n" 8529 "operator delete[](void *ptr) {}", 8530 Style); 8531 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8532 verifyFormat("const char *\n" 8533 "f(void)\n" // Break here. 8534 "{\n" 8535 " return \"\";\n" 8536 "}\n" 8537 "const char *bar(void);\n", // No break here. 8538 Style); 8539 verifyFormat("template <class T>\n" 8540 "T *\n" // Problem here: no line break 8541 "f(T &c)\n" // Break here. 8542 "{\n" 8543 " return NULL;\n" 8544 "}\n" 8545 "template <class T> T *f(T &c);\n", // No break here. 8546 Style); 8547 verifyFormat("int\n" 8548 "foo(A<bool> a)\n" 8549 "{\n" 8550 " return a;\n" 8551 "}\n", 8552 Style); 8553 verifyFormat("int\n" 8554 "foo(A<8> a)\n" 8555 "{\n" 8556 " return a;\n" 8557 "}\n", 8558 Style); 8559 verifyFormat("int\n" 8560 "foo(A<B<bool>, 8> a)\n" 8561 "{\n" 8562 " return a;\n" 8563 "}\n", 8564 Style); 8565 verifyFormat("int\n" 8566 "foo(A<B<8>, bool> a)\n" 8567 "{\n" 8568 " return a;\n" 8569 "}\n", 8570 Style); 8571 verifyFormat("int\n" 8572 "foo(A<B<bool>, bool> a)\n" 8573 "{\n" 8574 " return a;\n" 8575 "}\n", 8576 Style); 8577 verifyFormat("int\n" 8578 "foo(A<B<8>, 8> a)\n" 8579 "{\n" 8580 " return a;\n" 8581 "}\n", 8582 Style); 8583 8584 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8585 Style.BraceWrapping.AfterFunction = true; 8586 verifyFormat("int f(i);\n" // No break here. 8587 "int\n" // Break here. 8588 "f(i)\n" 8589 "{\n" 8590 " return i + 1;\n" 8591 "}\n" 8592 "int\n" // Break here. 8593 "f(i)\n" 8594 "{\n" 8595 " return i + 1;\n" 8596 "};", 8597 Style); 8598 verifyFormat("int f(a, b, c);\n" // No break here. 8599 "int\n" // Break here. 8600 "f(a, b, c)\n" // Break here. 8601 "short a, b;\n" 8602 "float c;\n" 8603 "{\n" 8604 " return a + b < c;\n" 8605 "}\n" 8606 "int\n" // Break here. 8607 "f(a, b, c)\n" // Break here. 8608 "short a, b;\n" 8609 "float c;\n" 8610 "{\n" 8611 " return a + b < c;\n" 8612 "};", 8613 Style); 8614 verifyFormat("byte *\n" // Break here. 8615 "f(a)\n" // Break here. 8616 "byte a[];\n" 8617 "{\n" 8618 " return a;\n" 8619 "}", 8620 Style); 8621 verifyFormat("bool f(int a, int) override;\n" 8622 "Bar g(int a, Bar) final;\n" 8623 "Bar h(a, Bar) final;", 8624 Style); 8625 verifyFormat("int\n" 8626 "f(a)", 8627 Style); 8628 verifyFormat("bool\n" 8629 "f(size_t = 0, bool b = false)\n" 8630 "{\n" 8631 " return !b;\n" 8632 "}", 8633 Style); 8634 8635 // The return breaking style doesn't affect: 8636 // * function and object definitions with attribute-like macros 8637 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8638 " ABSL_GUARDED_BY(mutex) = {};", 8639 getGoogleStyleWithColumns(40)); 8640 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8641 " ABSL_GUARDED_BY(mutex); // comment", 8642 getGoogleStyleWithColumns(40)); 8643 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8644 " ABSL_GUARDED_BY(mutex1)\n" 8645 " ABSL_GUARDED_BY(mutex2);", 8646 getGoogleStyleWithColumns(40)); 8647 verifyFormat("Tttttt f(int a, int b)\n" 8648 " ABSL_GUARDED_BY(mutex1)\n" 8649 " ABSL_GUARDED_BY(mutex2);", 8650 getGoogleStyleWithColumns(40)); 8651 // * typedefs 8652 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 8653 8654 Style = getGNUStyle(); 8655 8656 // Test for comments at the end of function declarations. 8657 verifyFormat("void\n" 8658 "foo (int a, /*abc*/ int b) // def\n" 8659 "{\n" 8660 "}\n", 8661 Style); 8662 8663 verifyFormat("void\n" 8664 "foo (int a, /* abc */ int b) /* def */\n" 8665 "{\n" 8666 "}\n", 8667 Style); 8668 8669 // Definitions that should not break after return type 8670 verifyFormat("void foo (int a, int b); // def\n", Style); 8671 verifyFormat("void foo (int a, int b); /* def */\n", Style); 8672 verifyFormat("void foo (int a, int b);\n", Style); 8673 } 8674 8675 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 8676 FormatStyle NoBreak = getLLVMStyle(); 8677 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 8678 FormatStyle Break = getLLVMStyle(); 8679 Break.AlwaysBreakBeforeMultilineStrings = true; 8680 verifyFormat("aaaa = \"bbbb\"\n" 8681 " \"cccc\";", 8682 NoBreak); 8683 verifyFormat("aaaa =\n" 8684 " \"bbbb\"\n" 8685 " \"cccc\";", 8686 Break); 8687 verifyFormat("aaaa(\"bbbb\"\n" 8688 " \"cccc\");", 8689 NoBreak); 8690 verifyFormat("aaaa(\n" 8691 " \"bbbb\"\n" 8692 " \"cccc\");", 8693 Break); 8694 verifyFormat("aaaa(qqq, \"bbbb\"\n" 8695 " \"cccc\");", 8696 NoBreak); 8697 verifyFormat("aaaa(qqq,\n" 8698 " \"bbbb\"\n" 8699 " \"cccc\");", 8700 Break); 8701 verifyFormat("aaaa(qqq,\n" 8702 " L\"bbbb\"\n" 8703 " L\"cccc\");", 8704 Break); 8705 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 8706 " \"bbbb\"));", 8707 Break); 8708 verifyFormat("string s = someFunction(\n" 8709 " \"abc\"\n" 8710 " \"abc\");", 8711 Break); 8712 8713 // As we break before unary operators, breaking right after them is bad. 8714 verifyFormat("string foo = abc ? \"x\"\n" 8715 " \"blah blah blah blah blah blah\"\n" 8716 " : \"y\";", 8717 Break); 8718 8719 // Don't break if there is no column gain. 8720 verifyFormat("f(\"aaaa\"\n" 8721 " \"bbbb\");", 8722 Break); 8723 8724 // Treat literals with escaped newlines like multi-line string literals. 8725 EXPECT_EQ("x = \"a\\\n" 8726 "b\\\n" 8727 "c\";", 8728 format("x = \"a\\\n" 8729 "b\\\n" 8730 "c\";", 8731 NoBreak)); 8732 EXPECT_EQ("xxxx =\n" 8733 " \"a\\\n" 8734 "b\\\n" 8735 "c\";", 8736 format("xxxx = \"a\\\n" 8737 "b\\\n" 8738 "c\";", 8739 Break)); 8740 8741 EXPECT_EQ("NSString *const kString =\n" 8742 " @\"aaaa\"\n" 8743 " @\"bbbb\";", 8744 format("NSString *const kString = @\"aaaa\"\n" 8745 "@\"bbbb\";", 8746 Break)); 8747 8748 Break.ColumnLimit = 0; 8749 verifyFormat("const char *hello = \"hello llvm\";", Break); 8750 } 8751 8752 TEST_F(FormatTest, AlignsPipes) { 8753 verifyFormat( 8754 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8755 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8756 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8757 verifyFormat( 8758 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 8759 " << aaaaaaaaaaaaaaaaaaaa;"); 8760 verifyFormat( 8761 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8762 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8763 verifyFormat( 8764 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 8765 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8766 verifyFormat( 8767 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 8768 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 8769 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 8770 verifyFormat( 8771 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8772 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8773 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8774 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8775 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8776 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8777 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8778 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 8779 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 8780 verifyFormat( 8781 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8782 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8783 verifyFormat( 8784 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 8785 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8786 8787 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 8788 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 8789 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8790 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8791 " aaaaaaaaaaaaaaaaaaaaa)\n" 8792 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8793 verifyFormat("LOG_IF(aaa == //\n" 8794 " bbb)\n" 8795 " << a << b;"); 8796 8797 // But sometimes, breaking before the first "<<" is desirable. 8798 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8799 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 8800 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 8801 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8802 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8803 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 8804 " << BEF << IsTemplate << Description << E->getType();"); 8805 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8806 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8807 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8808 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8809 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8810 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8811 " << aaa;"); 8812 8813 verifyFormat( 8814 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8815 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 8816 8817 // Incomplete string literal. 8818 EXPECT_EQ("llvm::errs() << \"\n" 8819 " << a;", 8820 format("llvm::errs() << \"\n<<a;")); 8821 8822 verifyFormat("void f() {\n" 8823 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 8824 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 8825 "}"); 8826 8827 // Handle 'endl'. 8828 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 8829 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8830 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8831 8832 // Handle '\n'. 8833 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 8834 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8835 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 8836 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 8837 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 8838 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 8839 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8840 } 8841 8842 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 8843 verifyFormat("return out << \"somepacket = {\\n\"\n" 8844 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 8845 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 8846 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 8847 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 8848 " << \"}\";"); 8849 8850 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8851 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8852 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 8853 verifyFormat( 8854 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 8855 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 8856 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 8857 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 8858 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 8859 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 8860 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8861 verifyFormat( 8862 "void f() {\n" 8863 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 8864 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 8865 "}"); 8866 8867 // Breaking before the first "<<" is generally not desirable. 8868 verifyFormat( 8869 "llvm::errs()\n" 8870 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8871 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8872 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8873 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8874 getLLVMStyleWithColumns(70)); 8875 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8876 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8877 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8878 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8879 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8880 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8881 getLLVMStyleWithColumns(70)); 8882 8883 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8884 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8885 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 8886 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8887 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8888 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 8889 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 8890 " (aaaa + aaaa);", 8891 getLLVMStyleWithColumns(40)); 8892 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 8893 " (aaaaaaa + aaaaa));", 8894 getLLVMStyleWithColumns(40)); 8895 verifyFormat( 8896 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 8897 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 8898 " bbbbbbbbbbbbbbbbbbbbbbb);"); 8899 } 8900 8901 TEST_F(FormatTest, UnderstandsEquals) { 8902 verifyFormat( 8903 "aaaaaaaaaaaaaaaaa =\n" 8904 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8905 verifyFormat( 8906 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8907 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 8908 verifyFormat( 8909 "if (a) {\n" 8910 " f();\n" 8911 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8912 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 8913 "}"); 8914 8915 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8916 " 100000000 + 10000000) {\n}"); 8917 } 8918 8919 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 8920 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 8921 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 8922 8923 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 8924 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 8925 8926 verifyFormat( 8927 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 8928 " Parameter2);"); 8929 8930 verifyFormat( 8931 "ShortObject->shortFunction(\n" 8932 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 8933 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 8934 8935 verifyFormat("loooooooooooooongFunction(\n" 8936 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 8937 8938 verifyFormat( 8939 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 8940 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 8941 8942 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 8943 " .WillRepeatedly(Return(SomeValue));"); 8944 verifyFormat("void f() {\n" 8945 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 8946 " .Times(2)\n" 8947 " .WillRepeatedly(Return(SomeValue));\n" 8948 "}"); 8949 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 8950 " ccccccccccccccccccccccc);"); 8951 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8952 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8953 " .aaaaa(aaaaa),\n" 8954 " aaaaaaaaaaaaaaaaaaaaa);"); 8955 verifyFormat("void f() {\n" 8956 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8957 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 8958 "}"); 8959 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8960 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8961 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8962 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8963 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 8964 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8965 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8966 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8967 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 8968 "}"); 8969 8970 // Here, it is not necessary to wrap at "." or "->". 8971 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 8972 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 8973 verifyFormat( 8974 "aaaaaaaaaaa->aaaaaaaaa(\n" 8975 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8976 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 8977 8978 verifyFormat( 8979 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8980 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 8981 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 8982 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 8983 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 8984 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 8985 8986 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8988 " .a();"); 8989 8990 FormatStyle NoBinPacking = getLLVMStyle(); 8991 NoBinPacking.BinPackParameters = false; 8992 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 8993 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 8994 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 8995 " aaaaaaaaaaaaaaaaaaa,\n" 8996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8997 NoBinPacking); 8998 8999 // If there is a subsequent call, change to hanging indentation. 9000 verifyFormat( 9001 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9002 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9003 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9004 verifyFormat( 9005 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9006 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9007 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9008 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9009 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9010 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9012 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9013 } 9014 9015 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9016 verifyFormat("template <typename T>\n" 9017 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9018 verifyFormat("template <typename T>\n" 9019 "// T should be one of {A, B}.\n" 9020 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9021 verifyFormat( 9022 "template <typename T>\n" 9023 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9024 verifyFormat("template <typename T>\n" 9025 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9026 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9027 verifyFormat( 9028 "template <typename T>\n" 9029 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9030 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9031 verifyFormat( 9032 "template <typename T>\n" 9033 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9034 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9035 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9036 verifyFormat("template <typename T>\n" 9037 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9038 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9039 verifyFormat( 9040 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9041 " typename T4 = char>\n" 9042 "void f();"); 9043 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9044 " template <typename> class cccccccccccccccccccccc,\n" 9045 " typename ddddddddddddd>\n" 9046 "class C {};"); 9047 verifyFormat( 9048 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9049 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9050 9051 verifyFormat("void f() {\n" 9052 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9053 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9054 "}"); 9055 9056 verifyFormat("template <typename T> class C {};"); 9057 verifyFormat("template <typename T> void f();"); 9058 verifyFormat("template <typename T> void f() {}"); 9059 verifyFormat( 9060 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9061 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9062 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9063 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9064 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9066 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9067 getLLVMStyleWithColumns(72)); 9068 EXPECT_EQ("static_cast<A< //\n" 9069 " B> *>(\n" 9070 "\n" 9071 ");", 9072 format("static_cast<A<//\n" 9073 " B>*>(\n" 9074 "\n" 9075 " );")); 9076 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9077 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9078 9079 FormatStyle AlwaysBreak = getLLVMStyle(); 9080 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9081 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9082 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9083 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9084 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9085 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9086 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9087 verifyFormat("template <template <typename> class Fooooooo,\n" 9088 " template <typename> class Baaaaaaar>\n" 9089 "struct C {};", 9090 AlwaysBreak); 9091 verifyFormat("template <typename T> // T can be A, B or C.\n" 9092 "struct C {};", 9093 AlwaysBreak); 9094 verifyFormat("template <enum E> class A {\n" 9095 "public:\n" 9096 " E *f();\n" 9097 "};"); 9098 9099 FormatStyle NeverBreak = getLLVMStyle(); 9100 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9101 verifyFormat("template <typename T> class C {};", NeverBreak); 9102 verifyFormat("template <typename T> void f();", NeverBreak); 9103 verifyFormat("template <typename T> void f() {}", NeverBreak); 9104 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9105 "bbbbbbbbbbbbbbbbbbbb) {}", 9106 NeverBreak); 9107 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9108 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9109 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9110 NeverBreak); 9111 verifyFormat("template <template <typename> class Fooooooo,\n" 9112 " template <typename> class Baaaaaaar>\n" 9113 "struct C {};", 9114 NeverBreak); 9115 verifyFormat("template <typename T> // T can be A, B or C.\n" 9116 "struct C {};", 9117 NeverBreak); 9118 verifyFormat("template <enum E> class A {\n" 9119 "public:\n" 9120 " E *f();\n" 9121 "};", 9122 NeverBreak); 9123 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9124 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9125 "bbbbbbbbbbbbbbbbbbbb) {}", 9126 NeverBreak); 9127 } 9128 9129 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9130 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9131 Style.ColumnLimit = 60; 9132 EXPECT_EQ("// Baseline - no comments.\n" 9133 "template <\n" 9134 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9135 "void f() {}", 9136 format("// Baseline - no comments.\n" 9137 "template <\n" 9138 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9139 "void f() {}", 9140 Style)); 9141 9142 EXPECT_EQ("template <\n" 9143 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9144 "void f() {}", 9145 format("template <\n" 9146 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9147 "void f() {}", 9148 Style)); 9149 9150 EXPECT_EQ( 9151 "template <\n" 9152 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9153 "void f() {}", 9154 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9155 "void f() {}", 9156 Style)); 9157 9158 EXPECT_EQ( 9159 "template <\n" 9160 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9161 " // multiline\n" 9162 "void f() {}", 9163 format("template <\n" 9164 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9165 " // multiline\n" 9166 "void f() {}", 9167 Style)); 9168 9169 EXPECT_EQ( 9170 "template <typename aaaaaaaaaa<\n" 9171 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9172 "void f() {}", 9173 format( 9174 "template <\n" 9175 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9176 "void f() {}", 9177 Style)); 9178 } 9179 9180 TEST_F(FormatTest, WrapsTemplateParameters) { 9181 FormatStyle Style = getLLVMStyle(); 9182 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9183 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9184 verifyFormat( 9185 "template <typename... a> struct q {};\n" 9186 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9187 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9188 " y;", 9189 Style); 9190 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9191 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9192 verifyFormat( 9193 "template <typename... a> struct r {};\n" 9194 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9195 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9196 " y;", 9197 Style); 9198 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9199 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9200 verifyFormat("template <typename... a> struct s {};\n" 9201 "extern s<\n" 9202 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9203 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9204 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9205 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9206 " y;", 9207 Style); 9208 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9209 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9210 verifyFormat("template <typename... a> struct t {};\n" 9211 "extern t<\n" 9212 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9213 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9214 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9215 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9216 " y;", 9217 Style); 9218 } 9219 9220 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9221 verifyFormat( 9222 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9224 verifyFormat( 9225 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9226 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9227 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9228 9229 // FIXME: Should we have the extra indent after the second break? 9230 verifyFormat( 9231 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9232 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9233 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9234 9235 verifyFormat( 9236 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9237 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9238 9239 // Breaking at nested name specifiers is generally not desirable. 9240 verifyFormat( 9241 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9242 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9243 9244 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9245 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9246 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9247 " aaaaaaaaaaaaaaaaaaaaa);", 9248 getLLVMStyleWithColumns(74)); 9249 9250 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9251 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9252 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9253 } 9254 9255 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9256 verifyFormat("A<int> a;"); 9257 verifyFormat("A<A<A<int>>> a;"); 9258 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9259 verifyFormat("bool x = a < 1 || 2 > a;"); 9260 verifyFormat("bool x = 5 < f<int>();"); 9261 verifyFormat("bool x = f<int>() > 5;"); 9262 verifyFormat("bool x = 5 < a<int>::x;"); 9263 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9264 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9265 9266 verifyGoogleFormat("A<A<int>> a;"); 9267 verifyGoogleFormat("A<A<A<int>>> a;"); 9268 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9269 verifyGoogleFormat("A<A<int> > a;"); 9270 verifyGoogleFormat("A<A<A<int> > > a;"); 9271 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9272 verifyGoogleFormat("A<::A<int>> a;"); 9273 verifyGoogleFormat("A<::A> a;"); 9274 verifyGoogleFormat("A< ::A> a;"); 9275 verifyGoogleFormat("A< ::A<int> > a;"); 9276 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9277 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9278 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9279 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9280 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9281 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9282 9283 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9284 9285 // template closer followed by a token that starts with > or = 9286 verifyFormat("bool b = a<1> > 1;"); 9287 verifyFormat("bool b = a<1> >= 1;"); 9288 verifyFormat("int i = a<1> >> 1;"); 9289 FormatStyle Style = getLLVMStyle(); 9290 Style.SpaceBeforeAssignmentOperators = false; 9291 verifyFormat("bool b= a<1> == 1;", Style); 9292 verifyFormat("a<int> = 1;", Style); 9293 verifyFormat("a<int> >>= 1;", Style); 9294 9295 verifyFormat("test < a | b >> c;"); 9296 verifyFormat("test<test<a | b>> c;"); 9297 verifyFormat("test >> a >> b;"); 9298 verifyFormat("test << a >> b;"); 9299 9300 verifyFormat("f<int>();"); 9301 verifyFormat("template <typename T> void f() {}"); 9302 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9303 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9304 "sizeof(char)>::type>;"); 9305 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9306 verifyFormat("f(a.operator()<A>());"); 9307 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9308 " .template operator()<A>());", 9309 getLLVMStyleWithColumns(35)); 9310 9311 // Not template parameters. 9312 verifyFormat("return a < b && c > d;"); 9313 verifyFormat("void f() {\n" 9314 " while (a < b && c > d) {\n" 9315 " }\n" 9316 "}"); 9317 verifyFormat("template <typename... Types>\n" 9318 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9319 9320 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9321 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9322 getLLVMStyleWithColumns(60)); 9323 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9324 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9325 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9326 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9327 } 9328 9329 TEST_F(FormatTest, UnderstandsShiftOperators) { 9330 verifyFormat("if (i < x >> 1)"); 9331 verifyFormat("while (i < x >> 1)"); 9332 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9333 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9334 verifyFormat( 9335 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9336 verifyFormat("Foo.call<Bar<Function>>()"); 9337 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9338 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9339 "++i, v = v >> 1)"); 9340 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9341 } 9342 9343 TEST_F(FormatTest, BitshiftOperatorWidth) { 9344 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9345 " bar */", 9346 format("int a=1<<2; /* foo\n" 9347 " bar */")); 9348 9349 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9350 " bar */", 9351 format("int b =256>>1 ; /* foo\n" 9352 " bar */")); 9353 } 9354 9355 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9356 verifyFormat("COMPARE(a, ==, b);"); 9357 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9358 } 9359 9360 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9361 verifyFormat("int A::*x;"); 9362 verifyFormat("int (S::*func)(void *);"); 9363 verifyFormat("void f() { int (S::*func)(void *); }"); 9364 verifyFormat("typedef bool *(Class::*Member)() const;"); 9365 verifyFormat("void f() {\n" 9366 " (a->*f)();\n" 9367 " a->*x;\n" 9368 " (a.*f)();\n" 9369 " ((*a).*f)();\n" 9370 " a.*x;\n" 9371 "}"); 9372 verifyFormat("void f() {\n" 9373 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9374 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9375 "}"); 9376 verifyFormat( 9377 "(aaaaaaaaaa->*bbbbbbb)(\n" 9378 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9379 FormatStyle Style = getLLVMStyle(); 9380 Style.PointerAlignment = FormatStyle::PAS_Left; 9381 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9382 } 9383 9384 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9385 verifyFormat("int a = -2;"); 9386 verifyFormat("f(-1, -2, -3);"); 9387 verifyFormat("a[-1] = 5;"); 9388 verifyFormat("int a = 5 + -2;"); 9389 verifyFormat("if (i == -1) {\n}"); 9390 verifyFormat("if (i != -1) {\n}"); 9391 verifyFormat("if (i > -1) {\n}"); 9392 verifyFormat("if (i < -1) {\n}"); 9393 verifyFormat("++(a->f());"); 9394 verifyFormat("--(a->f());"); 9395 verifyFormat("(a->f())++;"); 9396 verifyFormat("a[42]++;"); 9397 verifyFormat("if (!(a->f())) {\n}"); 9398 verifyFormat("if (!+i) {\n}"); 9399 verifyFormat("~&a;"); 9400 9401 verifyFormat("a-- > b;"); 9402 verifyFormat("b ? -a : c;"); 9403 verifyFormat("n * sizeof char16;"); 9404 verifyFormat("n * alignof char16;", getGoogleStyle()); 9405 verifyFormat("sizeof(char);"); 9406 verifyFormat("alignof(char);", getGoogleStyle()); 9407 9408 verifyFormat("return -1;"); 9409 verifyFormat("throw -1;"); 9410 verifyFormat("switch (a) {\n" 9411 "case -1:\n" 9412 " break;\n" 9413 "}"); 9414 verifyFormat("#define X -1"); 9415 verifyFormat("#define X -kConstant"); 9416 9417 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9418 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9419 9420 verifyFormat("int a = /* confusing comment */ -1;"); 9421 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9422 verifyFormat("int a = i /* confusing comment */++;"); 9423 9424 verifyFormat("co_yield -1;"); 9425 verifyFormat("co_return -1;"); 9426 9427 // Check that * is not treated as a binary operator when we set 9428 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9429 FormatStyle PASLeftStyle = getLLVMStyle(); 9430 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9431 verifyFormat("co_return *a;", PASLeftStyle); 9432 verifyFormat("co_await *a;", PASLeftStyle); 9433 verifyFormat("co_yield *a", PASLeftStyle); 9434 verifyFormat("return *a;", PASLeftStyle); 9435 } 9436 9437 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9438 verifyFormat("if (!aaaaaaaaaa( // break\n" 9439 " aaaaa)) {\n" 9440 "}"); 9441 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9442 " aaaaa));"); 9443 verifyFormat("*aaa = aaaaaaa( // break\n" 9444 " bbbbbb);"); 9445 } 9446 9447 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9448 verifyFormat("bool operator<();"); 9449 verifyFormat("bool operator>();"); 9450 verifyFormat("bool operator=();"); 9451 verifyFormat("bool operator==();"); 9452 verifyFormat("bool operator!=();"); 9453 verifyFormat("int operator+();"); 9454 verifyFormat("int operator++();"); 9455 verifyFormat("int operator++(int) volatile noexcept;"); 9456 verifyFormat("bool operator,();"); 9457 verifyFormat("bool operator();"); 9458 verifyFormat("bool operator()();"); 9459 verifyFormat("bool operator[]();"); 9460 verifyFormat("operator bool();"); 9461 verifyFormat("operator int();"); 9462 verifyFormat("operator void *();"); 9463 verifyFormat("operator SomeType<int>();"); 9464 verifyFormat("operator SomeType<int, int>();"); 9465 verifyFormat("operator SomeType<SomeType<int>>();"); 9466 verifyFormat("void *operator new(std::size_t size);"); 9467 verifyFormat("void *operator new[](std::size_t size);"); 9468 verifyFormat("void operator delete(void *ptr);"); 9469 verifyFormat("void operator delete[](void *ptr);"); 9470 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9471 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9472 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9473 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9474 9475 verifyFormat( 9476 "ostream &operator<<(ostream &OutputStream,\n" 9477 " SomeReallyLongType WithSomeReallyLongValue);"); 9478 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9479 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9480 " return left.group < right.group;\n" 9481 "}"); 9482 verifyFormat("SomeType &operator=(const SomeType &S);"); 9483 verifyFormat("f.template operator()<int>();"); 9484 9485 verifyGoogleFormat("operator void*();"); 9486 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9487 verifyGoogleFormat("operator ::A();"); 9488 9489 verifyFormat("using A::operator+;"); 9490 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9491 "int i;"); 9492 9493 // Calling an operator as a member function. 9494 verifyFormat("void f() { a.operator*(); }"); 9495 verifyFormat("void f() { a.operator*(b & b); }"); 9496 verifyFormat("void f() { a->operator&(a * b); }"); 9497 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9498 // TODO: Calling an operator as a non-member function is hard to distinguish. 9499 // https://llvm.org/PR50629 9500 // verifyFormat("void f() { operator*(a & a); }"); 9501 // verifyFormat("void f() { operator&(a, b * b); }"); 9502 9503 verifyFormat("::operator delete(foo);"); 9504 verifyFormat("::operator new(n * sizeof(foo));"); 9505 verifyFormat("foo() { ::operator delete(foo); }"); 9506 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9507 } 9508 9509 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9510 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9511 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9512 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9513 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9514 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9515 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9516 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9517 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9518 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9519 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9520 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9521 verifyFormat("void Fn(T const &) const &;"); 9522 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9523 verifyFormat("template <typename T>\n" 9524 "void F(T) && = delete;", 9525 getGoogleStyle()); 9526 9527 FormatStyle AlignLeft = getLLVMStyle(); 9528 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9529 verifyFormat("void A::b() && {}", AlignLeft); 9530 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9531 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9532 AlignLeft); 9533 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9534 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9535 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9536 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9537 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9538 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9539 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9540 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9541 9542 FormatStyle Spaces = getLLVMStyle(); 9543 Spaces.SpacesInCStyleCastParentheses = true; 9544 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9545 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9546 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9547 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9548 9549 Spaces.SpacesInCStyleCastParentheses = false; 9550 Spaces.SpacesInParentheses = true; 9551 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9552 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9553 Spaces); 9554 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9555 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9556 9557 FormatStyle BreakTemplate = getLLVMStyle(); 9558 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9559 9560 verifyFormat("struct f {\n" 9561 " template <class T>\n" 9562 " int &foo(const std::string &str) &noexcept {}\n" 9563 "};", 9564 BreakTemplate); 9565 9566 verifyFormat("struct f {\n" 9567 " template <class T>\n" 9568 " int &foo(const std::string &str) &&noexcept {}\n" 9569 "};", 9570 BreakTemplate); 9571 9572 verifyFormat("struct f {\n" 9573 " template <class T>\n" 9574 " int &foo(const std::string &str) const &noexcept {}\n" 9575 "};", 9576 BreakTemplate); 9577 9578 verifyFormat("struct f {\n" 9579 " template <class T>\n" 9580 " int &foo(const std::string &str) const &noexcept {}\n" 9581 "};", 9582 BreakTemplate); 9583 9584 verifyFormat("struct f {\n" 9585 " template <class T>\n" 9586 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 9587 "};", 9588 BreakTemplate); 9589 9590 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 9591 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 9592 FormatStyle::BTDS_Yes; 9593 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 9594 9595 verifyFormat("struct f {\n" 9596 " template <class T>\n" 9597 " int& foo(const std::string& str) & noexcept {}\n" 9598 "};", 9599 AlignLeftBreakTemplate); 9600 9601 verifyFormat("struct f {\n" 9602 " template <class T>\n" 9603 " int& foo(const std::string& str) && noexcept {}\n" 9604 "};", 9605 AlignLeftBreakTemplate); 9606 9607 verifyFormat("struct f {\n" 9608 " template <class T>\n" 9609 " int& foo(const std::string& str) const& noexcept {}\n" 9610 "};", 9611 AlignLeftBreakTemplate); 9612 9613 verifyFormat("struct f {\n" 9614 " template <class T>\n" 9615 " int& foo(const std::string& str) const&& noexcept {}\n" 9616 "};", 9617 AlignLeftBreakTemplate); 9618 9619 verifyFormat("struct f {\n" 9620 " template <class T>\n" 9621 " auto foo(const std::string& str) && noexcept -> int& {}\n" 9622 "};", 9623 AlignLeftBreakTemplate); 9624 9625 // The `&` in `Type&` should not be confused with a trailing `&` of 9626 // DEPRECATED(reason) member function. 9627 verifyFormat("struct f {\n" 9628 " template <class T>\n" 9629 " DEPRECATED(reason)\n" 9630 " Type &foo(arguments) {}\n" 9631 "};", 9632 BreakTemplate); 9633 9634 verifyFormat("struct f {\n" 9635 " template <class T>\n" 9636 " DEPRECATED(reason)\n" 9637 " Type& foo(arguments) {}\n" 9638 "};", 9639 AlignLeftBreakTemplate); 9640 9641 verifyFormat("void (*foopt)(int) = &func;"); 9642 } 9643 9644 TEST_F(FormatTest, UnderstandsNewAndDelete) { 9645 verifyFormat("void f() {\n" 9646 " A *a = new A;\n" 9647 " A *a = new (placement) A;\n" 9648 " delete a;\n" 9649 " delete (A *)a;\n" 9650 "}"); 9651 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9652 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9653 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9654 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9655 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9656 verifyFormat("delete[] h->p;"); 9657 9658 verifyFormat("void operator delete(void *foo) ATTRIB;"); 9659 verifyFormat("void operator new(void *foo) ATTRIB;"); 9660 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 9661 verifyFormat("void operator delete(void *ptr) noexcept;"); 9662 } 9663 9664 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 9665 verifyFormat("int *f(int *a) {}"); 9666 verifyFormat("int main(int argc, char **argv) {}"); 9667 verifyFormat("Test::Test(int b) : a(b * b) {}"); 9668 verifyIndependentOfContext("f(a, *a);"); 9669 verifyFormat("void g() { f(*a); }"); 9670 verifyIndependentOfContext("int a = b * 10;"); 9671 verifyIndependentOfContext("int a = 10 * b;"); 9672 verifyIndependentOfContext("int a = b * c;"); 9673 verifyIndependentOfContext("int a += b * c;"); 9674 verifyIndependentOfContext("int a -= b * c;"); 9675 verifyIndependentOfContext("int a *= b * c;"); 9676 verifyIndependentOfContext("int a /= b * c;"); 9677 verifyIndependentOfContext("int a = *b;"); 9678 verifyIndependentOfContext("int a = *b * c;"); 9679 verifyIndependentOfContext("int a = b * *c;"); 9680 verifyIndependentOfContext("int a = b * (10);"); 9681 verifyIndependentOfContext("S << b * (10);"); 9682 verifyIndependentOfContext("return 10 * b;"); 9683 verifyIndependentOfContext("return *b * *c;"); 9684 verifyIndependentOfContext("return a & ~b;"); 9685 verifyIndependentOfContext("f(b ? *c : *d);"); 9686 verifyIndependentOfContext("int a = b ? *c : *d;"); 9687 verifyIndependentOfContext("*b = a;"); 9688 verifyIndependentOfContext("a * ~b;"); 9689 verifyIndependentOfContext("a * !b;"); 9690 verifyIndependentOfContext("a * +b;"); 9691 verifyIndependentOfContext("a * -b;"); 9692 verifyIndependentOfContext("a * ++b;"); 9693 verifyIndependentOfContext("a * --b;"); 9694 verifyIndependentOfContext("a[4] * b;"); 9695 verifyIndependentOfContext("a[a * a] = 1;"); 9696 verifyIndependentOfContext("f() * b;"); 9697 verifyIndependentOfContext("a * [self dostuff];"); 9698 verifyIndependentOfContext("int x = a * (a + b);"); 9699 verifyIndependentOfContext("(a *)(a + b);"); 9700 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 9701 verifyIndependentOfContext("int *pa = (int *)&a;"); 9702 verifyIndependentOfContext("return sizeof(int **);"); 9703 verifyIndependentOfContext("return sizeof(int ******);"); 9704 verifyIndependentOfContext("return (int **&)a;"); 9705 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 9706 verifyFormat("void f(Type (*parameter)[10]) {}"); 9707 verifyFormat("void f(Type (¶meter)[10]) {}"); 9708 verifyGoogleFormat("return sizeof(int**);"); 9709 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 9710 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 9711 verifyFormat("auto a = [](int **&, int ***) {};"); 9712 verifyFormat("auto PointerBinding = [](const char *S) {};"); 9713 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 9714 verifyFormat("[](const decltype(*a) &value) {}"); 9715 verifyFormat("[](const typeof(*a) &value) {}"); 9716 verifyFormat("[](const _Atomic(a *) &value) {}"); 9717 verifyFormat("[](const __underlying_type(a) &value) {}"); 9718 verifyFormat("decltype(a * b) F();"); 9719 verifyFormat("typeof(a * b) F();"); 9720 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 9721 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 9722 verifyIndependentOfContext("typedef void (*f)(int *a);"); 9723 verifyIndependentOfContext("int i{a * b};"); 9724 verifyIndependentOfContext("aaa && aaa->f();"); 9725 verifyIndependentOfContext("int x = ~*p;"); 9726 verifyFormat("Constructor() : a(a), area(width * height) {}"); 9727 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 9728 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 9729 verifyFormat("void f() { f(a, c * d); }"); 9730 verifyFormat("void f() { f(new a(), c * d); }"); 9731 verifyFormat("void f(const MyOverride &override);"); 9732 verifyFormat("void f(const MyFinal &final);"); 9733 verifyIndependentOfContext("bool a = f() && override.f();"); 9734 verifyIndependentOfContext("bool a = f() && final.f();"); 9735 9736 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 9737 9738 verifyIndependentOfContext("A<int *> a;"); 9739 verifyIndependentOfContext("A<int **> a;"); 9740 verifyIndependentOfContext("A<int *, int *> a;"); 9741 verifyIndependentOfContext("A<int *[]> a;"); 9742 verifyIndependentOfContext( 9743 "const char *const p = reinterpret_cast<const char *const>(q);"); 9744 verifyIndependentOfContext("A<int **, int **> a;"); 9745 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 9746 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 9747 verifyFormat("for (; a && b;) {\n}"); 9748 verifyFormat("bool foo = true && [] { return false; }();"); 9749 9750 verifyFormat( 9751 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9752 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9753 9754 verifyGoogleFormat("int const* a = &b;"); 9755 verifyGoogleFormat("**outparam = 1;"); 9756 verifyGoogleFormat("*outparam = a * b;"); 9757 verifyGoogleFormat("int main(int argc, char** argv) {}"); 9758 verifyGoogleFormat("A<int*> a;"); 9759 verifyGoogleFormat("A<int**> a;"); 9760 verifyGoogleFormat("A<int*, int*> a;"); 9761 verifyGoogleFormat("A<int**, int**> a;"); 9762 verifyGoogleFormat("f(b ? *c : *d);"); 9763 verifyGoogleFormat("int a = b ? *c : *d;"); 9764 verifyGoogleFormat("Type* t = **x;"); 9765 verifyGoogleFormat("Type* t = *++*x;"); 9766 verifyGoogleFormat("*++*x;"); 9767 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 9768 verifyGoogleFormat("Type* t = x++ * y;"); 9769 verifyGoogleFormat( 9770 "const char* const p = reinterpret_cast<const char* const>(q);"); 9771 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 9772 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 9773 verifyGoogleFormat("template <typename T>\n" 9774 "void f(int i = 0, SomeType** temps = NULL);"); 9775 9776 FormatStyle Left = getLLVMStyle(); 9777 Left.PointerAlignment = FormatStyle::PAS_Left; 9778 verifyFormat("x = *a(x) = *a(y);", Left); 9779 verifyFormat("for (;; *a = b) {\n}", Left); 9780 verifyFormat("return *this += 1;", Left); 9781 verifyFormat("throw *x;", Left); 9782 verifyFormat("delete *x;", Left); 9783 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 9784 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 9785 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 9786 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 9787 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 9788 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 9789 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 9790 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 9791 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 9792 9793 verifyIndependentOfContext("a = *(x + y);"); 9794 verifyIndependentOfContext("a = &(x + y);"); 9795 verifyIndependentOfContext("*(x + y).call();"); 9796 verifyIndependentOfContext("&(x + y)->call();"); 9797 verifyFormat("void f() { &(*I).first; }"); 9798 9799 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 9800 verifyFormat("f(* /* confusing comment */ foo);"); 9801 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 9802 verifyFormat("void foo(int * // this is the first paramters\n" 9803 " ,\n" 9804 " int second);"); 9805 verifyFormat("double term = a * // first\n" 9806 " b;"); 9807 verifyFormat( 9808 "int *MyValues = {\n" 9809 " *A, // Operator detection might be confused by the '{'\n" 9810 " *BB // Operator detection might be confused by previous comment\n" 9811 "};"); 9812 9813 verifyIndependentOfContext("if (int *a = &b)"); 9814 verifyIndependentOfContext("if (int &a = *b)"); 9815 verifyIndependentOfContext("if (a & b[i])"); 9816 verifyIndependentOfContext("if constexpr (a & b[i])"); 9817 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 9818 verifyIndependentOfContext("if (a * (b * c))"); 9819 verifyIndependentOfContext("if constexpr (a * (b * c))"); 9820 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 9821 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 9822 verifyIndependentOfContext("if (*b[i])"); 9823 verifyIndependentOfContext("if (int *a = (&b))"); 9824 verifyIndependentOfContext("while (int *a = &b)"); 9825 verifyIndependentOfContext("while (a * (b * c))"); 9826 verifyIndependentOfContext("size = sizeof *a;"); 9827 verifyIndependentOfContext("if (a && (b = c))"); 9828 verifyFormat("void f() {\n" 9829 " for (const int &v : Values) {\n" 9830 " }\n" 9831 "}"); 9832 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 9833 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 9834 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 9835 9836 verifyFormat("#define A (!a * b)"); 9837 verifyFormat("#define MACRO \\\n" 9838 " int *i = a * b; \\\n" 9839 " void f(a *b);", 9840 getLLVMStyleWithColumns(19)); 9841 9842 verifyIndependentOfContext("A = new SomeType *[Length];"); 9843 verifyIndependentOfContext("A = new SomeType *[Length]();"); 9844 verifyIndependentOfContext("T **t = new T *;"); 9845 verifyIndependentOfContext("T **t = new T *();"); 9846 verifyGoogleFormat("A = new SomeType*[Length]();"); 9847 verifyGoogleFormat("A = new SomeType*[Length];"); 9848 verifyGoogleFormat("T** t = new T*;"); 9849 verifyGoogleFormat("T** t = new T*();"); 9850 9851 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 9852 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 9853 verifyFormat("template <bool a, bool b> " 9854 "typename t::if<x && y>::type f() {}"); 9855 verifyFormat("template <int *y> f() {}"); 9856 verifyFormat("vector<int *> v;"); 9857 verifyFormat("vector<int *const> v;"); 9858 verifyFormat("vector<int *const **const *> v;"); 9859 verifyFormat("vector<int *volatile> v;"); 9860 verifyFormat("vector<a *_Nonnull> v;"); 9861 verifyFormat("vector<a *_Nullable> v;"); 9862 verifyFormat("vector<a *_Null_unspecified> v;"); 9863 verifyFormat("vector<a *__ptr32> v;"); 9864 verifyFormat("vector<a *__ptr64> v;"); 9865 verifyFormat("vector<a *__capability> v;"); 9866 FormatStyle TypeMacros = getLLVMStyle(); 9867 TypeMacros.TypenameMacros = {"LIST"}; 9868 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 9869 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 9870 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 9871 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 9872 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 9873 9874 FormatStyle CustomQualifier = getLLVMStyle(); 9875 // Add identifiers that should not be parsed as a qualifier by default. 9876 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 9877 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 9878 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 9879 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 9880 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 9881 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 9882 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 9883 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 9884 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 9885 verifyFormat("vector<a * _NotAQualifier> v;"); 9886 verifyFormat("vector<a * __not_a_qualifier> v;"); 9887 verifyFormat("vector<a * b> v;"); 9888 verifyFormat("foo<b && false>();"); 9889 verifyFormat("foo<b & 1>();"); 9890 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 9891 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 9892 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 9893 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 9894 verifyFormat( 9895 "template <class T, class = typename std::enable_if<\n" 9896 " std::is_integral<T>::value &&\n" 9897 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 9898 "void F();", 9899 getLLVMStyleWithColumns(70)); 9900 verifyFormat("template <class T,\n" 9901 " class = typename std::enable_if<\n" 9902 " std::is_integral<T>::value &&\n" 9903 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 9904 " class U>\n" 9905 "void F();", 9906 getLLVMStyleWithColumns(70)); 9907 verifyFormat( 9908 "template <class T,\n" 9909 " class = typename ::std::enable_if<\n" 9910 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 9911 "void F();", 9912 getGoogleStyleWithColumns(68)); 9913 9914 verifyIndependentOfContext("MACRO(int *i);"); 9915 verifyIndependentOfContext("MACRO(auto *a);"); 9916 verifyIndependentOfContext("MACRO(const A *a);"); 9917 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 9918 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 9919 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 9920 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 9921 verifyIndependentOfContext("MACRO(A *const a);"); 9922 verifyIndependentOfContext("MACRO(A *restrict a);"); 9923 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 9924 verifyIndependentOfContext("MACRO(A *__restrict a);"); 9925 verifyIndependentOfContext("MACRO(A *volatile a);"); 9926 verifyIndependentOfContext("MACRO(A *__volatile a);"); 9927 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 9928 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 9929 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 9930 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 9931 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 9932 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 9933 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 9934 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 9935 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 9936 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 9937 verifyIndependentOfContext("MACRO(A *__capability);"); 9938 verifyIndependentOfContext("MACRO(A &__capability);"); 9939 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 9940 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 9941 // If we add __my_qualifier to AttributeMacros it should always be parsed as 9942 // a type declaration: 9943 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 9944 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 9945 // Also check that TypenameMacros prevents parsing it as multiplication: 9946 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 9947 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 9948 9949 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 9950 verifyFormat("void f() { f(float{1}, a * a); }"); 9951 verifyFormat("void f() { f(float(1), a * a); }"); 9952 9953 verifyFormat("f((void (*)(int))g);"); 9954 verifyFormat("f((void (&)(int))g);"); 9955 verifyFormat("f((void (^)(int))g);"); 9956 9957 // FIXME: Is there a way to make this work? 9958 // verifyIndependentOfContext("MACRO(A *a);"); 9959 verifyFormat("MACRO(A &B);"); 9960 verifyFormat("MACRO(A *B);"); 9961 verifyFormat("void f() { MACRO(A * B); }"); 9962 verifyFormat("void f() { MACRO(A & B); }"); 9963 9964 // This lambda was mis-formatted after D88956 (treating it as a binop): 9965 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 9966 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 9967 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 9968 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 9969 9970 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 9971 verifyFormat("return options != nullptr && operator==(*options);"); 9972 9973 EXPECT_EQ("#define OP(x) \\\n" 9974 " ostream &operator<<(ostream &s, const A &a) { \\\n" 9975 " return s << a.DebugString(); \\\n" 9976 " }", 9977 format("#define OP(x) \\\n" 9978 " ostream &operator<<(ostream &s, const A &a) { \\\n" 9979 " return s << a.DebugString(); \\\n" 9980 " }", 9981 getLLVMStyleWithColumns(50))); 9982 9983 // FIXME: We cannot handle this case yet; we might be able to figure out that 9984 // foo<x> d > v; doesn't make sense. 9985 verifyFormat("foo<a<b && c> d> v;"); 9986 9987 FormatStyle PointerMiddle = getLLVMStyle(); 9988 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9989 verifyFormat("delete *x;", PointerMiddle); 9990 verifyFormat("int * x;", PointerMiddle); 9991 verifyFormat("int *[] x;", PointerMiddle); 9992 verifyFormat("template <int * y> f() {}", PointerMiddle); 9993 verifyFormat("int * f(int * a) {}", PointerMiddle); 9994 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 9995 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 9996 verifyFormat("A<int *> a;", PointerMiddle); 9997 verifyFormat("A<int **> a;", PointerMiddle); 9998 verifyFormat("A<int *, int *> a;", PointerMiddle); 9999 verifyFormat("A<int *[]> a;", PointerMiddle); 10000 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10001 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10002 verifyFormat("T ** t = new T *;", PointerMiddle); 10003 10004 // Member function reference qualifiers aren't binary operators. 10005 verifyFormat("string // break\n" 10006 "operator()() & {}"); 10007 verifyFormat("string // break\n" 10008 "operator()() && {}"); 10009 verifyGoogleFormat("template <typename T>\n" 10010 "auto x() & -> int {}"); 10011 10012 // Should be binary operators when used as an argument expression (overloaded 10013 // operator invoked as a member function). 10014 verifyFormat("void f() { a.operator()(a * a); }"); 10015 verifyFormat("void f() { a->operator()(a & a); }"); 10016 verifyFormat("void f() { a.operator()(*a & *a); }"); 10017 verifyFormat("void f() { a->operator()(*a * *a); }"); 10018 10019 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10020 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10021 } 10022 10023 TEST_F(FormatTest, UnderstandsAttributes) { 10024 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10025 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10026 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10027 FormatStyle AfterType = getLLVMStyle(); 10028 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10029 verifyFormat("__attribute__((nodebug)) void\n" 10030 "foo() {}\n", 10031 AfterType); 10032 verifyFormat("__unused void\n" 10033 "foo() {}", 10034 AfterType); 10035 10036 FormatStyle CustomAttrs = getLLVMStyle(); 10037 CustomAttrs.AttributeMacros.push_back("__unused"); 10038 CustomAttrs.AttributeMacros.push_back("__attr1"); 10039 CustomAttrs.AttributeMacros.push_back("__attr2"); 10040 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10041 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10042 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10043 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10044 // Check that it is parsed as a multiplication without AttributeMacros and 10045 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10046 verifyFormat("vector<SomeType * __attr1> v;"); 10047 verifyFormat("vector<SomeType __attr1 *> v;"); 10048 verifyFormat("vector<SomeType __attr1 *const> v;"); 10049 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10050 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10051 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10052 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10053 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10054 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10055 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10056 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10057 10058 // Check that these are not parsed as function declarations: 10059 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10060 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10061 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10062 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10063 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10064 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10065 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10066 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10067 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10068 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10069 } 10070 10071 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10072 // Check that qualifiers on pointers don't break parsing of casts. 10073 verifyFormat("x = (foo *const)*v;"); 10074 verifyFormat("x = (foo *volatile)*v;"); 10075 verifyFormat("x = (foo *restrict)*v;"); 10076 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10077 verifyFormat("x = (foo *_Nonnull)*v;"); 10078 verifyFormat("x = (foo *_Nullable)*v;"); 10079 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10080 verifyFormat("x = (foo *_Nonnull)*v;"); 10081 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10082 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10083 verifyFormat("x = (foo *__ptr32)*v;"); 10084 verifyFormat("x = (foo *__ptr64)*v;"); 10085 verifyFormat("x = (foo *__capability)*v;"); 10086 10087 // Check that we handle multiple trailing qualifiers and skip them all to 10088 // determine that the expression is a cast to a pointer type. 10089 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10090 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10091 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10092 StringRef AllQualifiers = 10093 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10094 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10095 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10096 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10097 10098 // Also check that address-of is not parsed as a binary bitwise-and: 10099 verifyFormat("x = (foo *const)&v;"); 10100 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10101 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10102 10103 // Check custom qualifiers: 10104 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10105 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10106 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10107 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10108 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10109 CustomQualifier); 10110 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10111 CustomQualifier); 10112 10113 // Check that unknown identifiers result in binary operator parsing: 10114 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10115 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10116 } 10117 10118 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10119 verifyFormat("SomeType s [[unused]] (InitValue);"); 10120 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10121 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10122 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10123 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10124 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10125 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10126 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10127 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10128 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10129 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10130 10131 // Make sure we do not mistake attributes for array subscripts. 10132 verifyFormat("int a() {}\n" 10133 "[[unused]] int b() {}\n"); 10134 verifyFormat("NSArray *arr;\n" 10135 "arr[[Foo() bar]];"); 10136 10137 // On the other hand, we still need to correctly find array subscripts. 10138 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10139 10140 // Make sure that we do not mistake Objective-C method inside array literals 10141 // as attributes, even if those method names are also keywords. 10142 verifyFormat("@[ [foo bar] ];"); 10143 verifyFormat("@[ [NSArray class] ];"); 10144 verifyFormat("@[ [foo enum] ];"); 10145 10146 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10147 10148 // Make sure we do not parse attributes as lambda introducers. 10149 FormatStyle MultiLineFunctions = getLLVMStyle(); 10150 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10151 verifyFormat("[[unused]] int b() {\n" 10152 " return 42;\n" 10153 "}\n", 10154 MultiLineFunctions); 10155 } 10156 10157 TEST_F(FormatTest, AttributeClass) { 10158 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10159 verifyFormat("class S {\n" 10160 " S(S&&) = default;\n" 10161 "};", 10162 Style); 10163 verifyFormat("class [[nodiscard]] S {\n" 10164 " S(S&&) = default;\n" 10165 "};", 10166 Style); 10167 verifyFormat("class __attribute((maybeunused)) S {\n" 10168 " S(S&&) = default;\n" 10169 "};", 10170 Style); 10171 verifyFormat("struct S {\n" 10172 " S(S&&) = default;\n" 10173 "};", 10174 Style); 10175 verifyFormat("struct [[nodiscard]] S {\n" 10176 " S(S&&) = default;\n" 10177 "};", 10178 Style); 10179 } 10180 10181 TEST_F(FormatTest, AttributesAfterMacro) { 10182 FormatStyle Style = getLLVMStyle(); 10183 verifyFormat("MACRO;\n" 10184 "__attribute__((maybe_unused)) int foo() {\n" 10185 " //...\n" 10186 "}"); 10187 10188 verifyFormat("MACRO;\n" 10189 "[[nodiscard]] int foo() {\n" 10190 " //...\n" 10191 "}"); 10192 10193 EXPECT_EQ("MACRO\n\n" 10194 "__attribute__((maybe_unused)) int foo() {\n" 10195 " //...\n" 10196 "}", 10197 format("MACRO\n\n" 10198 "__attribute__((maybe_unused)) int foo() {\n" 10199 " //...\n" 10200 "}")); 10201 10202 EXPECT_EQ("MACRO\n\n" 10203 "[[nodiscard]] int foo() {\n" 10204 " //...\n" 10205 "}", 10206 format("MACRO\n\n" 10207 "[[nodiscard]] int foo() {\n" 10208 " //...\n" 10209 "}")); 10210 } 10211 10212 TEST_F(FormatTest, AttributePenaltyBreaking) { 10213 FormatStyle Style = getLLVMStyle(); 10214 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10215 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10216 Style); 10217 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10218 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10219 Style); 10220 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10221 "shared_ptr<ALongTypeName> &C d) {\n}", 10222 Style); 10223 } 10224 10225 TEST_F(FormatTest, UnderstandsEllipsis) { 10226 FormatStyle Style = getLLVMStyle(); 10227 verifyFormat("int printf(const char *fmt, ...);"); 10228 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10229 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10230 10231 verifyFormat("template <int *...PP> a;", Style); 10232 10233 Style.PointerAlignment = FormatStyle::PAS_Left; 10234 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10235 10236 verifyFormat("template <int*... PP> a;", Style); 10237 10238 Style.PointerAlignment = FormatStyle::PAS_Middle; 10239 verifyFormat("template <int *... PP> a;", Style); 10240 } 10241 10242 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10243 EXPECT_EQ("int *a;\n" 10244 "int *a;\n" 10245 "int *a;", 10246 format("int *a;\n" 10247 "int* a;\n" 10248 "int *a;", 10249 getGoogleStyle())); 10250 EXPECT_EQ("int* a;\n" 10251 "int* a;\n" 10252 "int* a;", 10253 format("int* a;\n" 10254 "int* a;\n" 10255 "int *a;", 10256 getGoogleStyle())); 10257 EXPECT_EQ("int *a;\n" 10258 "int *a;\n" 10259 "int *a;", 10260 format("int *a;\n" 10261 "int * a;\n" 10262 "int * a;", 10263 getGoogleStyle())); 10264 EXPECT_EQ("auto x = [] {\n" 10265 " int *a;\n" 10266 " int *a;\n" 10267 " int *a;\n" 10268 "};", 10269 format("auto x=[]{int *a;\n" 10270 "int * a;\n" 10271 "int * a;};", 10272 getGoogleStyle())); 10273 } 10274 10275 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10276 verifyFormat("int f(int &&a) {}"); 10277 verifyFormat("int f(int a, char &&b) {}"); 10278 verifyFormat("void f() { int &&a = b; }"); 10279 verifyGoogleFormat("int f(int a, char&& b) {}"); 10280 verifyGoogleFormat("void f() { int&& a = b; }"); 10281 10282 verifyIndependentOfContext("A<int &&> a;"); 10283 verifyIndependentOfContext("A<int &&, int &&> a;"); 10284 verifyGoogleFormat("A<int&&> a;"); 10285 verifyGoogleFormat("A<int&&, int&&> a;"); 10286 10287 // Not rvalue references: 10288 verifyFormat("template <bool B, bool C> class A {\n" 10289 " static_assert(B && C, \"Something is wrong\");\n" 10290 "};"); 10291 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10292 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10293 verifyFormat("#define A(a, b) (a && b)"); 10294 } 10295 10296 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10297 verifyFormat("void f() {\n" 10298 " x[aaaaaaaaa -\n" 10299 " b] = 23;\n" 10300 "}", 10301 getLLVMStyleWithColumns(15)); 10302 } 10303 10304 TEST_F(FormatTest, FormatsCasts) { 10305 verifyFormat("Type *A = static_cast<Type *>(P);"); 10306 verifyFormat("Type *A = (Type *)P;"); 10307 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10308 verifyFormat("int a = (int)(2.0f);"); 10309 verifyFormat("int a = (int)2.0f;"); 10310 verifyFormat("x[(int32)y];"); 10311 verifyFormat("x = (int32)y;"); 10312 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10313 verifyFormat("int a = (int)*b;"); 10314 verifyFormat("int a = (int)2.0f;"); 10315 verifyFormat("int a = (int)~0;"); 10316 verifyFormat("int a = (int)++a;"); 10317 verifyFormat("int a = (int)sizeof(int);"); 10318 verifyFormat("int a = (int)+2;"); 10319 verifyFormat("my_int a = (my_int)2.0f;"); 10320 verifyFormat("my_int a = (my_int)sizeof(int);"); 10321 verifyFormat("return (my_int)aaa;"); 10322 verifyFormat("#define x ((int)-1)"); 10323 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10324 verifyFormat("#define p(q) ((int *)&q)"); 10325 verifyFormat("fn(a)(b) + 1;"); 10326 10327 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10328 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10329 verifyFormat("my_int a = (my_int)~0;"); 10330 verifyFormat("my_int a = (my_int)++a;"); 10331 verifyFormat("my_int a = (my_int)-2;"); 10332 verifyFormat("my_int a = (my_int)1;"); 10333 verifyFormat("my_int a = (my_int *)1;"); 10334 verifyFormat("my_int a = (const my_int)-1;"); 10335 verifyFormat("my_int a = (const my_int *)-1;"); 10336 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10337 verifyFormat("my_int a = (ns::my_int)-2;"); 10338 verifyFormat("case (my_int)ONE:"); 10339 verifyFormat("auto x = (X)this;"); 10340 // Casts in Obj-C style calls used to not be recognized as such. 10341 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10342 10343 // FIXME: single value wrapped with paren will be treated as cast. 10344 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10345 10346 verifyFormat("{ (void)F; }"); 10347 10348 // Don't break after a cast's 10349 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10350 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10351 " bbbbbbbbbbbbbbbbbbbbbb);"); 10352 10353 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10354 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10355 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10356 verifyFormat("bool *y = (bool *)(void *)(x);"); 10357 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10358 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10359 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10360 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10361 10362 // These are not casts. 10363 verifyFormat("void f(int *) {}"); 10364 verifyFormat("f(foo)->b;"); 10365 verifyFormat("f(foo).b;"); 10366 verifyFormat("f(foo)(b);"); 10367 verifyFormat("f(foo)[b];"); 10368 verifyFormat("[](foo) { return 4; }(bar);"); 10369 verifyFormat("(*funptr)(foo)[4];"); 10370 verifyFormat("funptrs[4](foo)[4];"); 10371 verifyFormat("void f(int *);"); 10372 verifyFormat("void f(int *) = 0;"); 10373 verifyFormat("void f(SmallVector<int>) {}"); 10374 verifyFormat("void f(SmallVector<int>);"); 10375 verifyFormat("void f(SmallVector<int>) = 0;"); 10376 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10377 verifyFormat("int a = sizeof(int) * b;"); 10378 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10379 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10380 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10381 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10382 10383 // These are not casts, but at some point were confused with casts. 10384 verifyFormat("virtual void foo(int *) override;"); 10385 verifyFormat("virtual void foo(char &) const;"); 10386 verifyFormat("virtual void foo(int *a, char *) const;"); 10387 verifyFormat("int a = sizeof(int *) + b;"); 10388 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10389 verifyFormat("bool b = f(g<int>) && c;"); 10390 verifyFormat("typedef void (*f)(int i) func;"); 10391 verifyFormat("void operator++(int) noexcept;"); 10392 verifyFormat("void operator++(int &) noexcept;"); 10393 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10394 "&) noexcept;"); 10395 verifyFormat( 10396 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10397 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10398 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10399 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10400 verifyFormat("void operator delete(foo &) noexcept;"); 10401 verifyFormat("void operator delete(foo) noexcept;"); 10402 verifyFormat("void operator delete(int) noexcept;"); 10403 verifyFormat("void operator delete(int &) noexcept;"); 10404 verifyFormat("void operator delete(int &) volatile noexcept;"); 10405 verifyFormat("void operator delete(int &) const"); 10406 verifyFormat("void operator delete(int &) = default"); 10407 verifyFormat("void operator delete(int &) = delete"); 10408 verifyFormat("void operator delete(int &) [[noreturn]]"); 10409 verifyFormat("void operator delete(int &) throw();"); 10410 verifyFormat("void operator delete(int &) throw(int);"); 10411 verifyFormat("auto operator delete(int &) -> int;"); 10412 verifyFormat("auto operator delete(int &) override"); 10413 verifyFormat("auto operator delete(int &) final"); 10414 10415 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10416 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10417 // FIXME: The indentation here is not ideal. 10418 verifyFormat( 10419 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10420 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10421 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10422 } 10423 10424 TEST_F(FormatTest, FormatsFunctionTypes) { 10425 verifyFormat("A<bool()> a;"); 10426 verifyFormat("A<SomeType()> a;"); 10427 verifyFormat("A<void (*)(int, std::string)> a;"); 10428 verifyFormat("A<void *(int)>;"); 10429 verifyFormat("void *(*a)(int *, SomeType *);"); 10430 verifyFormat("int (*func)(void *);"); 10431 verifyFormat("void f() { int (*func)(void *); }"); 10432 verifyFormat("template <class CallbackClass>\n" 10433 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10434 10435 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10436 verifyGoogleFormat("void* (*a)(int);"); 10437 verifyGoogleFormat( 10438 "template <class CallbackClass>\n" 10439 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10440 10441 // Other constructs can look somewhat like function types: 10442 verifyFormat("A<sizeof(*x)> a;"); 10443 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10444 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10445 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10446 verifyFormat("int x = f(&h)();"); 10447 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10448 verifyFormat("std::function<\n" 10449 " LooooooooooongTemplatedType<\n" 10450 " SomeType>*(\n" 10451 " LooooooooooooooooongType type)>\n" 10452 " function;", 10453 getGoogleStyleWithColumns(40)); 10454 } 10455 10456 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10457 verifyFormat("A (*foo_)[6];"); 10458 verifyFormat("vector<int> (*foo_)[6];"); 10459 } 10460 10461 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10462 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10463 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10464 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10465 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10466 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10467 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10468 10469 // Different ways of ()-initializiation. 10470 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10471 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10472 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10473 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10474 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10475 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10476 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10477 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10478 10479 // Lambdas should not confuse the variable declaration heuristic. 10480 verifyFormat("LooooooooooooooooongType\n" 10481 " variable(nullptr, [](A *a) {});", 10482 getLLVMStyleWithColumns(40)); 10483 } 10484 10485 TEST_F(FormatTest, BreaksLongDeclarations) { 10486 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10487 " AnotherNameForTheLongType;"); 10488 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10489 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10490 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10491 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10492 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10493 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10494 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10495 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10496 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10497 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10498 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10499 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10500 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10501 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10502 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10503 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10504 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10505 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10506 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10507 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10508 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10509 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10510 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10511 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10512 FormatStyle Indented = getLLVMStyle(); 10513 Indented.IndentWrappedFunctionNames = true; 10514 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10515 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10516 Indented); 10517 verifyFormat( 10518 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10519 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10520 Indented); 10521 verifyFormat( 10522 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10523 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10524 Indented); 10525 verifyFormat( 10526 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10527 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10528 Indented); 10529 10530 // FIXME: Without the comment, this breaks after "(". 10531 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10532 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10533 getGoogleStyle()); 10534 10535 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10536 " int LoooooooooooooooooooongParam2) {}"); 10537 verifyFormat( 10538 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10539 " SourceLocation L, IdentifierIn *II,\n" 10540 " Type *T) {}"); 10541 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10542 "ReallyReaaallyLongFunctionName(\n" 10543 " const std::string &SomeParameter,\n" 10544 " const SomeType<string, SomeOtherTemplateParameter>\n" 10545 " &ReallyReallyLongParameterName,\n" 10546 " const SomeType<string, SomeOtherTemplateParameter>\n" 10547 " &AnotherLongParameterName) {}"); 10548 verifyFormat("template <typename A>\n" 10549 "SomeLoooooooooooooooooooooongType<\n" 10550 " typename some_namespace::SomeOtherType<A>::Type>\n" 10551 "Function() {}"); 10552 10553 verifyGoogleFormat( 10554 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 10555 " aaaaaaaaaaaaaaaaaaaaaaa;"); 10556 verifyGoogleFormat( 10557 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 10558 " SourceLocation L) {}"); 10559 verifyGoogleFormat( 10560 "some_namespace::LongReturnType\n" 10561 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 10562 " int first_long_parameter, int second_parameter) {}"); 10563 10564 verifyGoogleFormat("template <typename T>\n" 10565 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10566 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 10567 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10568 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 10569 10570 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 10571 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10572 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10573 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10574 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10575 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 10576 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10577 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 10578 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 10579 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10580 10581 verifyFormat("template <typename T> // Templates on own line.\n" 10582 "static int // Some comment.\n" 10583 "MyFunction(int a);", 10584 getLLVMStyle()); 10585 } 10586 10587 TEST_F(FormatTest, FormatsAccessModifiers) { 10588 FormatStyle Style = getLLVMStyle(); 10589 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 10590 FormatStyle::ELBAMS_LogicalBlock); 10591 verifyFormat("struct foo {\n" 10592 "private:\n" 10593 " void f() {}\n" 10594 "\n" 10595 "private:\n" 10596 " int i;\n" 10597 "\n" 10598 "protected:\n" 10599 " int j;\n" 10600 "};\n", 10601 Style); 10602 verifyFormat("struct foo {\n" 10603 "private:\n" 10604 " void f() {}\n" 10605 "\n" 10606 "private:\n" 10607 " int i;\n" 10608 "\n" 10609 "protected:\n" 10610 " int j;\n" 10611 "};\n", 10612 "struct foo {\n" 10613 "private:\n" 10614 " void f() {}\n" 10615 "private:\n" 10616 " int i;\n" 10617 "protected:\n" 10618 " int j;\n" 10619 "};\n", 10620 Style); 10621 verifyFormat("struct foo { /* comment */\n" 10622 "private:\n" 10623 " int i;\n" 10624 " // comment\n" 10625 "private:\n" 10626 " int j;\n" 10627 "};\n", 10628 Style); 10629 verifyFormat("struct foo {\n" 10630 "#ifdef FOO\n" 10631 "#endif\n" 10632 "private:\n" 10633 " int i;\n" 10634 "#ifdef FOO\n" 10635 "private:\n" 10636 "#endif\n" 10637 " int j;\n" 10638 "};\n", 10639 Style); 10640 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10641 verifyFormat("struct foo {\n" 10642 "private:\n" 10643 " void f() {}\n" 10644 "private:\n" 10645 " int i;\n" 10646 "protected:\n" 10647 " int j;\n" 10648 "};\n", 10649 Style); 10650 verifyFormat("struct foo {\n" 10651 "private:\n" 10652 " void f() {}\n" 10653 "private:\n" 10654 " int i;\n" 10655 "protected:\n" 10656 " int j;\n" 10657 "};\n", 10658 "struct foo {\n" 10659 "\n" 10660 "private:\n" 10661 " void f() {}\n" 10662 "\n" 10663 "private:\n" 10664 " int i;\n" 10665 "\n" 10666 "protected:\n" 10667 " int j;\n" 10668 "};\n", 10669 Style); 10670 verifyFormat("struct foo { /* comment */\n" 10671 "private:\n" 10672 " int i;\n" 10673 " // comment\n" 10674 "private:\n" 10675 " int j;\n" 10676 "};\n", 10677 "struct foo { /* comment */\n" 10678 "\n" 10679 "private:\n" 10680 " int i;\n" 10681 " // comment\n" 10682 "\n" 10683 "private:\n" 10684 " int j;\n" 10685 "};\n", 10686 Style); 10687 verifyFormat("struct foo {\n" 10688 "#ifdef FOO\n" 10689 "#endif\n" 10690 "private:\n" 10691 " int i;\n" 10692 "#ifdef FOO\n" 10693 "private:\n" 10694 "#endif\n" 10695 " int j;\n" 10696 "};\n", 10697 "struct foo {\n" 10698 "#ifdef FOO\n" 10699 "#endif\n" 10700 "\n" 10701 "private:\n" 10702 " int i;\n" 10703 "#ifdef FOO\n" 10704 "\n" 10705 "private:\n" 10706 "#endif\n" 10707 " int j;\n" 10708 "};\n", 10709 Style); 10710 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10711 verifyFormat("struct foo {\n" 10712 "private:\n" 10713 " void f() {}\n" 10714 "\n" 10715 "private:\n" 10716 " int i;\n" 10717 "\n" 10718 "protected:\n" 10719 " int j;\n" 10720 "};\n", 10721 Style); 10722 verifyFormat("struct foo {\n" 10723 "private:\n" 10724 " void f() {}\n" 10725 "\n" 10726 "private:\n" 10727 " int i;\n" 10728 "\n" 10729 "protected:\n" 10730 " int j;\n" 10731 "};\n", 10732 "struct foo {\n" 10733 "private:\n" 10734 " void f() {}\n" 10735 "private:\n" 10736 " int i;\n" 10737 "protected:\n" 10738 " int j;\n" 10739 "};\n", 10740 Style); 10741 verifyFormat("struct foo { /* comment */\n" 10742 "private:\n" 10743 " int i;\n" 10744 " // comment\n" 10745 "\n" 10746 "private:\n" 10747 " int j;\n" 10748 "};\n", 10749 "struct foo { /* comment */\n" 10750 "private:\n" 10751 " int i;\n" 10752 " // comment\n" 10753 "\n" 10754 "private:\n" 10755 " int j;\n" 10756 "};\n", 10757 Style); 10758 verifyFormat("struct foo {\n" 10759 "#ifdef FOO\n" 10760 "#endif\n" 10761 "\n" 10762 "private:\n" 10763 " int i;\n" 10764 "#ifdef FOO\n" 10765 "\n" 10766 "private:\n" 10767 "#endif\n" 10768 " int j;\n" 10769 "};\n", 10770 "struct foo {\n" 10771 "#ifdef FOO\n" 10772 "#endif\n" 10773 "private:\n" 10774 " int i;\n" 10775 "#ifdef FOO\n" 10776 "private:\n" 10777 "#endif\n" 10778 " int j;\n" 10779 "};\n", 10780 Style); 10781 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 10782 EXPECT_EQ("struct foo {\n" 10783 "\n" 10784 "private:\n" 10785 " void f() {}\n" 10786 "\n" 10787 "private:\n" 10788 " int i;\n" 10789 "\n" 10790 "protected:\n" 10791 " int j;\n" 10792 "};\n", 10793 format("struct foo {\n" 10794 "\n" 10795 "private:\n" 10796 " void f() {}\n" 10797 "\n" 10798 "private:\n" 10799 " int i;\n" 10800 "\n" 10801 "protected:\n" 10802 " int j;\n" 10803 "};\n", 10804 Style)); 10805 verifyFormat("struct foo {\n" 10806 "private:\n" 10807 " void f() {}\n" 10808 "private:\n" 10809 " int i;\n" 10810 "protected:\n" 10811 " int j;\n" 10812 "};\n", 10813 Style); 10814 EXPECT_EQ("struct foo { /* comment */\n" 10815 "\n" 10816 "private:\n" 10817 " int i;\n" 10818 " // comment\n" 10819 "\n" 10820 "private:\n" 10821 " int j;\n" 10822 "};\n", 10823 format("struct foo { /* comment */\n" 10824 "\n" 10825 "private:\n" 10826 " int i;\n" 10827 " // comment\n" 10828 "\n" 10829 "private:\n" 10830 " int j;\n" 10831 "};\n", 10832 Style)); 10833 verifyFormat("struct foo { /* comment */\n" 10834 "private:\n" 10835 " int i;\n" 10836 " // comment\n" 10837 "private:\n" 10838 " int j;\n" 10839 "};\n", 10840 Style); 10841 EXPECT_EQ("struct foo {\n" 10842 "#ifdef FOO\n" 10843 "#endif\n" 10844 "\n" 10845 "private:\n" 10846 " int i;\n" 10847 "#ifdef FOO\n" 10848 "\n" 10849 "private:\n" 10850 "#endif\n" 10851 " int j;\n" 10852 "};\n", 10853 format("struct foo {\n" 10854 "#ifdef FOO\n" 10855 "#endif\n" 10856 "\n" 10857 "private:\n" 10858 " int i;\n" 10859 "#ifdef FOO\n" 10860 "\n" 10861 "private:\n" 10862 "#endif\n" 10863 " int j;\n" 10864 "};\n", 10865 Style)); 10866 verifyFormat("struct foo {\n" 10867 "#ifdef FOO\n" 10868 "#endif\n" 10869 "private:\n" 10870 " int i;\n" 10871 "#ifdef FOO\n" 10872 "private:\n" 10873 "#endif\n" 10874 " int j;\n" 10875 "};\n", 10876 Style); 10877 10878 FormatStyle NoEmptyLines = getLLVMStyle(); 10879 NoEmptyLines.MaxEmptyLinesToKeep = 0; 10880 verifyFormat("struct foo {\n" 10881 "private:\n" 10882 " void f() {}\n" 10883 "\n" 10884 "private:\n" 10885 " int i;\n" 10886 "\n" 10887 "public:\n" 10888 "protected:\n" 10889 " int j;\n" 10890 "};\n", 10891 NoEmptyLines); 10892 10893 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10894 verifyFormat("struct foo {\n" 10895 "private:\n" 10896 " void f() {}\n" 10897 "private:\n" 10898 " int i;\n" 10899 "public:\n" 10900 "protected:\n" 10901 " int j;\n" 10902 "};\n", 10903 NoEmptyLines); 10904 10905 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10906 verifyFormat("struct foo {\n" 10907 "private:\n" 10908 " void f() {}\n" 10909 "\n" 10910 "private:\n" 10911 " int i;\n" 10912 "\n" 10913 "public:\n" 10914 "\n" 10915 "protected:\n" 10916 " int j;\n" 10917 "};\n", 10918 NoEmptyLines); 10919 } 10920 10921 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 10922 10923 FormatStyle Style = getLLVMStyle(); 10924 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 10925 verifyFormat("struct foo {\n" 10926 "private:\n" 10927 " void f() {}\n" 10928 "\n" 10929 "private:\n" 10930 " int i;\n" 10931 "\n" 10932 "protected:\n" 10933 " int j;\n" 10934 "};\n", 10935 Style); 10936 10937 // Check if lines are removed. 10938 verifyFormat("struct foo {\n" 10939 "private:\n" 10940 " void f() {}\n" 10941 "\n" 10942 "private:\n" 10943 " int i;\n" 10944 "\n" 10945 "protected:\n" 10946 " int j;\n" 10947 "};\n", 10948 "struct foo {\n" 10949 "private:\n" 10950 "\n" 10951 " void f() {}\n" 10952 "\n" 10953 "private:\n" 10954 "\n" 10955 " int i;\n" 10956 "\n" 10957 "protected:\n" 10958 "\n" 10959 " int j;\n" 10960 "};\n", 10961 Style); 10962 10963 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 10964 verifyFormat("struct foo {\n" 10965 "private:\n" 10966 "\n" 10967 " void f() {}\n" 10968 "\n" 10969 "private:\n" 10970 "\n" 10971 " int i;\n" 10972 "\n" 10973 "protected:\n" 10974 "\n" 10975 " int j;\n" 10976 "};\n", 10977 Style); 10978 10979 // Check if lines are added. 10980 verifyFormat("struct foo {\n" 10981 "private:\n" 10982 "\n" 10983 " void f() {}\n" 10984 "\n" 10985 "private:\n" 10986 "\n" 10987 " int i;\n" 10988 "\n" 10989 "protected:\n" 10990 "\n" 10991 " int j;\n" 10992 "};\n", 10993 "struct foo {\n" 10994 "private:\n" 10995 " void f() {}\n" 10996 "\n" 10997 "private:\n" 10998 " int i;\n" 10999 "\n" 11000 "protected:\n" 11001 " int j;\n" 11002 "};\n", 11003 Style); 11004 11005 // Leave tests rely on the code layout, test::messUp can not be used. 11006 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11007 Style.MaxEmptyLinesToKeep = 0u; 11008 verifyFormat("struct foo {\n" 11009 "private:\n" 11010 " void f() {}\n" 11011 "\n" 11012 "private:\n" 11013 " int i;\n" 11014 "\n" 11015 "protected:\n" 11016 " int j;\n" 11017 "};\n", 11018 Style); 11019 11020 // Check if MaxEmptyLinesToKeep is respected. 11021 EXPECT_EQ("struct foo {\n" 11022 "private:\n" 11023 " void f() {}\n" 11024 "\n" 11025 "private:\n" 11026 " int i;\n" 11027 "\n" 11028 "protected:\n" 11029 " int j;\n" 11030 "};\n", 11031 format("struct foo {\n" 11032 "private:\n" 11033 "\n\n\n" 11034 " void f() {}\n" 11035 "\n" 11036 "private:\n" 11037 "\n\n\n" 11038 " int i;\n" 11039 "\n" 11040 "protected:\n" 11041 "\n\n\n" 11042 " int j;\n" 11043 "};\n", 11044 Style)); 11045 11046 Style.MaxEmptyLinesToKeep = 1u; 11047 EXPECT_EQ("struct foo {\n" 11048 "private:\n" 11049 "\n" 11050 " void f() {}\n" 11051 "\n" 11052 "private:\n" 11053 "\n" 11054 " int i;\n" 11055 "\n" 11056 "protected:\n" 11057 "\n" 11058 " int j;\n" 11059 "};\n", 11060 format("struct foo {\n" 11061 "private:\n" 11062 "\n" 11063 " void f() {}\n" 11064 "\n" 11065 "private:\n" 11066 "\n" 11067 " int i;\n" 11068 "\n" 11069 "protected:\n" 11070 "\n" 11071 " int j;\n" 11072 "};\n", 11073 Style)); 11074 // Check if no lines are kept. 11075 EXPECT_EQ("struct foo {\n" 11076 "private:\n" 11077 " void f() {}\n" 11078 "\n" 11079 "private:\n" 11080 " int i;\n" 11081 "\n" 11082 "protected:\n" 11083 " int j;\n" 11084 "};\n", 11085 format("struct foo {\n" 11086 "private:\n" 11087 " void f() {}\n" 11088 "\n" 11089 "private:\n" 11090 " int i;\n" 11091 "\n" 11092 "protected:\n" 11093 " int j;\n" 11094 "};\n", 11095 Style)); 11096 // Check if MaxEmptyLinesToKeep is respected. 11097 EXPECT_EQ("struct foo {\n" 11098 "private:\n" 11099 "\n" 11100 " void f() {}\n" 11101 "\n" 11102 "private:\n" 11103 "\n" 11104 " int i;\n" 11105 "\n" 11106 "protected:\n" 11107 "\n" 11108 " int j;\n" 11109 "};\n", 11110 format("struct foo {\n" 11111 "private:\n" 11112 "\n\n\n" 11113 " void f() {}\n" 11114 "\n" 11115 "private:\n" 11116 "\n\n\n" 11117 " int i;\n" 11118 "\n" 11119 "protected:\n" 11120 "\n\n\n" 11121 " int j;\n" 11122 "};\n", 11123 Style)); 11124 11125 Style.MaxEmptyLinesToKeep = 10u; 11126 EXPECT_EQ("struct foo {\n" 11127 "private:\n" 11128 "\n\n\n" 11129 " void f() {}\n" 11130 "\n" 11131 "private:\n" 11132 "\n\n\n" 11133 " int i;\n" 11134 "\n" 11135 "protected:\n" 11136 "\n\n\n" 11137 " int j;\n" 11138 "};\n", 11139 format("struct foo {\n" 11140 "private:\n" 11141 "\n\n\n" 11142 " void f() {}\n" 11143 "\n" 11144 "private:\n" 11145 "\n\n\n" 11146 " int i;\n" 11147 "\n" 11148 "protected:\n" 11149 "\n\n\n" 11150 " int j;\n" 11151 "};\n", 11152 Style)); 11153 11154 // Test with comments. 11155 Style = getLLVMStyle(); 11156 verifyFormat("struct foo {\n" 11157 "private:\n" 11158 " // comment\n" 11159 " void f() {}\n" 11160 "\n" 11161 "private: /* comment */\n" 11162 " int i;\n" 11163 "};\n", 11164 Style); 11165 verifyFormat("struct foo {\n" 11166 "private:\n" 11167 " // comment\n" 11168 " void f() {}\n" 11169 "\n" 11170 "private: /* comment */\n" 11171 " int i;\n" 11172 "};\n", 11173 "struct foo {\n" 11174 "private:\n" 11175 "\n" 11176 " // comment\n" 11177 " void f() {}\n" 11178 "\n" 11179 "private: /* comment */\n" 11180 "\n" 11181 " int i;\n" 11182 "};\n", 11183 Style); 11184 11185 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11186 verifyFormat("struct foo {\n" 11187 "private:\n" 11188 "\n" 11189 " // comment\n" 11190 " void f() {}\n" 11191 "\n" 11192 "private: /* comment */\n" 11193 "\n" 11194 " int i;\n" 11195 "};\n", 11196 "struct foo {\n" 11197 "private:\n" 11198 " // comment\n" 11199 " void f() {}\n" 11200 "\n" 11201 "private: /* comment */\n" 11202 " int i;\n" 11203 "};\n", 11204 Style); 11205 verifyFormat("struct foo {\n" 11206 "private:\n" 11207 "\n" 11208 " // comment\n" 11209 " void f() {}\n" 11210 "\n" 11211 "private: /* comment */\n" 11212 "\n" 11213 " int i;\n" 11214 "};\n", 11215 Style); 11216 11217 // Test with preprocessor defines. 11218 Style = getLLVMStyle(); 11219 verifyFormat("struct foo {\n" 11220 "private:\n" 11221 "#ifdef FOO\n" 11222 "#endif\n" 11223 " void f() {}\n" 11224 "};\n", 11225 Style); 11226 verifyFormat("struct foo {\n" 11227 "private:\n" 11228 "#ifdef FOO\n" 11229 "#endif\n" 11230 " void f() {}\n" 11231 "};\n", 11232 "struct foo {\n" 11233 "private:\n" 11234 "\n" 11235 "#ifdef FOO\n" 11236 "#endif\n" 11237 " void f() {}\n" 11238 "};\n", 11239 Style); 11240 11241 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11242 verifyFormat("struct foo {\n" 11243 "private:\n" 11244 "\n" 11245 "#ifdef FOO\n" 11246 "#endif\n" 11247 " void f() {}\n" 11248 "};\n", 11249 "struct foo {\n" 11250 "private:\n" 11251 "#ifdef FOO\n" 11252 "#endif\n" 11253 " void f() {}\n" 11254 "};\n", 11255 Style); 11256 verifyFormat("struct foo {\n" 11257 "private:\n" 11258 "\n" 11259 "#ifdef FOO\n" 11260 "#endif\n" 11261 " void f() {}\n" 11262 "};\n", 11263 Style); 11264 } 11265 11266 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11267 // Combined tests of EmptyLineAfterAccessModifier and 11268 // EmptyLineBeforeAccessModifier. 11269 FormatStyle Style = getLLVMStyle(); 11270 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11271 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11272 verifyFormat("struct foo {\n" 11273 "private:\n" 11274 "\n" 11275 "protected:\n" 11276 "};\n", 11277 Style); 11278 11279 Style.MaxEmptyLinesToKeep = 10u; 11280 // Both remove all new lines. 11281 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11282 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11283 verifyFormat("struct foo {\n" 11284 "private:\n" 11285 "protected:\n" 11286 "};\n", 11287 "struct foo {\n" 11288 "private:\n" 11289 "\n\n\n" 11290 "protected:\n" 11291 "};\n", 11292 Style); 11293 11294 // Leave tests rely on the code layout, test::messUp can not be used. 11295 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11296 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11297 Style.MaxEmptyLinesToKeep = 10u; 11298 EXPECT_EQ("struct foo {\n" 11299 "private:\n" 11300 "\n\n\n" 11301 "protected:\n" 11302 "};\n", 11303 format("struct foo {\n" 11304 "private:\n" 11305 "\n\n\n" 11306 "protected:\n" 11307 "};\n", 11308 Style)); 11309 Style.MaxEmptyLinesToKeep = 3u; 11310 EXPECT_EQ("struct foo {\n" 11311 "private:\n" 11312 "\n\n\n" 11313 "protected:\n" 11314 "};\n", 11315 format("struct foo {\n" 11316 "private:\n" 11317 "\n\n\n" 11318 "protected:\n" 11319 "};\n", 11320 Style)); 11321 Style.MaxEmptyLinesToKeep = 1u; 11322 EXPECT_EQ("struct foo {\n" 11323 "private:\n" 11324 "\n\n\n" 11325 "protected:\n" 11326 "};\n", 11327 format("struct foo {\n" 11328 "private:\n" 11329 "\n\n\n" 11330 "protected:\n" 11331 "};\n", 11332 Style)); // Based on new lines in original document and not 11333 // on the setting. 11334 11335 Style.MaxEmptyLinesToKeep = 10u; 11336 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11337 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11338 // Newlines are kept if they are greater than zero, 11339 // test::messUp removes all new lines which changes the logic 11340 EXPECT_EQ("struct foo {\n" 11341 "private:\n" 11342 "\n\n\n" 11343 "protected:\n" 11344 "};\n", 11345 format("struct foo {\n" 11346 "private:\n" 11347 "\n\n\n" 11348 "protected:\n" 11349 "};\n", 11350 Style)); 11351 11352 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11353 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11354 // test::messUp removes all new lines which changes the logic 11355 EXPECT_EQ("struct foo {\n" 11356 "private:\n" 11357 "\n\n\n" 11358 "protected:\n" 11359 "};\n", 11360 format("struct foo {\n" 11361 "private:\n" 11362 "\n\n\n" 11363 "protected:\n" 11364 "};\n", 11365 Style)); 11366 11367 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11368 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11369 EXPECT_EQ("struct foo {\n" 11370 "private:\n" 11371 "\n\n\n" 11372 "protected:\n" 11373 "};\n", 11374 format("struct foo {\n" 11375 "private:\n" 11376 "\n\n\n" 11377 "protected:\n" 11378 "};\n", 11379 Style)); // test::messUp removes all new lines which changes 11380 // the logic. 11381 11382 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11383 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11384 verifyFormat("struct foo {\n" 11385 "private:\n" 11386 "protected:\n" 11387 "};\n", 11388 "struct foo {\n" 11389 "private:\n" 11390 "\n\n\n" 11391 "protected:\n" 11392 "};\n", 11393 Style); 11394 11395 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11396 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11397 EXPECT_EQ("struct foo {\n" 11398 "private:\n" 11399 "\n\n\n" 11400 "protected:\n" 11401 "};\n", 11402 format("struct foo {\n" 11403 "private:\n" 11404 "\n\n\n" 11405 "protected:\n" 11406 "};\n", 11407 Style)); // test::messUp removes all new lines which changes 11408 // the logic. 11409 11410 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11411 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11412 verifyFormat("struct foo {\n" 11413 "private:\n" 11414 "protected:\n" 11415 "};\n", 11416 "struct foo {\n" 11417 "private:\n" 11418 "\n\n\n" 11419 "protected:\n" 11420 "};\n", 11421 Style); 11422 11423 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11424 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11425 verifyFormat("struct foo {\n" 11426 "private:\n" 11427 "protected:\n" 11428 "};\n", 11429 "struct foo {\n" 11430 "private:\n" 11431 "\n\n\n" 11432 "protected:\n" 11433 "};\n", 11434 Style); 11435 11436 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11437 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11438 verifyFormat("struct foo {\n" 11439 "private:\n" 11440 "protected:\n" 11441 "};\n", 11442 "struct foo {\n" 11443 "private:\n" 11444 "\n\n\n" 11445 "protected:\n" 11446 "};\n", 11447 Style); 11448 11449 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11450 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11451 verifyFormat("struct foo {\n" 11452 "private:\n" 11453 "protected:\n" 11454 "};\n", 11455 "struct foo {\n" 11456 "private:\n" 11457 "\n\n\n" 11458 "protected:\n" 11459 "};\n", 11460 Style); 11461 } 11462 11463 TEST_F(FormatTest, FormatsArrays) { 11464 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11465 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11466 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11467 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11468 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11469 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11470 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11471 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11472 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11473 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11474 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11475 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11476 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11477 verifyFormat( 11478 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11479 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11480 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11481 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11482 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11483 11484 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11485 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11486 verifyFormat( 11487 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11488 " .aaaaaaa[0]\n" 11489 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11490 verifyFormat("a[::b::c];"); 11491 11492 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11493 11494 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11495 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11496 } 11497 11498 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11499 verifyFormat("(a)->b();"); 11500 verifyFormat("--a;"); 11501 } 11502 11503 TEST_F(FormatTest, HandlesIncludeDirectives) { 11504 verifyFormat("#include <string>\n" 11505 "#include <a/b/c.h>\n" 11506 "#include \"a/b/string\"\n" 11507 "#include \"string.h\"\n" 11508 "#include \"string.h\"\n" 11509 "#include <a-a>\n" 11510 "#include < path with space >\n" 11511 "#include_next <test.h>" 11512 "#include \"abc.h\" // this is included for ABC\n" 11513 "#include \"some long include\" // with a comment\n" 11514 "#include \"some very long include path\"\n" 11515 "#include <some/very/long/include/path>\n", 11516 getLLVMStyleWithColumns(35)); 11517 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11518 EXPECT_EQ("#include <a>", format("#include<a>")); 11519 11520 verifyFormat("#import <string>"); 11521 verifyFormat("#import <a/b/c.h>"); 11522 verifyFormat("#import \"a/b/string\""); 11523 verifyFormat("#import \"string.h\""); 11524 verifyFormat("#import \"string.h\""); 11525 verifyFormat("#if __has_include(<strstream>)\n" 11526 "#include <strstream>\n" 11527 "#endif"); 11528 11529 verifyFormat("#define MY_IMPORT <a/b>"); 11530 11531 verifyFormat("#if __has_include(<a/b>)"); 11532 verifyFormat("#if __has_include_next(<a/b>)"); 11533 verifyFormat("#define F __has_include(<a/b>)"); 11534 verifyFormat("#define F __has_include_next(<a/b>)"); 11535 11536 // Protocol buffer definition or missing "#". 11537 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11538 getLLVMStyleWithColumns(30)); 11539 11540 FormatStyle Style = getLLVMStyle(); 11541 Style.AlwaysBreakBeforeMultilineStrings = true; 11542 Style.ColumnLimit = 0; 11543 verifyFormat("#import \"abc.h\"", Style); 11544 11545 // But 'import' might also be a regular C++ namespace. 11546 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11547 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11548 } 11549 11550 //===----------------------------------------------------------------------===// 11551 // Error recovery tests. 11552 //===----------------------------------------------------------------------===// 11553 11554 TEST_F(FormatTest, IncompleteParameterLists) { 11555 FormatStyle NoBinPacking = getLLVMStyle(); 11556 NoBinPacking.BinPackParameters = false; 11557 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 11558 " double *min_x,\n" 11559 " double *max_x,\n" 11560 " double *min_y,\n" 11561 " double *max_y,\n" 11562 " double *min_z,\n" 11563 " double *max_z, ) {}", 11564 NoBinPacking); 11565 } 11566 11567 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 11568 verifyFormat("void f() { return; }\n42"); 11569 verifyFormat("void f() {\n" 11570 " if (0)\n" 11571 " return;\n" 11572 "}\n" 11573 "42"); 11574 verifyFormat("void f() { return }\n42"); 11575 verifyFormat("void f() {\n" 11576 " if (0)\n" 11577 " return\n" 11578 "}\n" 11579 "42"); 11580 } 11581 11582 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 11583 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 11584 EXPECT_EQ("void f() {\n" 11585 " if (a)\n" 11586 " return\n" 11587 "}", 11588 format("void f ( ) { if ( a ) return }")); 11589 EXPECT_EQ("namespace N {\n" 11590 "void f()\n" 11591 "}", 11592 format("namespace N { void f() }")); 11593 EXPECT_EQ("namespace N {\n" 11594 "void f() {}\n" 11595 "void g()\n" 11596 "} // namespace N", 11597 format("namespace N { void f( ) { } void g( ) }")); 11598 } 11599 11600 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 11601 verifyFormat("int aaaaaaaa =\n" 11602 " // Overlylongcomment\n" 11603 " b;", 11604 getLLVMStyleWithColumns(20)); 11605 verifyFormat("function(\n" 11606 " ShortArgument,\n" 11607 " LoooooooooooongArgument);\n", 11608 getLLVMStyleWithColumns(20)); 11609 } 11610 11611 TEST_F(FormatTest, IncorrectAccessSpecifier) { 11612 verifyFormat("public:"); 11613 verifyFormat("class A {\n" 11614 "public\n" 11615 " void f() {}\n" 11616 "};"); 11617 verifyFormat("public\n" 11618 "int qwerty;"); 11619 verifyFormat("public\n" 11620 "B {}"); 11621 verifyFormat("public\n" 11622 "{}"); 11623 verifyFormat("public\n" 11624 "B { int x; }"); 11625 } 11626 11627 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 11628 verifyFormat("{"); 11629 verifyFormat("#})"); 11630 verifyNoCrash("(/**/[:!] ?[)."); 11631 } 11632 11633 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 11634 // Found by oss-fuzz: 11635 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 11636 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 11637 Style.ColumnLimit = 60; 11638 verifyNoCrash( 11639 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 11640 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 11641 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 11642 Style); 11643 } 11644 11645 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 11646 verifyFormat("do {\n}"); 11647 verifyFormat("do {\n}\n" 11648 "f();"); 11649 verifyFormat("do {\n}\n" 11650 "wheeee(fun);"); 11651 verifyFormat("do {\n" 11652 " f();\n" 11653 "}"); 11654 } 11655 11656 TEST_F(FormatTest, IncorrectCodeMissingParens) { 11657 verifyFormat("if {\n foo;\n foo();\n}"); 11658 verifyFormat("switch {\n foo;\n foo();\n}"); 11659 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 11660 verifyFormat("while {\n foo;\n foo();\n}"); 11661 verifyFormat("do {\n foo;\n foo();\n} while;"); 11662 } 11663 11664 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 11665 verifyIncompleteFormat("namespace {\n" 11666 "class Foo { Foo (\n" 11667 "};\n" 11668 "} // namespace"); 11669 } 11670 11671 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 11672 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 11673 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 11674 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 11675 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 11676 11677 EXPECT_EQ("{\n" 11678 " {\n" 11679 " breakme(\n" 11680 " qwe);\n" 11681 " }\n", 11682 format("{\n" 11683 " {\n" 11684 " breakme(qwe);\n" 11685 "}\n", 11686 getLLVMStyleWithColumns(10))); 11687 } 11688 11689 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 11690 verifyFormat("int x = {\n" 11691 " avariable,\n" 11692 " b(alongervariable)};", 11693 getLLVMStyleWithColumns(25)); 11694 } 11695 11696 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 11697 verifyFormat("return (a)(b){1, 2, 3};"); 11698 } 11699 11700 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 11701 verifyFormat("vector<int> x{1, 2, 3, 4};"); 11702 verifyFormat("vector<int> x{\n" 11703 " 1,\n" 11704 " 2,\n" 11705 " 3,\n" 11706 " 4,\n" 11707 "};"); 11708 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 11709 verifyFormat("f({1, 2});"); 11710 verifyFormat("auto v = Foo{-1};"); 11711 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 11712 verifyFormat("Class::Class : member{1, 2, 3} {}"); 11713 verifyFormat("new vector<int>{1, 2, 3};"); 11714 verifyFormat("new int[3]{1, 2, 3};"); 11715 verifyFormat("new int{1};"); 11716 verifyFormat("return {arg1, arg2};"); 11717 verifyFormat("return {arg1, SomeType{parameter}};"); 11718 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 11719 verifyFormat("new T{arg1, arg2};"); 11720 verifyFormat("f(MyMap[{composite, key}]);"); 11721 verifyFormat("class Class {\n" 11722 " T member = {arg1, arg2};\n" 11723 "};"); 11724 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 11725 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 11726 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 11727 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 11728 verifyFormat("int a = std::is_integral<int>{} + 0;"); 11729 11730 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11731 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11732 verifyFormat("auto i = decltype(x){};"); 11733 verifyFormat("auto i = typeof(x){};"); 11734 verifyFormat("auto i = _Atomic(x){};"); 11735 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 11736 verifyFormat("Node n{1, Node{1000}, //\n" 11737 " 2};"); 11738 verifyFormat("Aaaa aaaaaaa{\n" 11739 " {\n" 11740 " aaaa,\n" 11741 " },\n" 11742 "};"); 11743 verifyFormat("class C : public D {\n" 11744 " SomeClass SC{2};\n" 11745 "};"); 11746 verifyFormat("class C : public A {\n" 11747 " class D : public B {\n" 11748 " void f() { int i{2}; }\n" 11749 " };\n" 11750 "};"); 11751 verifyFormat("#define A {a, a},"); 11752 // Don't confuse braced list initializers with compound statements. 11753 verifyFormat( 11754 "class A {\n" 11755 " A() : a{} {}\n" 11756 " A(int b) : b(b) {}\n" 11757 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 11758 " int a, b;\n" 11759 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 11760 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 11761 "{}\n" 11762 "};"); 11763 11764 // Avoid breaking between equal sign and opening brace 11765 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 11766 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 11767 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 11768 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 11769 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 11770 " {\"ccccccccccccccccccccc\", 2}};", 11771 AvoidBreakingFirstArgument); 11772 11773 // Binpacking only if there is no trailing comma 11774 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 11775 " cccccccccc, dddddddddd};", 11776 getLLVMStyleWithColumns(50)); 11777 verifyFormat("const Aaaaaa aaaaa = {\n" 11778 " aaaaaaaaaaa,\n" 11779 " bbbbbbbbbbb,\n" 11780 " ccccccccccc,\n" 11781 " ddddddddddd,\n" 11782 "};", 11783 getLLVMStyleWithColumns(50)); 11784 11785 // Cases where distinguising braced lists and blocks is hard. 11786 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 11787 verifyFormat("void f() {\n" 11788 " return; // comment\n" 11789 "}\n" 11790 "SomeType t;"); 11791 verifyFormat("void f() {\n" 11792 " if (a) {\n" 11793 " f();\n" 11794 " }\n" 11795 "}\n" 11796 "SomeType t;"); 11797 11798 // In combination with BinPackArguments = false. 11799 FormatStyle NoBinPacking = getLLVMStyle(); 11800 NoBinPacking.BinPackArguments = false; 11801 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 11802 " bbbbb,\n" 11803 " ccccc,\n" 11804 " ddddd,\n" 11805 " eeeee,\n" 11806 " ffffff,\n" 11807 " ggggg,\n" 11808 " hhhhhh,\n" 11809 " iiiiii,\n" 11810 " jjjjjj,\n" 11811 " kkkkkk};", 11812 NoBinPacking); 11813 verifyFormat("const Aaaaaa aaaaa = {\n" 11814 " aaaaa,\n" 11815 " bbbbb,\n" 11816 " ccccc,\n" 11817 " ddddd,\n" 11818 " eeeee,\n" 11819 " ffffff,\n" 11820 " ggggg,\n" 11821 " hhhhhh,\n" 11822 " iiiiii,\n" 11823 " jjjjjj,\n" 11824 " kkkkkk,\n" 11825 "};", 11826 NoBinPacking); 11827 verifyFormat( 11828 "const Aaaaaa aaaaa = {\n" 11829 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 11830 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 11831 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 11832 "};", 11833 NoBinPacking); 11834 11835 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 11836 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 11837 " CDDDP83848_BMCR_REGISTER,\n" 11838 " CDDDP83848_BMSR_REGISTER,\n" 11839 " CDDDP83848_RBR_REGISTER};", 11840 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 11841 " CDDDP83848_BMSR_REGISTER,\n" 11842 " CDDDP83848_RBR_REGISTER};", 11843 NoBinPacking)); 11844 11845 // FIXME: The alignment of these trailing comments might be bad. Then again, 11846 // this might be utterly useless in real code. 11847 verifyFormat("Constructor::Constructor()\n" 11848 " : some_value{ //\n" 11849 " aaaaaaa, //\n" 11850 " bbbbbbb} {}"); 11851 11852 // In braced lists, the first comment is always assumed to belong to the 11853 // first element. Thus, it can be moved to the next or previous line as 11854 // appropriate. 11855 EXPECT_EQ("function({// First element:\n" 11856 " 1,\n" 11857 " // Second element:\n" 11858 " 2});", 11859 format("function({\n" 11860 " // First element:\n" 11861 " 1,\n" 11862 " // Second element:\n" 11863 " 2});")); 11864 EXPECT_EQ("std::vector<int> MyNumbers{\n" 11865 " // First element:\n" 11866 " 1,\n" 11867 " // Second element:\n" 11868 " 2};", 11869 format("std::vector<int> MyNumbers{// First element:\n" 11870 " 1,\n" 11871 " // Second element:\n" 11872 " 2};", 11873 getLLVMStyleWithColumns(30))); 11874 // A trailing comma should still lead to an enforced line break and no 11875 // binpacking. 11876 EXPECT_EQ("vector<int> SomeVector = {\n" 11877 " // aaa\n" 11878 " 1,\n" 11879 " 2,\n" 11880 "};", 11881 format("vector<int> SomeVector = { // aaa\n" 11882 " 1, 2, };")); 11883 11884 // C++11 brace initializer list l-braces should not be treated any differently 11885 // when breaking before lambda bodies is enabled 11886 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 11887 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 11888 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 11889 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 11890 verifyFormat( 11891 "std::runtime_error{\n" 11892 " \"Long string which will force a break onto the next line...\"};", 11893 BreakBeforeLambdaBody); 11894 11895 FormatStyle ExtraSpaces = getLLVMStyle(); 11896 ExtraSpaces.Cpp11BracedListStyle = false; 11897 ExtraSpaces.ColumnLimit = 75; 11898 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 11899 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 11900 verifyFormat("f({ 1, 2 });", ExtraSpaces); 11901 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 11902 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 11903 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 11904 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 11905 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 11906 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 11907 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 11908 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 11909 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 11910 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 11911 verifyFormat("class Class {\n" 11912 " T member = { arg1, arg2 };\n" 11913 "};", 11914 ExtraSpaces); 11915 verifyFormat( 11916 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11917 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 11918 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 11919 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 11920 ExtraSpaces); 11921 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 11922 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 11923 ExtraSpaces); 11924 verifyFormat( 11925 "someFunction(OtherParam,\n" 11926 " BracedList{ // comment 1 (Forcing interesting break)\n" 11927 " param1, param2,\n" 11928 " // comment 2\n" 11929 " param3, param4 });", 11930 ExtraSpaces); 11931 verifyFormat( 11932 "std::this_thread::sleep_for(\n" 11933 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 11934 ExtraSpaces); 11935 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 11936 " aaaaaaa,\n" 11937 " aaaaaaaaaa,\n" 11938 " aaaaa,\n" 11939 " aaaaaaaaaaaaaaa,\n" 11940 " aaa,\n" 11941 " aaaaaaaaaa,\n" 11942 " a,\n" 11943 " aaaaaaaaaaaaaaaaaaaaa,\n" 11944 " aaaaaaaaaaaa,\n" 11945 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 11946 " aaaaaaa,\n" 11947 " a};"); 11948 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 11949 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 11950 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 11951 11952 // Avoid breaking between initializer/equal sign and opening brace 11953 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 11954 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 11955 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 11956 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 11957 " { \"ccccccccccccccccccccc\", 2 }\n" 11958 "};", 11959 ExtraSpaces); 11960 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 11961 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 11962 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 11963 " { \"ccccccccccccccccccccc\", 2 }\n" 11964 "};", 11965 ExtraSpaces); 11966 11967 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 11968 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 11969 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 11970 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 11971 11972 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 11973 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 11974 SpaceBetweenBraces.SpacesInParentheses = true; 11975 SpaceBetweenBraces.SpacesInSquareBrackets = true; 11976 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 11977 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 11978 verifyFormat("vector< int > x{ // comment 1\n" 11979 " 1, 2, 3, 4 };", 11980 SpaceBetweenBraces); 11981 SpaceBetweenBraces.ColumnLimit = 20; 11982 EXPECT_EQ("vector< int > x{\n" 11983 " 1, 2, 3, 4 };", 11984 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 11985 SpaceBetweenBraces.ColumnLimit = 24; 11986 EXPECT_EQ("vector< int > x{ 1, 2,\n" 11987 " 3, 4 };", 11988 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 11989 EXPECT_EQ("vector< int > x{\n" 11990 " 1,\n" 11991 " 2,\n" 11992 " 3,\n" 11993 " 4,\n" 11994 "};", 11995 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 11996 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 11997 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 11998 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 11999 } 12000 12001 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12002 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12003 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12004 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12005 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12006 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12007 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12008 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12009 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12010 " 1, 22, 333, 4444, 55555, //\n" 12011 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12012 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12013 verifyFormat( 12014 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12015 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12016 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12017 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12018 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12019 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12020 " 7777777};"); 12021 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12022 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12023 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12024 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12025 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12026 " // Separating comment.\n" 12027 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12028 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12029 " // Leading comment\n" 12030 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12031 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12032 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12033 " 1, 1, 1, 1};", 12034 getLLVMStyleWithColumns(39)); 12035 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12036 " 1, 1, 1, 1};", 12037 getLLVMStyleWithColumns(38)); 12038 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12039 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12040 getLLVMStyleWithColumns(43)); 12041 verifyFormat( 12042 "static unsigned SomeValues[10][3] = {\n" 12043 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12044 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12045 verifyFormat("static auto fields = new vector<string>{\n" 12046 " \"aaaaaaaaaaaaa\",\n" 12047 " \"aaaaaaaaaaaaa\",\n" 12048 " \"aaaaaaaaaaaa\",\n" 12049 " \"aaaaaaaaaaaaaa\",\n" 12050 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12051 " \"aaaaaaaaaaaa\",\n" 12052 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12053 "};"); 12054 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12055 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12056 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12057 " 3, cccccccccccccccccccccc};", 12058 getLLVMStyleWithColumns(60)); 12059 12060 // Trailing commas. 12061 verifyFormat("vector<int> x = {\n" 12062 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12063 "};", 12064 getLLVMStyleWithColumns(39)); 12065 verifyFormat("vector<int> x = {\n" 12066 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12067 "};", 12068 getLLVMStyleWithColumns(39)); 12069 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12070 " 1, 1, 1, 1,\n" 12071 " /**/ /**/};", 12072 getLLVMStyleWithColumns(39)); 12073 12074 // Trailing comment in the first line. 12075 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12076 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12077 " 111111111, 222222222, 3333333333, 444444444, //\n" 12078 " 11111111, 22222222, 333333333, 44444444};"); 12079 // Trailing comment in the last line. 12080 verifyFormat("int aaaaa[] = {\n" 12081 " 1, 2, 3, // comment\n" 12082 " 4, 5, 6 // comment\n" 12083 "};"); 12084 12085 // With nested lists, we should either format one item per line or all nested 12086 // lists one on line. 12087 // FIXME: For some nested lists, we can do better. 12088 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12089 " {aaaaaaaaaaaaaaaaaaa},\n" 12090 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12091 " {aaaaaaaaaaaaaaaaa}};", 12092 getLLVMStyleWithColumns(60)); 12093 verifyFormat( 12094 "SomeStruct my_struct_array = {\n" 12095 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12096 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12097 " {aaa, aaa},\n" 12098 " {aaa, aaa},\n" 12099 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12100 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12101 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12102 12103 // No column layout should be used here. 12104 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12105 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12106 12107 verifyNoCrash("a<,"); 12108 12109 // No braced initializer here. 12110 verifyFormat("void f() {\n" 12111 " struct Dummy {};\n" 12112 " f(v);\n" 12113 "}"); 12114 12115 // Long lists should be formatted in columns even if they are nested. 12116 verifyFormat( 12117 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12118 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12119 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12120 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12121 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12122 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12123 12124 // Allow "single-column" layout even if that violates the column limit. There 12125 // isn't going to be a better way. 12126 verifyFormat("std::vector<int> a = {\n" 12127 " aaaaaaaa,\n" 12128 " aaaaaaaa,\n" 12129 " aaaaaaaa,\n" 12130 " aaaaaaaa,\n" 12131 " aaaaaaaaaa,\n" 12132 " aaaaaaaa,\n" 12133 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12134 getLLVMStyleWithColumns(30)); 12135 verifyFormat("vector<int> aaaa = {\n" 12136 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12137 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12138 " aaaaaa.aaaaaaa,\n" 12139 " aaaaaa.aaaaaaa,\n" 12140 " aaaaaa.aaaaaaa,\n" 12141 " aaaaaa.aaaaaaa,\n" 12142 "};"); 12143 12144 // Don't create hanging lists. 12145 verifyFormat("someFunction(Param, {List1, List2,\n" 12146 " List3});", 12147 getLLVMStyleWithColumns(35)); 12148 verifyFormat("someFunction(Param, Param,\n" 12149 " {List1, List2,\n" 12150 " List3});", 12151 getLLVMStyleWithColumns(35)); 12152 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12153 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12154 } 12155 12156 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12157 FormatStyle DoNotMerge = getLLVMStyle(); 12158 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12159 12160 verifyFormat("void f() { return 42; }"); 12161 verifyFormat("void f() {\n" 12162 " return 42;\n" 12163 "}", 12164 DoNotMerge); 12165 verifyFormat("void f() {\n" 12166 " // Comment\n" 12167 "}"); 12168 verifyFormat("{\n" 12169 "#error {\n" 12170 " int a;\n" 12171 "}"); 12172 verifyFormat("{\n" 12173 " int a;\n" 12174 "#error {\n" 12175 "}"); 12176 verifyFormat("void f() {} // comment"); 12177 verifyFormat("void f() { int a; } // comment"); 12178 verifyFormat("void f() {\n" 12179 "} // comment", 12180 DoNotMerge); 12181 verifyFormat("void f() {\n" 12182 " int a;\n" 12183 "} // comment", 12184 DoNotMerge); 12185 verifyFormat("void f() {\n" 12186 "} // comment", 12187 getLLVMStyleWithColumns(15)); 12188 12189 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12190 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12191 12192 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12193 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12194 verifyFormat("class C {\n" 12195 " C()\n" 12196 " : iiiiiiii(nullptr),\n" 12197 " kkkkkkk(nullptr),\n" 12198 " mmmmmmm(nullptr),\n" 12199 " nnnnnnn(nullptr) {}\n" 12200 "};", 12201 getGoogleStyle()); 12202 12203 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12204 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12205 EXPECT_EQ("class C {\n" 12206 " A() : b(0) {}\n" 12207 "};", 12208 format("class C{A():b(0){}};", NoColumnLimit)); 12209 EXPECT_EQ("A()\n" 12210 " : b(0) {\n" 12211 "}", 12212 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12213 12214 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12215 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12216 FormatStyle::SFS_None; 12217 EXPECT_EQ("A()\n" 12218 " : b(0) {\n" 12219 "}", 12220 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12221 EXPECT_EQ("A()\n" 12222 " : b(0) {\n" 12223 "}", 12224 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12225 12226 verifyFormat("#define A \\\n" 12227 " void f() { \\\n" 12228 " int i; \\\n" 12229 " }", 12230 getLLVMStyleWithColumns(20)); 12231 verifyFormat("#define A \\\n" 12232 " void f() { int i; }", 12233 getLLVMStyleWithColumns(21)); 12234 verifyFormat("#define A \\\n" 12235 " void f() { \\\n" 12236 " int i; \\\n" 12237 " } \\\n" 12238 " int j;", 12239 getLLVMStyleWithColumns(22)); 12240 verifyFormat("#define A \\\n" 12241 " void f() { int i; } \\\n" 12242 " int j;", 12243 getLLVMStyleWithColumns(23)); 12244 } 12245 12246 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12247 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12248 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12249 verifyFormat("class C {\n" 12250 " int f() {}\n" 12251 "};", 12252 MergeEmptyOnly); 12253 verifyFormat("class C {\n" 12254 " int f() {\n" 12255 " return 42;\n" 12256 " }\n" 12257 "};", 12258 MergeEmptyOnly); 12259 verifyFormat("int f() {}", MergeEmptyOnly); 12260 verifyFormat("int f() {\n" 12261 " return 42;\n" 12262 "}", 12263 MergeEmptyOnly); 12264 12265 // Also verify behavior when BraceWrapping.AfterFunction = true 12266 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12267 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12268 verifyFormat("int f() {}", MergeEmptyOnly); 12269 verifyFormat("class C {\n" 12270 " int f() {}\n" 12271 "};", 12272 MergeEmptyOnly); 12273 } 12274 12275 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12276 FormatStyle MergeInlineOnly = getLLVMStyle(); 12277 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12278 verifyFormat("class C {\n" 12279 " int f() { return 42; }\n" 12280 "};", 12281 MergeInlineOnly); 12282 verifyFormat("int f() {\n" 12283 " return 42;\n" 12284 "}", 12285 MergeInlineOnly); 12286 12287 // SFS_Inline implies SFS_Empty 12288 verifyFormat("class C {\n" 12289 " int f() {}\n" 12290 "};", 12291 MergeInlineOnly); 12292 verifyFormat("int f() {}", MergeInlineOnly); 12293 12294 // Also verify behavior when BraceWrapping.AfterFunction = true 12295 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12296 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12297 verifyFormat("class C {\n" 12298 " int f() { return 42; }\n" 12299 "};", 12300 MergeInlineOnly); 12301 verifyFormat("int f()\n" 12302 "{\n" 12303 " return 42;\n" 12304 "}", 12305 MergeInlineOnly); 12306 12307 // SFS_Inline implies SFS_Empty 12308 verifyFormat("int f() {}", MergeInlineOnly); 12309 verifyFormat("class C {\n" 12310 " int f() {}\n" 12311 "};", 12312 MergeInlineOnly); 12313 } 12314 12315 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12316 FormatStyle MergeInlineOnly = getLLVMStyle(); 12317 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12318 FormatStyle::SFS_InlineOnly; 12319 verifyFormat("class C {\n" 12320 " int f() { return 42; }\n" 12321 "};", 12322 MergeInlineOnly); 12323 verifyFormat("int f() {\n" 12324 " return 42;\n" 12325 "}", 12326 MergeInlineOnly); 12327 12328 // SFS_InlineOnly does not imply SFS_Empty 12329 verifyFormat("class C {\n" 12330 " int f() {}\n" 12331 "};", 12332 MergeInlineOnly); 12333 verifyFormat("int f() {\n" 12334 "}", 12335 MergeInlineOnly); 12336 12337 // Also verify behavior when BraceWrapping.AfterFunction = true 12338 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12339 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12340 verifyFormat("class C {\n" 12341 " int f() { return 42; }\n" 12342 "};", 12343 MergeInlineOnly); 12344 verifyFormat("int f()\n" 12345 "{\n" 12346 " return 42;\n" 12347 "}", 12348 MergeInlineOnly); 12349 12350 // SFS_InlineOnly does not imply SFS_Empty 12351 verifyFormat("int f()\n" 12352 "{\n" 12353 "}", 12354 MergeInlineOnly); 12355 verifyFormat("class C {\n" 12356 " int f() {}\n" 12357 "};", 12358 MergeInlineOnly); 12359 } 12360 12361 TEST_F(FormatTest, SplitEmptyFunction) { 12362 FormatStyle Style = getLLVMStyleWithColumns(40); 12363 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12364 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12365 Style.BraceWrapping.AfterFunction = true; 12366 Style.BraceWrapping.SplitEmptyFunction = false; 12367 12368 verifyFormat("int f()\n" 12369 "{}", 12370 Style); 12371 verifyFormat("int f()\n" 12372 "{\n" 12373 " return 42;\n" 12374 "}", 12375 Style); 12376 verifyFormat("int f()\n" 12377 "{\n" 12378 " // some comment\n" 12379 "}", 12380 Style); 12381 12382 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12383 verifyFormat("int f() {}", Style); 12384 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12385 "{}", 12386 Style); 12387 verifyFormat("int f()\n" 12388 "{\n" 12389 " return 0;\n" 12390 "}", 12391 Style); 12392 12393 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12394 verifyFormat("class Foo {\n" 12395 " int f() {}\n" 12396 "};\n", 12397 Style); 12398 verifyFormat("class Foo {\n" 12399 " int f() { return 0; }\n" 12400 "};\n", 12401 Style); 12402 verifyFormat("class Foo {\n" 12403 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12404 " {}\n" 12405 "};\n", 12406 Style); 12407 verifyFormat("class Foo {\n" 12408 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12409 " {\n" 12410 " return 0;\n" 12411 " }\n" 12412 "};\n", 12413 Style); 12414 12415 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12416 verifyFormat("int f() {}", Style); 12417 verifyFormat("int f() { return 0; }", Style); 12418 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12419 "{}", 12420 Style); 12421 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12422 "{\n" 12423 " return 0;\n" 12424 "}", 12425 Style); 12426 } 12427 12428 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12429 FormatStyle Style = getLLVMStyleWithColumns(40); 12430 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12431 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12432 Style.BraceWrapping.AfterFunction = true; 12433 Style.BraceWrapping.SplitEmptyFunction = true; 12434 Style.BraceWrapping.SplitEmptyRecord = false; 12435 12436 verifyFormat("class C {};", Style); 12437 verifyFormat("struct C {};", Style); 12438 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12439 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12440 "{\n" 12441 "}", 12442 Style); 12443 verifyFormat("class C {\n" 12444 " C()\n" 12445 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12446 " bbbbbbbbbbbbbbbbbbb()\n" 12447 " {\n" 12448 " }\n" 12449 " void\n" 12450 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12451 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12452 " {\n" 12453 " }\n" 12454 "};", 12455 Style); 12456 } 12457 12458 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12459 FormatStyle Style = getLLVMStyle(); 12460 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12461 verifyFormat("#ifdef A\n" 12462 "int f() {}\n" 12463 "#else\n" 12464 "int g() {}\n" 12465 "#endif", 12466 Style); 12467 } 12468 12469 TEST_F(FormatTest, SplitEmptyClass) { 12470 FormatStyle Style = getLLVMStyle(); 12471 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12472 Style.BraceWrapping.AfterClass = true; 12473 Style.BraceWrapping.SplitEmptyRecord = false; 12474 12475 verifyFormat("class Foo\n" 12476 "{};", 12477 Style); 12478 verifyFormat("/* something */ class Foo\n" 12479 "{};", 12480 Style); 12481 verifyFormat("template <typename X> class Foo\n" 12482 "{};", 12483 Style); 12484 verifyFormat("class Foo\n" 12485 "{\n" 12486 " Foo();\n" 12487 "};", 12488 Style); 12489 verifyFormat("typedef class Foo\n" 12490 "{\n" 12491 "} Foo_t;", 12492 Style); 12493 12494 Style.BraceWrapping.SplitEmptyRecord = true; 12495 Style.BraceWrapping.AfterStruct = true; 12496 verifyFormat("class rep\n" 12497 "{\n" 12498 "};", 12499 Style); 12500 verifyFormat("struct rep\n" 12501 "{\n" 12502 "};", 12503 Style); 12504 verifyFormat("template <typename T> class rep\n" 12505 "{\n" 12506 "};", 12507 Style); 12508 verifyFormat("template <typename T> struct rep\n" 12509 "{\n" 12510 "};", 12511 Style); 12512 verifyFormat("class rep\n" 12513 "{\n" 12514 " int x;\n" 12515 "};", 12516 Style); 12517 verifyFormat("struct rep\n" 12518 "{\n" 12519 " int x;\n" 12520 "};", 12521 Style); 12522 verifyFormat("template <typename T> class rep\n" 12523 "{\n" 12524 " int x;\n" 12525 "};", 12526 Style); 12527 verifyFormat("template <typename T> struct rep\n" 12528 "{\n" 12529 " int x;\n" 12530 "};", 12531 Style); 12532 verifyFormat("template <typename T> class rep // Foo\n" 12533 "{\n" 12534 " int x;\n" 12535 "};", 12536 Style); 12537 verifyFormat("template <typename T> struct rep // Bar\n" 12538 "{\n" 12539 " int x;\n" 12540 "};", 12541 Style); 12542 12543 verifyFormat("template <typename T> class rep<T>\n" 12544 "{\n" 12545 " int x;\n" 12546 "};", 12547 Style); 12548 12549 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12550 "{\n" 12551 " int x;\n" 12552 "};", 12553 Style); 12554 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12555 "{\n" 12556 "};", 12557 Style); 12558 12559 verifyFormat("#include \"stdint.h\"\n" 12560 "namespace rep {}", 12561 Style); 12562 verifyFormat("#include <stdint.h>\n" 12563 "namespace rep {}", 12564 Style); 12565 verifyFormat("#include <stdint.h>\n" 12566 "namespace rep {}", 12567 "#include <stdint.h>\n" 12568 "namespace rep {\n" 12569 "\n" 12570 "\n" 12571 "}", 12572 Style); 12573 } 12574 12575 TEST_F(FormatTest, SplitEmptyStruct) { 12576 FormatStyle Style = getLLVMStyle(); 12577 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12578 Style.BraceWrapping.AfterStruct = true; 12579 Style.BraceWrapping.SplitEmptyRecord = false; 12580 12581 verifyFormat("struct Foo\n" 12582 "{};", 12583 Style); 12584 verifyFormat("/* something */ struct Foo\n" 12585 "{};", 12586 Style); 12587 verifyFormat("template <typename X> struct Foo\n" 12588 "{};", 12589 Style); 12590 verifyFormat("struct Foo\n" 12591 "{\n" 12592 " Foo();\n" 12593 "};", 12594 Style); 12595 verifyFormat("typedef struct Foo\n" 12596 "{\n" 12597 "} Foo_t;", 12598 Style); 12599 // typedef struct Bar {} Bar_t; 12600 } 12601 12602 TEST_F(FormatTest, SplitEmptyUnion) { 12603 FormatStyle Style = getLLVMStyle(); 12604 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12605 Style.BraceWrapping.AfterUnion = true; 12606 Style.BraceWrapping.SplitEmptyRecord = false; 12607 12608 verifyFormat("union Foo\n" 12609 "{};", 12610 Style); 12611 verifyFormat("/* something */ union Foo\n" 12612 "{};", 12613 Style); 12614 verifyFormat("union Foo\n" 12615 "{\n" 12616 " A,\n" 12617 "};", 12618 Style); 12619 verifyFormat("typedef union Foo\n" 12620 "{\n" 12621 "} Foo_t;", 12622 Style); 12623 } 12624 12625 TEST_F(FormatTest, SplitEmptyNamespace) { 12626 FormatStyle Style = getLLVMStyle(); 12627 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12628 Style.BraceWrapping.AfterNamespace = true; 12629 Style.BraceWrapping.SplitEmptyNamespace = false; 12630 12631 verifyFormat("namespace Foo\n" 12632 "{};", 12633 Style); 12634 verifyFormat("/* something */ namespace Foo\n" 12635 "{};", 12636 Style); 12637 verifyFormat("inline namespace Foo\n" 12638 "{};", 12639 Style); 12640 verifyFormat("/* something */ inline namespace Foo\n" 12641 "{};", 12642 Style); 12643 verifyFormat("export namespace Foo\n" 12644 "{};", 12645 Style); 12646 verifyFormat("namespace Foo\n" 12647 "{\n" 12648 "void Bar();\n" 12649 "};", 12650 Style); 12651 } 12652 12653 TEST_F(FormatTest, NeverMergeShortRecords) { 12654 FormatStyle Style = getLLVMStyle(); 12655 12656 verifyFormat("class Foo {\n" 12657 " Foo();\n" 12658 "};", 12659 Style); 12660 verifyFormat("typedef class Foo {\n" 12661 " Foo();\n" 12662 "} Foo_t;", 12663 Style); 12664 verifyFormat("struct Foo {\n" 12665 " Foo();\n" 12666 "};", 12667 Style); 12668 verifyFormat("typedef struct Foo {\n" 12669 " Foo();\n" 12670 "} Foo_t;", 12671 Style); 12672 verifyFormat("union Foo {\n" 12673 " A,\n" 12674 "};", 12675 Style); 12676 verifyFormat("typedef union Foo {\n" 12677 " A,\n" 12678 "} Foo_t;", 12679 Style); 12680 verifyFormat("namespace Foo {\n" 12681 "void Bar();\n" 12682 "};", 12683 Style); 12684 12685 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12686 Style.BraceWrapping.AfterClass = true; 12687 Style.BraceWrapping.AfterStruct = true; 12688 Style.BraceWrapping.AfterUnion = true; 12689 Style.BraceWrapping.AfterNamespace = true; 12690 verifyFormat("class Foo\n" 12691 "{\n" 12692 " Foo();\n" 12693 "};", 12694 Style); 12695 verifyFormat("typedef class Foo\n" 12696 "{\n" 12697 " Foo();\n" 12698 "} Foo_t;", 12699 Style); 12700 verifyFormat("struct Foo\n" 12701 "{\n" 12702 " Foo();\n" 12703 "};", 12704 Style); 12705 verifyFormat("typedef struct Foo\n" 12706 "{\n" 12707 " Foo();\n" 12708 "} Foo_t;", 12709 Style); 12710 verifyFormat("union Foo\n" 12711 "{\n" 12712 " A,\n" 12713 "};", 12714 Style); 12715 verifyFormat("typedef union Foo\n" 12716 "{\n" 12717 " A,\n" 12718 "} Foo_t;", 12719 Style); 12720 verifyFormat("namespace Foo\n" 12721 "{\n" 12722 "void Bar();\n" 12723 "};", 12724 Style); 12725 } 12726 12727 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 12728 // Elaborate type variable declarations. 12729 verifyFormat("struct foo a = {bar};\nint n;"); 12730 verifyFormat("class foo a = {bar};\nint n;"); 12731 verifyFormat("union foo a = {bar};\nint n;"); 12732 12733 // Elaborate types inside function definitions. 12734 verifyFormat("struct foo f() {}\nint n;"); 12735 verifyFormat("class foo f() {}\nint n;"); 12736 verifyFormat("union foo f() {}\nint n;"); 12737 12738 // Templates. 12739 verifyFormat("template <class X> void f() {}\nint n;"); 12740 verifyFormat("template <struct X> void f() {}\nint n;"); 12741 verifyFormat("template <union X> void f() {}\nint n;"); 12742 12743 // Actual definitions... 12744 verifyFormat("struct {\n} n;"); 12745 verifyFormat( 12746 "template <template <class T, class Y>, class Z> class X {\n} n;"); 12747 verifyFormat("union Z {\n int n;\n} x;"); 12748 verifyFormat("class MACRO Z {\n} n;"); 12749 verifyFormat("class MACRO(X) Z {\n} n;"); 12750 verifyFormat("class __attribute__(X) Z {\n} n;"); 12751 verifyFormat("class __declspec(X) Z {\n} n;"); 12752 verifyFormat("class A##B##C {\n} n;"); 12753 verifyFormat("class alignas(16) Z {\n} n;"); 12754 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 12755 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 12756 12757 // Redefinition from nested context: 12758 verifyFormat("class A::B::C {\n} n;"); 12759 12760 // Template definitions. 12761 verifyFormat( 12762 "template <typename F>\n" 12763 "Matcher(const Matcher<F> &Other,\n" 12764 " typename enable_if_c<is_base_of<F, T>::value &&\n" 12765 " !is_same<F, T>::value>::type * = 0)\n" 12766 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 12767 12768 // FIXME: This is still incorrectly handled at the formatter side. 12769 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 12770 verifyFormat("int i = SomeFunction(a<b, a> b);"); 12771 12772 // FIXME: 12773 // This now gets parsed incorrectly as class definition. 12774 // verifyFormat("class A<int> f() {\n}\nint n;"); 12775 12776 // Elaborate types where incorrectly parsing the structural element would 12777 // break the indent. 12778 verifyFormat("if (true)\n" 12779 " class X x;\n" 12780 "else\n" 12781 " f();\n"); 12782 12783 // This is simply incomplete. Formatting is not important, but must not crash. 12784 verifyFormat("class A:"); 12785 } 12786 12787 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 12788 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 12789 format("#error Leave all white!!!!! space* alone!\n")); 12790 EXPECT_EQ( 12791 "#warning Leave all white!!!!! space* alone!\n", 12792 format("#warning Leave all white!!!!! space* alone!\n")); 12793 EXPECT_EQ("#error 1", format(" # error 1")); 12794 EXPECT_EQ("#warning 1", format(" # warning 1")); 12795 } 12796 12797 TEST_F(FormatTest, FormatHashIfExpressions) { 12798 verifyFormat("#if AAAA && BBBB"); 12799 verifyFormat("#if (AAAA && BBBB)"); 12800 verifyFormat("#elif (AAAA && BBBB)"); 12801 // FIXME: Come up with a better indentation for #elif. 12802 verifyFormat( 12803 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 12804 " defined(BBBBBBBB)\n" 12805 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 12806 " defined(BBBBBBBB)\n" 12807 "#endif", 12808 getLLVMStyleWithColumns(65)); 12809 } 12810 12811 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 12812 FormatStyle AllowsMergedIf = getGoogleStyle(); 12813 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 12814 FormatStyle::SIS_WithoutElse; 12815 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 12816 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 12817 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 12818 EXPECT_EQ("if (true) return 42;", 12819 format("if (true)\nreturn 42;", AllowsMergedIf)); 12820 FormatStyle ShortMergedIf = AllowsMergedIf; 12821 ShortMergedIf.ColumnLimit = 25; 12822 verifyFormat("#define A \\\n" 12823 " if (true) return 42;", 12824 ShortMergedIf); 12825 verifyFormat("#define A \\\n" 12826 " f(); \\\n" 12827 " if (true)\n" 12828 "#define B", 12829 ShortMergedIf); 12830 verifyFormat("#define A \\\n" 12831 " f(); \\\n" 12832 " if (true)\n" 12833 "g();", 12834 ShortMergedIf); 12835 verifyFormat("{\n" 12836 "#ifdef A\n" 12837 " // Comment\n" 12838 " if (true) continue;\n" 12839 "#endif\n" 12840 " // Comment\n" 12841 " if (true) continue;\n" 12842 "}", 12843 ShortMergedIf); 12844 ShortMergedIf.ColumnLimit = 33; 12845 verifyFormat("#define A \\\n" 12846 " if constexpr (true) return 42;", 12847 ShortMergedIf); 12848 verifyFormat("#define A \\\n" 12849 " if CONSTEXPR (true) return 42;", 12850 ShortMergedIf); 12851 ShortMergedIf.ColumnLimit = 29; 12852 verifyFormat("#define A \\\n" 12853 " if (aaaaaaaaaa) return 1; \\\n" 12854 " return 2;", 12855 ShortMergedIf); 12856 ShortMergedIf.ColumnLimit = 28; 12857 verifyFormat("#define A \\\n" 12858 " if (aaaaaaaaaa) \\\n" 12859 " return 1; \\\n" 12860 " return 2;", 12861 ShortMergedIf); 12862 verifyFormat("#define A \\\n" 12863 " if constexpr (aaaaaaa) \\\n" 12864 " return 1; \\\n" 12865 " return 2;", 12866 ShortMergedIf); 12867 verifyFormat("#define A \\\n" 12868 " if CONSTEXPR (aaaaaaa) \\\n" 12869 " return 1; \\\n" 12870 " return 2;", 12871 ShortMergedIf); 12872 } 12873 12874 TEST_F(FormatTest, FormatStarDependingOnContext) { 12875 verifyFormat("void f(int *a);"); 12876 verifyFormat("void f() { f(fint * b); }"); 12877 verifyFormat("class A {\n void f(int *a);\n};"); 12878 verifyFormat("class A {\n int *a;\n};"); 12879 verifyFormat("namespace a {\n" 12880 "namespace b {\n" 12881 "class A {\n" 12882 " void f() {}\n" 12883 " int *a;\n" 12884 "};\n" 12885 "} // namespace b\n" 12886 "} // namespace a"); 12887 } 12888 12889 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 12890 verifyFormat("while"); 12891 verifyFormat("operator"); 12892 } 12893 12894 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 12895 // This code would be painfully slow to format if we didn't skip it. 12896 std::string Code("A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" // 20x 12897 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12898 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12899 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12900 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12901 "A(1, 1)\n" 12902 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 12903 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12904 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12905 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12906 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12907 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12908 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12909 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12910 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12911 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 12912 // Deeply nested part is untouched, rest is formatted. 12913 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 12914 format(std::string("int i;\n") + Code + "int j;\n", 12915 getLLVMStyle(), SC_ExpectIncomplete)); 12916 } 12917 12918 //===----------------------------------------------------------------------===// 12919 // Objective-C tests. 12920 //===----------------------------------------------------------------------===// 12921 12922 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 12923 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 12924 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 12925 format("-(NSUInteger)indexOfObject:(id)anObject;")); 12926 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 12927 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 12928 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 12929 format("-(NSInteger)Method3:(id)anObject;")); 12930 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 12931 format("-(NSInteger)Method4:(id)anObject;")); 12932 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 12933 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 12934 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 12935 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 12936 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 12937 "forAllCells:(BOOL)flag;", 12938 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 12939 "forAllCells:(BOOL)flag;")); 12940 12941 // Very long objectiveC method declaration. 12942 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 12943 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 12944 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 12945 " inRange:(NSRange)range\n" 12946 " outRange:(NSRange)out_range\n" 12947 " outRange1:(NSRange)out_range1\n" 12948 " outRange2:(NSRange)out_range2\n" 12949 " outRange3:(NSRange)out_range3\n" 12950 " outRange4:(NSRange)out_range4\n" 12951 " outRange5:(NSRange)out_range5\n" 12952 " outRange6:(NSRange)out_range6\n" 12953 " outRange7:(NSRange)out_range7\n" 12954 " outRange8:(NSRange)out_range8\n" 12955 " outRange9:(NSRange)out_range9;"); 12956 12957 // When the function name has to be wrapped. 12958 FormatStyle Style = getLLVMStyle(); 12959 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 12960 // and always indents instead. 12961 Style.IndentWrappedFunctionNames = false; 12962 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 12963 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 12964 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 12965 "}", 12966 Style); 12967 Style.IndentWrappedFunctionNames = true; 12968 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 12969 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 12970 " anotherName:(NSString)dddddddddddddd {\n" 12971 "}", 12972 Style); 12973 12974 verifyFormat("- (int)sum:(vector<int>)numbers;"); 12975 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 12976 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 12977 // protocol lists (but not for template classes): 12978 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 12979 12980 verifyFormat("- (int (*)())foo:(int (*)())f;"); 12981 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 12982 12983 // If there's no return type (very rare in practice!), LLVM and Google style 12984 // agree. 12985 verifyFormat("- foo;"); 12986 verifyFormat("- foo:(int)f;"); 12987 verifyGoogleFormat("- foo:(int)foo;"); 12988 } 12989 12990 TEST_F(FormatTest, BreaksStringLiterals) { 12991 EXPECT_EQ("\"some text \"\n" 12992 "\"other\";", 12993 format("\"some text other\";", getLLVMStyleWithColumns(12))); 12994 EXPECT_EQ("\"some text \"\n" 12995 "\"other\";", 12996 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 12997 EXPECT_EQ( 12998 "#define A \\\n" 12999 " \"some \" \\\n" 13000 " \"text \" \\\n" 13001 " \"other\";", 13002 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13003 EXPECT_EQ( 13004 "#define A \\\n" 13005 " \"so \" \\\n" 13006 " \"text \" \\\n" 13007 " \"other\";", 13008 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13009 13010 EXPECT_EQ("\"some text\"", 13011 format("\"some text\"", getLLVMStyleWithColumns(1))); 13012 EXPECT_EQ("\"some text\"", 13013 format("\"some text\"", getLLVMStyleWithColumns(11))); 13014 EXPECT_EQ("\"some \"\n" 13015 "\"text\"", 13016 format("\"some text\"", getLLVMStyleWithColumns(10))); 13017 EXPECT_EQ("\"some \"\n" 13018 "\"text\"", 13019 format("\"some text\"", getLLVMStyleWithColumns(7))); 13020 EXPECT_EQ("\"some\"\n" 13021 "\" tex\"\n" 13022 "\"t\"", 13023 format("\"some text\"", getLLVMStyleWithColumns(6))); 13024 EXPECT_EQ("\"some\"\n" 13025 "\" tex\"\n" 13026 "\" and\"", 13027 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13028 EXPECT_EQ("\"some\"\n" 13029 "\"/tex\"\n" 13030 "\"/and\"", 13031 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13032 13033 EXPECT_EQ("variable =\n" 13034 " \"long string \"\n" 13035 " \"literal\";", 13036 format("variable = \"long string literal\";", 13037 getLLVMStyleWithColumns(20))); 13038 13039 EXPECT_EQ("variable = f(\n" 13040 " \"long string \"\n" 13041 " \"literal\",\n" 13042 " short,\n" 13043 " loooooooooooooooooooong);", 13044 format("variable = f(\"long string literal\", short, " 13045 "loooooooooooooooooooong);", 13046 getLLVMStyleWithColumns(20))); 13047 13048 EXPECT_EQ( 13049 "f(g(\"long string \"\n" 13050 " \"literal\"),\n" 13051 " b);", 13052 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13053 EXPECT_EQ("f(g(\"long string \"\n" 13054 " \"literal\",\n" 13055 " a),\n" 13056 " b);", 13057 format("f(g(\"long string literal\", a), b);", 13058 getLLVMStyleWithColumns(20))); 13059 EXPECT_EQ( 13060 "f(\"one two\".split(\n" 13061 " variable));", 13062 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13063 EXPECT_EQ("f(\"one two three four five six \"\n" 13064 " \"seven\".split(\n" 13065 " really_looooong_variable));", 13066 format("f(\"one two three four five six seven\"." 13067 "split(really_looooong_variable));", 13068 getLLVMStyleWithColumns(33))); 13069 13070 EXPECT_EQ("f(\"some \"\n" 13071 " \"text\",\n" 13072 " other);", 13073 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13074 13075 // Only break as a last resort. 13076 verifyFormat( 13077 "aaaaaaaaaaaaaaaaaaaa(\n" 13078 " aaaaaaaaaaaaaaaaaaaa,\n" 13079 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13080 13081 EXPECT_EQ("\"splitmea\"\n" 13082 "\"trandomp\"\n" 13083 "\"oint\"", 13084 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13085 13086 EXPECT_EQ("\"split/\"\n" 13087 "\"pathat/\"\n" 13088 "\"slashes\"", 13089 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13090 13091 EXPECT_EQ("\"split/\"\n" 13092 "\"pathat/\"\n" 13093 "\"slashes\"", 13094 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13095 EXPECT_EQ("\"split at \"\n" 13096 "\"spaces/at/\"\n" 13097 "\"slashes.at.any$\"\n" 13098 "\"non-alphanumeric%\"\n" 13099 "\"1111111111characte\"\n" 13100 "\"rs\"", 13101 format("\"split at " 13102 "spaces/at/" 13103 "slashes.at." 13104 "any$non-" 13105 "alphanumeric%" 13106 "1111111111characte" 13107 "rs\"", 13108 getLLVMStyleWithColumns(20))); 13109 13110 // Verify that splitting the strings understands 13111 // Style::AlwaysBreakBeforeMultilineStrings. 13112 EXPECT_EQ("aaaaaaaaaaaa(\n" 13113 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13114 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13115 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13116 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13117 "aaaaaaaaaaaaaaaaaaaaaa\");", 13118 getGoogleStyle())); 13119 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13120 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13121 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13122 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13123 "aaaaaaaaaaaaaaaaaaaaaa\";", 13124 getGoogleStyle())); 13125 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13126 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13127 format("llvm::outs() << " 13128 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13129 "aaaaaaaaaaaaaaaaaaa\";")); 13130 EXPECT_EQ("ffff(\n" 13131 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13132 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13133 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13134 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13135 getGoogleStyle())); 13136 13137 FormatStyle Style = getLLVMStyleWithColumns(12); 13138 Style.BreakStringLiterals = false; 13139 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13140 13141 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13142 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13143 EXPECT_EQ("#define A \\\n" 13144 " \"some \" \\\n" 13145 " \"text \" \\\n" 13146 " \"other\";", 13147 format("#define A \"some text other\";", AlignLeft)); 13148 } 13149 13150 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13151 EXPECT_EQ("C a = \"some more \"\n" 13152 " \"text\";", 13153 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13154 } 13155 13156 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13157 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13158 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13159 EXPECT_EQ("int i = a(b());", 13160 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13161 } 13162 13163 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13164 EXPECT_EQ( 13165 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13166 "(\n" 13167 " \"x\t\");", 13168 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13169 "aaaaaaa(" 13170 "\"x\t\");")); 13171 } 13172 13173 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13174 EXPECT_EQ( 13175 "u8\"utf8 string \"\n" 13176 "u8\"literal\";", 13177 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13178 EXPECT_EQ( 13179 "u\"utf16 string \"\n" 13180 "u\"literal\";", 13181 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13182 EXPECT_EQ( 13183 "U\"utf32 string \"\n" 13184 "U\"literal\";", 13185 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13186 EXPECT_EQ("L\"wide string \"\n" 13187 "L\"literal\";", 13188 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13189 EXPECT_EQ("@\"NSString \"\n" 13190 "@\"literal\";", 13191 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13192 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13193 13194 // This input makes clang-format try to split the incomplete unicode escape 13195 // sequence, which used to lead to a crasher. 13196 verifyNoCrash( 13197 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13198 getLLVMStyleWithColumns(60)); 13199 } 13200 13201 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13202 FormatStyle Style = getGoogleStyleWithColumns(15); 13203 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13204 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13205 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13206 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13207 EXPECT_EQ("u8R\"x(raw literal)x\";", 13208 format("u8R\"x(raw literal)x\";", Style)); 13209 } 13210 13211 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13212 FormatStyle Style = getLLVMStyleWithColumns(20); 13213 EXPECT_EQ( 13214 "_T(\"aaaaaaaaaaaaaa\")\n" 13215 "_T(\"aaaaaaaaaaaaaa\")\n" 13216 "_T(\"aaaaaaaaaaaa\")", 13217 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13218 EXPECT_EQ("f(x,\n" 13219 " _T(\"aaaaaaaaaaaa\")\n" 13220 " _T(\"aaa\"),\n" 13221 " z);", 13222 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13223 13224 // FIXME: Handle embedded spaces in one iteration. 13225 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13226 // "_T(\"aaaaaaaaaaaaa\")\n" 13227 // "_T(\"aaaaaaaaaaaaa\")\n" 13228 // "_T(\"a\")", 13229 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13230 // getLLVMStyleWithColumns(20))); 13231 EXPECT_EQ( 13232 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13233 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13234 EXPECT_EQ("f(\n" 13235 "#if !TEST\n" 13236 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13237 "#endif\n" 13238 ");", 13239 format("f(\n" 13240 "#if !TEST\n" 13241 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13242 "#endif\n" 13243 ");")); 13244 EXPECT_EQ("f(\n" 13245 "\n" 13246 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13247 format("f(\n" 13248 "\n" 13249 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13250 // Regression test for accessing tokens past the end of a vector in the 13251 // TokenLexer. 13252 verifyNoCrash(R"(_T( 13253 " 13254 ) 13255 )"); 13256 } 13257 13258 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13259 // In a function call with two operands, the second can be broken with no line 13260 // break before it. 13261 EXPECT_EQ( 13262 "func(a, \"long long \"\n" 13263 " \"long long\");", 13264 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13265 // In a function call with three operands, the second must be broken with a 13266 // line break before it. 13267 EXPECT_EQ("func(a,\n" 13268 " \"long long long \"\n" 13269 " \"long\",\n" 13270 " c);", 13271 format("func(a, \"long long long long\", c);", 13272 getLLVMStyleWithColumns(24))); 13273 // In a function call with three operands, the third must be broken with a 13274 // line break before it. 13275 EXPECT_EQ("func(a, b,\n" 13276 " \"long long long \"\n" 13277 " \"long\");", 13278 format("func(a, b, \"long long long long\");", 13279 getLLVMStyleWithColumns(24))); 13280 // In a function call with three operands, both the second and the third must 13281 // be broken with a line break before them. 13282 EXPECT_EQ("func(a,\n" 13283 " \"long long long \"\n" 13284 " \"long\",\n" 13285 " \"long long long \"\n" 13286 " \"long\");", 13287 format("func(a, \"long long long long\", \"long long long long\");", 13288 getLLVMStyleWithColumns(24))); 13289 // In a chain of << with two operands, the second can be broken with no line 13290 // break before it. 13291 EXPECT_EQ("a << \"line line \"\n" 13292 " \"line\";", 13293 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13294 // In a chain of << with three operands, the second can be broken with no line 13295 // break before it. 13296 EXPECT_EQ( 13297 "abcde << \"line \"\n" 13298 " \"line line\"\n" 13299 " << c;", 13300 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13301 // In a chain of << with three operands, the third must be broken with a line 13302 // break before it. 13303 EXPECT_EQ( 13304 "a << b\n" 13305 " << \"line line \"\n" 13306 " \"line\";", 13307 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13308 // In a chain of << with three operands, the second can be broken with no line 13309 // break before it and the third must be broken with a line break before it. 13310 EXPECT_EQ("abcd << \"line line \"\n" 13311 " \"line\"\n" 13312 " << \"line line \"\n" 13313 " \"line\";", 13314 format("abcd << \"line line line\" << \"line line line\";", 13315 getLLVMStyleWithColumns(20))); 13316 // In a chain of binary operators with two operands, the second can be broken 13317 // with no line break before it. 13318 EXPECT_EQ( 13319 "abcd + \"line line \"\n" 13320 " \"line line\";", 13321 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13322 // In a chain of binary operators with three operands, the second must be 13323 // broken with a line break before it. 13324 EXPECT_EQ("abcd +\n" 13325 " \"line line \"\n" 13326 " \"line line\" +\n" 13327 " e;", 13328 format("abcd + \"line line line line\" + e;", 13329 getLLVMStyleWithColumns(20))); 13330 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13331 // the first must be broken with a line break before it. 13332 FormatStyle Style = getLLVMStyleWithColumns(25); 13333 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13334 EXPECT_EQ("someFunction(\n" 13335 " \"long long long \"\n" 13336 " \"long\",\n" 13337 " a);", 13338 format("someFunction(\"long long long long\", a);", Style)); 13339 } 13340 13341 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13342 EXPECT_EQ( 13343 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13344 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13345 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13346 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13347 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13348 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13349 } 13350 13351 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13352 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13353 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13354 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13355 "multiline raw string literal xxxxxxxxxxxxxx\n" 13356 ")x\",\n" 13357 " a),\n" 13358 " b);", 13359 format("fffffffffff(g(R\"x(\n" 13360 "multiline raw string literal xxxxxxxxxxxxxx\n" 13361 ")x\", a), b);", 13362 getGoogleStyleWithColumns(20))); 13363 EXPECT_EQ("fffffffffff(\n" 13364 " g(R\"x(qqq\n" 13365 "multiline raw string literal xxxxxxxxxxxxxx\n" 13366 ")x\",\n" 13367 " a),\n" 13368 " b);", 13369 format("fffffffffff(g(R\"x(qqq\n" 13370 "multiline raw string literal xxxxxxxxxxxxxx\n" 13371 ")x\", a), b);", 13372 getGoogleStyleWithColumns(20))); 13373 13374 EXPECT_EQ("fffffffffff(R\"x(\n" 13375 "multiline raw string literal xxxxxxxxxxxxxx\n" 13376 ")x\");", 13377 format("fffffffffff(R\"x(\n" 13378 "multiline raw string literal xxxxxxxxxxxxxx\n" 13379 ")x\");", 13380 getGoogleStyleWithColumns(20))); 13381 EXPECT_EQ("fffffffffff(R\"x(\n" 13382 "multiline raw string literal xxxxxxxxxxxxxx\n" 13383 ")x\" + bbbbbb);", 13384 format("fffffffffff(R\"x(\n" 13385 "multiline raw string literal xxxxxxxxxxxxxx\n" 13386 ")x\" + bbbbbb);", 13387 getGoogleStyleWithColumns(20))); 13388 EXPECT_EQ("fffffffffff(\n" 13389 " R\"x(\n" 13390 "multiline raw string literal xxxxxxxxxxxxxx\n" 13391 ")x\" +\n" 13392 " bbbbbb);", 13393 format("fffffffffff(\n" 13394 " R\"x(\n" 13395 "multiline raw string literal xxxxxxxxxxxxxx\n" 13396 ")x\" + bbbbbb);", 13397 getGoogleStyleWithColumns(20))); 13398 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13399 format("fffffffffff(\n" 13400 " R\"(single line raw string)\" + bbbbbb);")); 13401 } 13402 13403 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13404 verifyFormat("string a = \"unterminated;"); 13405 EXPECT_EQ("function(\"unterminated,\n" 13406 " OtherParameter);", 13407 format("function( \"unterminated,\n" 13408 " OtherParameter);")); 13409 } 13410 13411 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13412 FormatStyle Style = getLLVMStyle(); 13413 Style.Standard = FormatStyle::LS_Cpp03; 13414 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13415 format("#define x(_a) printf(\"foo\"_a);", Style)); 13416 } 13417 13418 TEST_F(FormatTest, CppLexVersion) { 13419 FormatStyle Style = getLLVMStyle(); 13420 // Formatting of x * y differs if x is a type. 13421 verifyFormat("void foo() { MACRO(a * b); }", Style); 13422 verifyFormat("void foo() { MACRO(int *b); }", Style); 13423 13424 // LLVM style uses latest lexer. 13425 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13426 Style.Standard = FormatStyle::LS_Cpp17; 13427 // But in c++17, char8_t isn't a keyword. 13428 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13429 } 13430 13431 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13432 13433 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13434 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13435 " \"ddeeefff\");", 13436 format("someFunction(\"aaabbbcccdddeeefff\");", 13437 getLLVMStyleWithColumns(25))); 13438 EXPECT_EQ("someFunction1234567890(\n" 13439 " \"aaabbbcccdddeeefff\");", 13440 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13441 getLLVMStyleWithColumns(26))); 13442 EXPECT_EQ("someFunction1234567890(\n" 13443 " \"aaabbbcccdddeeeff\"\n" 13444 " \"f\");", 13445 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13446 getLLVMStyleWithColumns(25))); 13447 EXPECT_EQ("someFunction1234567890(\n" 13448 " \"aaabbbcccdddeeeff\"\n" 13449 " \"f\");", 13450 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13451 getLLVMStyleWithColumns(24))); 13452 EXPECT_EQ("someFunction(\n" 13453 " \"aaabbbcc ddde \"\n" 13454 " \"efff\");", 13455 format("someFunction(\"aaabbbcc ddde efff\");", 13456 getLLVMStyleWithColumns(25))); 13457 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13458 " \"ddeeefff\");", 13459 format("someFunction(\"aaabbbccc ddeeefff\");", 13460 getLLVMStyleWithColumns(25))); 13461 EXPECT_EQ("someFunction1234567890(\n" 13462 " \"aaabb \"\n" 13463 " \"cccdddeeefff\");", 13464 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13465 getLLVMStyleWithColumns(25))); 13466 EXPECT_EQ("#define A \\\n" 13467 " string s = \\\n" 13468 " \"123456789\" \\\n" 13469 " \"0\"; \\\n" 13470 " int i;", 13471 format("#define A string s = \"1234567890\"; int i;", 13472 getLLVMStyleWithColumns(20))); 13473 EXPECT_EQ("someFunction(\n" 13474 " \"aaabbbcc \"\n" 13475 " \"dddeeefff\");", 13476 format("someFunction(\"aaabbbcc dddeeefff\");", 13477 getLLVMStyleWithColumns(25))); 13478 } 13479 13480 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13481 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13482 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13483 EXPECT_EQ("\"test\"\n" 13484 "\"\\n\"", 13485 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13486 EXPECT_EQ("\"tes\\\\\"\n" 13487 "\"n\"", 13488 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13489 EXPECT_EQ("\"\\\\\\\\\"\n" 13490 "\"\\n\"", 13491 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13492 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13493 EXPECT_EQ("\"\\uff01\"\n" 13494 "\"test\"", 13495 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13496 EXPECT_EQ("\"\\Uff01ff02\"", 13497 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13498 EXPECT_EQ("\"\\x000000000001\"\n" 13499 "\"next\"", 13500 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13501 EXPECT_EQ("\"\\x000000000001next\"", 13502 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13503 EXPECT_EQ("\"\\x000000000001\"", 13504 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13505 EXPECT_EQ("\"test\"\n" 13506 "\"\\000000\"\n" 13507 "\"000001\"", 13508 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13509 EXPECT_EQ("\"test\\000\"\n" 13510 "\"00000000\"\n" 13511 "\"1\"", 13512 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13513 } 13514 13515 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13516 verifyFormat("void f() {\n" 13517 " return g() {}\n" 13518 " void h() {}"); 13519 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13520 "g();\n" 13521 "}"); 13522 } 13523 13524 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13525 verifyFormat( 13526 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13527 } 13528 13529 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13530 verifyFormat("class X {\n" 13531 " void f() {\n" 13532 " }\n" 13533 "};", 13534 getLLVMStyleWithColumns(12)); 13535 } 13536 13537 TEST_F(FormatTest, ConfigurableIndentWidth) { 13538 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13539 EightIndent.IndentWidth = 8; 13540 EightIndent.ContinuationIndentWidth = 8; 13541 verifyFormat("void f() {\n" 13542 " someFunction();\n" 13543 " if (true) {\n" 13544 " f();\n" 13545 " }\n" 13546 "}", 13547 EightIndent); 13548 verifyFormat("class X {\n" 13549 " void f() {\n" 13550 " }\n" 13551 "};", 13552 EightIndent); 13553 verifyFormat("int x[] = {\n" 13554 " call(),\n" 13555 " call()};", 13556 EightIndent); 13557 } 13558 13559 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13560 verifyFormat("double\n" 13561 "f();", 13562 getLLVMStyleWithColumns(8)); 13563 } 13564 13565 TEST_F(FormatTest, ConfigurableUseOfTab) { 13566 FormatStyle Tab = getLLVMStyleWithColumns(42); 13567 Tab.IndentWidth = 8; 13568 Tab.UseTab = FormatStyle::UT_Always; 13569 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13570 13571 EXPECT_EQ("if (aaaaaaaa && // q\n" 13572 " bb)\t\t// w\n" 13573 "\t;", 13574 format("if (aaaaaaaa &&// q\n" 13575 "bb)// w\n" 13576 ";", 13577 Tab)); 13578 EXPECT_EQ("if (aaa && bbb) // w\n" 13579 "\t;", 13580 format("if(aaa&&bbb)// w\n" 13581 ";", 13582 Tab)); 13583 13584 verifyFormat("class X {\n" 13585 "\tvoid f() {\n" 13586 "\t\tsomeFunction(parameter1,\n" 13587 "\t\t\t parameter2);\n" 13588 "\t}\n" 13589 "};", 13590 Tab); 13591 verifyFormat("#define A \\\n" 13592 "\tvoid f() { \\\n" 13593 "\t\tsomeFunction( \\\n" 13594 "\t\t parameter1, \\\n" 13595 "\t\t parameter2); \\\n" 13596 "\t}", 13597 Tab); 13598 verifyFormat("int a;\t // x\n" 13599 "int bbbbbbbb; // x\n", 13600 Tab); 13601 13602 Tab.TabWidth = 4; 13603 Tab.IndentWidth = 8; 13604 verifyFormat("class TabWidth4Indent8 {\n" 13605 "\t\tvoid f() {\n" 13606 "\t\t\t\tsomeFunction(parameter1,\n" 13607 "\t\t\t\t\t\t\t parameter2);\n" 13608 "\t\t}\n" 13609 "};", 13610 Tab); 13611 13612 Tab.TabWidth = 4; 13613 Tab.IndentWidth = 4; 13614 verifyFormat("class TabWidth4Indent4 {\n" 13615 "\tvoid f() {\n" 13616 "\t\tsomeFunction(parameter1,\n" 13617 "\t\t\t\t\t parameter2);\n" 13618 "\t}\n" 13619 "};", 13620 Tab); 13621 13622 Tab.TabWidth = 8; 13623 Tab.IndentWidth = 4; 13624 verifyFormat("class TabWidth8Indent4 {\n" 13625 " void f() {\n" 13626 "\tsomeFunction(parameter1,\n" 13627 "\t\t parameter2);\n" 13628 " }\n" 13629 "};", 13630 Tab); 13631 13632 Tab.TabWidth = 8; 13633 Tab.IndentWidth = 8; 13634 EXPECT_EQ("/*\n" 13635 "\t a\t\tcomment\n" 13636 "\t in multiple lines\n" 13637 " */", 13638 format(" /*\t \t \n" 13639 " \t \t a\t\tcomment\t \t\n" 13640 " \t \t in multiple lines\t\n" 13641 " \t */", 13642 Tab)); 13643 13644 Tab.UseTab = FormatStyle::UT_ForIndentation; 13645 verifyFormat("{\n" 13646 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13647 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13648 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13649 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13650 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13651 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13652 "};", 13653 Tab); 13654 verifyFormat("enum AA {\n" 13655 "\ta1, // Force multiple lines\n" 13656 "\ta2,\n" 13657 "\ta3\n" 13658 "};", 13659 Tab); 13660 EXPECT_EQ("if (aaaaaaaa && // q\n" 13661 " bb) // w\n" 13662 "\t;", 13663 format("if (aaaaaaaa &&// q\n" 13664 "bb)// w\n" 13665 ";", 13666 Tab)); 13667 verifyFormat("class X {\n" 13668 "\tvoid f() {\n" 13669 "\t\tsomeFunction(parameter1,\n" 13670 "\t\t parameter2);\n" 13671 "\t}\n" 13672 "};", 13673 Tab); 13674 verifyFormat("{\n" 13675 "\tQ(\n" 13676 "\t {\n" 13677 "\t\t int a;\n" 13678 "\t\t someFunction(aaaaaaaa,\n" 13679 "\t\t bbbbbbb);\n" 13680 "\t },\n" 13681 "\t p);\n" 13682 "}", 13683 Tab); 13684 EXPECT_EQ("{\n" 13685 "\t/* aaaa\n" 13686 "\t bbbb */\n" 13687 "}", 13688 format("{\n" 13689 "/* aaaa\n" 13690 " bbbb */\n" 13691 "}", 13692 Tab)); 13693 EXPECT_EQ("{\n" 13694 "\t/*\n" 13695 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13696 "\t bbbbbbbbbbbbb\n" 13697 "\t*/\n" 13698 "}", 13699 format("{\n" 13700 "/*\n" 13701 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13702 "*/\n" 13703 "}", 13704 Tab)); 13705 EXPECT_EQ("{\n" 13706 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13707 "\t// bbbbbbbbbbbbb\n" 13708 "}", 13709 format("{\n" 13710 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13711 "}", 13712 Tab)); 13713 EXPECT_EQ("{\n" 13714 "\t/*\n" 13715 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13716 "\t bbbbbbbbbbbbb\n" 13717 "\t*/\n" 13718 "}", 13719 format("{\n" 13720 "\t/*\n" 13721 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13722 "\t*/\n" 13723 "}", 13724 Tab)); 13725 EXPECT_EQ("{\n" 13726 "\t/*\n" 13727 "\n" 13728 "\t*/\n" 13729 "}", 13730 format("{\n" 13731 "\t/*\n" 13732 "\n" 13733 "\t*/\n" 13734 "}", 13735 Tab)); 13736 EXPECT_EQ("{\n" 13737 "\t/*\n" 13738 " asdf\n" 13739 "\t*/\n" 13740 "}", 13741 format("{\n" 13742 "\t/*\n" 13743 " asdf\n" 13744 "\t*/\n" 13745 "}", 13746 Tab)); 13747 13748 verifyFormat("void f() {\n" 13749 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 13750 "\t : bbbbbbbbbbbbbbbbbb\n" 13751 "}", 13752 Tab); 13753 FormatStyle TabNoBreak = Tab; 13754 TabNoBreak.BreakBeforeTernaryOperators = false; 13755 verifyFormat("void f() {\n" 13756 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 13757 "\t bbbbbbbbbbbbbbbbbb\n" 13758 "}", 13759 TabNoBreak); 13760 verifyFormat("void f() {\n" 13761 "\treturn true ?\n" 13762 "\t aaaaaaaaaaaaaaaaaaaa :\n" 13763 "\t bbbbbbbbbbbbbbbbbbbb\n" 13764 "}", 13765 TabNoBreak); 13766 13767 Tab.UseTab = FormatStyle::UT_Never; 13768 EXPECT_EQ("/*\n" 13769 " a\t\tcomment\n" 13770 " in multiple lines\n" 13771 " */", 13772 format(" /*\t \t \n" 13773 " \t \t a\t\tcomment\t \t\n" 13774 " \t \t in multiple lines\t\n" 13775 " \t */", 13776 Tab)); 13777 EXPECT_EQ("/* some\n" 13778 " comment */", 13779 format(" \t \t /* some\n" 13780 " \t \t comment */", 13781 Tab)); 13782 EXPECT_EQ("int a; /* some\n" 13783 " comment */", 13784 format(" \t \t int a; /* some\n" 13785 " \t \t comment */", 13786 Tab)); 13787 13788 EXPECT_EQ("int a; /* some\n" 13789 "comment */", 13790 format(" \t \t int\ta; /* some\n" 13791 " \t \t comment */", 13792 Tab)); 13793 EXPECT_EQ("f(\"\t\t\"); /* some\n" 13794 " comment */", 13795 format(" \t \t f(\"\t\t\"); /* some\n" 13796 " \t \t comment */", 13797 Tab)); 13798 EXPECT_EQ("{\n" 13799 " /*\n" 13800 " * Comment\n" 13801 " */\n" 13802 " int i;\n" 13803 "}", 13804 format("{\n" 13805 "\t/*\n" 13806 "\t * Comment\n" 13807 "\t */\n" 13808 "\t int i;\n" 13809 "}", 13810 Tab)); 13811 13812 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 13813 Tab.TabWidth = 8; 13814 Tab.IndentWidth = 8; 13815 EXPECT_EQ("if (aaaaaaaa && // q\n" 13816 " bb) // w\n" 13817 "\t;", 13818 format("if (aaaaaaaa &&// q\n" 13819 "bb)// w\n" 13820 ";", 13821 Tab)); 13822 EXPECT_EQ("if (aaa && bbb) // w\n" 13823 "\t;", 13824 format("if(aaa&&bbb)// w\n" 13825 ";", 13826 Tab)); 13827 verifyFormat("class X {\n" 13828 "\tvoid f() {\n" 13829 "\t\tsomeFunction(parameter1,\n" 13830 "\t\t\t parameter2);\n" 13831 "\t}\n" 13832 "};", 13833 Tab); 13834 verifyFormat("#define A \\\n" 13835 "\tvoid f() { \\\n" 13836 "\t\tsomeFunction( \\\n" 13837 "\t\t parameter1, \\\n" 13838 "\t\t parameter2); \\\n" 13839 "\t}", 13840 Tab); 13841 Tab.TabWidth = 4; 13842 Tab.IndentWidth = 8; 13843 verifyFormat("class TabWidth4Indent8 {\n" 13844 "\t\tvoid f() {\n" 13845 "\t\t\t\tsomeFunction(parameter1,\n" 13846 "\t\t\t\t\t\t\t parameter2);\n" 13847 "\t\t}\n" 13848 "};", 13849 Tab); 13850 Tab.TabWidth = 4; 13851 Tab.IndentWidth = 4; 13852 verifyFormat("class TabWidth4Indent4 {\n" 13853 "\tvoid f() {\n" 13854 "\t\tsomeFunction(parameter1,\n" 13855 "\t\t\t\t\t parameter2);\n" 13856 "\t}\n" 13857 "};", 13858 Tab); 13859 Tab.TabWidth = 8; 13860 Tab.IndentWidth = 4; 13861 verifyFormat("class TabWidth8Indent4 {\n" 13862 " void f() {\n" 13863 "\tsomeFunction(parameter1,\n" 13864 "\t\t parameter2);\n" 13865 " }\n" 13866 "};", 13867 Tab); 13868 Tab.TabWidth = 8; 13869 Tab.IndentWidth = 8; 13870 EXPECT_EQ("/*\n" 13871 "\t a\t\tcomment\n" 13872 "\t in multiple lines\n" 13873 " */", 13874 format(" /*\t \t \n" 13875 " \t \t a\t\tcomment\t \t\n" 13876 " \t \t in multiple lines\t\n" 13877 " \t */", 13878 Tab)); 13879 verifyFormat("{\n" 13880 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13881 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13882 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13883 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13884 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13885 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13886 "};", 13887 Tab); 13888 verifyFormat("enum AA {\n" 13889 "\ta1, // Force multiple lines\n" 13890 "\ta2,\n" 13891 "\ta3\n" 13892 "};", 13893 Tab); 13894 EXPECT_EQ("if (aaaaaaaa && // q\n" 13895 " bb) // w\n" 13896 "\t;", 13897 format("if (aaaaaaaa &&// q\n" 13898 "bb)// w\n" 13899 ";", 13900 Tab)); 13901 verifyFormat("class X {\n" 13902 "\tvoid f() {\n" 13903 "\t\tsomeFunction(parameter1,\n" 13904 "\t\t\t parameter2);\n" 13905 "\t}\n" 13906 "};", 13907 Tab); 13908 verifyFormat("{\n" 13909 "\tQ(\n" 13910 "\t {\n" 13911 "\t\t int a;\n" 13912 "\t\t someFunction(aaaaaaaa,\n" 13913 "\t\t\t\t bbbbbbb);\n" 13914 "\t },\n" 13915 "\t p);\n" 13916 "}", 13917 Tab); 13918 EXPECT_EQ("{\n" 13919 "\t/* aaaa\n" 13920 "\t bbbb */\n" 13921 "}", 13922 format("{\n" 13923 "/* aaaa\n" 13924 " bbbb */\n" 13925 "}", 13926 Tab)); 13927 EXPECT_EQ("{\n" 13928 "\t/*\n" 13929 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13930 "\t bbbbbbbbbbbbb\n" 13931 "\t*/\n" 13932 "}", 13933 format("{\n" 13934 "/*\n" 13935 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13936 "*/\n" 13937 "}", 13938 Tab)); 13939 EXPECT_EQ("{\n" 13940 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13941 "\t// bbbbbbbbbbbbb\n" 13942 "}", 13943 format("{\n" 13944 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13945 "}", 13946 Tab)); 13947 EXPECT_EQ("{\n" 13948 "\t/*\n" 13949 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13950 "\t bbbbbbbbbbbbb\n" 13951 "\t*/\n" 13952 "}", 13953 format("{\n" 13954 "\t/*\n" 13955 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13956 "\t*/\n" 13957 "}", 13958 Tab)); 13959 EXPECT_EQ("{\n" 13960 "\t/*\n" 13961 "\n" 13962 "\t*/\n" 13963 "}", 13964 format("{\n" 13965 "\t/*\n" 13966 "\n" 13967 "\t*/\n" 13968 "}", 13969 Tab)); 13970 EXPECT_EQ("{\n" 13971 "\t/*\n" 13972 " asdf\n" 13973 "\t*/\n" 13974 "}", 13975 format("{\n" 13976 "\t/*\n" 13977 " asdf\n" 13978 "\t*/\n" 13979 "}", 13980 Tab)); 13981 EXPECT_EQ("/* some\n" 13982 " comment */", 13983 format(" \t \t /* some\n" 13984 " \t \t comment */", 13985 Tab)); 13986 EXPECT_EQ("int a; /* some\n" 13987 " comment */", 13988 format(" \t \t int a; /* some\n" 13989 " \t \t comment */", 13990 Tab)); 13991 EXPECT_EQ("int a; /* some\n" 13992 "comment */", 13993 format(" \t \t int\ta; /* some\n" 13994 " \t \t comment */", 13995 Tab)); 13996 EXPECT_EQ("f(\"\t\t\"); /* some\n" 13997 " comment */", 13998 format(" \t \t f(\"\t\t\"); /* some\n" 13999 " \t \t comment */", 14000 Tab)); 14001 EXPECT_EQ("{\n" 14002 "\t/*\n" 14003 "\t * Comment\n" 14004 "\t */\n" 14005 "\tint i;\n" 14006 "}", 14007 format("{\n" 14008 "\t/*\n" 14009 "\t * Comment\n" 14010 "\t */\n" 14011 "\t int i;\n" 14012 "}", 14013 Tab)); 14014 Tab.TabWidth = 2; 14015 Tab.IndentWidth = 2; 14016 EXPECT_EQ("{\n" 14017 "\t/* aaaa\n" 14018 "\t\t bbbb */\n" 14019 "}", 14020 format("{\n" 14021 "/* aaaa\n" 14022 "\t bbbb */\n" 14023 "}", 14024 Tab)); 14025 EXPECT_EQ("{\n" 14026 "\t/*\n" 14027 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14028 "\t\tbbbbbbbbbbbbb\n" 14029 "\t*/\n" 14030 "}", 14031 format("{\n" 14032 "/*\n" 14033 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14034 "*/\n" 14035 "}", 14036 Tab)); 14037 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14038 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14039 Tab.TabWidth = 4; 14040 Tab.IndentWidth = 4; 14041 verifyFormat("class Assign {\n" 14042 "\tvoid f() {\n" 14043 "\t\tint x = 123;\n" 14044 "\t\tint random = 4;\n" 14045 "\t\tstd::string alphabet =\n" 14046 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14047 "\t}\n" 14048 "};", 14049 Tab); 14050 14051 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14052 Tab.TabWidth = 8; 14053 Tab.IndentWidth = 8; 14054 EXPECT_EQ("if (aaaaaaaa && // q\n" 14055 " bb) // w\n" 14056 "\t;", 14057 format("if (aaaaaaaa &&// q\n" 14058 "bb)// w\n" 14059 ";", 14060 Tab)); 14061 EXPECT_EQ("if (aaa && bbb) // w\n" 14062 "\t;", 14063 format("if(aaa&&bbb)// w\n" 14064 ";", 14065 Tab)); 14066 verifyFormat("class X {\n" 14067 "\tvoid f() {\n" 14068 "\t\tsomeFunction(parameter1,\n" 14069 "\t\t parameter2);\n" 14070 "\t}\n" 14071 "};", 14072 Tab); 14073 verifyFormat("#define A \\\n" 14074 "\tvoid f() { \\\n" 14075 "\t\tsomeFunction( \\\n" 14076 "\t\t parameter1, \\\n" 14077 "\t\t parameter2); \\\n" 14078 "\t}", 14079 Tab); 14080 Tab.TabWidth = 4; 14081 Tab.IndentWidth = 8; 14082 verifyFormat("class TabWidth4Indent8 {\n" 14083 "\t\tvoid f() {\n" 14084 "\t\t\t\tsomeFunction(parameter1,\n" 14085 "\t\t\t\t parameter2);\n" 14086 "\t\t}\n" 14087 "};", 14088 Tab); 14089 Tab.TabWidth = 4; 14090 Tab.IndentWidth = 4; 14091 verifyFormat("class TabWidth4Indent4 {\n" 14092 "\tvoid f() {\n" 14093 "\t\tsomeFunction(parameter1,\n" 14094 "\t\t parameter2);\n" 14095 "\t}\n" 14096 "};", 14097 Tab); 14098 Tab.TabWidth = 8; 14099 Tab.IndentWidth = 4; 14100 verifyFormat("class TabWidth8Indent4 {\n" 14101 " void f() {\n" 14102 "\tsomeFunction(parameter1,\n" 14103 "\t parameter2);\n" 14104 " }\n" 14105 "};", 14106 Tab); 14107 Tab.TabWidth = 8; 14108 Tab.IndentWidth = 8; 14109 EXPECT_EQ("/*\n" 14110 " a\t\tcomment\n" 14111 " in multiple lines\n" 14112 " */", 14113 format(" /*\t \t \n" 14114 " \t \t a\t\tcomment\t \t\n" 14115 " \t \t in multiple lines\t\n" 14116 " \t */", 14117 Tab)); 14118 verifyFormat("{\n" 14119 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14120 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14121 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14122 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14123 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14124 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14125 "};", 14126 Tab); 14127 verifyFormat("enum AA {\n" 14128 "\ta1, // Force multiple lines\n" 14129 "\ta2,\n" 14130 "\ta3\n" 14131 "};", 14132 Tab); 14133 EXPECT_EQ("if (aaaaaaaa && // q\n" 14134 " bb) // w\n" 14135 "\t;", 14136 format("if (aaaaaaaa &&// q\n" 14137 "bb)// w\n" 14138 ";", 14139 Tab)); 14140 verifyFormat("class X {\n" 14141 "\tvoid f() {\n" 14142 "\t\tsomeFunction(parameter1,\n" 14143 "\t\t parameter2);\n" 14144 "\t}\n" 14145 "};", 14146 Tab); 14147 verifyFormat("{\n" 14148 "\tQ(\n" 14149 "\t {\n" 14150 "\t\t int a;\n" 14151 "\t\t someFunction(aaaaaaaa,\n" 14152 "\t\t bbbbbbb);\n" 14153 "\t },\n" 14154 "\t p);\n" 14155 "}", 14156 Tab); 14157 EXPECT_EQ("{\n" 14158 "\t/* aaaa\n" 14159 "\t bbbb */\n" 14160 "}", 14161 format("{\n" 14162 "/* aaaa\n" 14163 " bbbb */\n" 14164 "}", 14165 Tab)); 14166 EXPECT_EQ("{\n" 14167 "\t/*\n" 14168 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14169 "\t bbbbbbbbbbbbb\n" 14170 "\t*/\n" 14171 "}", 14172 format("{\n" 14173 "/*\n" 14174 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14175 "*/\n" 14176 "}", 14177 Tab)); 14178 EXPECT_EQ("{\n" 14179 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14180 "\t// bbbbbbbbbbbbb\n" 14181 "}", 14182 format("{\n" 14183 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14184 "}", 14185 Tab)); 14186 EXPECT_EQ("{\n" 14187 "\t/*\n" 14188 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14189 "\t bbbbbbbbbbbbb\n" 14190 "\t*/\n" 14191 "}", 14192 format("{\n" 14193 "\t/*\n" 14194 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14195 "\t*/\n" 14196 "}", 14197 Tab)); 14198 EXPECT_EQ("{\n" 14199 "\t/*\n" 14200 "\n" 14201 "\t*/\n" 14202 "}", 14203 format("{\n" 14204 "\t/*\n" 14205 "\n" 14206 "\t*/\n" 14207 "}", 14208 Tab)); 14209 EXPECT_EQ("{\n" 14210 "\t/*\n" 14211 " asdf\n" 14212 "\t*/\n" 14213 "}", 14214 format("{\n" 14215 "\t/*\n" 14216 " asdf\n" 14217 "\t*/\n" 14218 "}", 14219 Tab)); 14220 EXPECT_EQ("/* some\n" 14221 " comment */", 14222 format(" \t \t /* some\n" 14223 " \t \t comment */", 14224 Tab)); 14225 EXPECT_EQ("int a; /* some\n" 14226 " comment */", 14227 format(" \t \t int a; /* some\n" 14228 " \t \t comment */", 14229 Tab)); 14230 EXPECT_EQ("int a; /* some\n" 14231 "comment */", 14232 format(" \t \t int\ta; /* some\n" 14233 " \t \t comment */", 14234 Tab)); 14235 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14236 " comment */", 14237 format(" \t \t f(\"\t\t\"); /* some\n" 14238 " \t \t comment */", 14239 Tab)); 14240 EXPECT_EQ("{\n" 14241 "\t/*\n" 14242 "\t * Comment\n" 14243 "\t */\n" 14244 "\tint i;\n" 14245 "}", 14246 format("{\n" 14247 "\t/*\n" 14248 "\t * Comment\n" 14249 "\t */\n" 14250 "\t int i;\n" 14251 "}", 14252 Tab)); 14253 Tab.TabWidth = 2; 14254 Tab.IndentWidth = 2; 14255 EXPECT_EQ("{\n" 14256 "\t/* aaaa\n" 14257 "\t bbbb */\n" 14258 "}", 14259 format("{\n" 14260 "/* aaaa\n" 14261 " bbbb */\n" 14262 "}", 14263 Tab)); 14264 EXPECT_EQ("{\n" 14265 "\t/*\n" 14266 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14267 "\t bbbbbbbbbbbbb\n" 14268 "\t*/\n" 14269 "}", 14270 format("{\n" 14271 "/*\n" 14272 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14273 "*/\n" 14274 "}", 14275 Tab)); 14276 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14277 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14278 Tab.TabWidth = 4; 14279 Tab.IndentWidth = 4; 14280 verifyFormat("class Assign {\n" 14281 "\tvoid f() {\n" 14282 "\t\tint x = 123;\n" 14283 "\t\tint random = 4;\n" 14284 "\t\tstd::string alphabet =\n" 14285 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14286 "\t}\n" 14287 "};", 14288 Tab); 14289 Tab.AlignOperands = FormatStyle::OAS_Align; 14290 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14291 " cccccccccccccccccccc;", 14292 Tab); 14293 // no alignment 14294 verifyFormat("int aaaaaaaaaa =\n" 14295 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14296 Tab); 14297 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14298 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14299 " : 333333333333333;", 14300 Tab); 14301 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14302 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14303 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14304 " + cccccccccccccccccccc;", 14305 Tab); 14306 } 14307 14308 TEST_F(FormatTest, ZeroTabWidth) { 14309 FormatStyle Tab = getLLVMStyleWithColumns(42); 14310 Tab.IndentWidth = 8; 14311 Tab.UseTab = FormatStyle::UT_Never; 14312 Tab.TabWidth = 0; 14313 EXPECT_EQ("void a(){\n" 14314 " // line starts with '\t'\n" 14315 "};", 14316 format("void a(){\n" 14317 "\t// line starts with '\t'\n" 14318 "};", 14319 Tab)); 14320 14321 EXPECT_EQ("void a(){\n" 14322 " // line starts with '\t'\n" 14323 "};", 14324 format("void a(){\n" 14325 "\t\t// line starts with '\t'\n" 14326 "};", 14327 Tab)); 14328 14329 Tab.UseTab = FormatStyle::UT_ForIndentation; 14330 EXPECT_EQ("void a(){\n" 14331 " // line starts with '\t'\n" 14332 "};", 14333 format("void a(){\n" 14334 "\t// line starts with '\t'\n" 14335 "};", 14336 Tab)); 14337 14338 EXPECT_EQ("void a(){\n" 14339 " // line starts with '\t'\n" 14340 "};", 14341 format("void a(){\n" 14342 "\t\t// line starts with '\t'\n" 14343 "};", 14344 Tab)); 14345 14346 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14347 EXPECT_EQ("void a(){\n" 14348 " // line starts with '\t'\n" 14349 "};", 14350 format("void a(){\n" 14351 "\t// line starts with '\t'\n" 14352 "};", 14353 Tab)); 14354 14355 EXPECT_EQ("void a(){\n" 14356 " // line starts with '\t'\n" 14357 "};", 14358 format("void a(){\n" 14359 "\t\t// line starts with '\t'\n" 14360 "};", 14361 Tab)); 14362 14363 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14364 EXPECT_EQ("void a(){\n" 14365 " // line starts with '\t'\n" 14366 "};", 14367 format("void a(){\n" 14368 "\t// line starts with '\t'\n" 14369 "};", 14370 Tab)); 14371 14372 EXPECT_EQ("void a(){\n" 14373 " // line starts with '\t'\n" 14374 "};", 14375 format("void a(){\n" 14376 "\t\t// line starts with '\t'\n" 14377 "};", 14378 Tab)); 14379 14380 Tab.UseTab = FormatStyle::UT_Always; 14381 EXPECT_EQ("void a(){\n" 14382 "// line starts with '\t'\n" 14383 "};", 14384 format("void a(){\n" 14385 "\t// line starts with '\t'\n" 14386 "};", 14387 Tab)); 14388 14389 EXPECT_EQ("void a(){\n" 14390 "// line starts with '\t'\n" 14391 "};", 14392 format("void a(){\n" 14393 "\t\t// line starts with '\t'\n" 14394 "};", 14395 Tab)); 14396 } 14397 14398 TEST_F(FormatTest, CalculatesOriginalColumn) { 14399 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14400 "q\"; /* some\n" 14401 " comment */", 14402 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14403 "q\"; /* some\n" 14404 " comment */", 14405 getLLVMStyle())); 14406 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14407 "/* some\n" 14408 " comment */", 14409 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14410 " /* some\n" 14411 " comment */", 14412 getLLVMStyle())); 14413 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14414 "qqq\n" 14415 "/* some\n" 14416 " comment */", 14417 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14418 "qqq\n" 14419 " /* some\n" 14420 " comment */", 14421 getLLVMStyle())); 14422 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14423 "wwww; /* some\n" 14424 " comment */", 14425 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14426 "wwww; /* some\n" 14427 " comment */", 14428 getLLVMStyle())); 14429 } 14430 14431 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14432 FormatStyle NoSpace = getLLVMStyle(); 14433 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14434 14435 verifyFormat("while(true)\n" 14436 " continue;", 14437 NoSpace); 14438 verifyFormat("for(;;)\n" 14439 " continue;", 14440 NoSpace); 14441 verifyFormat("if(true)\n" 14442 " f();\n" 14443 "else if(true)\n" 14444 " f();", 14445 NoSpace); 14446 verifyFormat("do {\n" 14447 " do_something();\n" 14448 "} while(something());", 14449 NoSpace); 14450 verifyFormat("switch(x) {\n" 14451 "default:\n" 14452 " break;\n" 14453 "}", 14454 NoSpace); 14455 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14456 verifyFormat("size_t x = sizeof(x);", NoSpace); 14457 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14458 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14459 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14460 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14461 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14462 verifyFormat("alignas(128) char a[128];", NoSpace); 14463 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14464 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14465 verifyFormat("int f() throw(Deprecated);", NoSpace); 14466 verifyFormat("typedef void (*cb)(int);", NoSpace); 14467 verifyFormat("T A::operator()();", NoSpace); 14468 verifyFormat("X A::operator++(T);", NoSpace); 14469 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14470 14471 FormatStyle Space = getLLVMStyle(); 14472 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14473 14474 verifyFormat("int f ();", Space); 14475 verifyFormat("void f (int a, T b) {\n" 14476 " while (true)\n" 14477 " continue;\n" 14478 "}", 14479 Space); 14480 verifyFormat("if (true)\n" 14481 " f ();\n" 14482 "else if (true)\n" 14483 " f ();", 14484 Space); 14485 verifyFormat("do {\n" 14486 " do_something ();\n" 14487 "} while (something ());", 14488 Space); 14489 verifyFormat("switch (x) {\n" 14490 "default:\n" 14491 " break;\n" 14492 "}", 14493 Space); 14494 verifyFormat("A::A () : a (1) {}", Space); 14495 verifyFormat("void f () __attribute__ ((asdf));", Space); 14496 verifyFormat("*(&a + 1);\n" 14497 "&((&a)[1]);\n" 14498 "a[(b + c) * d];\n" 14499 "(((a + 1) * 2) + 3) * 4;", 14500 Space); 14501 verifyFormat("#define A(x) x", Space); 14502 verifyFormat("#define A (x) x", Space); 14503 verifyFormat("#if defined(x)\n" 14504 "#endif", 14505 Space); 14506 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14507 verifyFormat("size_t x = sizeof (x);", Space); 14508 verifyFormat("auto f (int x) -> decltype (x);", Space); 14509 verifyFormat("auto f (int x) -> typeof (x);", Space); 14510 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14511 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14512 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14513 verifyFormat("alignas (128) char a[128];", Space); 14514 verifyFormat("size_t x = alignof (MyType);", Space); 14515 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14516 verifyFormat("int f () throw (Deprecated);", Space); 14517 verifyFormat("typedef void (*cb) (int);", Space); 14518 // FIXME these tests regressed behaviour. 14519 // verifyFormat("T A::operator() ();", Space); 14520 // verifyFormat("X A::operator++ (T);", Space); 14521 verifyFormat("auto lambda = [] () { return 0; };", Space); 14522 verifyFormat("int x = int (y);", Space); 14523 14524 FormatStyle SomeSpace = getLLVMStyle(); 14525 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14526 14527 verifyFormat("[]() -> float {}", SomeSpace); 14528 verifyFormat("[] (auto foo) {}", SomeSpace); 14529 verifyFormat("[foo]() -> int {}", SomeSpace); 14530 verifyFormat("int f();", SomeSpace); 14531 verifyFormat("void f (int a, T b) {\n" 14532 " while (true)\n" 14533 " continue;\n" 14534 "}", 14535 SomeSpace); 14536 verifyFormat("if (true)\n" 14537 " f();\n" 14538 "else if (true)\n" 14539 " f();", 14540 SomeSpace); 14541 verifyFormat("do {\n" 14542 " do_something();\n" 14543 "} while (something());", 14544 SomeSpace); 14545 verifyFormat("switch (x) {\n" 14546 "default:\n" 14547 " break;\n" 14548 "}", 14549 SomeSpace); 14550 verifyFormat("A::A() : a (1) {}", SomeSpace); 14551 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14552 verifyFormat("*(&a + 1);\n" 14553 "&((&a)[1]);\n" 14554 "a[(b + c) * d];\n" 14555 "(((a + 1) * 2) + 3) * 4;", 14556 SomeSpace); 14557 verifyFormat("#define A(x) x", SomeSpace); 14558 verifyFormat("#define A (x) x", SomeSpace); 14559 verifyFormat("#if defined(x)\n" 14560 "#endif", 14561 SomeSpace); 14562 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14563 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14564 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14565 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14566 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14567 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14568 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14569 verifyFormat("alignas (128) char a[128];", SomeSpace); 14570 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14571 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14572 SomeSpace); 14573 verifyFormat("int f() throw (Deprecated);", SomeSpace); 14574 verifyFormat("typedef void (*cb) (int);", SomeSpace); 14575 verifyFormat("T A::operator()();", SomeSpace); 14576 // FIXME these tests regressed behaviour. 14577 // verifyFormat("X A::operator++ (T);", SomeSpace); 14578 verifyFormat("int x = int (y);", SomeSpace); 14579 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 14580 14581 FormatStyle SpaceControlStatements = getLLVMStyle(); 14582 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14583 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 14584 14585 verifyFormat("while (true)\n" 14586 " continue;", 14587 SpaceControlStatements); 14588 verifyFormat("if (true)\n" 14589 " f();\n" 14590 "else if (true)\n" 14591 " f();", 14592 SpaceControlStatements); 14593 verifyFormat("for (;;) {\n" 14594 " do_something();\n" 14595 "}", 14596 SpaceControlStatements); 14597 verifyFormat("do {\n" 14598 " do_something();\n" 14599 "} while (something());", 14600 SpaceControlStatements); 14601 verifyFormat("switch (x) {\n" 14602 "default:\n" 14603 " break;\n" 14604 "}", 14605 SpaceControlStatements); 14606 14607 FormatStyle SpaceFuncDecl = getLLVMStyle(); 14608 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14609 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 14610 14611 verifyFormat("int f ();", SpaceFuncDecl); 14612 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 14613 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 14614 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 14615 verifyFormat("#define A(x) x", SpaceFuncDecl); 14616 verifyFormat("#define A (x) x", SpaceFuncDecl); 14617 verifyFormat("#if defined(x)\n" 14618 "#endif", 14619 SpaceFuncDecl); 14620 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 14621 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 14622 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 14623 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 14624 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 14625 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 14626 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 14627 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 14628 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 14629 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14630 SpaceFuncDecl); 14631 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 14632 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 14633 // FIXME these tests regressed behaviour. 14634 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 14635 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 14636 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 14637 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 14638 verifyFormat("int x = int(y);", SpaceFuncDecl); 14639 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14640 SpaceFuncDecl); 14641 14642 FormatStyle SpaceFuncDef = getLLVMStyle(); 14643 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14644 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 14645 14646 verifyFormat("int f();", SpaceFuncDef); 14647 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 14648 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 14649 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 14650 verifyFormat("#define A(x) x", SpaceFuncDef); 14651 verifyFormat("#define A (x) x", SpaceFuncDef); 14652 verifyFormat("#if defined(x)\n" 14653 "#endif", 14654 SpaceFuncDef); 14655 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 14656 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 14657 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 14658 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 14659 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 14660 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 14661 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 14662 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 14663 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 14664 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14665 SpaceFuncDef); 14666 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 14667 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 14668 verifyFormat("T A::operator()();", SpaceFuncDef); 14669 verifyFormat("X A::operator++(T);", SpaceFuncDef); 14670 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 14671 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 14672 verifyFormat("int x = int(y);", SpaceFuncDef); 14673 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14674 SpaceFuncDef); 14675 14676 FormatStyle SpaceIfMacros = getLLVMStyle(); 14677 SpaceIfMacros.IfMacros.clear(); 14678 SpaceIfMacros.IfMacros.push_back("MYIF"); 14679 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14680 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 14681 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 14682 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 14683 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 14684 14685 FormatStyle SpaceForeachMacros = getLLVMStyle(); 14686 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 14687 FormatStyle::SBS_Never); 14688 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 14689 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14690 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 14691 verifyFormat("for (;;) {\n" 14692 "}", 14693 SpaceForeachMacros); 14694 verifyFormat("foreach (Item *item, itemlist) {\n" 14695 "}", 14696 SpaceForeachMacros); 14697 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 14698 "}", 14699 SpaceForeachMacros); 14700 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 14701 "}", 14702 SpaceForeachMacros); 14703 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 14704 14705 FormatStyle SomeSpace2 = getLLVMStyle(); 14706 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14707 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 14708 verifyFormat("[]() -> float {}", SomeSpace2); 14709 verifyFormat("[] (auto foo) {}", SomeSpace2); 14710 verifyFormat("[foo]() -> int {}", SomeSpace2); 14711 verifyFormat("int f();", SomeSpace2); 14712 verifyFormat("void f (int a, T b) {\n" 14713 " while (true)\n" 14714 " continue;\n" 14715 "}", 14716 SomeSpace2); 14717 verifyFormat("if (true)\n" 14718 " f();\n" 14719 "else if (true)\n" 14720 " f();", 14721 SomeSpace2); 14722 verifyFormat("do {\n" 14723 " do_something();\n" 14724 "} while (something());", 14725 SomeSpace2); 14726 verifyFormat("switch (x) {\n" 14727 "default:\n" 14728 " break;\n" 14729 "}", 14730 SomeSpace2); 14731 verifyFormat("A::A() : a (1) {}", SomeSpace2); 14732 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 14733 verifyFormat("*(&a + 1);\n" 14734 "&((&a)[1]);\n" 14735 "a[(b + c) * d];\n" 14736 "(((a + 1) * 2) + 3) * 4;", 14737 SomeSpace2); 14738 verifyFormat("#define A(x) x", SomeSpace2); 14739 verifyFormat("#define A (x) x", SomeSpace2); 14740 verifyFormat("#if defined(x)\n" 14741 "#endif", 14742 SomeSpace2); 14743 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 14744 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 14745 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 14746 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 14747 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 14748 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 14749 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 14750 verifyFormat("alignas (128) char a[128];", SomeSpace2); 14751 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 14752 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14753 SomeSpace2); 14754 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 14755 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 14756 verifyFormat("T A::operator()();", SomeSpace2); 14757 // verifyFormat("X A::operator++ (T);", SomeSpace2); 14758 verifyFormat("int x = int (y);", SomeSpace2); 14759 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 14760 14761 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 14762 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14763 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 14764 .AfterOverloadedOperator = true; 14765 14766 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 14767 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 14768 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 14769 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 14770 14771 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 14772 .AfterOverloadedOperator = false; 14773 14774 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 14775 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 14776 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 14777 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 14778 } 14779 14780 TEST_F(FormatTest, SpaceAfterLogicalNot) { 14781 FormatStyle Spaces = getLLVMStyle(); 14782 Spaces.SpaceAfterLogicalNot = true; 14783 14784 verifyFormat("bool x = ! y", Spaces); 14785 verifyFormat("if (! isFailure())", Spaces); 14786 verifyFormat("if (! (a && b))", Spaces); 14787 verifyFormat("\"Error!\"", Spaces); 14788 verifyFormat("! ! x", Spaces); 14789 } 14790 14791 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 14792 FormatStyle Spaces = getLLVMStyle(); 14793 14794 Spaces.SpacesInParentheses = true; 14795 verifyFormat("do_something( ::globalVar );", Spaces); 14796 verifyFormat("call( x, y, z );", Spaces); 14797 verifyFormat("call();", Spaces); 14798 verifyFormat("std::function<void( int, int )> callback;", Spaces); 14799 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 14800 Spaces); 14801 verifyFormat("while ( (bool)1 )\n" 14802 " continue;", 14803 Spaces); 14804 verifyFormat("for ( ;; )\n" 14805 " continue;", 14806 Spaces); 14807 verifyFormat("if ( true )\n" 14808 " f();\n" 14809 "else if ( true )\n" 14810 " f();", 14811 Spaces); 14812 verifyFormat("do {\n" 14813 " do_something( (int)i );\n" 14814 "} while ( something() );", 14815 Spaces); 14816 verifyFormat("switch ( x ) {\n" 14817 "default:\n" 14818 " break;\n" 14819 "}", 14820 Spaces); 14821 14822 Spaces.SpacesInParentheses = false; 14823 Spaces.SpacesInCStyleCastParentheses = true; 14824 verifyFormat("Type *A = ( Type * )P;", Spaces); 14825 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 14826 verifyFormat("x = ( int32 )y;", Spaces); 14827 verifyFormat("int a = ( int )(2.0f);", Spaces); 14828 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 14829 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 14830 verifyFormat("#define x (( int )-1)", Spaces); 14831 14832 // Run the first set of tests again with: 14833 Spaces.SpacesInParentheses = false; 14834 Spaces.SpaceInEmptyParentheses = true; 14835 Spaces.SpacesInCStyleCastParentheses = true; 14836 verifyFormat("call(x, y, z);", Spaces); 14837 verifyFormat("call( );", Spaces); 14838 verifyFormat("std::function<void(int, int)> callback;", Spaces); 14839 verifyFormat("while (( bool )1)\n" 14840 " continue;", 14841 Spaces); 14842 verifyFormat("for (;;)\n" 14843 " continue;", 14844 Spaces); 14845 verifyFormat("if (true)\n" 14846 " f( );\n" 14847 "else if (true)\n" 14848 " f( );", 14849 Spaces); 14850 verifyFormat("do {\n" 14851 " do_something(( int )i);\n" 14852 "} while (something( ));", 14853 Spaces); 14854 verifyFormat("switch (x) {\n" 14855 "default:\n" 14856 " break;\n" 14857 "}", 14858 Spaces); 14859 14860 // Run the first set of tests again with: 14861 Spaces.SpaceAfterCStyleCast = true; 14862 verifyFormat("call(x, y, z);", Spaces); 14863 verifyFormat("call( );", Spaces); 14864 verifyFormat("std::function<void(int, int)> callback;", Spaces); 14865 verifyFormat("while (( bool ) 1)\n" 14866 " continue;", 14867 Spaces); 14868 verifyFormat("for (;;)\n" 14869 " continue;", 14870 Spaces); 14871 verifyFormat("if (true)\n" 14872 " f( );\n" 14873 "else if (true)\n" 14874 " f( );", 14875 Spaces); 14876 verifyFormat("do {\n" 14877 " do_something(( int ) i);\n" 14878 "} while (something( ));", 14879 Spaces); 14880 verifyFormat("switch (x) {\n" 14881 "default:\n" 14882 " break;\n" 14883 "}", 14884 Spaces); 14885 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 14886 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 14887 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 14888 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 14889 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 14890 14891 // Run subset of tests again with: 14892 Spaces.SpacesInCStyleCastParentheses = false; 14893 Spaces.SpaceAfterCStyleCast = true; 14894 verifyFormat("while ((bool) 1)\n" 14895 " continue;", 14896 Spaces); 14897 verifyFormat("do {\n" 14898 " do_something((int) i);\n" 14899 "} while (something( ));", 14900 Spaces); 14901 14902 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 14903 verifyFormat("size_t idx = (size_t) a;", Spaces); 14904 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 14905 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 14906 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 14907 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 14908 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 14909 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 14910 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 14911 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 14912 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 14913 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 14914 Spaces.ColumnLimit = 80; 14915 Spaces.IndentWidth = 4; 14916 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 14917 verifyFormat("void foo( ) {\n" 14918 " size_t foo = (*(function))(\n" 14919 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 14920 "BarrrrrrrrrrrrLong,\n" 14921 " FoooooooooLooooong);\n" 14922 "}", 14923 Spaces); 14924 Spaces.SpaceAfterCStyleCast = false; 14925 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 14926 verifyFormat("size_t idx = (size_t)a;", Spaces); 14927 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 14928 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 14929 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 14930 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 14931 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 14932 14933 verifyFormat("void foo( ) {\n" 14934 " size_t foo = (*(function))(\n" 14935 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 14936 "BarrrrrrrrrrrrLong,\n" 14937 " FoooooooooLooooong);\n" 14938 "}", 14939 Spaces); 14940 } 14941 14942 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 14943 verifyFormat("int a[5];"); 14944 verifyFormat("a[3] += 42;"); 14945 14946 FormatStyle Spaces = getLLVMStyle(); 14947 Spaces.SpacesInSquareBrackets = true; 14948 // Not lambdas. 14949 verifyFormat("int a[ 5 ];", Spaces); 14950 verifyFormat("a[ 3 ] += 42;", Spaces); 14951 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 14952 verifyFormat("double &operator[](int i) { return 0; }\n" 14953 "int i;", 14954 Spaces); 14955 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 14956 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 14957 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 14958 // Lambdas. 14959 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 14960 verifyFormat("return [ i, args... ] {};", Spaces); 14961 verifyFormat("int foo = [ &bar ]() {};", Spaces); 14962 verifyFormat("int foo = [ = ]() {};", Spaces); 14963 verifyFormat("int foo = [ & ]() {};", Spaces); 14964 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 14965 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 14966 } 14967 14968 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 14969 FormatStyle NoSpaceStyle = getLLVMStyle(); 14970 verifyFormat("int a[5];", NoSpaceStyle); 14971 verifyFormat("a[3] += 42;", NoSpaceStyle); 14972 14973 verifyFormat("int a[1];", NoSpaceStyle); 14974 verifyFormat("int 1 [a];", NoSpaceStyle); 14975 verifyFormat("int a[1][2];", NoSpaceStyle); 14976 verifyFormat("a[7] = 5;", NoSpaceStyle); 14977 verifyFormat("int a = (f())[23];", NoSpaceStyle); 14978 verifyFormat("f([] {})", NoSpaceStyle); 14979 14980 FormatStyle Space = getLLVMStyle(); 14981 Space.SpaceBeforeSquareBrackets = true; 14982 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 14983 verifyFormat("return [i, args...] {};", Space); 14984 14985 verifyFormat("int a [5];", Space); 14986 verifyFormat("a [3] += 42;", Space); 14987 verifyFormat("constexpr char hello []{\"hello\"};", Space); 14988 verifyFormat("double &operator[](int i) { return 0; }\n" 14989 "int i;", 14990 Space); 14991 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 14992 verifyFormat("int i = a [a][a]->f();", Space); 14993 verifyFormat("int i = (*b) [a]->f();", Space); 14994 14995 verifyFormat("int a [1];", Space); 14996 verifyFormat("int 1 [a];", Space); 14997 verifyFormat("int a [1][2];", Space); 14998 verifyFormat("a [7] = 5;", Space); 14999 verifyFormat("int a = (f()) [23];", Space); 15000 verifyFormat("f([] {})", Space); 15001 } 15002 15003 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15004 verifyFormat("int a = 5;"); 15005 verifyFormat("a += 42;"); 15006 verifyFormat("a or_eq 8;"); 15007 15008 FormatStyle Spaces = getLLVMStyle(); 15009 Spaces.SpaceBeforeAssignmentOperators = false; 15010 verifyFormat("int a= 5;", Spaces); 15011 verifyFormat("a+= 42;", Spaces); 15012 verifyFormat("a or_eq 8;", Spaces); 15013 } 15014 15015 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15016 verifyFormat("class Foo : public Bar {};"); 15017 verifyFormat("Foo::Foo() : foo(1) {}"); 15018 verifyFormat("for (auto a : b) {\n}"); 15019 verifyFormat("int x = a ? b : c;"); 15020 verifyFormat("{\n" 15021 "label0:\n" 15022 " int x = 0;\n" 15023 "}"); 15024 verifyFormat("switch (x) {\n" 15025 "case 1:\n" 15026 "default:\n" 15027 "}"); 15028 verifyFormat("switch (allBraces) {\n" 15029 "case 1: {\n" 15030 " break;\n" 15031 "}\n" 15032 "case 2: {\n" 15033 " [[fallthrough]];\n" 15034 "}\n" 15035 "default: {\n" 15036 " break;\n" 15037 "}\n" 15038 "}"); 15039 15040 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15041 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15042 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15043 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15044 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15045 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15046 verifyFormat("{\n" 15047 "label1:\n" 15048 " int x = 0;\n" 15049 "}", 15050 CtorInitializerStyle); 15051 verifyFormat("switch (x) {\n" 15052 "case 1:\n" 15053 "default:\n" 15054 "}", 15055 CtorInitializerStyle); 15056 verifyFormat("switch (allBraces) {\n" 15057 "case 1: {\n" 15058 " break;\n" 15059 "}\n" 15060 "case 2: {\n" 15061 " [[fallthrough]];\n" 15062 "}\n" 15063 "default: {\n" 15064 " break;\n" 15065 "}\n" 15066 "}", 15067 CtorInitializerStyle); 15068 CtorInitializerStyle.BreakConstructorInitializers = 15069 FormatStyle::BCIS_AfterColon; 15070 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15071 " aaaaaaaaaaaaaaaa(1),\n" 15072 " bbbbbbbbbbbbbbbb(2) {}", 15073 CtorInitializerStyle); 15074 CtorInitializerStyle.BreakConstructorInitializers = 15075 FormatStyle::BCIS_BeforeComma; 15076 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15077 " : aaaaaaaaaaaaaaaa(1)\n" 15078 " , bbbbbbbbbbbbbbbb(2) {}", 15079 CtorInitializerStyle); 15080 CtorInitializerStyle.BreakConstructorInitializers = 15081 FormatStyle::BCIS_BeforeColon; 15082 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15083 " : aaaaaaaaaaaaaaaa(1),\n" 15084 " bbbbbbbbbbbbbbbb(2) {}", 15085 CtorInitializerStyle); 15086 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15087 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15088 ": aaaaaaaaaaaaaaaa(1),\n" 15089 " bbbbbbbbbbbbbbbb(2) {}", 15090 CtorInitializerStyle); 15091 15092 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15093 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15094 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15095 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15096 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15097 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15098 verifyFormat("{\n" 15099 "label2:\n" 15100 " int x = 0;\n" 15101 "}", 15102 InheritanceStyle); 15103 verifyFormat("switch (x) {\n" 15104 "case 1:\n" 15105 "default:\n" 15106 "}", 15107 InheritanceStyle); 15108 verifyFormat("switch (allBraces) {\n" 15109 "case 1: {\n" 15110 " break;\n" 15111 "}\n" 15112 "case 2: {\n" 15113 " [[fallthrough]];\n" 15114 "}\n" 15115 "default: {\n" 15116 " break;\n" 15117 "}\n" 15118 "}", 15119 InheritanceStyle); 15120 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15121 verifyFormat("class Foooooooooooooooooooooo\n" 15122 " : public aaaaaaaaaaaaaaaaaa,\n" 15123 " public bbbbbbbbbbbbbbbbbb {\n" 15124 "}", 15125 InheritanceStyle); 15126 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15127 verifyFormat("class Foooooooooooooooooooooo:\n" 15128 " public aaaaaaaaaaaaaaaaaa,\n" 15129 " public bbbbbbbbbbbbbbbbbb {\n" 15130 "}", 15131 InheritanceStyle); 15132 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15133 verifyFormat("class Foooooooooooooooooooooo\n" 15134 " : public aaaaaaaaaaaaaaaaaa\n" 15135 " , public bbbbbbbbbbbbbbbbbb {\n" 15136 "}", 15137 InheritanceStyle); 15138 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15139 verifyFormat("class Foooooooooooooooooooooo\n" 15140 " : public aaaaaaaaaaaaaaaaaa,\n" 15141 " public bbbbbbbbbbbbbbbbbb {\n" 15142 "}", 15143 InheritanceStyle); 15144 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15145 verifyFormat("class Foooooooooooooooooooooo\n" 15146 ": public aaaaaaaaaaaaaaaaaa,\n" 15147 " public bbbbbbbbbbbbbbbbbb {}", 15148 InheritanceStyle); 15149 15150 FormatStyle ForLoopStyle = getLLVMStyle(); 15151 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15152 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15153 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15154 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15155 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15156 verifyFormat("{\n" 15157 "label2:\n" 15158 " int x = 0;\n" 15159 "}", 15160 ForLoopStyle); 15161 verifyFormat("switch (x) {\n" 15162 "case 1:\n" 15163 "default:\n" 15164 "}", 15165 ForLoopStyle); 15166 verifyFormat("switch (allBraces) {\n" 15167 "case 1: {\n" 15168 " break;\n" 15169 "}\n" 15170 "case 2: {\n" 15171 " [[fallthrough]];\n" 15172 "}\n" 15173 "default: {\n" 15174 " break;\n" 15175 "}\n" 15176 "}", 15177 ForLoopStyle); 15178 15179 FormatStyle CaseStyle = getLLVMStyle(); 15180 CaseStyle.SpaceBeforeCaseColon = true; 15181 verifyFormat("class Foo : public Bar {};", CaseStyle); 15182 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15183 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15184 verifyFormat("int x = a ? b : c;", CaseStyle); 15185 verifyFormat("switch (x) {\n" 15186 "case 1 :\n" 15187 "default :\n" 15188 "}", 15189 CaseStyle); 15190 verifyFormat("switch (allBraces) {\n" 15191 "case 1 : {\n" 15192 " break;\n" 15193 "}\n" 15194 "case 2 : {\n" 15195 " [[fallthrough]];\n" 15196 "}\n" 15197 "default : {\n" 15198 " break;\n" 15199 "}\n" 15200 "}", 15201 CaseStyle); 15202 15203 FormatStyle NoSpaceStyle = getLLVMStyle(); 15204 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15205 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15206 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15207 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15208 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15209 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15210 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15211 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15212 verifyFormat("{\n" 15213 "label3:\n" 15214 " int x = 0;\n" 15215 "}", 15216 NoSpaceStyle); 15217 verifyFormat("switch (x) {\n" 15218 "case 1:\n" 15219 "default:\n" 15220 "}", 15221 NoSpaceStyle); 15222 verifyFormat("switch (allBraces) {\n" 15223 "case 1: {\n" 15224 " break;\n" 15225 "}\n" 15226 "case 2: {\n" 15227 " [[fallthrough]];\n" 15228 "}\n" 15229 "default: {\n" 15230 " break;\n" 15231 "}\n" 15232 "}", 15233 NoSpaceStyle); 15234 15235 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15236 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15237 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15238 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15239 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15240 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15241 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15242 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15243 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15244 verifyFormat("{\n" 15245 "label3:\n" 15246 " int x = 0;\n" 15247 "}", 15248 InvertedSpaceStyle); 15249 verifyFormat("switch (x) {\n" 15250 "case 1 :\n" 15251 "case 2 : {\n" 15252 " break;\n" 15253 "}\n" 15254 "default :\n" 15255 " break;\n" 15256 "}", 15257 InvertedSpaceStyle); 15258 verifyFormat("switch (allBraces) {\n" 15259 "case 1 : {\n" 15260 " break;\n" 15261 "}\n" 15262 "case 2 : {\n" 15263 " [[fallthrough]];\n" 15264 "}\n" 15265 "default : {\n" 15266 " break;\n" 15267 "}\n" 15268 "}", 15269 InvertedSpaceStyle); 15270 } 15271 15272 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15273 FormatStyle Style = getLLVMStyle(); 15274 15275 Style.PointerAlignment = FormatStyle::PAS_Left; 15276 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15277 verifyFormat("void* const* x = NULL;", Style); 15278 15279 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15280 do { \ 15281 Style.PointerAlignment = FormatStyle::Pointers; \ 15282 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15283 verifyFormat(Code, Style); \ 15284 } while (false) 15285 15286 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15287 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15288 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15289 15290 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15291 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15292 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15293 15294 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15295 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15296 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15297 15298 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15299 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15300 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15301 15302 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15303 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15304 SAPQ_Default); 15305 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15306 SAPQ_Default); 15307 15308 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15309 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15310 SAPQ_Before); 15311 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15312 SAPQ_Before); 15313 15314 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15315 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15316 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15317 SAPQ_After); 15318 15319 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15320 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15321 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15322 15323 #undef verifyQualifierSpaces 15324 15325 FormatStyle Spaces = getLLVMStyle(); 15326 Spaces.AttributeMacros.push_back("qualified"); 15327 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15328 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15329 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15330 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15331 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15332 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15333 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15334 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15335 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15336 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15337 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15338 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15339 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15340 15341 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15342 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15343 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15344 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15345 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15346 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15347 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15348 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15349 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15350 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15351 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15352 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15353 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15354 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15355 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15356 15357 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15358 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15359 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15360 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15361 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15362 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15363 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15364 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15365 } 15366 15367 TEST_F(FormatTest, AlignConsecutiveMacros) { 15368 FormatStyle Style = getLLVMStyle(); 15369 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15370 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15371 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15372 15373 verifyFormat("#define a 3\n" 15374 "#define bbbb 4\n" 15375 "#define ccc (5)", 15376 Style); 15377 15378 verifyFormat("#define f(x) (x * x)\n" 15379 "#define fff(x, y, z) (x * y + z)\n" 15380 "#define ffff(x, y) (x - y)", 15381 Style); 15382 15383 verifyFormat("#define foo(x, y) (x + y)\n" 15384 "#define bar (5, 6)(2 + 2)", 15385 Style); 15386 15387 verifyFormat("#define a 3\n" 15388 "#define bbbb 4\n" 15389 "#define ccc (5)\n" 15390 "#define f(x) (x * x)\n" 15391 "#define fff(x, y, z) (x * y + z)\n" 15392 "#define ffff(x, y) (x - y)", 15393 Style); 15394 15395 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15396 verifyFormat("#define a 3\n" 15397 "#define bbbb 4\n" 15398 "#define ccc (5)", 15399 Style); 15400 15401 verifyFormat("#define f(x) (x * x)\n" 15402 "#define fff(x, y, z) (x * y + z)\n" 15403 "#define ffff(x, y) (x - y)", 15404 Style); 15405 15406 verifyFormat("#define foo(x, y) (x + y)\n" 15407 "#define bar (5, 6)(2 + 2)", 15408 Style); 15409 15410 verifyFormat("#define a 3\n" 15411 "#define bbbb 4\n" 15412 "#define ccc (5)\n" 15413 "#define f(x) (x * x)\n" 15414 "#define fff(x, y, z) (x * y + z)\n" 15415 "#define ffff(x, y) (x - y)", 15416 Style); 15417 15418 verifyFormat("#define a 5\n" 15419 "#define foo(x, y) (x + y)\n" 15420 "#define CCC (6)\n" 15421 "auto lambda = []() {\n" 15422 " auto ii = 0;\n" 15423 " float j = 0;\n" 15424 " return 0;\n" 15425 "};\n" 15426 "int i = 0;\n" 15427 "float i2 = 0;\n" 15428 "auto v = type{\n" 15429 " i = 1, //\n" 15430 " (i = 2), //\n" 15431 " i = 3 //\n" 15432 "};", 15433 Style); 15434 15435 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15436 Style.ColumnLimit = 20; 15437 15438 verifyFormat("#define a \\\n" 15439 " \"aabbbbbbbbbbbb\"\n" 15440 "#define D \\\n" 15441 " \"aabbbbbbbbbbbb\" \\\n" 15442 " \"ccddeeeeeeeee\"\n" 15443 "#define B \\\n" 15444 " \"QQQQQQQQQQQQQ\" \\\n" 15445 " \"FFFFFFFFFFFFF\" \\\n" 15446 " \"LLLLLLLL\"\n", 15447 Style); 15448 15449 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15450 verifyFormat("#define a \\\n" 15451 " \"aabbbbbbbbbbbb\"\n" 15452 "#define D \\\n" 15453 " \"aabbbbbbbbbbbb\" \\\n" 15454 " \"ccddeeeeeeeee\"\n" 15455 "#define B \\\n" 15456 " \"QQQQQQQQQQQQQ\" \\\n" 15457 " \"FFFFFFFFFFFFF\" \\\n" 15458 " \"LLLLLLLL\"\n", 15459 Style); 15460 15461 // Test across comments 15462 Style.MaxEmptyLinesToKeep = 10; 15463 Style.ReflowComments = false; 15464 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15465 EXPECT_EQ("#define a 3\n" 15466 "// line comment\n" 15467 "#define bbbb 4\n" 15468 "#define ccc (5)", 15469 format("#define a 3\n" 15470 "// line comment\n" 15471 "#define bbbb 4\n" 15472 "#define ccc (5)", 15473 Style)); 15474 15475 EXPECT_EQ("#define a 3\n" 15476 "/* block comment */\n" 15477 "#define bbbb 4\n" 15478 "#define ccc (5)", 15479 format("#define a 3\n" 15480 "/* block comment */\n" 15481 "#define bbbb 4\n" 15482 "#define ccc (5)", 15483 Style)); 15484 15485 EXPECT_EQ("#define a 3\n" 15486 "/* multi-line *\n" 15487 " * block comment */\n" 15488 "#define bbbb 4\n" 15489 "#define ccc (5)", 15490 format("#define a 3\n" 15491 "/* multi-line *\n" 15492 " * block comment */\n" 15493 "#define bbbb 4\n" 15494 "#define ccc (5)", 15495 Style)); 15496 15497 EXPECT_EQ("#define a 3\n" 15498 "// multi-line line comment\n" 15499 "//\n" 15500 "#define bbbb 4\n" 15501 "#define ccc (5)", 15502 format("#define a 3\n" 15503 "// multi-line line comment\n" 15504 "//\n" 15505 "#define bbbb 4\n" 15506 "#define ccc (5)", 15507 Style)); 15508 15509 EXPECT_EQ("#define a 3\n" 15510 "// empty lines still break.\n" 15511 "\n" 15512 "#define bbbb 4\n" 15513 "#define ccc (5)", 15514 format("#define a 3\n" 15515 "// empty lines still break.\n" 15516 "\n" 15517 "#define bbbb 4\n" 15518 "#define ccc (5)", 15519 Style)); 15520 15521 // Test across empty lines 15522 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 15523 EXPECT_EQ("#define a 3\n" 15524 "\n" 15525 "#define bbbb 4\n" 15526 "#define ccc (5)", 15527 format("#define a 3\n" 15528 "\n" 15529 "#define bbbb 4\n" 15530 "#define ccc (5)", 15531 Style)); 15532 15533 EXPECT_EQ("#define a 3\n" 15534 "\n" 15535 "\n" 15536 "\n" 15537 "#define bbbb 4\n" 15538 "#define ccc (5)", 15539 format("#define a 3\n" 15540 "\n" 15541 "\n" 15542 "\n" 15543 "#define bbbb 4\n" 15544 "#define ccc (5)", 15545 Style)); 15546 15547 EXPECT_EQ("#define a 3\n" 15548 "// comments should break alignment\n" 15549 "//\n" 15550 "#define bbbb 4\n" 15551 "#define ccc (5)", 15552 format("#define a 3\n" 15553 "// comments should break alignment\n" 15554 "//\n" 15555 "#define bbbb 4\n" 15556 "#define ccc (5)", 15557 Style)); 15558 15559 // Test across empty lines and comments 15560 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 15561 verifyFormat("#define a 3\n" 15562 "\n" 15563 "// line comment\n" 15564 "#define bbbb 4\n" 15565 "#define ccc (5)", 15566 Style); 15567 15568 EXPECT_EQ("#define a 3\n" 15569 "\n" 15570 "\n" 15571 "/* multi-line *\n" 15572 " * block comment */\n" 15573 "\n" 15574 "\n" 15575 "#define bbbb 4\n" 15576 "#define ccc (5)", 15577 format("#define a 3\n" 15578 "\n" 15579 "\n" 15580 "/* multi-line *\n" 15581 " * block comment */\n" 15582 "\n" 15583 "\n" 15584 "#define bbbb 4\n" 15585 "#define ccc (5)", 15586 Style)); 15587 15588 EXPECT_EQ("#define a 3\n" 15589 "\n" 15590 "\n" 15591 "/* multi-line *\n" 15592 " * block comment */\n" 15593 "\n" 15594 "\n" 15595 "#define bbbb 4\n" 15596 "#define ccc (5)", 15597 format("#define a 3\n" 15598 "\n" 15599 "\n" 15600 "/* multi-line *\n" 15601 " * block comment */\n" 15602 "\n" 15603 "\n" 15604 "#define bbbb 4\n" 15605 "#define ccc (5)", 15606 Style)); 15607 } 15608 15609 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 15610 FormatStyle Alignment = getLLVMStyle(); 15611 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15612 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 15613 15614 Alignment.MaxEmptyLinesToKeep = 10; 15615 /* Test alignment across empty lines */ 15616 EXPECT_EQ("int a = 5;\n" 15617 "\n" 15618 "int oneTwoThree = 123;", 15619 format("int a = 5;\n" 15620 "\n" 15621 "int oneTwoThree= 123;", 15622 Alignment)); 15623 EXPECT_EQ("int a = 5;\n" 15624 "int one = 1;\n" 15625 "\n" 15626 "int oneTwoThree = 123;", 15627 format("int a = 5;\n" 15628 "int one = 1;\n" 15629 "\n" 15630 "int oneTwoThree = 123;", 15631 Alignment)); 15632 EXPECT_EQ("int a = 5;\n" 15633 "int one = 1;\n" 15634 "\n" 15635 "int oneTwoThree = 123;\n" 15636 "int oneTwo = 12;", 15637 format("int a = 5;\n" 15638 "int one = 1;\n" 15639 "\n" 15640 "int oneTwoThree = 123;\n" 15641 "int oneTwo = 12;", 15642 Alignment)); 15643 15644 /* Test across comments */ 15645 EXPECT_EQ("int a = 5;\n" 15646 "/* block comment */\n" 15647 "int oneTwoThree = 123;", 15648 format("int a = 5;\n" 15649 "/* block comment */\n" 15650 "int oneTwoThree=123;", 15651 Alignment)); 15652 15653 EXPECT_EQ("int a = 5;\n" 15654 "// line comment\n" 15655 "int oneTwoThree = 123;", 15656 format("int a = 5;\n" 15657 "// line comment\n" 15658 "int oneTwoThree=123;", 15659 Alignment)); 15660 15661 /* Test across comments and newlines */ 15662 EXPECT_EQ("int a = 5;\n" 15663 "\n" 15664 "/* block comment */\n" 15665 "int oneTwoThree = 123;", 15666 format("int a = 5;\n" 15667 "\n" 15668 "/* block comment */\n" 15669 "int oneTwoThree=123;", 15670 Alignment)); 15671 15672 EXPECT_EQ("int a = 5;\n" 15673 "\n" 15674 "// line comment\n" 15675 "int oneTwoThree = 123;", 15676 format("int a = 5;\n" 15677 "\n" 15678 "// line comment\n" 15679 "int oneTwoThree=123;", 15680 Alignment)); 15681 } 15682 15683 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 15684 FormatStyle Alignment = getLLVMStyle(); 15685 Alignment.AlignConsecutiveDeclarations = 15686 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15687 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15688 15689 Alignment.MaxEmptyLinesToKeep = 10; 15690 /* Test alignment across empty lines */ 15691 EXPECT_EQ("int a = 5;\n" 15692 "\n" 15693 "float const oneTwoThree = 123;", 15694 format("int a = 5;\n" 15695 "\n" 15696 "float const oneTwoThree = 123;", 15697 Alignment)); 15698 EXPECT_EQ("int a = 5;\n" 15699 "float const one = 1;\n" 15700 "\n" 15701 "int oneTwoThree = 123;", 15702 format("int a = 5;\n" 15703 "float const one = 1;\n" 15704 "\n" 15705 "int oneTwoThree = 123;", 15706 Alignment)); 15707 15708 /* Test across comments */ 15709 EXPECT_EQ("float const a = 5;\n" 15710 "/* block comment */\n" 15711 "int oneTwoThree = 123;", 15712 format("float const a = 5;\n" 15713 "/* block comment */\n" 15714 "int oneTwoThree=123;", 15715 Alignment)); 15716 15717 EXPECT_EQ("float const a = 5;\n" 15718 "// line comment\n" 15719 "int oneTwoThree = 123;", 15720 format("float const a = 5;\n" 15721 "// line comment\n" 15722 "int oneTwoThree=123;", 15723 Alignment)); 15724 15725 /* Test across comments and newlines */ 15726 EXPECT_EQ("float const a = 5;\n" 15727 "\n" 15728 "/* block comment */\n" 15729 "int oneTwoThree = 123;", 15730 format("float const a = 5;\n" 15731 "\n" 15732 "/* block comment */\n" 15733 "int oneTwoThree=123;", 15734 Alignment)); 15735 15736 EXPECT_EQ("float const a = 5;\n" 15737 "\n" 15738 "// line comment\n" 15739 "int oneTwoThree = 123;", 15740 format("float const a = 5;\n" 15741 "\n" 15742 "// line comment\n" 15743 "int oneTwoThree=123;", 15744 Alignment)); 15745 } 15746 15747 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 15748 FormatStyle Alignment = getLLVMStyle(); 15749 Alignment.AlignConsecutiveBitFields = 15750 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15751 15752 Alignment.MaxEmptyLinesToKeep = 10; 15753 /* Test alignment across empty lines */ 15754 EXPECT_EQ("int a : 5;\n" 15755 "\n" 15756 "int longbitfield : 6;", 15757 format("int a : 5;\n" 15758 "\n" 15759 "int longbitfield : 6;", 15760 Alignment)); 15761 EXPECT_EQ("int a : 5;\n" 15762 "int one : 1;\n" 15763 "\n" 15764 "int longbitfield : 6;", 15765 format("int a : 5;\n" 15766 "int one : 1;\n" 15767 "\n" 15768 "int longbitfield : 6;", 15769 Alignment)); 15770 15771 /* Test across comments */ 15772 EXPECT_EQ("int a : 5;\n" 15773 "/* block comment */\n" 15774 "int longbitfield : 6;", 15775 format("int a : 5;\n" 15776 "/* block comment */\n" 15777 "int longbitfield : 6;", 15778 Alignment)); 15779 EXPECT_EQ("int a : 5;\n" 15780 "int one : 1;\n" 15781 "// line comment\n" 15782 "int longbitfield : 6;", 15783 format("int a : 5;\n" 15784 "int one : 1;\n" 15785 "// line comment\n" 15786 "int longbitfield : 6;", 15787 Alignment)); 15788 15789 /* Test across comments and newlines */ 15790 EXPECT_EQ("int a : 5;\n" 15791 "/* block comment */\n" 15792 "\n" 15793 "int longbitfield : 6;", 15794 format("int a : 5;\n" 15795 "/* block comment */\n" 15796 "\n" 15797 "int longbitfield : 6;", 15798 Alignment)); 15799 EXPECT_EQ("int a : 5;\n" 15800 "int one : 1;\n" 15801 "\n" 15802 "// line comment\n" 15803 "\n" 15804 "int longbitfield : 6;", 15805 format("int a : 5;\n" 15806 "int one : 1;\n" 15807 "\n" 15808 "// line comment \n" 15809 "\n" 15810 "int longbitfield : 6;", 15811 Alignment)); 15812 } 15813 15814 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 15815 FormatStyle Alignment = getLLVMStyle(); 15816 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15817 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 15818 15819 Alignment.MaxEmptyLinesToKeep = 10; 15820 /* Test alignment across empty lines */ 15821 EXPECT_EQ("int a = 5;\n" 15822 "\n" 15823 "int oneTwoThree = 123;", 15824 format("int a = 5;\n" 15825 "\n" 15826 "int oneTwoThree= 123;", 15827 Alignment)); 15828 EXPECT_EQ("int a = 5;\n" 15829 "int one = 1;\n" 15830 "\n" 15831 "int oneTwoThree = 123;", 15832 format("int a = 5;\n" 15833 "int one = 1;\n" 15834 "\n" 15835 "int oneTwoThree = 123;", 15836 Alignment)); 15837 15838 /* Test across comments */ 15839 EXPECT_EQ("int a = 5;\n" 15840 "/* block comment */\n" 15841 "int oneTwoThree = 123;", 15842 format("int a = 5;\n" 15843 "/* block comment */\n" 15844 "int oneTwoThree=123;", 15845 Alignment)); 15846 15847 EXPECT_EQ("int a = 5;\n" 15848 "// line comment\n" 15849 "int oneTwoThree = 123;", 15850 format("int a = 5;\n" 15851 "// line comment\n" 15852 "int oneTwoThree=123;", 15853 Alignment)); 15854 15855 EXPECT_EQ("int a = 5;\n" 15856 "/*\n" 15857 " * multi-line block comment\n" 15858 " */\n" 15859 "int oneTwoThree = 123;", 15860 format("int a = 5;\n" 15861 "/*\n" 15862 " * multi-line block comment\n" 15863 " */\n" 15864 "int oneTwoThree=123;", 15865 Alignment)); 15866 15867 EXPECT_EQ("int a = 5;\n" 15868 "//\n" 15869 "// multi-line line comment\n" 15870 "//\n" 15871 "int oneTwoThree = 123;", 15872 format("int a = 5;\n" 15873 "//\n" 15874 "// multi-line line comment\n" 15875 "//\n" 15876 "int oneTwoThree=123;", 15877 Alignment)); 15878 15879 /* Test across comments and newlines */ 15880 EXPECT_EQ("int a = 5;\n" 15881 "\n" 15882 "/* block comment */\n" 15883 "int oneTwoThree = 123;", 15884 format("int a = 5;\n" 15885 "\n" 15886 "/* block comment */\n" 15887 "int oneTwoThree=123;", 15888 Alignment)); 15889 15890 EXPECT_EQ("int a = 5;\n" 15891 "\n" 15892 "// line comment\n" 15893 "int oneTwoThree = 123;", 15894 format("int a = 5;\n" 15895 "\n" 15896 "// line comment\n" 15897 "int oneTwoThree=123;", 15898 Alignment)); 15899 } 15900 15901 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 15902 FormatStyle Alignment = getLLVMStyle(); 15903 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15904 Alignment.AlignConsecutiveAssignments = 15905 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15906 verifyFormat("int a = 5;\n" 15907 "int oneTwoThree = 123;", 15908 Alignment); 15909 verifyFormat("int a = method();\n" 15910 "int oneTwoThree = 133;", 15911 Alignment); 15912 verifyFormat("a &= 5;\n" 15913 "bcd *= 5;\n" 15914 "ghtyf += 5;\n" 15915 "dvfvdb -= 5;\n" 15916 "a /= 5;\n" 15917 "vdsvsv %= 5;\n" 15918 "sfdbddfbdfbb ^= 5;\n" 15919 "dvsdsv |= 5;\n" 15920 "int dsvvdvsdvvv = 123;", 15921 Alignment); 15922 verifyFormat("int i = 1, j = 10;\n" 15923 "something = 2000;", 15924 Alignment); 15925 verifyFormat("something = 2000;\n" 15926 "int i = 1, j = 10;\n", 15927 Alignment); 15928 verifyFormat("something = 2000;\n" 15929 "another = 911;\n" 15930 "int i = 1, j = 10;\n" 15931 "oneMore = 1;\n" 15932 "i = 2;", 15933 Alignment); 15934 verifyFormat("int a = 5;\n" 15935 "int one = 1;\n" 15936 "method();\n" 15937 "int oneTwoThree = 123;\n" 15938 "int oneTwo = 12;", 15939 Alignment); 15940 verifyFormat("int oneTwoThree = 123;\n" 15941 "int oneTwo = 12;\n" 15942 "method();\n", 15943 Alignment); 15944 verifyFormat("int oneTwoThree = 123; // comment\n" 15945 "int oneTwo = 12; // comment", 15946 Alignment); 15947 15948 // Bug 25167 15949 /* Uncomment when fixed 15950 verifyFormat("#if A\n" 15951 "#else\n" 15952 "int aaaaaaaa = 12;\n" 15953 "#endif\n" 15954 "#if B\n" 15955 "#else\n" 15956 "int a = 12;\n" 15957 "#endif\n", 15958 Alignment); 15959 verifyFormat("enum foo {\n" 15960 "#if A\n" 15961 "#else\n" 15962 " aaaaaaaa = 12;\n" 15963 "#endif\n" 15964 "#if B\n" 15965 "#else\n" 15966 " a = 12;\n" 15967 "#endif\n" 15968 "};\n", 15969 Alignment); 15970 */ 15971 15972 Alignment.MaxEmptyLinesToKeep = 10; 15973 /* Test alignment across empty lines */ 15974 EXPECT_EQ("int a = 5;\n" 15975 "\n" 15976 "int oneTwoThree = 123;", 15977 format("int a = 5;\n" 15978 "\n" 15979 "int oneTwoThree= 123;", 15980 Alignment)); 15981 EXPECT_EQ("int a = 5;\n" 15982 "int one = 1;\n" 15983 "\n" 15984 "int oneTwoThree = 123;", 15985 format("int a = 5;\n" 15986 "int one = 1;\n" 15987 "\n" 15988 "int oneTwoThree = 123;", 15989 Alignment)); 15990 EXPECT_EQ("int a = 5;\n" 15991 "int one = 1;\n" 15992 "\n" 15993 "int oneTwoThree = 123;\n" 15994 "int oneTwo = 12;", 15995 format("int a = 5;\n" 15996 "int one = 1;\n" 15997 "\n" 15998 "int oneTwoThree = 123;\n" 15999 "int oneTwo = 12;", 16000 Alignment)); 16001 16002 /* Test across comments */ 16003 EXPECT_EQ("int a = 5;\n" 16004 "/* block comment */\n" 16005 "int oneTwoThree = 123;", 16006 format("int a = 5;\n" 16007 "/* block comment */\n" 16008 "int oneTwoThree=123;", 16009 Alignment)); 16010 16011 EXPECT_EQ("int a = 5;\n" 16012 "// line comment\n" 16013 "int oneTwoThree = 123;", 16014 format("int a = 5;\n" 16015 "// line comment\n" 16016 "int oneTwoThree=123;", 16017 Alignment)); 16018 16019 /* Test across comments and newlines */ 16020 EXPECT_EQ("int a = 5;\n" 16021 "\n" 16022 "/* block comment */\n" 16023 "int oneTwoThree = 123;", 16024 format("int a = 5;\n" 16025 "\n" 16026 "/* block comment */\n" 16027 "int oneTwoThree=123;", 16028 Alignment)); 16029 16030 EXPECT_EQ("int a = 5;\n" 16031 "\n" 16032 "// line comment\n" 16033 "int oneTwoThree = 123;", 16034 format("int a = 5;\n" 16035 "\n" 16036 "// line comment\n" 16037 "int oneTwoThree=123;", 16038 Alignment)); 16039 16040 EXPECT_EQ("int a = 5;\n" 16041 "//\n" 16042 "// multi-line line comment\n" 16043 "//\n" 16044 "int oneTwoThree = 123;", 16045 format("int a = 5;\n" 16046 "//\n" 16047 "// multi-line line comment\n" 16048 "//\n" 16049 "int oneTwoThree=123;", 16050 Alignment)); 16051 16052 EXPECT_EQ("int a = 5;\n" 16053 "/*\n" 16054 " * multi-line block comment\n" 16055 " */\n" 16056 "int oneTwoThree = 123;", 16057 format("int a = 5;\n" 16058 "/*\n" 16059 " * multi-line block comment\n" 16060 " */\n" 16061 "int oneTwoThree=123;", 16062 Alignment)); 16063 16064 EXPECT_EQ("int a = 5;\n" 16065 "\n" 16066 "/* block comment */\n" 16067 "\n" 16068 "\n" 16069 "\n" 16070 "int oneTwoThree = 123;", 16071 format("int a = 5;\n" 16072 "\n" 16073 "/* block comment */\n" 16074 "\n" 16075 "\n" 16076 "\n" 16077 "int oneTwoThree=123;", 16078 Alignment)); 16079 16080 EXPECT_EQ("int a = 5;\n" 16081 "\n" 16082 "// line comment\n" 16083 "\n" 16084 "\n" 16085 "\n" 16086 "int oneTwoThree = 123;", 16087 format("int a = 5;\n" 16088 "\n" 16089 "// line comment\n" 16090 "\n" 16091 "\n" 16092 "\n" 16093 "int oneTwoThree=123;", 16094 Alignment)); 16095 16096 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16097 verifyFormat("#define A \\\n" 16098 " int aaaa = 12; \\\n" 16099 " int b = 23; \\\n" 16100 " int ccc = 234; \\\n" 16101 " int dddddddddd = 2345;", 16102 Alignment); 16103 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16104 verifyFormat("#define A \\\n" 16105 " int aaaa = 12; \\\n" 16106 " int b = 23; \\\n" 16107 " int ccc = 234; \\\n" 16108 " int dddddddddd = 2345;", 16109 Alignment); 16110 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16111 verifyFormat("#define A " 16112 " \\\n" 16113 " int aaaa = 12; " 16114 " \\\n" 16115 " int b = 23; " 16116 " \\\n" 16117 " int ccc = 234; " 16118 " \\\n" 16119 " int dddddddddd = 2345;", 16120 Alignment); 16121 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16122 "k = 4, int l = 5,\n" 16123 " int m = 6) {\n" 16124 " int j = 10;\n" 16125 " otherThing = 1;\n" 16126 "}", 16127 Alignment); 16128 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16129 " int i = 1;\n" 16130 " int j = 2;\n" 16131 " int big = 10000;\n" 16132 "}", 16133 Alignment); 16134 verifyFormat("class C {\n" 16135 "public:\n" 16136 " int i = 1;\n" 16137 " virtual void f() = 0;\n" 16138 "};", 16139 Alignment); 16140 verifyFormat("int i = 1;\n" 16141 "if (SomeType t = getSomething()) {\n" 16142 "}\n" 16143 "int j = 2;\n" 16144 "int big = 10000;", 16145 Alignment); 16146 verifyFormat("int j = 7;\n" 16147 "for (int k = 0; k < N; ++k) {\n" 16148 "}\n" 16149 "int j = 2;\n" 16150 "int big = 10000;\n" 16151 "}", 16152 Alignment); 16153 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16154 verifyFormat("int i = 1;\n" 16155 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16156 " = someLooooooooooooooooongFunction();\n" 16157 "int j = 2;", 16158 Alignment); 16159 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16160 verifyFormat("int i = 1;\n" 16161 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16162 " someLooooooooooooooooongFunction();\n" 16163 "int j = 2;", 16164 Alignment); 16165 16166 verifyFormat("auto lambda = []() {\n" 16167 " auto i = 0;\n" 16168 " return 0;\n" 16169 "};\n" 16170 "int i = 0;\n" 16171 "auto v = type{\n" 16172 " i = 1, //\n" 16173 " (i = 2), //\n" 16174 " i = 3 //\n" 16175 "};", 16176 Alignment); 16177 16178 verifyFormat( 16179 "int i = 1;\n" 16180 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16181 " loooooooooooooooooooooongParameterB);\n" 16182 "int j = 2;", 16183 Alignment); 16184 16185 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16186 " typename B = very_long_type_name_1,\n" 16187 " typename T_2 = very_long_type_name_2>\n" 16188 "auto foo() {}\n", 16189 Alignment); 16190 verifyFormat("int a, b = 1;\n" 16191 "int c = 2;\n" 16192 "int dd = 3;\n", 16193 Alignment); 16194 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16195 "float b[1][] = {{3.f}};\n", 16196 Alignment); 16197 verifyFormat("for (int i = 0; i < 1; i++)\n" 16198 " int x = 1;\n", 16199 Alignment); 16200 verifyFormat("for (i = 0; i < 1; i++)\n" 16201 " x = 1;\n" 16202 "y = 1;\n", 16203 Alignment); 16204 16205 Alignment.ReflowComments = true; 16206 Alignment.ColumnLimit = 50; 16207 EXPECT_EQ("int x = 0;\n" 16208 "int yy = 1; /// specificlennospace\n" 16209 "int zzz = 2;\n", 16210 format("int x = 0;\n" 16211 "int yy = 1; ///specificlennospace\n" 16212 "int zzz = 2;\n", 16213 Alignment)); 16214 } 16215 16216 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16217 FormatStyle Alignment = getLLVMStyle(); 16218 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16219 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16220 verifyFormat("int a = 5;\n" 16221 "int oneTwoThree = 123;", 16222 Alignment); 16223 verifyFormat("int a = 5;\n" 16224 "int oneTwoThree = 123;", 16225 Alignment); 16226 16227 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16228 verifyFormat("int a = 5;\n" 16229 "int oneTwoThree = 123;", 16230 Alignment); 16231 verifyFormat("int a = method();\n" 16232 "int oneTwoThree = 133;", 16233 Alignment); 16234 verifyFormat("a &= 5;\n" 16235 "bcd *= 5;\n" 16236 "ghtyf += 5;\n" 16237 "dvfvdb -= 5;\n" 16238 "a /= 5;\n" 16239 "vdsvsv %= 5;\n" 16240 "sfdbddfbdfbb ^= 5;\n" 16241 "dvsdsv |= 5;\n" 16242 "int dsvvdvsdvvv = 123;", 16243 Alignment); 16244 verifyFormat("int i = 1, j = 10;\n" 16245 "something = 2000;", 16246 Alignment); 16247 verifyFormat("something = 2000;\n" 16248 "int i = 1, j = 10;\n", 16249 Alignment); 16250 verifyFormat("something = 2000;\n" 16251 "another = 911;\n" 16252 "int i = 1, j = 10;\n" 16253 "oneMore = 1;\n" 16254 "i = 2;", 16255 Alignment); 16256 verifyFormat("int a = 5;\n" 16257 "int one = 1;\n" 16258 "method();\n" 16259 "int oneTwoThree = 123;\n" 16260 "int oneTwo = 12;", 16261 Alignment); 16262 verifyFormat("int oneTwoThree = 123;\n" 16263 "int oneTwo = 12;\n" 16264 "method();\n", 16265 Alignment); 16266 verifyFormat("int oneTwoThree = 123; // comment\n" 16267 "int oneTwo = 12; // comment", 16268 Alignment); 16269 verifyFormat("int f() = default;\n" 16270 "int &operator() = default;\n" 16271 "int &operator=() {", 16272 Alignment); 16273 verifyFormat("int f() = default; // comment\n" 16274 "int &operator() = default; // comment\n" 16275 "int &operator=() {", 16276 Alignment); 16277 verifyFormat("int f() = default;\n" 16278 "int &operator() = default;\n" 16279 "int &operator==() {", 16280 Alignment); 16281 verifyFormat("int f() = default;\n" 16282 "int &operator() = default;\n" 16283 "int &operator<=() {", 16284 Alignment); 16285 verifyFormat("int f() = default;\n" 16286 "int &operator() = default;\n" 16287 "int &operator!=() {", 16288 Alignment); 16289 verifyFormat("int f() = default;\n" 16290 "int &operator() = default;\n" 16291 "int &operator=();", 16292 Alignment); 16293 verifyFormat("/* long long padding */ int f() = default;\n" 16294 "int &operator() = default;\n" 16295 "int &operator/**/ =();", 16296 Alignment); 16297 16298 // Bug 25167 16299 /* Uncomment when fixed 16300 verifyFormat("#if A\n" 16301 "#else\n" 16302 "int aaaaaaaa = 12;\n" 16303 "#endif\n" 16304 "#if B\n" 16305 "#else\n" 16306 "int a = 12;\n" 16307 "#endif\n", 16308 Alignment); 16309 verifyFormat("enum foo {\n" 16310 "#if A\n" 16311 "#else\n" 16312 " aaaaaaaa = 12;\n" 16313 "#endif\n" 16314 "#if B\n" 16315 "#else\n" 16316 " a = 12;\n" 16317 "#endif\n" 16318 "};\n", 16319 Alignment); 16320 */ 16321 16322 EXPECT_EQ("int a = 5;\n" 16323 "\n" 16324 "int oneTwoThree = 123;", 16325 format("int a = 5;\n" 16326 "\n" 16327 "int oneTwoThree= 123;", 16328 Alignment)); 16329 EXPECT_EQ("int a = 5;\n" 16330 "int one = 1;\n" 16331 "\n" 16332 "int oneTwoThree = 123;", 16333 format("int a = 5;\n" 16334 "int one = 1;\n" 16335 "\n" 16336 "int oneTwoThree = 123;", 16337 Alignment)); 16338 EXPECT_EQ("int a = 5;\n" 16339 "int one = 1;\n" 16340 "\n" 16341 "int oneTwoThree = 123;\n" 16342 "int oneTwo = 12;", 16343 format("int a = 5;\n" 16344 "int one = 1;\n" 16345 "\n" 16346 "int oneTwoThree = 123;\n" 16347 "int oneTwo = 12;", 16348 Alignment)); 16349 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16350 verifyFormat("#define A \\\n" 16351 " int aaaa = 12; \\\n" 16352 " int b = 23; \\\n" 16353 " int ccc = 234; \\\n" 16354 " int dddddddddd = 2345;", 16355 Alignment); 16356 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16357 verifyFormat("#define A \\\n" 16358 " int aaaa = 12; \\\n" 16359 " int b = 23; \\\n" 16360 " int ccc = 234; \\\n" 16361 " int dddddddddd = 2345;", 16362 Alignment); 16363 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16364 verifyFormat("#define A " 16365 " \\\n" 16366 " int aaaa = 12; " 16367 " \\\n" 16368 " int b = 23; " 16369 " \\\n" 16370 " int ccc = 234; " 16371 " \\\n" 16372 " int dddddddddd = 2345;", 16373 Alignment); 16374 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16375 "k = 4, int l = 5,\n" 16376 " int m = 6) {\n" 16377 " int j = 10;\n" 16378 " otherThing = 1;\n" 16379 "}", 16380 Alignment); 16381 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16382 " int i = 1;\n" 16383 " int j = 2;\n" 16384 " int big = 10000;\n" 16385 "}", 16386 Alignment); 16387 verifyFormat("class C {\n" 16388 "public:\n" 16389 " int i = 1;\n" 16390 " virtual void f() = 0;\n" 16391 "};", 16392 Alignment); 16393 verifyFormat("int i = 1;\n" 16394 "if (SomeType t = getSomething()) {\n" 16395 "}\n" 16396 "int j = 2;\n" 16397 "int big = 10000;", 16398 Alignment); 16399 verifyFormat("int j = 7;\n" 16400 "for (int k = 0; k < N; ++k) {\n" 16401 "}\n" 16402 "int j = 2;\n" 16403 "int big = 10000;\n" 16404 "}", 16405 Alignment); 16406 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16407 verifyFormat("int i = 1;\n" 16408 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16409 " = someLooooooooooooooooongFunction();\n" 16410 "int j = 2;", 16411 Alignment); 16412 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16413 verifyFormat("int i = 1;\n" 16414 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16415 " someLooooooooooooooooongFunction();\n" 16416 "int j = 2;", 16417 Alignment); 16418 16419 verifyFormat("auto lambda = []() {\n" 16420 " auto i = 0;\n" 16421 " return 0;\n" 16422 "};\n" 16423 "int i = 0;\n" 16424 "auto v = type{\n" 16425 " i = 1, //\n" 16426 " (i = 2), //\n" 16427 " i = 3 //\n" 16428 "};", 16429 Alignment); 16430 16431 verifyFormat( 16432 "int i = 1;\n" 16433 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16434 " loooooooooooooooooooooongParameterB);\n" 16435 "int j = 2;", 16436 Alignment); 16437 16438 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16439 " typename B = very_long_type_name_1,\n" 16440 " typename T_2 = very_long_type_name_2>\n" 16441 "auto foo() {}\n", 16442 Alignment); 16443 verifyFormat("int a, b = 1;\n" 16444 "int c = 2;\n" 16445 "int dd = 3;\n", 16446 Alignment); 16447 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16448 "float b[1][] = {{3.f}};\n", 16449 Alignment); 16450 verifyFormat("for (int i = 0; i < 1; i++)\n" 16451 " int x = 1;\n", 16452 Alignment); 16453 verifyFormat("for (i = 0; i < 1; i++)\n" 16454 " x = 1;\n" 16455 "y = 1;\n", 16456 Alignment); 16457 16458 Alignment.ReflowComments = true; 16459 Alignment.ColumnLimit = 50; 16460 EXPECT_EQ("int x = 0;\n" 16461 "int yy = 1; /// specificlennospace\n" 16462 "int zzz = 2;\n", 16463 format("int x = 0;\n" 16464 "int yy = 1; ///specificlennospace\n" 16465 "int zzz = 2;\n", 16466 Alignment)); 16467 } 16468 16469 TEST_F(FormatTest, AlignConsecutiveBitFields) { 16470 FormatStyle Alignment = getLLVMStyle(); 16471 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 16472 verifyFormat("int const a : 5;\n" 16473 "int oneTwoThree : 23;", 16474 Alignment); 16475 16476 // Initializers are allowed starting with c++2a 16477 verifyFormat("int const a : 5 = 1;\n" 16478 "int oneTwoThree : 23 = 0;", 16479 Alignment); 16480 16481 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16482 verifyFormat("int const a : 5;\n" 16483 "int oneTwoThree : 23;", 16484 Alignment); 16485 16486 verifyFormat("int const a : 5; // comment\n" 16487 "int oneTwoThree : 23; // comment", 16488 Alignment); 16489 16490 verifyFormat("int const a : 5 = 1;\n" 16491 "int oneTwoThree : 23 = 0;", 16492 Alignment); 16493 16494 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16495 verifyFormat("int const a : 5 = 1;\n" 16496 "int oneTwoThree : 23 = 0;", 16497 Alignment); 16498 verifyFormat("int const a : 5 = {1};\n" 16499 "int oneTwoThree : 23 = 0;", 16500 Alignment); 16501 16502 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 16503 verifyFormat("int const a :5;\n" 16504 "int oneTwoThree:23;", 16505 Alignment); 16506 16507 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 16508 verifyFormat("int const a :5;\n" 16509 "int oneTwoThree :23;", 16510 Alignment); 16511 16512 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 16513 verifyFormat("int const a : 5;\n" 16514 "int oneTwoThree: 23;", 16515 Alignment); 16516 16517 // Known limitations: ':' is only recognized as a bitfield colon when 16518 // followed by a number. 16519 /* 16520 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 16521 "int a : 5;", 16522 Alignment); 16523 */ 16524 } 16525 16526 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 16527 FormatStyle Alignment = getLLVMStyle(); 16528 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16529 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 16530 Alignment.PointerAlignment = FormatStyle::PAS_Right; 16531 verifyFormat("float const a = 5;\n" 16532 "int oneTwoThree = 123;", 16533 Alignment); 16534 verifyFormat("int a = 5;\n" 16535 "float const oneTwoThree = 123;", 16536 Alignment); 16537 16538 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16539 verifyFormat("float const a = 5;\n" 16540 "int oneTwoThree = 123;", 16541 Alignment); 16542 verifyFormat("int a = method();\n" 16543 "float const oneTwoThree = 133;", 16544 Alignment); 16545 verifyFormat("int i = 1, j = 10;\n" 16546 "something = 2000;", 16547 Alignment); 16548 verifyFormat("something = 2000;\n" 16549 "int i = 1, j = 10;\n", 16550 Alignment); 16551 verifyFormat("float something = 2000;\n" 16552 "double another = 911;\n" 16553 "int i = 1, j = 10;\n" 16554 "const int *oneMore = 1;\n" 16555 "unsigned i = 2;", 16556 Alignment); 16557 verifyFormat("float a = 5;\n" 16558 "int one = 1;\n" 16559 "method();\n" 16560 "const double oneTwoThree = 123;\n" 16561 "const unsigned int oneTwo = 12;", 16562 Alignment); 16563 verifyFormat("int oneTwoThree{0}; // comment\n" 16564 "unsigned oneTwo; // comment", 16565 Alignment); 16566 verifyFormat("unsigned int *a;\n" 16567 "int *b;\n" 16568 "unsigned int Const *c;\n" 16569 "unsigned int const *d;\n" 16570 "unsigned int Const &e;\n" 16571 "unsigned int const &f;", 16572 Alignment); 16573 verifyFormat("Const unsigned int *c;\n" 16574 "const unsigned int *d;\n" 16575 "Const unsigned int &e;\n" 16576 "const unsigned int &f;\n" 16577 "const unsigned g;\n" 16578 "Const unsigned h;", 16579 Alignment); 16580 EXPECT_EQ("float const a = 5;\n" 16581 "\n" 16582 "int oneTwoThree = 123;", 16583 format("float const a = 5;\n" 16584 "\n" 16585 "int oneTwoThree= 123;", 16586 Alignment)); 16587 EXPECT_EQ("float a = 5;\n" 16588 "int one = 1;\n" 16589 "\n" 16590 "unsigned oneTwoThree = 123;", 16591 format("float a = 5;\n" 16592 "int one = 1;\n" 16593 "\n" 16594 "unsigned oneTwoThree = 123;", 16595 Alignment)); 16596 EXPECT_EQ("float a = 5;\n" 16597 "int one = 1;\n" 16598 "\n" 16599 "unsigned oneTwoThree = 123;\n" 16600 "int oneTwo = 12;", 16601 format("float a = 5;\n" 16602 "int one = 1;\n" 16603 "\n" 16604 "unsigned oneTwoThree = 123;\n" 16605 "int oneTwo = 12;", 16606 Alignment)); 16607 // Function prototype alignment 16608 verifyFormat("int a();\n" 16609 "double b();", 16610 Alignment); 16611 verifyFormat("int a(int x);\n" 16612 "double b();", 16613 Alignment); 16614 unsigned OldColumnLimit = Alignment.ColumnLimit; 16615 // We need to set ColumnLimit to zero, in order to stress nested alignments, 16616 // otherwise the function parameters will be re-flowed onto a single line. 16617 Alignment.ColumnLimit = 0; 16618 EXPECT_EQ("int a(int x,\n" 16619 " float y);\n" 16620 "double b(int x,\n" 16621 " double y);", 16622 format("int a(int x,\n" 16623 " float y);\n" 16624 "double b(int x,\n" 16625 " double y);", 16626 Alignment)); 16627 // This ensures that function parameters of function declarations are 16628 // correctly indented when their owning functions are indented. 16629 // The failure case here is for 'double y' to not be indented enough. 16630 EXPECT_EQ("double a(int x);\n" 16631 "int b(int y,\n" 16632 " double z);", 16633 format("double a(int x);\n" 16634 "int b(int y,\n" 16635 " double z);", 16636 Alignment)); 16637 // Set ColumnLimit low so that we induce wrapping immediately after 16638 // the function name and opening paren. 16639 Alignment.ColumnLimit = 13; 16640 verifyFormat("int function(\n" 16641 " int x,\n" 16642 " bool y);", 16643 Alignment); 16644 Alignment.ColumnLimit = OldColumnLimit; 16645 // Ensure function pointers don't screw up recursive alignment 16646 verifyFormat("int a(int x, void (*fp)(int y));\n" 16647 "double b();", 16648 Alignment); 16649 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16650 // Ensure recursive alignment is broken by function braces, so that the 16651 // "a = 1" does not align with subsequent assignments inside the function 16652 // body. 16653 verifyFormat("int func(int a = 1) {\n" 16654 " int b = 2;\n" 16655 " int cc = 3;\n" 16656 "}", 16657 Alignment); 16658 verifyFormat("float something = 2000;\n" 16659 "double another = 911;\n" 16660 "int i = 1, j = 10;\n" 16661 "const int *oneMore = 1;\n" 16662 "unsigned i = 2;", 16663 Alignment); 16664 verifyFormat("int oneTwoThree = {0}; // comment\n" 16665 "unsigned oneTwo = 0; // comment", 16666 Alignment); 16667 // Make sure that scope is correctly tracked, in the absence of braces 16668 verifyFormat("for (int i = 0; i < n; i++)\n" 16669 " j = i;\n" 16670 "double x = 1;\n", 16671 Alignment); 16672 verifyFormat("if (int i = 0)\n" 16673 " j = i;\n" 16674 "double x = 1;\n", 16675 Alignment); 16676 // Ensure operator[] and operator() are comprehended 16677 verifyFormat("struct test {\n" 16678 " long long int foo();\n" 16679 " int operator[](int a);\n" 16680 " double bar();\n" 16681 "};\n", 16682 Alignment); 16683 verifyFormat("struct test {\n" 16684 " long long int foo();\n" 16685 " int operator()(int a);\n" 16686 " double bar();\n" 16687 "};\n", 16688 Alignment); 16689 // http://llvm.org/PR52914 16690 verifyFormat("char *a[] = {\"a\", // comment\n" 16691 " \"bb\"};\n" 16692 "int bbbbbbb = 0;", 16693 Alignment); 16694 16695 // PAS_Right 16696 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16697 " int const i = 1;\n" 16698 " int *j = 2;\n" 16699 " int big = 10000;\n" 16700 "\n" 16701 " unsigned oneTwoThree = 123;\n" 16702 " int oneTwo = 12;\n" 16703 " method();\n" 16704 " float k = 2;\n" 16705 " int ll = 10000;\n" 16706 "}", 16707 format("void SomeFunction(int parameter= 0) {\n" 16708 " int const i= 1;\n" 16709 " int *j=2;\n" 16710 " int big = 10000;\n" 16711 "\n" 16712 "unsigned oneTwoThree =123;\n" 16713 "int oneTwo = 12;\n" 16714 " method();\n" 16715 "float k= 2;\n" 16716 "int ll=10000;\n" 16717 "}", 16718 Alignment)); 16719 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16720 " int const i = 1;\n" 16721 " int **j = 2, ***k;\n" 16722 " int &k = i;\n" 16723 " int &&l = i + j;\n" 16724 " int big = 10000;\n" 16725 "\n" 16726 " unsigned oneTwoThree = 123;\n" 16727 " int oneTwo = 12;\n" 16728 " method();\n" 16729 " float k = 2;\n" 16730 " int ll = 10000;\n" 16731 "}", 16732 format("void SomeFunction(int parameter= 0) {\n" 16733 " int const i= 1;\n" 16734 " int **j=2,***k;\n" 16735 "int &k=i;\n" 16736 "int &&l=i+j;\n" 16737 " int big = 10000;\n" 16738 "\n" 16739 "unsigned oneTwoThree =123;\n" 16740 "int oneTwo = 12;\n" 16741 " method();\n" 16742 "float k= 2;\n" 16743 "int ll=10000;\n" 16744 "}", 16745 Alignment)); 16746 // variables are aligned at their name, pointers are at the right most 16747 // position 16748 verifyFormat("int *a;\n" 16749 "int **b;\n" 16750 "int ***c;\n" 16751 "int foobar;\n", 16752 Alignment); 16753 16754 // PAS_Left 16755 FormatStyle AlignmentLeft = Alignment; 16756 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 16757 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16758 " int const i = 1;\n" 16759 " int* j = 2;\n" 16760 " int big = 10000;\n" 16761 "\n" 16762 " unsigned oneTwoThree = 123;\n" 16763 " int oneTwo = 12;\n" 16764 " method();\n" 16765 " float k = 2;\n" 16766 " int ll = 10000;\n" 16767 "}", 16768 format("void SomeFunction(int parameter= 0) {\n" 16769 " int const i= 1;\n" 16770 " int *j=2;\n" 16771 " int big = 10000;\n" 16772 "\n" 16773 "unsigned oneTwoThree =123;\n" 16774 "int oneTwo = 12;\n" 16775 " method();\n" 16776 "float k= 2;\n" 16777 "int ll=10000;\n" 16778 "}", 16779 AlignmentLeft)); 16780 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16781 " int const i = 1;\n" 16782 " int** j = 2;\n" 16783 " int& k = i;\n" 16784 " int&& l = i + j;\n" 16785 " int big = 10000;\n" 16786 "\n" 16787 " unsigned oneTwoThree = 123;\n" 16788 " int oneTwo = 12;\n" 16789 " method();\n" 16790 " float k = 2;\n" 16791 " int ll = 10000;\n" 16792 "}", 16793 format("void SomeFunction(int parameter= 0) {\n" 16794 " int const i= 1;\n" 16795 " int **j=2;\n" 16796 "int &k=i;\n" 16797 "int &&l=i+j;\n" 16798 " int big = 10000;\n" 16799 "\n" 16800 "unsigned oneTwoThree =123;\n" 16801 "int oneTwo = 12;\n" 16802 " method();\n" 16803 "float k= 2;\n" 16804 "int ll=10000;\n" 16805 "}", 16806 AlignmentLeft)); 16807 // variables are aligned at their name, pointers are at the left most position 16808 verifyFormat("int* a;\n" 16809 "int** b;\n" 16810 "int*** c;\n" 16811 "int foobar;\n", 16812 AlignmentLeft); 16813 16814 // PAS_Middle 16815 FormatStyle AlignmentMiddle = Alignment; 16816 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 16817 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16818 " int const i = 1;\n" 16819 " int * j = 2;\n" 16820 " int big = 10000;\n" 16821 "\n" 16822 " unsigned oneTwoThree = 123;\n" 16823 " int oneTwo = 12;\n" 16824 " method();\n" 16825 " float k = 2;\n" 16826 " int ll = 10000;\n" 16827 "}", 16828 format("void SomeFunction(int parameter= 0) {\n" 16829 " int const i= 1;\n" 16830 " int *j=2;\n" 16831 " int big = 10000;\n" 16832 "\n" 16833 "unsigned oneTwoThree =123;\n" 16834 "int oneTwo = 12;\n" 16835 " method();\n" 16836 "float k= 2;\n" 16837 "int ll=10000;\n" 16838 "}", 16839 AlignmentMiddle)); 16840 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16841 " int const i = 1;\n" 16842 " int ** j = 2, ***k;\n" 16843 " int & k = i;\n" 16844 " int && l = i + j;\n" 16845 " int big = 10000;\n" 16846 "\n" 16847 " unsigned oneTwoThree = 123;\n" 16848 " int oneTwo = 12;\n" 16849 " method();\n" 16850 " float k = 2;\n" 16851 " int ll = 10000;\n" 16852 "}", 16853 format("void SomeFunction(int parameter= 0) {\n" 16854 " int const i= 1;\n" 16855 " int **j=2,***k;\n" 16856 "int &k=i;\n" 16857 "int &&l=i+j;\n" 16858 " int big = 10000;\n" 16859 "\n" 16860 "unsigned oneTwoThree =123;\n" 16861 "int oneTwo = 12;\n" 16862 " method();\n" 16863 "float k= 2;\n" 16864 "int ll=10000;\n" 16865 "}", 16866 AlignmentMiddle)); 16867 // variables are aligned at their name, pointers are in the middle 16868 verifyFormat("int * a;\n" 16869 "int * b;\n" 16870 "int *** c;\n" 16871 "int foobar;\n", 16872 AlignmentMiddle); 16873 16874 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16875 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16876 verifyFormat("#define A \\\n" 16877 " int aaaa = 12; \\\n" 16878 " float b = 23; \\\n" 16879 " const int ccc = 234; \\\n" 16880 " unsigned dddddddddd = 2345;", 16881 Alignment); 16882 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16883 verifyFormat("#define A \\\n" 16884 " int aaaa = 12; \\\n" 16885 " float b = 23; \\\n" 16886 " const int ccc = 234; \\\n" 16887 " unsigned dddddddddd = 2345;", 16888 Alignment); 16889 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16890 Alignment.ColumnLimit = 30; 16891 verifyFormat("#define A \\\n" 16892 " int aaaa = 12; \\\n" 16893 " float b = 23; \\\n" 16894 " const int ccc = 234; \\\n" 16895 " int dddddddddd = 2345;", 16896 Alignment); 16897 Alignment.ColumnLimit = 80; 16898 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16899 "k = 4, int l = 5,\n" 16900 " int m = 6) {\n" 16901 " const int j = 10;\n" 16902 " otherThing = 1;\n" 16903 "}", 16904 Alignment); 16905 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16906 " int const i = 1;\n" 16907 " int *j = 2;\n" 16908 " int big = 10000;\n" 16909 "}", 16910 Alignment); 16911 verifyFormat("class C {\n" 16912 "public:\n" 16913 " int i = 1;\n" 16914 " virtual void f() = 0;\n" 16915 "};", 16916 Alignment); 16917 verifyFormat("float i = 1;\n" 16918 "if (SomeType t = getSomething()) {\n" 16919 "}\n" 16920 "const unsigned j = 2;\n" 16921 "int big = 10000;", 16922 Alignment); 16923 verifyFormat("float j = 7;\n" 16924 "for (int k = 0; k < N; ++k) {\n" 16925 "}\n" 16926 "unsigned j = 2;\n" 16927 "int big = 10000;\n" 16928 "}", 16929 Alignment); 16930 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16931 verifyFormat("float i = 1;\n" 16932 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16933 " = someLooooooooooooooooongFunction();\n" 16934 "int j = 2;", 16935 Alignment); 16936 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16937 verifyFormat("int i = 1;\n" 16938 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16939 " someLooooooooooooooooongFunction();\n" 16940 "int j = 2;", 16941 Alignment); 16942 16943 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16944 verifyFormat("auto lambda = []() {\n" 16945 " auto ii = 0;\n" 16946 " float j = 0;\n" 16947 " return 0;\n" 16948 "};\n" 16949 "int i = 0;\n" 16950 "float i2 = 0;\n" 16951 "auto v = type{\n" 16952 " i = 1, //\n" 16953 " (i = 2), //\n" 16954 " i = 3 //\n" 16955 "};", 16956 Alignment); 16957 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16958 16959 verifyFormat( 16960 "int i = 1;\n" 16961 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16962 " loooooooooooooooooooooongParameterB);\n" 16963 "int j = 2;", 16964 Alignment); 16965 16966 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 16967 // We expect declarations and assignments to align, as long as it doesn't 16968 // exceed the column limit, starting a new alignment sequence whenever it 16969 // happens. 16970 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16971 Alignment.ColumnLimit = 30; 16972 verifyFormat("float ii = 1;\n" 16973 "unsigned j = 2;\n" 16974 "int someVerylongVariable = 1;\n" 16975 "AnotherLongType ll = 123456;\n" 16976 "VeryVeryLongType k = 2;\n" 16977 "int myvar = 1;", 16978 Alignment); 16979 Alignment.ColumnLimit = 80; 16980 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16981 16982 verifyFormat( 16983 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 16984 " typename LongType, typename B>\n" 16985 "auto foo() {}\n", 16986 Alignment); 16987 verifyFormat("float a, b = 1;\n" 16988 "int c = 2;\n" 16989 "int dd = 3;\n", 16990 Alignment); 16991 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16992 "float b[1][] = {{3.f}};\n", 16993 Alignment); 16994 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16995 verifyFormat("float a, b = 1;\n" 16996 "int c = 2;\n" 16997 "int dd = 3;\n", 16998 Alignment); 16999 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17000 "float b[1][] = {{3.f}};\n", 17001 Alignment); 17002 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17003 17004 Alignment.ColumnLimit = 30; 17005 Alignment.BinPackParameters = false; 17006 verifyFormat("void foo(float a,\n" 17007 " float b,\n" 17008 " int c,\n" 17009 " uint32_t *d) {\n" 17010 " int *e = 0;\n" 17011 " float f = 0;\n" 17012 " double g = 0;\n" 17013 "}\n" 17014 "void bar(ino_t a,\n" 17015 " int b,\n" 17016 " uint32_t *c,\n" 17017 " bool d) {}\n", 17018 Alignment); 17019 Alignment.BinPackParameters = true; 17020 Alignment.ColumnLimit = 80; 17021 17022 // Bug 33507 17023 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17024 verifyFormat( 17025 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17026 " static const Version verVs2017;\n" 17027 " return true;\n" 17028 "});\n", 17029 Alignment); 17030 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17031 17032 // See llvm.org/PR35641 17033 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17034 verifyFormat("int func() { //\n" 17035 " int b;\n" 17036 " unsigned c;\n" 17037 "}", 17038 Alignment); 17039 17040 // See PR37175 17041 FormatStyle Style = getMozillaStyle(); 17042 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17043 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17044 "foo(int a);", 17045 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17046 17047 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17048 verifyFormat("unsigned int* a;\n" 17049 "int* b;\n" 17050 "unsigned int Const* c;\n" 17051 "unsigned int const* d;\n" 17052 "unsigned int Const& e;\n" 17053 "unsigned int const& f;", 17054 Alignment); 17055 verifyFormat("Const unsigned int* c;\n" 17056 "const unsigned int* d;\n" 17057 "Const unsigned int& e;\n" 17058 "const unsigned int& f;\n" 17059 "const unsigned g;\n" 17060 "Const unsigned h;", 17061 Alignment); 17062 17063 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17064 verifyFormat("unsigned int * a;\n" 17065 "int * b;\n" 17066 "unsigned int Const * c;\n" 17067 "unsigned int const * d;\n" 17068 "unsigned int Const & e;\n" 17069 "unsigned int const & f;", 17070 Alignment); 17071 verifyFormat("Const unsigned int * c;\n" 17072 "const unsigned int * d;\n" 17073 "Const unsigned int & e;\n" 17074 "const unsigned int & f;\n" 17075 "const unsigned g;\n" 17076 "Const unsigned h;", 17077 Alignment); 17078 } 17079 17080 TEST_F(FormatTest, AlignWithLineBreaks) { 17081 auto Style = getLLVMStyleWithColumns(120); 17082 17083 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 17084 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 17085 verifyFormat("void foo() {\n" 17086 " int myVar = 5;\n" 17087 " double x = 3.14;\n" 17088 " auto str = \"Hello \"\n" 17089 " \"World\";\n" 17090 " auto s = \"Hello \"\n" 17091 " \"Again\";\n" 17092 "}", 17093 Style); 17094 17095 // clang-format off 17096 verifyFormat("void foo() {\n" 17097 " const int capacityBefore = Entries.capacity();\n" 17098 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17099 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17100 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17101 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17102 "}", 17103 Style); 17104 // clang-format on 17105 17106 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17107 verifyFormat("void foo() {\n" 17108 " int myVar = 5;\n" 17109 " double x = 3.14;\n" 17110 " auto str = \"Hello \"\n" 17111 " \"World\";\n" 17112 " auto s = \"Hello \"\n" 17113 " \"Again\";\n" 17114 "}", 17115 Style); 17116 17117 // clang-format off 17118 verifyFormat("void foo() {\n" 17119 " const int capacityBefore = Entries.capacity();\n" 17120 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17121 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17122 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17123 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17124 "}", 17125 Style); 17126 // clang-format on 17127 17128 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17129 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17130 verifyFormat("void foo() {\n" 17131 " int myVar = 5;\n" 17132 " double x = 3.14;\n" 17133 " auto str = \"Hello \"\n" 17134 " \"World\";\n" 17135 " auto s = \"Hello \"\n" 17136 " \"Again\";\n" 17137 "}", 17138 Style); 17139 17140 // clang-format off 17141 verifyFormat("void foo() {\n" 17142 " const int capacityBefore = Entries.capacity();\n" 17143 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17144 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17145 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17146 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17147 "}", 17148 Style); 17149 // clang-format on 17150 17151 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17152 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17153 17154 verifyFormat("void foo() {\n" 17155 " int myVar = 5;\n" 17156 " double x = 3.14;\n" 17157 " auto str = \"Hello \"\n" 17158 " \"World\";\n" 17159 " auto s = \"Hello \"\n" 17160 " \"Again\";\n" 17161 "}", 17162 Style); 17163 17164 // clang-format off 17165 verifyFormat("void foo() {\n" 17166 " const int capacityBefore = Entries.capacity();\n" 17167 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17168 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17169 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17170 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17171 "}", 17172 Style); 17173 // clang-format on 17174 17175 Style = getLLVMStyleWithColumns(120); 17176 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17177 Style.ContinuationIndentWidth = 4; 17178 Style.IndentWidth = 4; 17179 17180 // clang-format off 17181 verifyFormat("void SomeFunc() {\n" 17182 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17183 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17184 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17185 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17186 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17187 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17188 "}", 17189 Style); 17190 // clang-format on 17191 17192 Style.BinPackArguments = false; 17193 17194 // clang-format off 17195 verifyFormat("void SomeFunc() {\n" 17196 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17197 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17198 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17199 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17200 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17201 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17202 "}", 17203 Style); 17204 // clang-format on 17205 } 17206 17207 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17208 auto Style = getLLVMStyleWithColumns(60); 17209 17210 verifyFormat("void foo1(void) {\n" 17211 " BYTE p[1] = 1;\n" 17212 " A B = {.one_foooooooooooooooo = 2,\n" 17213 " .two_fooooooooooooo = 3,\n" 17214 " .three_fooooooooooooo = 4};\n" 17215 " BYTE payload = 2;\n" 17216 "}", 17217 Style); 17218 17219 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17220 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17221 verifyFormat("void foo2(void) {\n" 17222 " BYTE p[1] = 1;\n" 17223 " A B = {.one_foooooooooooooooo = 2,\n" 17224 " .two_fooooooooooooo = 3,\n" 17225 " .three_fooooooooooooo = 4};\n" 17226 " BYTE payload = 2;\n" 17227 "}", 17228 Style); 17229 17230 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17231 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17232 verifyFormat("void foo3(void) {\n" 17233 " BYTE p[1] = 1;\n" 17234 " A B = {.one_foooooooooooooooo = 2,\n" 17235 " .two_fooooooooooooo = 3,\n" 17236 " .three_fooooooooooooo = 4};\n" 17237 " BYTE payload = 2;\n" 17238 "}", 17239 Style); 17240 17241 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17242 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17243 verifyFormat("void foo4(void) {\n" 17244 " BYTE p[1] = 1;\n" 17245 " A B = {.one_foooooooooooooooo = 2,\n" 17246 " .two_fooooooooooooo = 3,\n" 17247 " .three_fooooooooooooo = 4};\n" 17248 " BYTE payload = 2;\n" 17249 "}", 17250 Style); 17251 } 17252 17253 TEST_F(FormatTest, LinuxBraceBreaking) { 17254 FormatStyle LinuxBraceStyle = getLLVMStyle(); 17255 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 17256 verifyFormat("namespace a\n" 17257 "{\n" 17258 "class A\n" 17259 "{\n" 17260 " void f()\n" 17261 " {\n" 17262 " if (true) {\n" 17263 " a();\n" 17264 " b();\n" 17265 " } else {\n" 17266 " a();\n" 17267 " }\n" 17268 " }\n" 17269 " void g() { return; }\n" 17270 "};\n" 17271 "struct B {\n" 17272 " int x;\n" 17273 "};\n" 17274 "} // namespace a\n", 17275 LinuxBraceStyle); 17276 verifyFormat("enum X {\n" 17277 " Y = 0,\n" 17278 "}\n", 17279 LinuxBraceStyle); 17280 verifyFormat("struct S {\n" 17281 " int Type;\n" 17282 " union {\n" 17283 " int x;\n" 17284 " double y;\n" 17285 " } Value;\n" 17286 " class C\n" 17287 " {\n" 17288 " MyFavoriteType Value;\n" 17289 " } Class;\n" 17290 "}\n", 17291 LinuxBraceStyle); 17292 } 17293 17294 TEST_F(FormatTest, MozillaBraceBreaking) { 17295 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17296 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17297 MozillaBraceStyle.FixNamespaceComments = false; 17298 verifyFormat("namespace a {\n" 17299 "class A\n" 17300 "{\n" 17301 " void f()\n" 17302 " {\n" 17303 " if (true) {\n" 17304 " a();\n" 17305 " b();\n" 17306 " }\n" 17307 " }\n" 17308 " void g() { return; }\n" 17309 "};\n" 17310 "enum E\n" 17311 "{\n" 17312 " A,\n" 17313 " // foo\n" 17314 " B,\n" 17315 " C\n" 17316 "};\n" 17317 "struct B\n" 17318 "{\n" 17319 " int x;\n" 17320 "};\n" 17321 "}\n", 17322 MozillaBraceStyle); 17323 verifyFormat("struct S\n" 17324 "{\n" 17325 " int Type;\n" 17326 " union\n" 17327 " {\n" 17328 " int x;\n" 17329 " double y;\n" 17330 " } Value;\n" 17331 " class C\n" 17332 " {\n" 17333 " MyFavoriteType Value;\n" 17334 " } Class;\n" 17335 "}\n", 17336 MozillaBraceStyle); 17337 } 17338 17339 TEST_F(FormatTest, StroustrupBraceBreaking) { 17340 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17341 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17342 verifyFormat("namespace a {\n" 17343 "class A {\n" 17344 " void f()\n" 17345 " {\n" 17346 " if (true) {\n" 17347 " a();\n" 17348 " b();\n" 17349 " }\n" 17350 " }\n" 17351 " void g() { return; }\n" 17352 "};\n" 17353 "struct B {\n" 17354 " int x;\n" 17355 "};\n" 17356 "} // namespace a\n", 17357 StroustrupBraceStyle); 17358 17359 verifyFormat("void foo()\n" 17360 "{\n" 17361 " if (a) {\n" 17362 " a();\n" 17363 " }\n" 17364 " else {\n" 17365 " b();\n" 17366 " }\n" 17367 "}\n", 17368 StroustrupBraceStyle); 17369 17370 verifyFormat("#ifdef _DEBUG\n" 17371 "int foo(int i = 0)\n" 17372 "#else\n" 17373 "int foo(int i = 5)\n" 17374 "#endif\n" 17375 "{\n" 17376 " return i;\n" 17377 "}", 17378 StroustrupBraceStyle); 17379 17380 verifyFormat("void foo() {}\n" 17381 "void bar()\n" 17382 "#ifdef _DEBUG\n" 17383 "{\n" 17384 " foo();\n" 17385 "}\n" 17386 "#else\n" 17387 "{\n" 17388 "}\n" 17389 "#endif", 17390 StroustrupBraceStyle); 17391 17392 verifyFormat("void foobar() { int i = 5; }\n" 17393 "#ifdef _DEBUG\n" 17394 "void bar() {}\n" 17395 "#else\n" 17396 "void bar() { foobar(); }\n" 17397 "#endif", 17398 StroustrupBraceStyle); 17399 } 17400 17401 TEST_F(FormatTest, AllmanBraceBreaking) { 17402 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17403 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17404 17405 EXPECT_EQ("namespace a\n" 17406 "{\n" 17407 "void f();\n" 17408 "void g();\n" 17409 "} // namespace a\n", 17410 format("namespace a\n" 17411 "{\n" 17412 "void f();\n" 17413 "void g();\n" 17414 "}\n", 17415 AllmanBraceStyle)); 17416 17417 verifyFormat("namespace a\n" 17418 "{\n" 17419 "class A\n" 17420 "{\n" 17421 " void f()\n" 17422 " {\n" 17423 " if (true)\n" 17424 " {\n" 17425 " a();\n" 17426 " b();\n" 17427 " }\n" 17428 " }\n" 17429 " void g() { return; }\n" 17430 "};\n" 17431 "struct B\n" 17432 "{\n" 17433 " int x;\n" 17434 "};\n" 17435 "union C\n" 17436 "{\n" 17437 "};\n" 17438 "} // namespace a", 17439 AllmanBraceStyle); 17440 17441 verifyFormat("void f()\n" 17442 "{\n" 17443 " if (true)\n" 17444 " {\n" 17445 " a();\n" 17446 " }\n" 17447 " else if (false)\n" 17448 " {\n" 17449 " b();\n" 17450 " }\n" 17451 " else\n" 17452 " {\n" 17453 " c();\n" 17454 " }\n" 17455 "}\n", 17456 AllmanBraceStyle); 17457 17458 verifyFormat("void f()\n" 17459 "{\n" 17460 " for (int i = 0; i < 10; ++i)\n" 17461 " {\n" 17462 " a();\n" 17463 " }\n" 17464 " while (false)\n" 17465 " {\n" 17466 " b();\n" 17467 " }\n" 17468 " do\n" 17469 " {\n" 17470 " c();\n" 17471 " } while (false)\n" 17472 "}\n", 17473 AllmanBraceStyle); 17474 17475 verifyFormat("void f(int a)\n" 17476 "{\n" 17477 " switch (a)\n" 17478 " {\n" 17479 " case 0:\n" 17480 " break;\n" 17481 " case 1:\n" 17482 " {\n" 17483 " break;\n" 17484 " }\n" 17485 " case 2:\n" 17486 " {\n" 17487 " }\n" 17488 " break;\n" 17489 " default:\n" 17490 " break;\n" 17491 " }\n" 17492 "}\n", 17493 AllmanBraceStyle); 17494 17495 verifyFormat("enum X\n" 17496 "{\n" 17497 " Y = 0,\n" 17498 "}\n", 17499 AllmanBraceStyle); 17500 verifyFormat("enum X\n" 17501 "{\n" 17502 " Y = 0\n" 17503 "}\n", 17504 AllmanBraceStyle); 17505 17506 verifyFormat("@interface BSApplicationController ()\n" 17507 "{\n" 17508 "@private\n" 17509 " id _extraIvar;\n" 17510 "}\n" 17511 "@end\n", 17512 AllmanBraceStyle); 17513 17514 verifyFormat("#ifdef _DEBUG\n" 17515 "int foo(int i = 0)\n" 17516 "#else\n" 17517 "int foo(int i = 5)\n" 17518 "#endif\n" 17519 "{\n" 17520 " return i;\n" 17521 "}", 17522 AllmanBraceStyle); 17523 17524 verifyFormat("void foo() {}\n" 17525 "void bar()\n" 17526 "#ifdef _DEBUG\n" 17527 "{\n" 17528 " foo();\n" 17529 "}\n" 17530 "#else\n" 17531 "{\n" 17532 "}\n" 17533 "#endif", 17534 AllmanBraceStyle); 17535 17536 verifyFormat("void foobar() { int i = 5; }\n" 17537 "#ifdef _DEBUG\n" 17538 "void bar() {}\n" 17539 "#else\n" 17540 "void bar() { foobar(); }\n" 17541 "#endif", 17542 AllmanBraceStyle); 17543 17544 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 17545 FormatStyle::SLS_All); 17546 17547 verifyFormat("[](int i) { return i + 2; };\n" 17548 "[](int i, int j)\n" 17549 "{\n" 17550 " auto x = i + j;\n" 17551 " auto y = i * j;\n" 17552 " return x ^ y;\n" 17553 "};\n" 17554 "void foo()\n" 17555 "{\n" 17556 " auto shortLambda = [](int i) { return i + 2; };\n" 17557 " auto longLambda = [](int i, int j)\n" 17558 " {\n" 17559 " auto x = i + j;\n" 17560 " auto y = i * j;\n" 17561 " return x ^ y;\n" 17562 " };\n" 17563 "}", 17564 AllmanBraceStyle); 17565 17566 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17567 17568 verifyFormat("[](int i)\n" 17569 "{\n" 17570 " return i + 2;\n" 17571 "};\n" 17572 "[](int i, int j)\n" 17573 "{\n" 17574 " auto x = i + j;\n" 17575 " auto y = i * j;\n" 17576 " return x ^ y;\n" 17577 "};\n" 17578 "void foo()\n" 17579 "{\n" 17580 " auto shortLambda = [](int i)\n" 17581 " {\n" 17582 " return i + 2;\n" 17583 " };\n" 17584 " auto longLambda = [](int i, int j)\n" 17585 " {\n" 17586 " auto x = i + j;\n" 17587 " auto y = i * j;\n" 17588 " return x ^ y;\n" 17589 " };\n" 17590 "}", 17591 AllmanBraceStyle); 17592 17593 // Reset 17594 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 17595 17596 // This shouldn't affect ObjC blocks.. 17597 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 17598 " // ...\n" 17599 " int i;\n" 17600 "}];", 17601 AllmanBraceStyle); 17602 verifyFormat("void (^block)(void) = ^{\n" 17603 " // ...\n" 17604 " int i;\n" 17605 "};", 17606 AllmanBraceStyle); 17607 // .. or dict literals. 17608 verifyFormat("void f()\n" 17609 "{\n" 17610 " // ...\n" 17611 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 17612 "}", 17613 AllmanBraceStyle); 17614 verifyFormat("void f()\n" 17615 "{\n" 17616 " // ...\n" 17617 " [object someMethod:@{a : @\"b\"}];\n" 17618 "}", 17619 AllmanBraceStyle); 17620 verifyFormat("int f()\n" 17621 "{ // comment\n" 17622 " return 42;\n" 17623 "}", 17624 AllmanBraceStyle); 17625 17626 AllmanBraceStyle.ColumnLimit = 19; 17627 verifyFormat("void f() { int i; }", AllmanBraceStyle); 17628 AllmanBraceStyle.ColumnLimit = 18; 17629 verifyFormat("void f()\n" 17630 "{\n" 17631 " int i;\n" 17632 "}", 17633 AllmanBraceStyle); 17634 AllmanBraceStyle.ColumnLimit = 80; 17635 17636 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 17637 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 17638 FormatStyle::SIS_WithoutElse; 17639 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 17640 verifyFormat("void f(bool b)\n" 17641 "{\n" 17642 " if (b)\n" 17643 " {\n" 17644 " return;\n" 17645 " }\n" 17646 "}\n", 17647 BreakBeforeBraceShortIfs); 17648 verifyFormat("void f(bool b)\n" 17649 "{\n" 17650 " if constexpr (b)\n" 17651 " {\n" 17652 " return;\n" 17653 " }\n" 17654 "}\n", 17655 BreakBeforeBraceShortIfs); 17656 verifyFormat("void f(bool b)\n" 17657 "{\n" 17658 " if CONSTEXPR (b)\n" 17659 " {\n" 17660 " return;\n" 17661 " }\n" 17662 "}\n", 17663 BreakBeforeBraceShortIfs); 17664 verifyFormat("void f(bool b)\n" 17665 "{\n" 17666 " if (b) return;\n" 17667 "}\n", 17668 BreakBeforeBraceShortIfs); 17669 verifyFormat("void f(bool b)\n" 17670 "{\n" 17671 " if constexpr (b) return;\n" 17672 "}\n", 17673 BreakBeforeBraceShortIfs); 17674 verifyFormat("void f(bool b)\n" 17675 "{\n" 17676 " if CONSTEXPR (b) return;\n" 17677 "}\n", 17678 BreakBeforeBraceShortIfs); 17679 verifyFormat("void f(bool b)\n" 17680 "{\n" 17681 " while (b)\n" 17682 " {\n" 17683 " return;\n" 17684 " }\n" 17685 "}\n", 17686 BreakBeforeBraceShortIfs); 17687 } 17688 17689 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 17690 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 17691 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 17692 17693 // Make a few changes to the style for testing purposes 17694 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 17695 FormatStyle::SFS_Empty; 17696 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17697 17698 // FIXME: this test case can't decide whether there should be a blank line 17699 // after the ~D() line or not. It adds one if one doesn't exist in the test 17700 // and it removes the line if one exists. 17701 /* 17702 verifyFormat("class A;\n" 17703 "namespace B\n" 17704 " {\n" 17705 "class C;\n" 17706 "// Comment\n" 17707 "class D\n" 17708 " {\n" 17709 "public:\n" 17710 " D();\n" 17711 " ~D() {}\n" 17712 "private:\n" 17713 " enum E\n" 17714 " {\n" 17715 " F\n" 17716 " }\n" 17717 " };\n" 17718 " } // namespace B\n", 17719 WhitesmithsBraceStyle); 17720 */ 17721 17722 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 17723 verifyFormat("namespace a\n" 17724 " {\n" 17725 "class A\n" 17726 " {\n" 17727 " void f()\n" 17728 " {\n" 17729 " if (true)\n" 17730 " {\n" 17731 " a();\n" 17732 " b();\n" 17733 " }\n" 17734 " }\n" 17735 " void g()\n" 17736 " {\n" 17737 " return;\n" 17738 " }\n" 17739 " };\n" 17740 "struct B\n" 17741 " {\n" 17742 " int x;\n" 17743 " };\n" 17744 " } // namespace a", 17745 WhitesmithsBraceStyle); 17746 17747 verifyFormat("namespace a\n" 17748 " {\n" 17749 "namespace b\n" 17750 " {\n" 17751 "class A\n" 17752 " {\n" 17753 " void f()\n" 17754 " {\n" 17755 " if (true)\n" 17756 " {\n" 17757 " a();\n" 17758 " b();\n" 17759 " }\n" 17760 " }\n" 17761 " void g()\n" 17762 " {\n" 17763 " return;\n" 17764 " }\n" 17765 " };\n" 17766 "struct B\n" 17767 " {\n" 17768 " int x;\n" 17769 " };\n" 17770 " } // namespace b\n" 17771 " } // namespace a", 17772 WhitesmithsBraceStyle); 17773 17774 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 17775 verifyFormat("namespace a\n" 17776 " {\n" 17777 "namespace b\n" 17778 " {\n" 17779 " class A\n" 17780 " {\n" 17781 " void f()\n" 17782 " {\n" 17783 " if (true)\n" 17784 " {\n" 17785 " a();\n" 17786 " b();\n" 17787 " }\n" 17788 " }\n" 17789 " void g()\n" 17790 " {\n" 17791 " return;\n" 17792 " }\n" 17793 " };\n" 17794 " struct B\n" 17795 " {\n" 17796 " int x;\n" 17797 " };\n" 17798 " } // namespace b\n" 17799 " } // namespace a", 17800 WhitesmithsBraceStyle); 17801 17802 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 17803 verifyFormat("namespace a\n" 17804 " {\n" 17805 " namespace b\n" 17806 " {\n" 17807 " class A\n" 17808 " {\n" 17809 " void f()\n" 17810 " {\n" 17811 " if (true)\n" 17812 " {\n" 17813 " a();\n" 17814 " b();\n" 17815 " }\n" 17816 " }\n" 17817 " void g()\n" 17818 " {\n" 17819 " return;\n" 17820 " }\n" 17821 " };\n" 17822 " struct B\n" 17823 " {\n" 17824 " int x;\n" 17825 " };\n" 17826 " } // namespace b\n" 17827 " } // namespace a", 17828 WhitesmithsBraceStyle); 17829 17830 verifyFormat("void f()\n" 17831 " {\n" 17832 " if (true)\n" 17833 " {\n" 17834 " a();\n" 17835 " }\n" 17836 " else if (false)\n" 17837 " {\n" 17838 " b();\n" 17839 " }\n" 17840 " else\n" 17841 " {\n" 17842 " c();\n" 17843 " }\n" 17844 " }\n", 17845 WhitesmithsBraceStyle); 17846 17847 verifyFormat("void f()\n" 17848 " {\n" 17849 " for (int i = 0; i < 10; ++i)\n" 17850 " {\n" 17851 " a();\n" 17852 " }\n" 17853 " while (false)\n" 17854 " {\n" 17855 " b();\n" 17856 " }\n" 17857 " do\n" 17858 " {\n" 17859 " c();\n" 17860 " } while (false)\n" 17861 " }\n", 17862 WhitesmithsBraceStyle); 17863 17864 WhitesmithsBraceStyle.IndentCaseLabels = true; 17865 verifyFormat("void switchTest1(int a)\n" 17866 " {\n" 17867 " switch (a)\n" 17868 " {\n" 17869 " case 2:\n" 17870 " {\n" 17871 " }\n" 17872 " break;\n" 17873 " }\n" 17874 " }\n", 17875 WhitesmithsBraceStyle); 17876 17877 verifyFormat("void switchTest2(int a)\n" 17878 " {\n" 17879 " switch (a)\n" 17880 " {\n" 17881 " case 0:\n" 17882 " break;\n" 17883 " case 1:\n" 17884 " {\n" 17885 " break;\n" 17886 " }\n" 17887 " case 2:\n" 17888 " {\n" 17889 " }\n" 17890 " break;\n" 17891 " default:\n" 17892 " break;\n" 17893 " }\n" 17894 " }\n", 17895 WhitesmithsBraceStyle); 17896 17897 verifyFormat("void switchTest3(int a)\n" 17898 " {\n" 17899 " switch (a)\n" 17900 " {\n" 17901 " case 0:\n" 17902 " {\n" 17903 " foo(x);\n" 17904 " }\n" 17905 " break;\n" 17906 " default:\n" 17907 " {\n" 17908 " foo(1);\n" 17909 " }\n" 17910 " break;\n" 17911 " }\n" 17912 " }\n", 17913 WhitesmithsBraceStyle); 17914 17915 WhitesmithsBraceStyle.IndentCaseLabels = false; 17916 17917 verifyFormat("void switchTest4(int a)\n" 17918 " {\n" 17919 " switch (a)\n" 17920 " {\n" 17921 " case 2:\n" 17922 " {\n" 17923 " }\n" 17924 " break;\n" 17925 " }\n" 17926 " }\n", 17927 WhitesmithsBraceStyle); 17928 17929 verifyFormat("void switchTest5(int a)\n" 17930 " {\n" 17931 " switch (a)\n" 17932 " {\n" 17933 " case 0:\n" 17934 " break;\n" 17935 " case 1:\n" 17936 " {\n" 17937 " foo();\n" 17938 " break;\n" 17939 " }\n" 17940 " case 2:\n" 17941 " {\n" 17942 " }\n" 17943 " break;\n" 17944 " default:\n" 17945 " break;\n" 17946 " }\n" 17947 " }\n", 17948 WhitesmithsBraceStyle); 17949 17950 verifyFormat("void switchTest6(int a)\n" 17951 " {\n" 17952 " switch (a)\n" 17953 " {\n" 17954 " case 0:\n" 17955 " {\n" 17956 " foo(x);\n" 17957 " }\n" 17958 " break;\n" 17959 " default:\n" 17960 " {\n" 17961 " foo(1);\n" 17962 " }\n" 17963 " break;\n" 17964 " }\n" 17965 " }\n", 17966 WhitesmithsBraceStyle); 17967 17968 verifyFormat("enum X\n" 17969 " {\n" 17970 " Y = 0, // testing\n" 17971 " }\n", 17972 WhitesmithsBraceStyle); 17973 17974 verifyFormat("enum X\n" 17975 " {\n" 17976 " Y = 0\n" 17977 " }\n", 17978 WhitesmithsBraceStyle); 17979 verifyFormat("enum X\n" 17980 " {\n" 17981 " Y = 0,\n" 17982 " Z = 1\n" 17983 " };\n", 17984 WhitesmithsBraceStyle); 17985 17986 verifyFormat("@interface BSApplicationController ()\n" 17987 " {\n" 17988 "@private\n" 17989 " id _extraIvar;\n" 17990 " }\n" 17991 "@end\n", 17992 WhitesmithsBraceStyle); 17993 17994 verifyFormat("#ifdef _DEBUG\n" 17995 "int foo(int i = 0)\n" 17996 "#else\n" 17997 "int foo(int i = 5)\n" 17998 "#endif\n" 17999 " {\n" 18000 " return i;\n" 18001 " }", 18002 WhitesmithsBraceStyle); 18003 18004 verifyFormat("void foo() {}\n" 18005 "void bar()\n" 18006 "#ifdef _DEBUG\n" 18007 " {\n" 18008 " foo();\n" 18009 " }\n" 18010 "#else\n" 18011 " {\n" 18012 " }\n" 18013 "#endif", 18014 WhitesmithsBraceStyle); 18015 18016 verifyFormat("void foobar()\n" 18017 " {\n" 18018 " int i = 5;\n" 18019 " }\n" 18020 "#ifdef _DEBUG\n" 18021 "void bar()\n" 18022 " {\n" 18023 " }\n" 18024 "#else\n" 18025 "void bar()\n" 18026 " {\n" 18027 " foobar();\n" 18028 " }\n" 18029 "#endif", 18030 WhitesmithsBraceStyle); 18031 18032 // This shouldn't affect ObjC blocks.. 18033 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18034 " // ...\n" 18035 " int i;\n" 18036 "}];", 18037 WhitesmithsBraceStyle); 18038 verifyFormat("void (^block)(void) = ^{\n" 18039 " // ...\n" 18040 " int i;\n" 18041 "};", 18042 WhitesmithsBraceStyle); 18043 // .. or dict literals. 18044 verifyFormat("void f()\n" 18045 " {\n" 18046 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18047 " }", 18048 WhitesmithsBraceStyle); 18049 18050 verifyFormat("int f()\n" 18051 " { // comment\n" 18052 " return 42;\n" 18053 " }", 18054 WhitesmithsBraceStyle); 18055 18056 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18057 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18058 FormatStyle::SIS_OnlyFirstIf; 18059 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18060 verifyFormat("void f(bool b)\n" 18061 " {\n" 18062 " if (b)\n" 18063 " {\n" 18064 " return;\n" 18065 " }\n" 18066 " }\n", 18067 BreakBeforeBraceShortIfs); 18068 verifyFormat("void f(bool b)\n" 18069 " {\n" 18070 " if (b) return;\n" 18071 " }\n", 18072 BreakBeforeBraceShortIfs); 18073 verifyFormat("void f(bool b)\n" 18074 " {\n" 18075 " while (b)\n" 18076 " {\n" 18077 " return;\n" 18078 " }\n" 18079 " }\n", 18080 BreakBeforeBraceShortIfs); 18081 } 18082 18083 TEST_F(FormatTest, GNUBraceBreaking) { 18084 FormatStyle GNUBraceStyle = getLLVMStyle(); 18085 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18086 verifyFormat("namespace a\n" 18087 "{\n" 18088 "class A\n" 18089 "{\n" 18090 " void f()\n" 18091 " {\n" 18092 " int a;\n" 18093 " {\n" 18094 " int b;\n" 18095 " }\n" 18096 " if (true)\n" 18097 " {\n" 18098 " a();\n" 18099 " b();\n" 18100 " }\n" 18101 " }\n" 18102 " void g() { return; }\n" 18103 "}\n" 18104 "} // namespace a", 18105 GNUBraceStyle); 18106 18107 verifyFormat("void f()\n" 18108 "{\n" 18109 " if (true)\n" 18110 " {\n" 18111 " a();\n" 18112 " }\n" 18113 " else if (false)\n" 18114 " {\n" 18115 " b();\n" 18116 " }\n" 18117 " else\n" 18118 " {\n" 18119 " c();\n" 18120 " }\n" 18121 "}\n", 18122 GNUBraceStyle); 18123 18124 verifyFormat("void f()\n" 18125 "{\n" 18126 " for (int i = 0; i < 10; ++i)\n" 18127 " {\n" 18128 " a();\n" 18129 " }\n" 18130 " while (false)\n" 18131 " {\n" 18132 " b();\n" 18133 " }\n" 18134 " do\n" 18135 " {\n" 18136 " c();\n" 18137 " }\n" 18138 " while (false);\n" 18139 "}\n", 18140 GNUBraceStyle); 18141 18142 verifyFormat("void f(int a)\n" 18143 "{\n" 18144 " switch (a)\n" 18145 " {\n" 18146 " case 0:\n" 18147 " break;\n" 18148 " case 1:\n" 18149 " {\n" 18150 " break;\n" 18151 " }\n" 18152 " case 2:\n" 18153 " {\n" 18154 " }\n" 18155 " break;\n" 18156 " default:\n" 18157 " break;\n" 18158 " }\n" 18159 "}\n", 18160 GNUBraceStyle); 18161 18162 verifyFormat("enum X\n" 18163 "{\n" 18164 " Y = 0,\n" 18165 "}\n", 18166 GNUBraceStyle); 18167 18168 verifyFormat("@interface BSApplicationController ()\n" 18169 "{\n" 18170 "@private\n" 18171 " id _extraIvar;\n" 18172 "}\n" 18173 "@end\n", 18174 GNUBraceStyle); 18175 18176 verifyFormat("#ifdef _DEBUG\n" 18177 "int foo(int i = 0)\n" 18178 "#else\n" 18179 "int foo(int i = 5)\n" 18180 "#endif\n" 18181 "{\n" 18182 " return i;\n" 18183 "}", 18184 GNUBraceStyle); 18185 18186 verifyFormat("void foo() {}\n" 18187 "void bar()\n" 18188 "#ifdef _DEBUG\n" 18189 "{\n" 18190 " foo();\n" 18191 "}\n" 18192 "#else\n" 18193 "{\n" 18194 "}\n" 18195 "#endif", 18196 GNUBraceStyle); 18197 18198 verifyFormat("void foobar() { int i = 5; }\n" 18199 "#ifdef _DEBUG\n" 18200 "void bar() {}\n" 18201 "#else\n" 18202 "void bar() { foobar(); }\n" 18203 "#endif", 18204 GNUBraceStyle); 18205 } 18206 18207 TEST_F(FormatTest, WebKitBraceBreaking) { 18208 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18209 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18210 WebKitBraceStyle.FixNamespaceComments = false; 18211 verifyFormat("namespace a {\n" 18212 "class A {\n" 18213 " void f()\n" 18214 " {\n" 18215 " if (true) {\n" 18216 " a();\n" 18217 " b();\n" 18218 " }\n" 18219 " }\n" 18220 " void g() { return; }\n" 18221 "};\n" 18222 "enum E {\n" 18223 " A,\n" 18224 " // foo\n" 18225 " B,\n" 18226 " C\n" 18227 "};\n" 18228 "struct B {\n" 18229 " int x;\n" 18230 "};\n" 18231 "}\n", 18232 WebKitBraceStyle); 18233 verifyFormat("struct S {\n" 18234 " int Type;\n" 18235 " union {\n" 18236 " int x;\n" 18237 " double y;\n" 18238 " } Value;\n" 18239 " class C {\n" 18240 " MyFavoriteType Value;\n" 18241 " } Class;\n" 18242 "};\n", 18243 WebKitBraceStyle); 18244 } 18245 18246 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 18247 verifyFormat("void f() {\n" 18248 " try {\n" 18249 " } catch (const Exception &e) {\n" 18250 " }\n" 18251 "}\n", 18252 getLLVMStyle()); 18253 } 18254 18255 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 18256 auto Style = getLLVMStyle(); 18257 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18258 Style.AlignConsecutiveAssignments = 18259 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18260 Style.AlignConsecutiveDeclarations = 18261 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18262 verifyFormat("struct test demo[] = {\n" 18263 " {56, 23, \"hello\"},\n" 18264 " {-1, 93463, \"world\"},\n" 18265 " { 7, 5, \"!!\"}\n" 18266 "};\n", 18267 Style); 18268 18269 verifyFormat("struct test demo[] = {\n" 18270 " {56, 23, \"hello\"}, // first line\n" 18271 " {-1, 93463, \"world\"}, // second line\n" 18272 " { 7, 5, \"!!\"} // third line\n" 18273 "};\n", 18274 Style); 18275 18276 verifyFormat("struct test demo[4] = {\n" 18277 " { 56, 23, 21, \"oh\"}, // first line\n" 18278 " { -1, 93463, 22, \"my\"}, // second line\n" 18279 " { 7, 5, 1, \"goodness\"} // third line\n" 18280 " {234, 5, 1, \"gracious\"} // fourth line\n" 18281 "};\n", 18282 Style); 18283 18284 verifyFormat("struct test demo[3] = {\n" 18285 " {56, 23, \"hello\"},\n" 18286 " {-1, 93463, \"world\"},\n" 18287 " { 7, 5, \"!!\"}\n" 18288 "};\n", 18289 Style); 18290 18291 verifyFormat("struct test demo[3] = {\n" 18292 " {int{56}, 23, \"hello\"},\n" 18293 " {int{-1}, 93463, \"world\"},\n" 18294 " { int{7}, 5, \"!!\"}\n" 18295 "};\n", 18296 Style); 18297 18298 verifyFormat("struct test demo[] = {\n" 18299 " {56, 23, \"hello\"},\n" 18300 " {-1, 93463, \"world\"},\n" 18301 " { 7, 5, \"!!\"},\n" 18302 "};\n", 18303 Style); 18304 18305 verifyFormat("test demo[] = {\n" 18306 " {56, 23, \"hello\"},\n" 18307 " {-1, 93463, \"world\"},\n" 18308 " { 7, 5, \"!!\"},\n" 18309 "};\n", 18310 Style); 18311 18312 verifyFormat("demo = std::array<struct test, 3>{\n" 18313 " test{56, 23, \"hello\"},\n" 18314 " test{-1, 93463, \"world\"},\n" 18315 " test{ 7, 5, \"!!\"},\n" 18316 "};\n", 18317 Style); 18318 18319 verifyFormat("test demo[] = {\n" 18320 " {56, 23, \"hello\"},\n" 18321 "#if X\n" 18322 " {-1, 93463, \"world\"},\n" 18323 "#endif\n" 18324 " { 7, 5, \"!!\"}\n" 18325 "};\n", 18326 Style); 18327 18328 verifyFormat( 18329 "test demo[] = {\n" 18330 " { 7, 23,\n" 18331 " \"hello world i am a very long line that really, in any\"\n" 18332 " \"just world, ought to be split over multiple lines\"},\n" 18333 " {-1, 93463, \"world\"},\n" 18334 " {56, 5, \"!!\"}\n" 18335 "};\n", 18336 Style); 18337 18338 verifyFormat("return GradForUnaryCwise(g, {\n" 18339 " {{\"sign\"}, \"Sign\", " 18340 " {\"x\", \"dy\"}},\n" 18341 " { {\"dx\"}, \"Mul\", {\"dy\"" 18342 ", \"sign\"}},\n" 18343 "});\n", 18344 Style); 18345 18346 Style.ColumnLimit = 0; 18347 EXPECT_EQ( 18348 "test demo[] = {\n" 18349 " {56, 23, \"hello world i am a very long line that really, " 18350 "in any just world, ought to be split over multiple lines\"},\n" 18351 " {-1, 93463, " 18352 " \"world\"},\n" 18353 " { 7, 5, " 18354 " \"!!\"},\n" 18355 "};", 18356 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18357 "that really, in any just world, ought to be split over multiple " 18358 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18359 Style)); 18360 18361 Style.ColumnLimit = 80; 18362 verifyFormat("test demo[] = {\n" 18363 " {56, 23, /* a comment */ \"hello\"},\n" 18364 " {-1, 93463, \"world\"},\n" 18365 " { 7, 5, \"!!\"}\n" 18366 "};\n", 18367 Style); 18368 18369 verifyFormat("test demo[] = {\n" 18370 " {56, 23, \"hello\"},\n" 18371 " {-1, 93463, \"world\" /* comment here */},\n" 18372 " { 7, 5, \"!!\"}\n" 18373 "};\n", 18374 Style); 18375 18376 verifyFormat("test demo[] = {\n" 18377 " {56, /* a comment */ 23, \"hello\"},\n" 18378 " {-1, 93463, \"world\"},\n" 18379 " { 7, 5, \"!!\"}\n" 18380 "};\n", 18381 Style); 18382 18383 Style.ColumnLimit = 20; 18384 EXPECT_EQ( 18385 "demo = std::array<\n" 18386 " struct test, 3>{\n" 18387 " test{\n" 18388 " 56, 23,\n" 18389 " \"hello \"\n" 18390 " \"world i \"\n" 18391 " \"am a very \"\n" 18392 " \"long line \"\n" 18393 " \"that \"\n" 18394 " \"really, \"\n" 18395 " \"in any \"\n" 18396 " \"just \"\n" 18397 " \"world, \"\n" 18398 " \"ought to \"\n" 18399 " \"be split \"\n" 18400 " \"over \"\n" 18401 " \"multiple \"\n" 18402 " \"lines\"},\n" 18403 " test{-1, 93463,\n" 18404 " \"world\"},\n" 18405 " test{ 7, 5,\n" 18406 " \"!!\" },\n" 18407 "};", 18408 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18409 "i am a very long line that really, in any just world, ought " 18410 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18411 "test{7, 5, \"!!\"},};", 18412 Style)); 18413 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18414 Style = getLLVMStyleWithColumns(50); 18415 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18416 verifyFormat("static A x = {\n" 18417 " {{init1, init2, init3, init4},\n" 18418 " {init1, init2, init3, init4}}\n" 18419 "};", 18420 Style); 18421 Style.ColumnLimit = 100; 18422 EXPECT_EQ( 18423 "test demo[] = {\n" 18424 " {56, 23,\n" 18425 " \"hello world i am a very long line that really, in any just world" 18426 ", ought to be split over \"\n" 18427 " \"multiple lines\" },\n" 18428 " {-1, 93463, \"world\"},\n" 18429 " { 7, 5, \"!!\"},\n" 18430 "};", 18431 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18432 "that really, in any just world, ought to be split over multiple " 18433 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18434 Style)); 18435 18436 Style = getLLVMStyleWithColumns(50); 18437 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18438 Style.AlignConsecutiveAssignments = 18439 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18440 Style.AlignConsecutiveDeclarations = 18441 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18442 verifyFormat("struct test demo[] = {\n" 18443 " {56, 23, \"hello\"},\n" 18444 " {-1, 93463, \"world\"},\n" 18445 " { 7, 5, \"!!\"}\n" 18446 "};\n" 18447 "static A x = {\n" 18448 " {{init1, init2, init3, init4},\n" 18449 " {init1, init2, init3, init4}}\n" 18450 "};", 18451 Style); 18452 Style.ColumnLimit = 100; 18453 Style.AlignConsecutiveAssignments = 18454 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18455 Style.AlignConsecutiveDeclarations = 18456 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18457 verifyFormat("struct test demo[] = {\n" 18458 " {56, 23, \"hello\"},\n" 18459 " {-1, 93463, \"world\"},\n" 18460 " { 7, 5, \"!!\"}\n" 18461 "};\n" 18462 "struct test demo[4] = {\n" 18463 " { 56, 23, 21, \"oh\"}, // first line\n" 18464 " { -1, 93463, 22, \"my\"}, // second line\n" 18465 " { 7, 5, 1, \"goodness\"} // third line\n" 18466 " {234, 5, 1, \"gracious\"} // fourth line\n" 18467 "};\n", 18468 Style); 18469 EXPECT_EQ( 18470 "test demo[] = {\n" 18471 " {56,\n" 18472 " \"hello world i am a very long line that really, in any just world" 18473 ", ought to be split over \"\n" 18474 " \"multiple lines\", 23},\n" 18475 " {-1, \"world\", 93463},\n" 18476 " { 7, \"!!\", 5},\n" 18477 "};", 18478 format("test demo[] = {{56, \"hello world i am a very long line " 18479 "that really, in any just world, ought to be split over multiple " 18480 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 18481 Style)); 18482 } 18483 18484 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 18485 auto Style = getLLVMStyle(); 18486 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18487 /* FIXME: This case gets misformatted. 18488 verifyFormat("auto foo = Items{\n" 18489 " Section{0, bar(), },\n" 18490 " Section{1, boo() }\n" 18491 "};\n", 18492 Style); 18493 */ 18494 verifyFormat("auto foo = Items{\n" 18495 " Section{\n" 18496 " 0, bar(),\n" 18497 " }\n" 18498 "};\n", 18499 Style); 18500 verifyFormat("struct test demo[] = {\n" 18501 " {56, 23, \"hello\"},\n" 18502 " {-1, 93463, \"world\"},\n" 18503 " {7, 5, \"!!\" }\n" 18504 "};\n", 18505 Style); 18506 verifyFormat("struct test demo[] = {\n" 18507 " {56, 23, \"hello\"}, // first line\n" 18508 " {-1, 93463, \"world\"}, // second line\n" 18509 " {7, 5, \"!!\" } // third line\n" 18510 "};\n", 18511 Style); 18512 verifyFormat("struct test demo[4] = {\n" 18513 " {56, 23, 21, \"oh\" }, // first line\n" 18514 " {-1, 93463, 22, \"my\" }, // second line\n" 18515 " {7, 5, 1, \"goodness\"} // third line\n" 18516 " {234, 5, 1, \"gracious\"} // fourth line\n" 18517 "};\n", 18518 Style); 18519 verifyFormat("struct test demo[3] = {\n" 18520 " {56, 23, \"hello\"},\n" 18521 " {-1, 93463, \"world\"},\n" 18522 " {7, 5, \"!!\" }\n" 18523 "};\n", 18524 Style); 18525 18526 verifyFormat("struct test demo[3] = {\n" 18527 " {int{56}, 23, \"hello\"},\n" 18528 " {int{-1}, 93463, \"world\"},\n" 18529 " {int{7}, 5, \"!!\" }\n" 18530 "};\n", 18531 Style); 18532 verifyFormat("struct test demo[] = {\n" 18533 " {56, 23, \"hello\"},\n" 18534 " {-1, 93463, \"world\"},\n" 18535 " {7, 5, \"!!\" },\n" 18536 "};\n", 18537 Style); 18538 verifyFormat("test demo[] = {\n" 18539 " {56, 23, \"hello\"},\n" 18540 " {-1, 93463, \"world\"},\n" 18541 " {7, 5, \"!!\" },\n" 18542 "};\n", 18543 Style); 18544 verifyFormat("demo = std::array<struct test, 3>{\n" 18545 " test{56, 23, \"hello\"},\n" 18546 " test{-1, 93463, \"world\"},\n" 18547 " test{7, 5, \"!!\" },\n" 18548 "};\n", 18549 Style); 18550 verifyFormat("test demo[] = {\n" 18551 " {56, 23, \"hello\"},\n" 18552 "#if X\n" 18553 " {-1, 93463, \"world\"},\n" 18554 "#endif\n" 18555 " {7, 5, \"!!\" }\n" 18556 "};\n", 18557 Style); 18558 verifyFormat( 18559 "test demo[] = {\n" 18560 " {7, 23,\n" 18561 " \"hello world i am a very long line that really, in any\"\n" 18562 " \"just world, ought to be split over multiple lines\"},\n" 18563 " {-1, 93463, \"world\" },\n" 18564 " {56, 5, \"!!\" }\n" 18565 "};\n", 18566 Style); 18567 18568 verifyFormat("return GradForUnaryCwise(g, {\n" 18569 " {{\"sign\"}, \"Sign\", {\"x\", " 18570 "\"dy\"} },\n" 18571 " {{\"dx\"}, \"Mul\", " 18572 "{\"dy\", \"sign\"}},\n" 18573 "});\n", 18574 Style); 18575 18576 Style.ColumnLimit = 0; 18577 EXPECT_EQ( 18578 "test demo[] = {\n" 18579 " {56, 23, \"hello world i am a very long line that really, in any " 18580 "just world, ought to be split over multiple lines\"},\n" 18581 " {-1, 93463, \"world\" " 18582 " },\n" 18583 " {7, 5, \"!!\" " 18584 " },\n" 18585 "};", 18586 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18587 "that really, in any just world, ought to be split over multiple " 18588 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18589 Style)); 18590 18591 Style.ColumnLimit = 80; 18592 verifyFormat("test demo[] = {\n" 18593 " {56, 23, /* a comment */ \"hello\"},\n" 18594 " {-1, 93463, \"world\" },\n" 18595 " {7, 5, \"!!\" }\n" 18596 "};\n", 18597 Style); 18598 18599 verifyFormat("test demo[] = {\n" 18600 " {56, 23, \"hello\" },\n" 18601 " {-1, 93463, \"world\" /* comment here */},\n" 18602 " {7, 5, \"!!\" }\n" 18603 "};\n", 18604 Style); 18605 18606 verifyFormat("test demo[] = {\n" 18607 " {56, /* a comment */ 23, \"hello\"},\n" 18608 " {-1, 93463, \"world\"},\n" 18609 " {7, 5, \"!!\" }\n" 18610 "};\n", 18611 Style); 18612 18613 Style.ColumnLimit = 20; 18614 EXPECT_EQ( 18615 "demo = std::array<\n" 18616 " struct test, 3>{\n" 18617 " test{\n" 18618 " 56, 23,\n" 18619 " \"hello \"\n" 18620 " \"world i \"\n" 18621 " \"am a very \"\n" 18622 " \"long line \"\n" 18623 " \"that \"\n" 18624 " \"really, \"\n" 18625 " \"in any \"\n" 18626 " \"just \"\n" 18627 " \"world, \"\n" 18628 " \"ought to \"\n" 18629 " \"be split \"\n" 18630 " \"over \"\n" 18631 " \"multiple \"\n" 18632 " \"lines\"},\n" 18633 " test{-1, 93463,\n" 18634 " \"world\"},\n" 18635 " test{7, 5,\n" 18636 " \"!!\" },\n" 18637 "};", 18638 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18639 "i am a very long line that really, in any just world, ought " 18640 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18641 "test{7, 5, \"!!\"},};", 18642 Style)); 18643 18644 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18645 Style = getLLVMStyleWithColumns(50); 18646 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18647 verifyFormat("static A x = {\n" 18648 " {{init1, init2, init3, init4},\n" 18649 " {init1, init2, init3, init4}}\n" 18650 "};", 18651 Style); 18652 Style.ColumnLimit = 100; 18653 EXPECT_EQ( 18654 "test demo[] = {\n" 18655 " {56, 23,\n" 18656 " \"hello world i am a very long line that really, in any just world" 18657 ", ought to be split over \"\n" 18658 " \"multiple lines\" },\n" 18659 " {-1, 93463, \"world\"},\n" 18660 " {7, 5, \"!!\" },\n" 18661 "};", 18662 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18663 "that really, in any just world, ought to be split over multiple " 18664 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18665 Style)); 18666 } 18667 18668 TEST_F(FormatTest, UnderstandsPragmas) { 18669 verifyFormat("#pragma omp reduction(| : var)"); 18670 verifyFormat("#pragma omp reduction(+ : var)"); 18671 18672 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 18673 "(including parentheses).", 18674 format("#pragma mark Any non-hyphenated or hyphenated string " 18675 "(including parentheses).")); 18676 } 18677 18678 TEST_F(FormatTest, UnderstandPragmaOption) { 18679 verifyFormat("#pragma option -C -A"); 18680 18681 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 18682 } 18683 18684 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 18685 FormatStyle Style = getLLVMStyleWithColumns(20); 18686 18687 // See PR41213 18688 EXPECT_EQ("/*\n" 18689 " *\t9012345\n" 18690 " * /8901\n" 18691 " */", 18692 format("/*\n" 18693 " *\t9012345 /8901\n" 18694 " */", 18695 Style)); 18696 EXPECT_EQ("/*\n" 18697 " *345678\n" 18698 " *\t/8901\n" 18699 " */", 18700 format("/*\n" 18701 " *345678\t/8901\n" 18702 " */", 18703 Style)); 18704 18705 verifyFormat("int a; // the\n" 18706 " // comment", 18707 Style); 18708 EXPECT_EQ("int a; /* first line\n" 18709 " * second\n" 18710 " * line third\n" 18711 " * line\n" 18712 " */", 18713 format("int a; /* first line\n" 18714 " * second\n" 18715 " * line third\n" 18716 " * line\n" 18717 " */", 18718 Style)); 18719 EXPECT_EQ("int a; // first line\n" 18720 " // second\n" 18721 " // line third\n" 18722 " // line", 18723 format("int a; // first line\n" 18724 " // second line\n" 18725 " // third line", 18726 Style)); 18727 18728 Style.PenaltyExcessCharacter = 90; 18729 verifyFormat("int a; // the comment", Style); 18730 EXPECT_EQ("int a; // the comment\n" 18731 " // aaa", 18732 format("int a; // the comment aaa", Style)); 18733 EXPECT_EQ("int a; /* first line\n" 18734 " * second line\n" 18735 " * third line\n" 18736 " */", 18737 format("int a; /* first line\n" 18738 " * second line\n" 18739 " * third line\n" 18740 " */", 18741 Style)); 18742 EXPECT_EQ("int a; // first line\n" 18743 " // second line\n" 18744 " // third line", 18745 format("int a; // first line\n" 18746 " // second line\n" 18747 " // third line", 18748 Style)); 18749 // FIXME: Investigate why this is not getting the same layout as the test 18750 // above. 18751 EXPECT_EQ("int a; /* first line\n" 18752 " * second line\n" 18753 " * third line\n" 18754 " */", 18755 format("int a; /* first line second line third line" 18756 "\n*/", 18757 Style)); 18758 18759 EXPECT_EQ("// foo bar baz bazfoo\n" 18760 "// foo bar foo bar\n", 18761 format("// foo bar baz bazfoo\n" 18762 "// foo bar foo bar\n", 18763 Style)); 18764 EXPECT_EQ("// foo bar baz bazfoo\n" 18765 "// foo bar foo bar\n", 18766 format("// foo bar baz bazfoo\n" 18767 "// foo bar foo bar\n", 18768 Style)); 18769 18770 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 18771 // next one. 18772 EXPECT_EQ("// foo bar baz bazfoo\n" 18773 "// bar foo bar\n", 18774 format("// foo bar baz bazfoo bar\n" 18775 "// foo bar\n", 18776 Style)); 18777 18778 EXPECT_EQ("// foo bar baz bazfoo\n" 18779 "// foo bar baz bazfoo\n" 18780 "// bar foo bar\n", 18781 format("// foo bar baz bazfoo\n" 18782 "// foo bar baz bazfoo bar\n" 18783 "// foo bar\n", 18784 Style)); 18785 18786 EXPECT_EQ("// foo bar baz bazfoo\n" 18787 "// foo bar baz bazfoo\n" 18788 "// bar foo bar\n", 18789 format("// foo bar baz bazfoo\n" 18790 "// foo bar baz bazfoo bar\n" 18791 "// foo bar\n", 18792 Style)); 18793 18794 // Make sure we do not keep protruding characters if strict mode reflow is 18795 // cheaper than keeping protruding characters. 18796 Style.ColumnLimit = 21; 18797 EXPECT_EQ( 18798 "// foo foo foo foo\n" 18799 "// foo foo foo foo\n" 18800 "// foo foo foo foo\n", 18801 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 18802 18803 EXPECT_EQ("int a = /* long block\n" 18804 " comment */\n" 18805 " 42;", 18806 format("int a = /* long block comment */ 42;", Style)); 18807 } 18808 18809 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 18810 FormatStyle Style = getLLVMStyle(); 18811 Style.ColumnLimit = 8; 18812 Style.PenaltyExcessCharacter = 15; 18813 verifyFormat("int foo(\n" 18814 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 18815 Style); 18816 Style.PenaltyBreakOpenParenthesis = 200; 18817 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 18818 format("int foo(\n" 18819 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 18820 Style)); 18821 } 18822 18823 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 18824 FormatStyle Style = getLLVMStyle(); 18825 Style.ColumnLimit = 5; 18826 Style.PenaltyExcessCharacter = 150; 18827 verifyFormat("foo((\n" 18828 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 18829 18830 Style); 18831 Style.PenaltyBreakOpenParenthesis = 100000; 18832 EXPECT_EQ("foo((int)\n" 18833 " aaaaaaaaaaaaaaaaaaaaaaaa);", 18834 format("foo((\n" 18835 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 18836 Style)); 18837 } 18838 18839 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 18840 FormatStyle Style = getLLVMStyle(); 18841 Style.ColumnLimit = 4; 18842 Style.PenaltyExcessCharacter = 100; 18843 verifyFormat("for (\n" 18844 " int iiiiiiiiiiiiiiiii =\n" 18845 " 0;\n" 18846 " iiiiiiiiiiiiiiiii <\n" 18847 " 2;\n" 18848 " iiiiiiiiiiiiiiiii++) {\n" 18849 "}", 18850 18851 Style); 18852 Style.PenaltyBreakOpenParenthesis = 1250; 18853 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 18854 " 0;\n" 18855 " iiiiiiiiiiiiiiiii <\n" 18856 " 2;\n" 18857 " iiiiiiiiiiiiiiiii++) {\n" 18858 "}", 18859 format("for (\n" 18860 " int iiiiiiiiiiiiiiiii =\n" 18861 " 0;\n" 18862 " iiiiiiiiiiiiiiiii <\n" 18863 " 2;\n" 18864 " iiiiiiiiiiiiiiiii++) {\n" 18865 "}", 18866 Style)); 18867 } 18868 18869 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 18870 for (size_t i = 1; i < Styles.size(); ++i) \ 18871 EXPECT_EQ(Styles[0], Styles[i]) \ 18872 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 18873 18874 TEST_F(FormatTest, GetsPredefinedStyleByName) { 18875 SmallVector<FormatStyle, 3> Styles; 18876 Styles.resize(3); 18877 18878 Styles[0] = getLLVMStyle(); 18879 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 18880 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 18881 EXPECT_ALL_STYLES_EQUAL(Styles); 18882 18883 Styles[0] = getGoogleStyle(); 18884 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 18885 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 18886 EXPECT_ALL_STYLES_EQUAL(Styles); 18887 18888 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 18889 EXPECT_TRUE( 18890 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 18891 EXPECT_TRUE( 18892 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 18893 EXPECT_ALL_STYLES_EQUAL(Styles); 18894 18895 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 18896 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 18897 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 18898 EXPECT_ALL_STYLES_EQUAL(Styles); 18899 18900 Styles[0] = getMozillaStyle(); 18901 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 18902 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 18903 EXPECT_ALL_STYLES_EQUAL(Styles); 18904 18905 Styles[0] = getWebKitStyle(); 18906 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 18907 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 18908 EXPECT_ALL_STYLES_EQUAL(Styles); 18909 18910 Styles[0] = getGNUStyle(); 18911 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 18912 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 18913 EXPECT_ALL_STYLES_EQUAL(Styles); 18914 18915 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 18916 } 18917 18918 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 18919 SmallVector<FormatStyle, 8> Styles; 18920 Styles.resize(2); 18921 18922 Styles[0] = getGoogleStyle(); 18923 Styles[1] = getLLVMStyle(); 18924 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 18925 EXPECT_ALL_STYLES_EQUAL(Styles); 18926 18927 Styles.resize(5); 18928 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 18929 Styles[1] = getLLVMStyle(); 18930 Styles[1].Language = FormatStyle::LK_JavaScript; 18931 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 18932 18933 Styles[2] = getLLVMStyle(); 18934 Styles[2].Language = FormatStyle::LK_JavaScript; 18935 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 18936 "BasedOnStyle: Google", 18937 &Styles[2]) 18938 .value()); 18939 18940 Styles[3] = getLLVMStyle(); 18941 Styles[3].Language = FormatStyle::LK_JavaScript; 18942 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 18943 "Language: JavaScript", 18944 &Styles[3]) 18945 .value()); 18946 18947 Styles[4] = getLLVMStyle(); 18948 Styles[4].Language = FormatStyle::LK_JavaScript; 18949 EXPECT_EQ(0, parseConfiguration("---\n" 18950 "BasedOnStyle: LLVM\n" 18951 "IndentWidth: 123\n" 18952 "---\n" 18953 "BasedOnStyle: Google\n" 18954 "Language: JavaScript", 18955 &Styles[4]) 18956 .value()); 18957 EXPECT_ALL_STYLES_EQUAL(Styles); 18958 } 18959 18960 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 18961 Style.FIELD = false; \ 18962 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 18963 EXPECT_TRUE(Style.FIELD); \ 18964 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 18965 EXPECT_FALSE(Style.FIELD); 18966 18967 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 18968 18969 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 18970 Style.STRUCT.FIELD = false; \ 18971 EXPECT_EQ(0, \ 18972 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 18973 .value()); \ 18974 EXPECT_TRUE(Style.STRUCT.FIELD); \ 18975 EXPECT_EQ(0, \ 18976 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 18977 .value()); \ 18978 EXPECT_FALSE(Style.STRUCT.FIELD); 18979 18980 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 18981 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 18982 18983 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 18984 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 18985 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 18986 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 18987 18988 TEST_F(FormatTest, ParsesConfigurationBools) { 18989 FormatStyle Style = {}; 18990 Style.Language = FormatStyle::LK_Cpp; 18991 CHECK_PARSE_BOOL(AlignTrailingComments); 18992 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 18993 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 18994 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 18995 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 18996 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 18997 CHECK_PARSE_BOOL(BinPackArguments); 18998 CHECK_PARSE_BOOL(BinPackParameters); 18999 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19000 CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations); 19001 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19002 CHECK_PARSE_BOOL(BreakStringLiterals); 19003 CHECK_PARSE_BOOL(CompactNamespaces); 19004 CHECK_PARSE_BOOL(DeriveLineEnding); 19005 CHECK_PARSE_BOOL(DerivePointerAlignment); 19006 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19007 CHECK_PARSE_BOOL(DisableFormat); 19008 CHECK_PARSE_BOOL(IndentAccessModifiers); 19009 CHECK_PARSE_BOOL(IndentCaseLabels); 19010 CHECK_PARSE_BOOL(IndentCaseBlocks); 19011 CHECK_PARSE_BOOL(IndentGotoLabels); 19012 CHECK_PARSE_BOOL(IndentRequires); 19013 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19014 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19015 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19016 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19017 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19018 CHECK_PARSE_BOOL(ReflowComments); 19019 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19020 CHECK_PARSE_BOOL(SortUsingDeclarations); 19021 CHECK_PARSE_BOOL(SpacesInParentheses); 19022 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19023 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19024 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19025 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19026 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19027 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19028 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19029 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19030 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19031 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19032 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19033 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19034 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19035 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19036 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19037 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19038 CHECK_PARSE_BOOL(UseCRLF); 19039 19040 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19041 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19042 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19043 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19044 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19045 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19046 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19047 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19048 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19049 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19050 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19051 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19052 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19053 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19054 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19055 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19056 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19057 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19058 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19059 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19060 AfterFunctionDeclarationName); 19061 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19062 AfterFunctionDefinitionName); 19063 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19064 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19065 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19066 } 19067 19068 #undef CHECK_PARSE_BOOL 19069 19070 TEST_F(FormatTest, ParsesConfiguration) { 19071 FormatStyle Style = {}; 19072 Style.Language = FormatStyle::LK_Cpp; 19073 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19074 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19075 ConstructorInitializerIndentWidth, 1234u); 19076 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19077 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19078 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19079 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19080 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19081 PenaltyBreakBeforeFirstCallParameter, 1234u); 19082 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19083 PenaltyBreakTemplateDeclaration, 1234u); 19084 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19085 1234u); 19086 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19087 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19088 PenaltyReturnTypeOnItsOwnLine, 1234u); 19089 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19090 SpacesBeforeTrailingComments, 1234u); 19091 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19092 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19093 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19094 19095 Style.QualifierAlignment = FormatStyle::QAS_Right; 19096 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19097 FormatStyle::QAS_Leave); 19098 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19099 FormatStyle::QAS_Right); 19100 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19101 FormatStyle::QAS_Left); 19102 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19103 FormatStyle::QAS_Custom); 19104 19105 Style.QualifierOrder.clear(); 19106 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19107 std::vector<std::string>({"const", "volatile", "type"})); 19108 Style.QualifierOrder.clear(); 19109 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19110 std::vector<std::string>({"const", "type"})); 19111 Style.QualifierOrder.clear(); 19112 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19113 std::vector<std::string>({"volatile", "type"})); 19114 19115 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19116 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 19117 FormatStyle::ACS_None); 19118 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 19119 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 19120 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 19121 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 19122 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 19123 AlignConsecutiveAssignments, 19124 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19125 // For backwards compability, false / true should still parse 19126 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 19127 FormatStyle::ACS_None); 19128 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 19129 FormatStyle::ACS_Consecutive); 19130 19131 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 19132 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 19133 FormatStyle::ACS_None); 19134 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 19135 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 19136 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 19137 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 19138 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 19139 AlignConsecutiveBitFields, 19140 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19141 // For backwards compability, false / true should still parse 19142 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 19143 FormatStyle::ACS_None); 19144 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 19145 FormatStyle::ACS_Consecutive); 19146 19147 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 19148 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 19149 FormatStyle::ACS_None); 19150 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 19151 FormatStyle::ACS_Consecutive); 19152 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 19153 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 19154 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 19155 AlignConsecutiveMacros, 19156 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19157 // For backwards compability, false / true should still parse 19158 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 19159 FormatStyle::ACS_None); 19160 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 19161 FormatStyle::ACS_Consecutive); 19162 19163 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 19164 CHECK_PARSE("AlignConsecutiveDeclarations: None", 19165 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19166 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 19167 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19168 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 19169 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 19170 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 19171 AlignConsecutiveDeclarations, 19172 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19173 // For backwards compability, false / true should still parse 19174 CHECK_PARSE("AlignConsecutiveDeclarations: false", 19175 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19176 CHECK_PARSE("AlignConsecutiveDeclarations: true", 19177 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19178 19179 Style.PointerAlignment = FormatStyle::PAS_Middle; 19180 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19181 FormatStyle::PAS_Left); 19182 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19183 FormatStyle::PAS_Right); 19184 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19185 FormatStyle::PAS_Middle); 19186 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19187 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19188 FormatStyle::RAS_Pointer); 19189 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19190 FormatStyle::RAS_Left); 19191 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19192 FormatStyle::RAS_Right); 19193 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19194 FormatStyle::RAS_Middle); 19195 // For backward compatibility: 19196 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19197 FormatStyle::PAS_Left); 19198 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19199 FormatStyle::PAS_Right); 19200 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19201 FormatStyle::PAS_Middle); 19202 19203 Style.Standard = FormatStyle::LS_Auto; 19204 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19205 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19206 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19207 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19208 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19209 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19210 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19211 // Legacy aliases: 19212 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19213 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19214 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19215 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19216 19217 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19218 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19219 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19220 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19221 FormatStyle::BOS_None); 19222 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19223 FormatStyle::BOS_All); 19224 // For backward compatibility: 19225 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19226 FormatStyle::BOS_None); 19227 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19228 FormatStyle::BOS_All); 19229 19230 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 19231 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 19232 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19233 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 19234 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 19235 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 19236 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 19237 // For backward compatibility: 19238 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 19239 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19240 19241 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 19242 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 19243 FormatStyle::BILS_AfterComma); 19244 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 19245 FormatStyle::BILS_BeforeComma); 19246 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 19247 FormatStyle::BILS_AfterColon); 19248 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 19249 FormatStyle::BILS_BeforeColon); 19250 // For backward compatibility: 19251 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 19252 FormatStyle::BILS_BeforeComma); 19253 19254 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19255 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 19256 FormatStyle::PCIS_Never); 19257 CHECK_PARSE("PackConstructorInitializers: BinPack", 19258 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19259 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 19260 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19261 CHECK_PARSE("PackConstructorInitializers: NextLine", 19262 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19263 // For backward compatibility: 19264 CHECK_PARSE("BasedOnStyle: Google\n" 19265 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19266 "AllowAllConstructorInitializersOnNextLine: false", 19267 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19268 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19269 CHECK_PARSE("BasedOnStyle: Google\n" 19270 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 19271 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19272 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19273 "AllowAllConstructorInitializersOnNextLine: true", 19274 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19275 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19276 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19277 "AllowAllConstructorInitializersOnNextLine: false", 19278 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19279 19280 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 19281 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 19282 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 19283 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 19284 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 19285 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 19286 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 19287 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 19288 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 19289 19290 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19291 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 19292 FormatStyle::BAS_Align); 19293 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 19294 FormatStyle::BAS_DontAlign); 19295 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 19296 FormatStyle::BAS_AlwaysBreak); 19297 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 19298 FormatStyle::BAS_BlockIndent); 19299 // For backward compatibility: 19300 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 19301 FormatStyle::BAS_DontAlign); 19302 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 19303 FormatStyle::BAS_Align); 19304 19305 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 19306 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 19307 FormatStyle::ENAS_DontAlign); 19308 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 19309 FormatStyle::ENAS_Left); 19310 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 19311 FormatStyle::ENAS_Right); 19312 // For backward compatibility: 19313 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 19314 FormatStyle::ENAS_Left); 19315 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 19316 FormatStyle::ENAS_Right); 19317 19318 Style.AlignOperands = FormatStyle::OAS_Align; 19319 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 19320 FormatStyle::OAS_DontAlign); 19321 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 19322 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 19323 FormatStyle::OAS_AlignAfterOperator); 19324 // For backward compatibility: 19325 CHECK_PARSE("AlignOperands: false", AlignOperands, 19326 FormatStyle::OAS_DontAlign); 19327 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 19328 19329 Style.UseTab = FormatStyle::UT_ForIndentation; 19330 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 19331 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 19332 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 19333 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 19334 FormatStyle::UT_ForContinuationAndIndentation); 19335 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 19336 FormatStyle::UT_AlignWithSpaces); 19337 // For backward compatibility: 19338 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 19339 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 19340 19341 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 19342 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 19343 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19344 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 19345 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 19346 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 19347 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19348 // For backward compatibility: 19349 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 19350 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19351 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 19352 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19353 19354 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 19355 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 19356 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19357 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 19358 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 19359 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 19360 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 19361 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 19362 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19363 // For backward compatibility: 19364 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19365 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19366 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19367 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19368 19369 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19370 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19371 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19372 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19373 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19374 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19375 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19376 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19377 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19378 19379 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19380 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19381 FormatStyle::SBPO_Never); 19382 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19383 FormatStyle::SBPO_Always); 19384 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19385 FormatStyle::SBPO_ControlStatements); 19386 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19387 SpaceBeforeParens, 19388 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19389 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19390 FormatStyle::SBPO_NonEmptyParentheses); 19391 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19392 FormatStyle::SBPO_Custom); 19393 // For backward compatibility: 19394 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19395 FormatStyle::SBPO_Never); 19396 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19397 FormatStyle::SBPO_ControlStatements); 19398 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19399 SpaceBeforeParens, 19400 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19401 19402 Style.ColumnLimit = 123; 19403 FormatStyle BaseStyle = getLLVMStyle(); 19404 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19405 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19406 19407 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19408 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19409 FormatStyle::BS_Attach); 19410 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19411 FormatStyle::BS_Linux); 19412 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 19413 FormatStyle::BS_Mozilla); 19414 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 19415 FormatStyle::BS_Stroustrup); 19416 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 19417 FormatStyle::BS_Allman); 19418 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 19419 FormatStyle::BS_Whitesmiths); 19420 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 19421 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 19422 FormatStyle::BS_WebKit); 19423 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 19424 FormatStyle::BS_Custom); 19425 19426 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 19427 CHECK_PARSE("BraceWrapping:\n" 19428 " AfterControlStatement: MultiLine", 19429 BraceWrapping.AfterControlStatement, 19430 FormatStyle::BWACS_MultiLine); 19431 CHECK_PARSE("BraceWrapping:\n" 19432 " AfterControlStatement: Always", 19433 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19434 CHECK_PARSE("BraceWrapping:\n" 19435 " AfterControlStatement: Never", 19436 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19437 // For backward compatibility: 19438 CHECK_PARSE("BraceWrapping:\n" 19439 " AfterControlStatement: true", 19440 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19441 CHECK_PARSE("BraceWrapping:\n" 19442 " AfterControlStatement: false", 19443 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19444 19445 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 19446 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 19447 FormatStyle::RTBS_None); 19448 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 19449 FormatStyle::RTBS_All); 19450 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 19451 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 19452 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 19453 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 19454 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 19455 AlwaysBreakAfterReturnType, 19456 FormatStyle::RTBS_TopLevelDefinitions); 19457 19458 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 19459 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 19460 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 19461 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 19462 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19463 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 19464 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19465 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 19466 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19467 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 19468 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19469 19470 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 19471 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 19472 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 19473 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 19474 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 19475 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 19476 AlwaysBreakAfterDefinitionReturnType, 19477 FormatStyle::DRTBS_TopLevel); 19478 19479 Style.NamespaceIndentation = FormatStyle::NI_All; 19480 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 19481 FormatStyle::NI_None); 19482 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 19483 FormatStyle::NI_Inner); 19484 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 19485 FormatStyle::NI_All); 19486 19487 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 19488 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 19489 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19490 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 19491 AllowShortIfStatementsOnASingleLine, 19492 FormatStyle::SIS_WithoutElse); 19493 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 19494 AllowShortIfStatementsOnASingleLine, 19495 FormatStyle::SIS_OnlyFirstIf); 19496 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 19497 AllowShortIfStatementsOnASingleLine, 19498 FormatStyle::SIS_AllIfsAndElse); 19499 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 19500 AllowShortIfStatementsOnASingleLine, 19501 FormatStyle::SIS_OnlyFirstIf); 19502 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 19503 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19504 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 19505 AllowShortIfStatementsOnASingleLine, 19506 FormatStyle::SIS_WithoutElse); 19507 19508 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 19509 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 19510 FormatStyle::IEBS_AfterExternBlock); 19511 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 19512 FormatStyle::IEBS_Indent); 19513 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 19514 FormatStyle::IEBS_NoIndent); 19515 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 19516 FormatStyle::IEBS_Indent); 19517 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 19518 FormatStyle::IEBS_NoIndent); 19519 19520 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 19521 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 19522 FormatStyle::BFCS_Both); 19523 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 19524 FormatStyle::BFCS_None); 19525 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 19526 FormatStyle::BFCS_Before); 19527 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 19528 FormatStyle::BFCS_After); 19529 19530 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 19531 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 19532 FormatStyle::SJSIO_After); 19533 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 19534 FormatStyle::SJSIO_Before); 19535 19536 // FIXME: This is required because parsing a configuration simply overwrites 19537 // the first N elements of the list instead of resetting it. 19538 Style.ForEachMacros.clear(); 19539 std::vector<std::string> BoostForeach; 19540 BoostForeach.push_back("BOOST_FOREACH"); 19541 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 19542 std::vector<std::string> BoostAndQForeach; 19543 BoostAndQForeach.push_back("BOOST_FOREACH"); 19544 BoostAndQForeach.push_back("Q_FOREACH"); 19545 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 19546 BoostAndQForeach); 19547 19548 Style.IfMacros.clear(); 19549 std::vector<std::string> CustomIfs; 19550 CustomIfs.push_back("MYIF"); 19551 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 19552 19553 Style.AttributeMacros.clear(); 19554 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 19555 std::vector<std::string>{"__capability"}); 19556 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 19557 std::vector<std::string>({"attr1", "attr2"})); 19558 19559 Style.StatementAttributeLikeMacros.clear(); 19560 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 19561 StatementAttributeLikeMacros, 19562 std::vector<std::string>({"emit", "Q_EMIT"})); 19563 19564 Style.StatementMacros.clear(); 19565 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 19566 std::vector<std::string>{"QUNUSED"}); 19567 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 19568 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 19569 19570 Style.NamespaceMacros.clear(); 19571 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 19572 std::vector<std::string>{"TESTSUITE"}); 19573 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 19574 std::vector<std::string>({"TESTSUITE", "SUITE"})); 19575 19576 Style.WhitespaceSensitiveMacros.clear(); 19577 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 19578 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19579 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 19580 WhitespaceSensitiveMacros, 19581 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19582 Style.WhitespaceSensitiveMacros.clear(); 19583 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 19584 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19585 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 19586 WhitespaceSensitiveMacros, 19587 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19588 19589 Style.IncludeStyle.IncludeCategories.clear(); 19590 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 19591 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 19592 CHECK_PARSE("IncludeCategories:\n" 19593 " - Regex: abc/.*\n" 19594 " Priority: 2\n" 19595 " - Regex: .*\n" 19596 " Priority: 1\n" 19597 " CaseSensitive: true\n", 19598 IncludeStyle.IncludeCategories, ExpectedCategories); 19599 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 19600 "abc$"); 19601 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 19602 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 19603 19604 Style.SortIncludes = FormatStyle::SI_Never; 19605 CHECK_PARSE("SortIncludes: true", SortIncludes, 19606 FormatStyle::SI_CaseSensitive); 19607 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 19608 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 19609 FormatStyle::SI_CaseInsensitive); 19610 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 19611 FormatStyle::SI_CaseSensitive); 19612 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 19613 19614 Style.RawStringFormats.clear(); 19615 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 19616 { 19617 FormatStyle::LK_TextProto, 19618 {"pb", "proto"}, 19619 {"PARSE_TEXT_PROTO"}, 19620 /*CanonicalDelimiter=*/"", 19621 "llvm", 19622 }, 19623 { 19624 FormatStyle::LK_Cpp, 19625 {"cc", "cpp"}, 19626 {"C_CODEBLOCK", "CPPEVAL"}, 19627 /*CanonicalDelimiter=*/"cc", 19628 /*BasedOnStyle=*/"", 19629 }, 19630 }; 19631 19632 CHECK_PARSE("RawStringFormats:\n" 19633 " - Language: TextProto\n" 19634 " Delimiters:\n" 19635 " - 'pb'\n" 19636 " - 'proto'\n" 19637 " EnclosingFunctions:\n" 19638 " - 'PARSE_TEXT_PROTO'\n" 19639 " BasedOnStyle: llvm\n" 19640 " - Language: Cpp\n" 19641 " Delimiters:\n" 19642 " - 'cc'\n" 19643 " - 'cpp'\n" 19644 " EnclosingFunctions:\n" 19645 " - 'C_CODEBLOCK'\n" 19646 " - 'CPPEVAL'\n" 19647 " CanonicalDelimiter: 'cc'", 19648 RawStringFormats, ExpectedRawStringFormats); 19649 19650 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19651 " Minimum: 0\n" 19652 " Maximum: 0", 19653 SpacesInLineCommentPrefix.Minimum, 0u); 19654 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 19655 Style.SpacesInLineCommentPrefix.Minimum = 1; 19656 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19657 " Minimum: 2", 19658 SpacesInLineCommentPrefix.Minimum, 0u); 19659 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19660 " Maximum: -1", 19661 SpacesInLineCommentPrefix.Maximum, -1u); 19662 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19663 " Minimum: 2", 19664 SpacesInLineCommentPrefix.Minimum, 2u); 19665 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19666 " Maximum: 1", 19667 SpacesInLineCommentPrefix.Maximum, 1u); 19668 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 19669 19670 Style.SpacesInAngles = FormatStyle::SIAS_Always; 19671 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 19672 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 19673 FormatStyle::SIAS_Always); 19674 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 19675 // For backward compatibility: 19676 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 19677 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 19678 } 19679 19680 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 19681 FormatStyle Style = {}; 19682 Style.Language = FormatStyle::LK_Cpp; 19683 CHECK_PARSE("Language: Cpp\n" 19684 "IndentWidth: 12", 19685 IndentWidth, 12u); 19686 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 19687 "IndentWidth: 34", 19688 &Style), 19689 ParseError::Unsuitable); 19690 FormatStyle BinPackedTCS = {}; 19691 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 19692 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 19693 "InsertTrailingCommas: Wrapped", 19694 &BinPackedTCS), 19695 ParseError::BinPackTrailingCommaConflict); 19696 EXPECT_EQ(12u, Style.IndentWidth); 19697 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19698 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19699 19700 Style.Language = FormatStyle::LK_JavaScript; 19701 CHECK_PARSE("Language: JavaScript\n" 19702 "IndentWidth: 12", 19703 IndentWidth, 12u); 19704 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 19705 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 19706 "IndentWidth: 34", 19707 &Style), 19708 ParseError::Unsuitable); 19709 EXPECT_EQ(23u, Style.IndentWidth); 19710 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19711 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 19712 19713 CHECK_PARSE("BasedOnStyle: LLVM\n" 19714 "IndentWidth: 67", 19715 IndentWidth, 67u); 19716 19717 CHECK_PARSE("---\n" 19718 "Language: JavaScript\n" 19719 "IndentWidth: 12\n" 19720 "---\n" 19721 "Language: Cpp\n" 19722 "IndentWidth: 34\n" 19723 "...\n", 19724 IndentWidth, 12u); 19725 19726 Style.Language = FormatStyle::LK_Cpp; 19727 CHECK_PARSE("---\n" 19728 "Language: JavaScript\n" 19729 "IndentWidth: 12\n" 19730 "---\n" 19731 "Language: Cpp\n" 19732 "IndentWidth: 34\n" 19733 "...\n", 19734 IndentWidth, 34u); 19735 CHECK_PARSE("---\n" 19736 "IndentWidth: 78\n" 19737 "---\n" 19738 "Language: JavaScript\n" 19739 "IndentWidth: 56\n" 19740 "...\n", 19741 IndentWidth, 78u); 19742 19743 Style.ColumnLimit = 123; 19744 Style.IndentWidth = 234; 19745 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 19746 Style.TabWidth = 345; 19747 EXPECT_FALSE(parseConfiguration("---\n" 19748 "IndentWidth: 456\n" 19749 "BreakBeforeBraces: Allman\n" 19750 "---\n" 19751 "Language: JavaScript\n" 19752 "IndentWidth: 111\n" 19753 "TabWidth: 111\n" 19754 "---\n" 19755 "Language: Cpp\n" 19756 "BreakBeforeBraces: Stroustrup\n" 19757 "TabWidth: 789\n" 19758 "...\n", 19759 &Style)); 19760 EXPECT_EQ(123u, Style.ColumnLimit); 19761 EXPECT_EQ(456u, Style.IndentWidth); 19762 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 19763 EXPECT_EQ(789u, Style.TabWidth); 19764 19765 EXPECT_EQ(parseConfiguration("---\n" 19766 "Language: JavaScript\n" 19767 "IndentWidth: 56\n" 19768 "---\n" 19769 "IndentWidth: 78\n" 19770 "...\n", 19771 &Style), 19772 ParseError::Error); 19773 EXPECT_EQ(parseConfiguration("---\n" 19774 "Language: JavaScript\n" 19775 "IndentWidth: 56\n" 19776 "---\n" 19777 "Language: JavaScript\n" 19778 "IndentWidth: 78\n" 19779 "...\n", 19780 &Style), 19781 ParseError::Error); 19782 19783 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19784 } 19785 19786 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 19787 FormatStyle Style = {}; 19788 Style.Language = FormatStyle::LK_JavaScript; 19789 Style.BreakBeforeTernaryOperators = true; 19790 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 19791 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 19792 19793 Style.BreakBeforeTernaryOperators = true; 19794 EXPECT_EQ(0, parseConfiguration("---\n" 19795 "BasedOnStyle: Google\n" 19796 "---\n" 19797 "Language: JavaScript\n" 19798 "IndentWidth: 76\n" 19799 "...\n", 19800 &Style) 19801 .value()); 19802 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 19803 EXPECT_EQ(76u, Style.IndentWidth); 19804 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 19805 } 19806 19807 TEST_F(FormatTest, ConfigurationRoundTripTest) { 19808 FormatStyle Style = getLLVMStyle(); 19809 std::string YAML = configurationAsText(Style); 19810 FormatStyle ParsedStyle = {}; 19811 ParsedStyle.Language = FormatStyle::LK_Cpp; 19812 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 19813 EXPECT_EQ(Style, ParsedStyle); 19814 } 19815 19816 TEST_F(FormatTest, WorksFor8bitEncodings) { 19817 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 19818 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 19819 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 19820 "\"\xef\xee\xf0\xf3...\"", 19821 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 19822 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 19823 "\xef\xee\xf0\xf3...\"", 19824 getLLVMStyleWithColumns(12))); 19825 } 19826 19827 TEST_F(FormatTest, HandlesUTF8BOM) { 19828 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 19829 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 19830 format("\xef\xbb\xbf#include <iostream>")); 19831 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 19832 format("\xef\xbb\xbf\n#include <iostream>")); 19833 } 19834 19835 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 19836 #if !defined(_MSC_VER) 19837 19838 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 19839 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 19840 getLLVMStyleWithColumns(35)); 19841 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 19842 getLLVMStyleWithColumns(31)); 19843 verifyFormat("// Однажды в студёную зимнюю пору...", 19844 getLLVMStyleWithColumns(36)); 19845 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 19846 verifyFormat("/* Однажды в студёную зимнюю пору... */", 19847 getLLVMStyleWithColumns(39)); 19848 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 19849 getLLVMStyleWithColumns(35)); 19850 } 19851 19852 TEST_F(FormatTest, SplitsUTF8Strings) { 19853 // Non-printable characters' width is currently considered to be the length in 19854 // bytes in UTF8. The characters can be displayed in very different manner 19855 // (zero-width, single width with a substitution glyph, expanded to their code 19856 // (e.g. "<8d>"), so there's no single correct way to handle them. 19857 EXPECT_EQ("\"aaaaÄ\"\n" 19858 "\"\xc2\x8d\";", 19859 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 19860 EXPECT_EQ("\"aaaaaaaÄ\"\n" 19861 "\"\xc2\x8d\";", 19862 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 19863 EXPECT_EQ("\"Однажды, в \"\n" 19864 "\"студёную \"\n" 19865 "\"зимнюю \"\n" 19866 "\"пору,\"", 19867 format("\"Однажды, в студёную зимнюю пору,\"", 19868 getLLVMStyleWithColumns(13))); 19869 EXPECT_EQ( 19870 "\"一 二 三 \"\n" 19871 "\"四 五六 \"\n" 19872 "\"七 八 九 \"\n" 19873 "\"十\"", 19874 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 19875 EXPECT_EQ("\"一\t\"\n" 19876 "\"二 \t\"\n" 19877 "\"三 四 \"\n" 19878 "\"五\t\"\n" 19879 "\"六 \t\"\n" 19880 "\"七 \"\n" 19881 "\"八九十\tqq\"", 19882 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 19883 getLLVMStyleWithColumns(11))); 19884 19885 // UTF8 character in an escape sequence. 19886 EXPECT_EQ("\"aaaaaa\"\n" 19887 "\"\\\xC2\x8D\"", 19888 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 19889 } 19890 19891 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 19892 EXPECT_EQ("const char *sssss =\n" 19893 " \"一二三四五六七八\\\n" 19894 " 九 十\";", 19895 format("const char *sssss = \"一二三四五六七八\\\n" 19896 " 九 十\";", 19897 getLLVMStyleWithColumns(30))); 19898 } 19899 19900 TEST_F(FormatTest, SplitsUTF8LineComments) { 19901 EXPECT_EQ("// aaaaÄ\xc2\x8d", 19902 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 19903 EXPECT_EQ("// Я из лесу\n" 19904 "// вышел; был\n" 19905 "// сильный\n" 19906 "// мороз.", 19907 format("// Я из лесу вышел; был сильный мороз.", 19908 getLLVMStyleWithColumns(13))); 19909 EXPECT_EQ("// 一二三\n" 19910 "// 四五六七\n" 19911 "// 八 九\n" 19912 "// 十", 19913 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 19914 } 19915 19916 TEST_F(FormatTest, SplitsUTF8BlockComments) { 19917 EXPECT_EQ("/* Гляжу,\n" 19918 " * поднимается\n" 19919 " * медленно в\n" 19920 " * гору\n" 19921 " * Лошадка,\n" 19922 " * везущая\n" 19923 " * хворосту\n" 19924 " * воз. */", 19925 format("/* Гляжу, поднимается медленно в гору\n" 19926 " * Лошадка, везущая хворосту воз. */", 19927 getLLVMStyleWithColumns(13))); 19928 EXPECT_EQ( 19929 "/* 一二三\n" 19930 " * 四五六七\n" 19931 " * 八 九\n" 19932 " * 十 */", 19933 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 19934 EXPECT_EQ("/* \n" 19935 " * \n" 19936 " * - */", 19937 format("/* - */", getLLVMStyleWithColumns(12))); 19938 } 19939 19940 #endif // _MSC_VER 19941 19942 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 19943 FormatStyle Style = getLLVMStyle(); 19944 19945 Style.ConstructorInitializerIndentWidth = 4; 19946 verifyFormat( 19947 "SomeClass::Constructor()\n" 19948 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19949 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19950 Style); 19951 19952 Style.ConstructorInitializerIndentWidth = 2; 19953 verifyFormat( 19954 "SomeClass::Constructor()\n" 19955 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19956 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19957 Style); 19958 19959 Style.ConstructorInitializerIndentWidth = 0; 19960 verifyFormat( 19961 "SomeClass::Constructor()\n" 19962 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19963 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19964 Style); 19965 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19966 verifyFormat( 19967 "SomeLongTemplateVariableName<\n" 19968 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 19969 Style); 19970 verifyFormat("bool smaller = 1 < " 19971 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 19972 " " 19973 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 19974 Style); 19975 19976 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 19977 verifyFormat("SomeClass::Constructor() :\n" 19978 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 19979 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 19980 Style); 19981 } 19982 19983 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 19984 FormatStyle Style = getLLVMStyle(); 19985 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 19986 Style.ConstructorInitializerIndentWidth = 4; 19987 verifyFormat("SomeClass::Constructor()\n" 19988 " : a(a)\n" 19989 " , b(b)\n" 19990 " , c(c) {}", 19991 Style); 19992 verifyFormat("SomeClass::Constructor()\n" 19993 " : a(a) {}", 19994 Style); 19995 19996 Style.ColumnLimit = 0; 19997 verifyFormat("SomeClass::Constructor()\n" 19998 " : a(a) {}", 19999 Style); 20000 verifyFormat("SomeClass::Constructor() noexcept\n" 20001 " : a(a) {}", 20002 Style); 20003 verifyFormat("SomeClass::Constructor()\n" 20004 " : a(a)\n" 20005 " , b(b)\n" 20006 " , c(c) {}", 20007 Style); 20008 verifyFormat("SomeClass::Constructor()\n" 20009 " : a(a) {\n" 20010 " foo();\n" 20011 " bar();\n" 20012 "}", 20013 Style); 20014 20015 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20016 verifyFormat("SomeClass::Constructor()\n" 20017 " : a(a)\n" 20018 " , b(b)\n" 20019 " , c(c) {\n}", 20020 Style); 20021 verifyFormat("SomeClass::Constructor()\n" 20022 " : a(a) {\n}", 20023 Style); 20024 20025 Style.ColumnLimit = 80; 20026 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20027 Style.ConstructorInitializerIndentWidth = 2; 20028 verifyFormat("SomeClass::Constructor()\n" 20029 " : a(a)\n" 20030 " , b(b)\n" 20031 " , c(c) {}", 20032 Style); 20033 20034 Style.ConstructorInitializerIndentWidth = 0; 20035 verifyFormat("SomeClass::Constructor()\n" 20036 ": a(a)\n" 20037 ", b(b)\n" 20038 ", c(c) {}", 20039 Style); 20040 20041 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20042 Style.ConstructorInitializerIndentWidth = 4; 20043 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20044 verifyFormat( 20045 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20046 Style); 20047 verifyFormat( 20048 "SomeClass::Constructor()\n" 20049 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20050 Style); 20051 Style.ConstructorInitializerIndentWidth = 4; 20052 Style.ColumnLimit = 60; 20053 verifyFormat("SomeClass::Constructor()\n" 20054 " : aaaaaaaa(aaaaaaaa)\n" 20055 " , aaaaaaaa(aaaaaaaa)\n" 20056 " , aaaaaaaa(aaaaaaaa) {}", 20057 Style); 20058 } 20059 20060 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20061 FormatStyle Style = getLLVMStyle(); 20062 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20063 Style.ConstructorInitializerIndentWidth = 4; 20064 verifyFormat("SomeClass::Constructor()\n" 20065 " : a{a}\n" 20066 " , b{b} {}", 20067 Style); 20068 verifyFormat("SomeClass::Constructor()\n" 20069 " : a{a}\n" 20070 "#if CONDITION\n" 20071 " , b{b}\n" 20072 "#endif\n" 20073 "{\n}", 20074 Style); 20075 Style.ConstructorInitializerIndentWidth = 2; 20076 verifyFormat("SomeClass::Constructor()\n" 20077 "#if CONDITION\n" 20078 " : a{a}\n" 20079 "#endif\n" 20080 " , b{b}\n" 20081 " , c{c} {\n}", 20082 Style); 20083 Style.ConstructorInitializerIndentWidth = 0; 20084 verifyFormat("SomeClass::Constructor()\n" 20085 ": a{a}\n" 20086 "#ifdef CONDITION\n" 20087 ", b{b}\n" 20088 "#else\n" 20089 ", c{c}\n" 20090 "#endif\n" 20091 ", d{d} {\n}", 20092 Style); 20093 Style.ConstructorInitializerIndentWidth = 4; 20094 verifyFormat("SomeClass::Constructor()\n" 20095 " : a{a}\n" 20096 "#if WINDOWS\n" 20097 "#if DEBUG\n" 20098 " , b{0}\n" 20099 "#else\n" 20100 " , b{1}\n" 20101 "#endif\n" 20102 "#else\n" 20103 "#if DEBUG\n" 20104 " , b{2}\n" 20105 "#else\n" 20106 " , b{3}\n" 20107 "#endif\n" 20108 "#endif\n" 20109 "{\n}", 20110 Style); 20111 verifyFormat("SomeClass::Constructor()\n" 20112 " : a{a}\n" 20113 "#if WINDOWS\n" 20114 " , b{0}\n" 20115 "#if DEBUG\n" 20116 " , c{0}\n" 20117 "#else\n" 20118 " , c{1}\n" 20119 "#endif\n" 20120 "#else\n" 20121 "#if DEBUG\n" 20122 " , c{2}\n" 20123 "#else\n" 20124 " , c{3}\n" 20125 "#endif\n" 20126 " , b{1}\n" 20127 "#endif\n" 20128 "{\n}", 20129 Style); 20130 } 20131 20132 TEST_F(FormatTest, Destructors) { 20133 verifyFormat("void F(int &i) { i.~int(); }"); 20134 verifyFormat("void F(int &i) { i->~int(); }"); 20135 } 20136 20137 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20138 FormatStyle Style = getWebKitStyle(); 20139 20140 // Don't indent in outer namespaces. 20141 verifyFormat("namespace outer {\n" 20142 "int i;\n" 20143 "namespace inner {\n" 20144 " int i;\n" 20145 "} // namespace inner\n" 20146 "} // namespace outer\n" 20147 "namespace other_outer {\n" 20148 "int i;\n" 20149 "}", 20150 Style); 20151 20152 // Don't indent case labels. 20153 verifyFormat("switch (variable) {\n" 20154 "case 1:\n" 20155 "case 2:\n" 20156 " doSomething();\n" 20157 " break;\n" 20158 "default:\n" 20159 " ++variable;\n" 20160 "}", 20161 Style); 20162 20163 // Wrap before binary operators. 20164 EXPECT_EQ("void f()\n" 20165 "{\n" 20166 " if (aaaaaaaaaaaaaaaa\n" 20167 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20168 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20169 " return;\n" 20170 "}", 20171 format("void f() {\n" 20172 "if (aaaaaaaaaaaaaaaa\n" 20173 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20174 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20175 "return;\n" 20176 "}", 20177 Style)); 20178 20179 // Allow functions on a single line. 20180 verifyFormat("void f() { return; }", Style); 20181 20182 // Allow empty blocks on a single line and insert a space in empty blocks. 20183 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20184 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20185 // However, don't merge non-empty short loops. 20186 EXPECT_EQ("while (true) {\n" 20187 " continue;\n" 20188 "}", 20189 format("while (true) { continue; }", Style)); 20190 20191 // Constructor initializers are formatted one per line with the "," on the 20192 // new line. 20193 verifyFormat("Constructor()\n" 20194 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20195 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20196 " aaaaaaaaaaaaaa)\n" 20197 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20198 "{\n" 20199 "}", 20200 Style); 20201 verifyFormat("SomeClass::Constructor()\n" 20202 " : a(a)\n" 20203 "{\n" 20204 "}", 20205 Style); 20206 EXPECT_EQ("SomeClass::Constructor()\n" 20207 " : a(a)\n" 20208 "{\n" 20209 "}", 20210 format("SomeClass::Constructor():a(a){}", Style)); 20211 verifyFormat("SomeClass::Constructor()\n" 20212 " : a(a)\n" 20213 " , b(b)\n" 20214 " , c(c)\n" 20215 "{\n" 20216 "}", 20217 Style); 20218 verifyFormat("SomeClass::Constructor()\n" 20219 " : a(a)\n" 20220 "{\n" 20221 " foo();\n" 20222 " bar();\n" 20223 "}", 20224 Style); 20225 20226 // Access specifiers should be aligned left. 20227 verifyFormat("class C {\n" 20228 "public:\n" 20229 " int i;\n" 20230 "};", 20231 Style); 20232 20233 // Do not align comments. 20234 verifyFormat("int a; // Do not\n" 20235 "double b; // align comments.", 20236 Style); 20237 20238 // Do not align operands. 20239 EXPECT_EQ("ASSERT(aaaa\n" 20240 " || bbbb);", 20241 format("ASSERT ( aaaa\n||bbbb);", Style)); 20242 20243 // Accept input's line breaks. 20244 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 20245 " || bbbbbbbbbbbbbbb) {\n" 20246 " i++;\n" 20247 "}", 20248 format("if (aaaaaaaaaaaaaaa\n" 20249 "|| bbbbbbbbbbbbbbb) { i++; }", 20250 Style)); 20251 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 20252 " i++;\n" 20253 "}", 20254 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 20255 20256 // Don't automatically break all macro definitions (llvm.org/PR17842). 20257 verifyFormat("#define aNumber 10", Style); 20258 // However, generally keep the line breaks that the user authored. 20259 EXPECT_EQ("#define aNumber \\\n" 20260 " 10", 20261 format("#define aNumber \\\n" 20262 " 10", 20263 Style)); 20264 20265 // Keep empty and one-element array literals on a single line. 20266 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 20267 " copyItems:YES];", 20268 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 20269 "copyItems:YES];", 20270 Style)); 20271 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 20272 " copyItems:YES];", 20273 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 20274 " copyItems:YES];", 20275 Style)); 20276 // FIXME: This does not seem right, there should be more indentation before 20277 // the array literal's entries. Nested blocks have the same problem. 20278 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20279 " @\"a\",\n" 20280 " @\"a\"\n" 20281 "]\n" 20282 " copyItems:YES];", 20283 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20284 " @\"a\",\n" 20285 " @\"a\"\n" 20286 " ]\n" 20287 " copyItems:YES];", 20288 Style)); 20289 EXPECT_EQ( 20290 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20291 " copyItems:YES];", 20292 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20293 " copyItems:YES];", 20294 Style)); 20295 20296 verifyFormat("[self.a b:c c:d];", Style); 20297 EXPECT_EQ("[self.a b:c\n" 20298 " c:d];", 20299 format("[self.a b:c\n" 20300 "c:d];", 20301 Style)); 20302 } 20303 20304 TEST_F(FormatTest, FormatsLambdas) { 20305 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 20306 verifyFormat( 20307 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 20308 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 20309 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 20310 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 20311 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 20312 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 20313 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 20314 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 20315 verifyFormat("int x = f(*+[] {});"); 20316 verifyFormat("void f() {\n" 20317 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 20318 "}\n"); 20319 verifyFormat("void f() {\n" 20320 " other(x.begin(), //\n" 20321 " x.end(), //\n" 20322 " [&](int, int) { return 1; });\n" 20323 "}\n"); 20324 verifyFormat("void f() {\n" 20325 " other.other.other.other.other(\n" 20326 " x.begin(), x.end(),\n" 20327 " [something, rather](int, int, int, int, int, int, int) { " 20328 "return 1; });\n" 20329 "}\n"); 20330 verifyFormat( 20331 "void f() {\n" 20332 " other.other.other.other.other(\n" 20333 " x.begin(), x.end(),\n" 20334 " [something, rather](int, int, int, int, int, int, int) {\n" 20335 " //\n" 20336 " });\n" 20337 "}\n"); 20338 verifyFormat("SomeFunction([]() { // A cool function...\n" 20339 " return 43;\n" 20340 "});"); 20341 EXPECT_EQ("SomeFunction([]() {\n" 20342 "#define A a\n" 20343 " return 43;\n" 20344 "});", 20345 format("SomeFunction([](){\n" 20346 "#define A a\n" 20347 "return 43;\n" 20348 "});")); 20349 verifyFormat("void f() {\n" 20350 " SomeFunction([](decltype(x), A *a) {});\n" 20351 " SomeFunction([](typeof(x), A *a) {});\n" 20352 " SomeFunction([](_Atomic(x), A *a) {});\n" 20353 " SomeFunction([](__underlying_type(x), A *a) {});\n" 20354 "}"); 20355 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20356 " [](const aaaaaaaaaa &a) { return a; });"); 20357 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 20358 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 20359 "});"); 20360 verifyFormat("Constructor()\n" 20361 " : Field([] { // comment\n" 20362 " int i;\n" 20363 " }) {}"); 20364 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20365 " return some_parameter.size();\n" 20366 "};"); 20367 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20368 " [](const string &s) { return s; };"); 20369 verifyFormat("int i = aaaaaa ? 1 //\n" 20370 " : [] {\n" 20371 " return 2; //\n" 20372 " }();"); 20373 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20374 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20375 " return x == 2; // force break\n" 20376 " });"); 20377 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20378 " [=](int iiiiiiiiiiii) {\n" 20379 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20380 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20381 " });", 20382 getLLVMStyleWithColumns(60)); 20383 20384 verifyFormat("SomeFunction({[&] {\n" 20385 " // comment\n" 20386 " },\n" 20387 " [&] {\n" 20388 " // comment\n" 20389 " }});"); 20390 verifyFormat("SomeFunction({[&] {\n" 20391 " // comment\n" 20392 "}});"); 20393 verifyFormat( 20394 "virtual aaaaaaaaaaaaaaaa(\n" 20395 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 20396 " aaaaa aaaaaaaaa);"); 20397 20398 // Lambdas with return types. 20399 verifyFormat("int c = []() -> int { return 2; }();\n"); 20400 verifyFormat("int c = []() -> int * { return 2; }();\n"); 20401 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 20402 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 20403 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 20404 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 20405 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 20406 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 20407 verifyFormat("[a, a]() -> a<1> {};"); 20408 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 20409 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 20410 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 20411 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 20412 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 20413 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 20414 verifyFormat("[]() -> foo<!5> { return {}; };"); 20415 verifyFormat("[]() -> foo<~5> { return {}; };"); 20416 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 20417 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 20418 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 20419 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 20420 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 20421 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 20422 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 20423 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 20424 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 20425 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 20426 verifyFormat("namespace bar {\n" 20427 "// broken:\n" 20428 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 20429 "} // namespace bar"); 20430 verifyFormat("namespace bar {\n" 20431 "// broken:\n" 20432 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 20433 "} // namespace bar"); 20434 verifyFormat("namespace bar {\n" 20435 "// broken:\n" 20436 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 20437 "} // namespace bar"); 20438 verifyFormat("namespace bar {\n" 20439 "// broken:\n" 20440 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 20441 "} // namespace bar"); 20442 verifyFormat("namespace bar {\n" 20443 "// broken:\n" 20444 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 20445 "} // namespace bar"); 20446 verifyFormat("namespace bar {\n" 20447 "// broken:\n" 20448 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 20449 "} // namespace bar"); 20450 verifyFormat("namespace bar {\n" 20451 "// broken:\n" 20452 "auto foo{[]() -> foo<!5> { return {}; }};\n" 20453 "} // namespace bar"); 20454 verifyFormat("namespace bar {\n" 20455 "// broken:\n" 20456 "auto foo{[]() -> foo<~5> { return {}; }};\n" 20457 "} // namespace bar"); 20458 verifyFormat("namespace bar {\n" 20459 "// broken:\n" 20460 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 20461 "} // namespace bar"); 20462 verifyFormat("namespace bar {\n" 20463 "// broken:\n" 20464 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 20465 "} // namespace bar"); 20466 verifyFormat("namespace bar {\n" 20467 "// broken:\n" 20468 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 20469 "} // namespace bar"); 20470 verifyFormat("namespace bar {\n" 20471 "// broken:\n" 20472 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 20473 "} // namespace bar"); 20474 verifyFormat("namespace bar {\n" 20475 "// broken:\n" 20476 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 20477 "} // namespace bar"); 20478 verifyFormat("namespace bar {\n" 20479 "// broken:\n" 20480 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 20481 "} // namespace bar"); 20482 verifyFormat("namespace bar {\n" 20483 "// broken:\n" 20484 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 20485 "} // namespace bar"); 20486 verifyFormat("namespace bar {\n" 20487 "// broken:\n" 20488 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 20489 "} // namespace bar"); 20490 verifyFormat("namespace bar {\n" 20491 "// broken:\n" 20492 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 20493 "} // namespace bar"); 20494 verifyFormat("namespace bar {\n" 20495 "// broken:\n" 20496 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 20497 "} // namespace bar"); 20498 verifyFormat("[]() -> a<1> {};"); 20499 verifyFormat("[]() -> a<1> { ; };"); 20500 verifyFormat("[]() -> a<1> { ; }();"); 20501 verifyFormat("[a, a]() -> a<true> {};"); 20502 verifyFormat("[]() -> a<true> {};"); 20503 verifyFormat("[]() -> a<true> { ; };"); 20504 verifyFormat("[]() -> a<true> { ; }();"); 20505 verifyFormat("[a, a]() -> a<false> {};"); 20506 verifyFormat("[]() -> a<false> {};"); 20507 verifyFormat("[]() -> a<false> { ; };"); 20508 verifyFormat("[]() -> a<false> { ; }();"); 20509 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 20510 verifyFormat("namespace bar {\n" 20511 "auto foo{[]() -> foo<false> { ; }};\n" 20512 "} // namespace bar"); 20513 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 20514 " int j) -> int {\n" 20515 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 20516 "};"); 20517 verifyFormat( 20518 "aaaaaaaaaaaaaaaaaaaaaa(\n" 20519 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 20520 " return aaaaaaaaaaaaaaaaa;\n" 20521 " });", 20522 getLLVMStyleWithColumns(70)); 20523 verifyFormat("[]() //\n" 20524 " -> int {\n" 20525 " return 1; //\n" 20526 "};"); 20527 verifyFormat("[]() -> Void<T...> {};"); 20528 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 20529 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 20530 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 20531 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 20532 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 20533 verifyFormat("return int{[x = x]() { return x; }()};"); 20534 20535 // Lambdas with explicit template argument lists. 20536 verifyFormat( 20537 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 20538 20539 // Multiple lambdas in the same parentheses change indentation rules. These 20540 // lambdas are forced to start on new lines. 20541 verifyFormat("SomeFunction(\n" 20542 " []() {\n" 20543 " //\n" 20544 " },\n" 20545 " []() {\n" 20546 " //\n" 20547 " });"); 20548 20549 // A lambda passed as arg0 is always pushed to the next line. 20550 verifyFormat("SomeFunction(\n" 20551 " [this] {\n" 20552 " //\n" 20553 " },\n" 20554 " 1);\n"); 20555 20556 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 20557 // the arg0 case above. 20558 auto Style = getGoogleStyle(); 20559 Style.BinPackArguments = false; 20560 verifyFormat("SomeFunction(\n" 20561 " a,\n" 20562 " [this] {\n" 20563 " //\n" 20564 " },\n" 20565 " b);\n", 20566 Style); 20567 verifyFormat("SomeFunction(\n" 20568 " a,\n" 20569 " [this] {\n" 20570 " //\n" 20571 " },\n" 20572 " b);\n"); 20573 20574 // A lambda with a very long line forces arg0 to be pushed out irrespective of 20575 // the BinPackArguments value (as long as the code is wide enough). 20576 verifyFormat( 20577 "something->SomeFunction(\n" 20578 " a,\n" 20579 " [this] {\n" 20580 " " 20581 "D0000000000000000000000000000000000000000000000000000000000001();\n" 20582 " },\n" 20583 " b);\n"); 20584 20585 // A multi-line lambda is pulled up as long as the introducer fits on the 20586 // previous line and there are no further args. 20587 verifyFormat("function(1, [this, that] {\n" 20588 " //\n" 20589 "});\n"); 20590 verifyFormat("function([this, that] {\n" 20591 " //\n" 20592 "});\n"); 20593 // FIXME: this format is not ideal and we should consider forcing the first 20594 // arg onto its own line. 20595 verifyFormat("function(a, b, c, //\n" 20596 " d, [this, that] {\n" 20597 " //\n" 20598 " });\n"); 20599 20600 // Multiple lambdas are treated correctly even when there is a short arg0. 20601 verifyFormat("SomeFunction(\n" 20602 " 1,\n" 20603 " [this] {\n" 20604 " //\n" 20605 " },\n" 20606 " [this] {\n" 20607 " //\n" 20608 " },\n" 20609 " 1);\n"); 20610 20611 // More complex introducers. 20612 verifyFormat("return [i, args...] {};"); 20613 20614 // Not lambdas. 20615 verifyFormat("constexpr char hello[]{\"hello\"};"); 20616 verifyFormat("double &operator[](int i) { return 0; }\n" 20617 "int i;"); 20618 verifyFormat("std::unique_ptr<int[]> foo() {}"); 20619 verifyFormat("int i = a[a][a]->f();"); 20620 verifyFormat("int i = (*b)[a]->f();"); 20621 20622 // Other corner cases. 20623 verifyFormat("void f() {\n" 20624 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 20625 " );\n" 20626 "}"); 20627 20628 // Lambdas created through weird macros. 20629 verifyFormat("void f() {\n" 20630 " MACRO((const AA &a) { return 1; });\n" 20631 " MACRO((AA &a) { return 1; });\n" 20632 "}"); 20633 20634 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 20635 " doo_dah();\n" 20636 " doo_dah();\n" 20637 " })) {\n" 20638 "}"); 20639 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 20640 " doo_dah();\n" 20641 " doo_dah();\n" 20642 " })) {\n" 20643 "}"); 20644 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 20645 " doo_dah();\n" 20646 " doo_dah();\n" 20647 " })) {\n" 20648 "}"); 20649 verifyFormat("auto lambda = []() {\n" 20650 " int a = 2\n" 20651 "#if A\n" 20652 " + 2\n" 20653 "#endif\n" 20654 " ;\n" 20655 "};"); 20656 20657 // Lambdas with complex multiline introducers. 20658 verifyFormat( 20659 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20660 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 20661 " -> ::std::unordered_set<\n" 20662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 20663 " //\n" 20664 " });"); 20665 20666 FormatStyle DoNotMerge = getLLVMStyle(); 20667 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 20668 verifyFormat("auto c = []() {\n" 20669 " return b;\n" 20670 "};", 20671 "auto c = []() { return b; };", DoNotMerge); 20672 verifyFormat("auto c = []() {\n" 20673 "};", 20674 " auto c = []() {};", DoNotMerge); 20675 20676 FormatStyle MergeEmptyOnly = getLLVMStyle(); 20677 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 20678 verifyFormat("auto c = []() {\n" 20679 " return b;\n" 20680 "};", 20681 "auto c = []() {\n" 20682 " return b;\n" 20683 " };", 20684 MergeEmptyOnly); 20685 verifyFormat("auto c = []() {};", 20686 "auto c = []() {\n" 20687 "};", 20688 MergeEmptyOnly); 20689 20690 FormatStyle MergeInline = getLLVMStyle(); 20691 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 20692 verifyFormat("auto c = []() {\n" 20693 " return b;\n" 20694 "};", 20695 "auto c = []() { return b; };", MergeInline); 20696 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 20697 MergeInline); 20698 verifyFormat("function([]() { return b; }, a)", 20699 "function([]() { return b; }, a)", MergeInline); 20700 verifyFormat("function(a, []() { return b; })", 20701 "function(a, []() { return b; })", MergeInline); 20702 20703 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 20704 // AllowShortLambdasOnASingleLine 20705 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 20706 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 20707 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 20708 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20709 FormatStyle::ShortLambdaStyle::SLS_None; 20710 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 20711 " []()\n" 20712 " {\n" 20713 " return 17;\n" 20714 " });", 20715 LLVMWithBeforeLambdaBody); 20716 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 20717 " []()\n" 20718 " {\n" 20719 " });", 20720 LLVMWithBeforeLambdaBody); 20721 verifyFormat("auto fct_SLS_None = []()\n" 20722 "{\n" 20723 " return 17;\n" 20724 "};", 20725 LLVMWithBeforeLambdaBody); 20726 verifyFormat("TwoNestedLambdas_SLS_None(\n" 20727 " []()\n" 20728 " {\n" 20729 " return Call(\n" 20730 " []()\n" 20731 " {\n" 20732 " return 17;\n" 20733 " });\n" 20734 " });", 20735 LLVMWithBeforeLambdaBody); 20736 verifyFormat("void Fct() {\n" 20737 " return {[]()\n" 20738 " {\n" 20739 " return 17;\n" 20740 " }};\n" 20741 "}", 20742 LLVMWithBeforeLambdaBody); 20743 20744 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20745 FormatStyle::ShortLambdaStyle::SLS_Empty; 20746 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 20747 " []()\n" 20748 " {\n" 20749 " return 17;\n" 20750 " });", 20751 LLVMWithBeforeLambdaBody); 20752 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 20753 LLVMWithBeforeLambdaBody); 20754 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 20755 "ongFunctionName_SLS_Empty(\n" 20756 " []() {});", 20757 LLVMWithBeforeLambdaBody); 20758 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 20759 " []()\n" 20760 " {\n" 20761 " return 17;\n" 20762 " });", 20763 LLVMWithBeforeLambdaBody); 20764 verifyFormat("auto fct_SLS_Empty = []()\n" 20765 "{\n" 20766 " return 17;\n" 20767 "};", 20768 LLVMWithBeforeLambdaBody); 20769 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 20770 " []()\n" 20771 " {\n" 20772 " return Call([]() {});\n" 20773 " });", 20774 LLVMWithBeforeLambdaBody); 20775 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 20776 " []()\n" 20777 " {\n" 20778 " return Call([]() {});\n" 20779 " });", 20780 LLVMWithBeforeLambdaBody); 20781 verifyFormat( 20782 "FctWithLongLineInLambda_SLS_Empty(\n" 20783 " []()\n" 20784 " {\n" 20785 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20786 " AndShouldNotBeConsiderAsInline,\n" 20787 " LambdaBodyMustBeBreak);\n" 20788 " });", 20789 LLVMWithBeforeLambdaBody); 20790 20791 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20792 FormatStyle::ShortLambdaStyle::SLS_Inline; 20793 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 20794 LLVMWithBeforeLambdaBody); 20795 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 20796 LLVMWithBeforeLambdaBody); 20797 verifyFormat("auto fct_SLS_Inline = []()\n" 20798 "{\n" 20799 " return 17;\n" 20800 "};", 20801 LLVMWithBeforeLambdaBody); 20802 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 20803 "17; }); });", 20804 LLVMWithBeforeLambdaBody); 20805 verifyFormat( 20806 "FctWithLongLineInLambda_SLS_Inline(\n" 20807 " []()\n" 20808 " {\n" 20809 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20810 " AndShouldNotBeConsiderAsInline,\n" 20811 " LambdaBodyMustBeBreak);\n" 20812 " });", 20813 LLVMWithBeforeLambdaBody); 20814 verifyFormat("FctWithMultipleParams_SLS_Inline(" 20815 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 20816 " []() { return 17; });", 20817 LLVMWithBeforeLambdaBody); 20818 verifyFormat( 20819 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 20820 LLVMWithBeforeLambdaBody); 20821 20822 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20823 FormatStyle::ShortLambdaStyle::SLS_All; 20824 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 20825 LLVMWithBeforeLambdaBody); 20826 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 20827 LLVMWithBeforeLambdaBody); 20828 verifyFormat("auto fct_SLS_All = []() { return 17; };", 20829 LLVMWithBeforeLambdaBody); 20830 verifyFormat("FctWithOneParam_SLS_All(\n" 20831 " []()\n" 20832 " {\n" 20833 " // A cool function...\n" 20834 " return 43;\n" 20835 " });", 20836 LLVMWithBeforeLambdaBody); 20837 verifyFormat("FctWithMultipleParams_SLS_All(" 20838 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 20839 " []() { return 17; });", 20840 LLVMWithBeforeLambdaBody); 20841 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 20842 LLVMWithBeforeLambdaBody); 20843 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 20844 LLVMWithBeforeLambdaBody); 20845 verifyFormat( 20846 "FctWithLongLineInLambda_SLS_All(\n" 20847 " []()\n" 20848 " {\n" 20849 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20850 " AndShouldNotBeConsiderAsInline,\n" 20851 " LambdaBodyMustBeBreak);\n" 20852 " });", 20853 LLVMWithBeforeLambdaBody); 20854 verifyFormat( 20855 "auto fct_SLS_All = []()\n" 20856 "{\n" 20857 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20858 " AndShouldNotBeConsiderAsInline,\n" 20859 " LambdaBodyMustBeBreak);\n" 20860 "};", 20861 LLVMWithBeforeLambdaBody); 20862 LLVMWithBeforeLambdaBody.BinPackParameters = false; 20863 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 20864 LLVMWithBeforeLambdaBody); 20865 verifyFormat( 20866 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 20867 " FirstParam,\n" 20868 " SecondParam,\n" 20869 " ThirdParam,\n" 20870 " FourthParam);", 20871 LLVMWithBeforeLambdaBody); 20872 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 20873 " []() { return " 20874 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 20875 " FirstParam,\n" 20876 " SecondParam,\n" 20877 " ThirdParam,\n" 20878 " FourthParam);", 20879 LLVMWithBeforeLambdaBody); 20880 verifyFormat( 20881 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 20882 " SecondParam,\n" 20883 " ThirdParam,\n" 20884 " FourthParam,\n" 20885 " []() { return SomeValueNotSoLong; });", 20886 LLVMWithBeforeLambdaBody); 20887 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 20888 " []()\n" 20889 " {\n" 20890 " return " 20891 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 20892 "eConsiderAsInline;\n" 20893 " });", 20894 LLVMWithBeforeLambdaBody); 20895 verifyFormat( 20896 "FctWithLongLineInLambda_SLS_All(\n" 20897 " []()\n" 20898 " {\n" 20899 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20900 " AndShouldNotBeConsiderAsInline,\n" 20901 " LambdaBodyMustBeBreak);\n" 20902 " });", 20903 LLVMWithBeforeLambdaBody); 20904 verifyFormat("FctWithTwoParams_SLS_All(\n" 20905 " []()\n" 20906 " {\n" 20907 " // A cool function...\n" 20908 " return 43;\n" 20909 " },\n" 20910 " 87);", 20911 LLVMWithBeforeLambdaBody); 20912 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 20913 LLVMWithBeforeLambdaBody); 20914 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 20915 LLVMWithBeforeLambdaBody); 20916 verifyFormat( 20917 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 20918 LLVMWithBeforeLambdaBody); 20919 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 20920 "}); }, x);", 20921 LLVMWithBeforeLambdaBody); 20922 verifyFormat("TwoNestedLambdas_SLS_All(\n" 20923 " []()\n" 20924 " {\n" 20925 " // A cool function...\n" 20926 " return Call([]() { return 17; });\n" 20927 " });", 20928 LLVMWithBeforeLambdaBody); 20929 verifyFormat("TwoNestedLambdas_SLS_All(\n" 20930 " []()\n" 20931 " {\n" 20932 " return Call(\n" 20933 " []()\n" 20934 " {\n" 20935 " // A cool function...\n" 20936 " return 17;\n" 20937 " });\n" 20938 " });", 20939 LLVMWithBeforeLambdaBody); 20940 20941 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20942 FormatStyle::ShortLambdaStyle::SLS_None; 20943 20944 verifyFormat("auto select = [this]() -> const Library::Object *\n" 20945 "{\n" 20946 " return MyAssignment::SelectFromList(this);\n" 20947 "};\n", 20948 LLVMWithBeforeLambdaBody); 20949 20950 verifyFormat("auto select = [this]() -> const Library::Object &\n" 20951 "{\n" 20952 " return MyAssignment::SelectFromList(this);\n" 20953 "};\n", 20954 LLVMWithBeforeLambdaBody); 20955 20956 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 20957 "{\n" 20958 " return MyAssignment::SelectFromList(this);\n" 20959 "};\n", 20960 LLVMWithBeforeLambdaBody); 20961 20962 verifyFormat("namespace test {\n" 20963 "class Test {\n" 20964 "public:\n" 20965 " Test() = default;\n" 20966 "};\n" 20967 "} // namespace test", 20968 LLVMWithBeforeLambdaBody); 20969 20970 // Lambdas with different indentation styles. 20971 Style = getLLVMStyleWithColumns(100); 20972 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 20973 " return promise.then(\n" 20974 " [this, &someVariable, someObject = " 20975 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 20976 " return someObject.startAsyncAction().then(\n" 20977 " [this, &someVariable](AsyncActionResult result) " 20978 "mutable { result.processMore(); });\n" 20979 " });\n" 20980 "}\n", 20981 format("SomeResult doSomething(SomeObject promise) {\n" 20982 " return promise.then([this, &someVariable, someObject = " 20983 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 20984 " return someObject.startAsyncAction().then([this, " 20985 "&someVariable](AsyncActionResult result) mutable {\n" 20986 " result.processMore();\n" 20987 " });\n" 20988 " });\n" 20989 "}\n", 20990 Style)); 20991 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 20992 verifyFormat("test() {\n" 20993 " ([]() -> {\n" 20994 " int b = 32;\n" 20995 " return 3;\n" 20996 " }).foo();\n" 20997 "}", 20998 Style); 20999 verifyFormat("test() {\n" 21000 " []() -> {\n" 21001 " int b = 32;\n" 21002 " return 3;\n" 21003 " }\n" 21004 "}", 21005 Style); 21006 verifyFormat("std::sort(v.begin(), v.end(),\n" 21007 " [](const auto &someLongArgumentName, const auto " 21008 "&someOtherLongArgumentName) {\n" 21009 " return someLongArgumentName.someMemberVariable < " 21010 "someOtherLongArgumentName.someMemberVariable;\n" 21011 "});", 21012 Style); 21013 verifyFormat("test() {\n" 21014 " (\n" 21015 " []() -> {\n" 21016 " int b = 32;\n" 21017 " return 3;\n" 21018 " },\n" 21019 " foo, bar)\n" 21020 " .foo();\n" 21021 "}", 21022 Style); 21023 verifyFormat("test() {\n" 21024 " ([]() -> {\n" 21025 " int b = 32;\n" 21026 " return 3;\n" 21027 " })\n" 21028 " .foo()\n" 21029 " .bar();\n" 21030 "}", 21031 Style); 21032 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21033 " return promise.then(\n" 21034 " [this, &someVariable, someObject = " 21035 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21036 " return someObject.startAsyncAction().then(\n" 21037 " [this, &someVariable](AsyncActionResult result) mutable { " 21038 "result.processMore(); });\n" 21039 " });\n" 21040 "}\n", 21041 format("SomeResult doSomething(SomeObject promise) {\n" 21042 " return promise.then([this, &someVariable, someObject = " 21043 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21044 " return someObject.startAsyncAction().then([this, " 21045 "&someVariable](AsyncActionResult result) mutable {\n" 21046 " result.processMore();\n" 21047 " });\n" 21048 " });\n" 21049 "}\n", 21050 Style)); 21051 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21052 " return promise.then([this, &someVariable] {\n" 21053 " return someObject.startAsyncAction().then(\n" 21054 " [this, &someVariable](AsyncActionResult result) mutable { " 21055 "result.processMore(); });\n" 21056 " });\n" 21057 "}\n", 21058 format("SomeResult doSomething(SomeObject promise) {\n" 21059 " return promise.then([this, &someVariable] {\n" 21060 " return someObject.startAsyncAction().then([this, " 21061 "&someVariable](AsyncActionResult result) mutable {\n" 21062 " result.processMore();\n" 21063 " });\n" 21064 " });\n" 21065 "}\n", 21066 Style)); 21067 Style = getGoogleStyle(); 21068 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21069 EXPECT_EQ("#define A \\\n" 21070 " [] { \\\n" 21071 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21072 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21073 " }", 21074 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21075 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21076 Style)); 21077 // TODO: The current formatting has a minor issue that's not worth fixing 21078 // right now whereby the closing brace is indented relative to the signature 21079 // instead of being aligned. This only happens with macros. 21080 } 21081 21082 TEST_F(FormatTest, LambdaWithLineComments) { 21083 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21084 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21085 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21086 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21087 FormatStyle::ShortLambdaStyle::SLS_All; 21088 21089 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21090 verifyFormat("auto k = []() // comment\n" 21091 "{ return; }", 21092 LLVMWithBeforeLambdaBody); 21093 verifyFormat("auto k = []() /* comment */ { return; }", 21094 LLVMWithBeforeLambdaBody); 21095 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21096 LLVMWithBeforeLambdaBody); 21097 verifyFormat("auto k = []() // X\n" 21098 "{ return; }", 21099 LLVMWithBeforeLambdaBody); 21100 verifyFormat( 21101 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21102 "{ return; }", 21103 LLVMWithBeforeLambdaBody); 21104 } 21105 21106 TEST_F(FormatTest, EmptyLinesInLambdas) { 21107 verifyFormat("auto lambda = []() {\n" 21108 " x(); //\n" 21109 "};", 21110 "auto lambda = []() {\n" 21111 "\n" 21112 " x(); //\n" 21113 "\n" 21114 "};"); 21115 } 21116 21117 TEST_F(FormatTest, FormatsBlocks) { 21118 FormatStyle ShortBlocks = getLLVMStyle(); 21119 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21120 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21121 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21122 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21123 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21124 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21125 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21126 21127 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21128 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21129 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21130 21131 verifyFormat("[operation setCompletionBlock:^{\n" 21132 " [self onOperationDone];\n" 21133 "}];"); 21134 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21135 " [self onOperationDone];\n" 21136 "}]};"); 21137 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21138 " f();\n" 21139 "}];"); 21140 verifyFormat("int a = [operation block:^int(int *i) {\n" 21141 " return 1;\n" 21142 "}];"); 21143 verifyFormat("[myObject doSomethingWith:arg1\n" 21144 " aaa:^int(int *a) {\n" 21145 " return 1;\n" 21146 " }\n" 21147 " bbb:f(a * bbbbbbbb)];"); 21148 21149 verifyFormat("[operation setCompletionBlock:^{\n" 21150 " [self.delegate newDataAvailable];\n" 21151 "}];", 21152 getLLVMStyleWithColumns(60)); 21153 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21154 " NSString *path = [self sessionFilePath];\n" 21155 " if (path) {\n" 21156 " // ...\n" 21157 " }\n" 21158 "});"); 21159 verifyFormat("[[SessionService sharedService]\n" 21160 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21161 " if (window) {\n" 21162 " [self windowDidLoad:window];\n" 21163 " } else {\n" 21164 " [self errorLoadingWindow];\n" 21165 " }\n" 21166 " }];"); 21167 verifyFormat("void (^largeBlock)(void) = ^{\n" 21168 " // ...\n" 21169 "};\n", 21170 getLLVMStyleWithColumns(40)); 21171 verifyFormat("[[SessionService sharedService]\n" 21172 " loadWindowWithCompletionBlock: //\n" 21173 " ^(SessionWindow *window) {\n" 21174 " if (window) {\n" 21175 " [self windowDidLoad:window];\n" 21176 " } else {\n" 21177 " [self errorLoadingWindow];\n" 21178 " }\n" 21179 " }];", 21180 getLLVMStyleWithColumns(60)); 21181 verifyFormat("[myObject doSomethingWith:arg1\n" 21182 " firstBlock:^(Foo *a) {\n" 21183 " // ...\n" 21184 " int i;\n" 21185 " }\n" 21186 " secondBlock:^(Bar *b) {\n" 21187 " // ...\n" 21188 " int i;\n" 21189 " }\n" 21190 " thirdBlock:^Foo(Bar *b) {\n" 21191 " // ...\n" 21192 " int i;\n" 21193 " }];"); 21194 verifyFormat("[myObject doSomethingWith:arg1\n" 21195 " firstBlock:-1\n" 21196 " secondBlock:^(Bar *b) {\n" 21197 " // ...\n" 21198 " int i;\n" 21199 " }];"); 21200 21201 verifyFormat("f(^{\n" 21202 " @autoreleasepool {\n" 21203 " if (a) {\n" 21204 " g();\n" 21205 " }\n" 21206 " }\n" 21207 "});"); 21208 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 21209 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 21210 "};"); 21211 21212 FormatStyle FourIndent = getLLVMStyle(); 21213 FourIndent.ObjCBlockIndentWidth = 4; 21214 verifyFormat("[operation setCompletionBlock:^{\n" 21215 " [self onOperationDone];\n" 21216 "}];", 21217 FourIndent); 21218 } 21219 21220 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 21221 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 21222 21223 verifyFormat("[[SessionService sharedService] " 21224 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21225 " if (window) {\n" 21226 " [self windowDidLoad:window];\n" 21227 " } else {\n" 21228 " [self errorLoadingWindow];\n" 21229 " }\n" 21230 "}];", 21231 ZeroColumn); 21232 EXPECT_EQ("[[SessionService sharedService]\n" 21233 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21234 " if (window) {\n" 21235 " [self windowDidLoad:window];\n" 21236 " } else {\n" 21237 " [self errorLoadingWindow];\n" 21238 " }\n" 21239 " }];", 21240 format("[[SessionService sharedService]\n" 21241 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21242 " if (window) {\n" 21243 " [self windowDidLoad:window];\n" 21244 " } else {\n" 21245 " [self errorLoadingWindow];\n" 21246 " }\n" 21247 "}];", 21248 ZeroColumn)); 21249 verifyFormat("[myObject doSomethingWith:arg1\n" 21250 " firstBlock:^(Foo *a) {\n" 21251 " // ...\n" 21252 " int i;\n" 21253 " }\n" 21254 " secondBlock:^(Bar *b) {\n" 21255 " // ...\n" 21256 " int i;\n" 21257 " }\n" 21258 " thirdBlock:^Foo(Bar *b) {\n" 21259 " // ...\n" 21260 " int i;\n" 21261 " }];", 21262 ZeroColumn); 21263 verifyFormat("f(^{\n" 21264 " @autoreleasepool {\n" 21265 " if (a) {\n" 21266 " g();\n" 21267 " }\n" 21268 " }\n" 21269 "});", 21270 ZeroColumn); 21271 verifyFormat("void (^largeBlock)(void) = ^{\n" 21272 " // ...\n" 21273 "};", 21274 ZeroColumn); 21275 21276 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21277 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 21278 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21279 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 21280 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 21281 " int i;\n" 21282 "};", 21283 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21284 } 21285 21286 TEST_F(FormatTest, SupportsCRLF) { 21287 EXPECT_EQ("int a;\r\n" 21288 "int b;\r\n" 21289 "int c;\r\n", 21290 format("int a;\r\n" 21291 " int b;\r\n" 21292 " int c;\r\n", 21293 getLLVMStyle())); 21294 EXPECT_EQ("int a;\r\n" 21295 "int b;\r\n" 21296 "int c;\r\n", 21297 format("int a;\r\n" 21298 " int b;\n" 21299 " int c;\r\n", 21300 getLLVMStyle())); 21301 EXPECT_EQ("int a;\n" 21302 "int b;\n" 21303 "int c;\n", 21304 format("int a;\r\n" 21305 " int b;\n" 21306 " int c;\n", 21307 getLLVMStyle())); 21308 EXPECT_EQ("\"aaaaaaa \"\r\n" 21309 "\"bbbbbbb\";\r\n", 21310 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 21311 EXPECT_EQ("#define A \\\r\n" 21312 " b; \\\r\n" 21313 " c; \\\r\n" 21314 " d;\r\n", 21315 format("#define A \\\r\n" 21316 " b; \\\r\n" 21317 " c; d; \r\n", 21318 getGoogleStyle())); 21319 21320 EXPECT_EQ("/*\r\n" 21321 "multi line block comments\r\n" 21322 "should not introduce\r\n" 21323 "an extra carriage return\r\n" 21324 "*/\r\n", 21325 format("/*\r\n" 21326 "multi line block comments\r\n" 21327 "should not introduce\r\n" 21328 "an extra carriage return\r\n" 21329 "*/\r\n")); 21330 EXPECT_EQ("/*\r\n" 21331 "\r\n" 21332 "*/", 21333 format("/*\r\n" 21334 " \r\r\r\n" 21335 "*/")); 21336 21337 FormatStyle style = getLLVMStyle(); 21338 21339 style.DeriveLineEnding = true; 21340 style.UseCRLF = false; 21341 EXPECT_EQ("union FooBarBazQux {\n" 21342 " int foo;\n" 21343 " int bar;\n" 21344 " int baz;\n" 21345 "};", 21346 format("union FooBarBazQux {\r\n" 21347 " int foo;\n" 21348 " int bar;\r\n" 21349 " int baz;\n" 21350 "};", 21351 style)); 21352 style.UseCRLF = true; 21353 EXPECT_EQ("union FooBarBazQux {\r\n" 21354 " int foo;\r\n" 21355 " int bar;\r\n" 21356 " int baz;\r\n" 21357 "};", 21358 format("union FooBarBazQux {\r\n" 21359 " int foo;\n" 21360 " int bar;\r\n" 21361 " int baz;\n" 21362 "};", 21363 style)); 21364 21365 style.DeriveLineEnding = false; 21366 style.UseCRLF = false; 21367 EXPECT_EQ("union FooBarBazQux {\n" 21368 " int foo;\n" 21369 " int bar;\n" 21370 " int baz;\n" 21371 " int qux;\n" 21372 "};", 21373 format("union FooBarBazQux {\r\n" 21374 " int foo;\n" 21375 " int bar;\r\n" 21376 " int baz;\n" 21377 " int qux;\r\n" 21378 "};", 21379 style)); 21380 style.UseCRLF = true; 21381 EXPECT_EQ("union FooBarBazQux {\r\n" 21382 " int foo;\r\n" 21383 " int bar;\r\n" 21384 " int baz;\r\n" 21385 " int qux;\r\n" 21386 "};", 21387 format("union FooBarBazQux {\r\n" 21388 " int foo;\n" 21389 " int bar;\r\n" 21390 " int baz;\n" 21391 " int qux;\n" 21392 "};", 21393 style)); 21394 21395 style.DeriveLineEnding = true; 21396 style.UseCRLF = false; 21397 EXPECT_EQ("union FooBarBazQux {\r\n" 21398 " int foo;\r\n" 21399 " int bar;\r\n" 21400 " int baz;\r\n" 21401 " int qux;\r\n" 21402 "};", 21403 format("union FooBarBazQux {\r\n" 21404 " int foo;\n" 21405 " int bar;\r\n" 21406 " int baz;\n" 21407 " int qux;\r\n" 21408 "};", 21409 style)); 21410 style.UseCRLF = true; 21411 EXPECT_EQ("union FooBarBazQux {\n" 21412 " int foo;\n" 21413 " int bar;\n" 21414 " int baz;\n" 21415 " int qux;\n" 21416 "};", 21417 format("union FooBarBazQux {\r\n" 21418 " int foo;\n" 21419 " int bar;\r\n" 21420 " int baz;\n" 21421 " int qux;\n" 21422 "};", 21423 style)); 21424 } 21425 21426 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 21427 verifyFormat("MY_CLASS(C) {\n" 21428 " int i;\n" 21429 " int j;\n" 21430 "};"); 21431 } 21432 21433 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 21434 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 21435 TwoIndent.ContinuationIndentWidth = 2; 21436 21437 EXPECT_EQ("int i =\n" 21438 " longFunction(\n" 21439 " arg);", 21440 format("int i = longFunction(arg);", TwoIndent)); 21441 21442 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 21443 SixIndent.ContinuationIndentWidth = 6; 21444 21445 EXPECT_EQ("int i =\n" 21446 " longFunction(\n" 21447 " arg);", 21448 format("int i = longFunction(arg);", SixIndent)); 21449 } 21450 21451 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 21452 FormatStyle Style = getLLVMStyle(); 21453 verifyFormat("int Foo::getter(\n" 21454 " //\n" 21455 ") const {\n" 21456 " return foo;\n" 21457 "}", 21458 Style); 21459 verifyFormat("void Foo::setter(\n" 21460 " //\n" 21461 ") {\n" 21462 " foo = 1;\n" 21463 "}", 21464 Style); 21465 } 21466 21467 TEST_F(FormatTest, SpacesInAngles) { 21468 FormatStyle Spaces = getLLVMStyle(); 21469 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21470 21471 verifyFormat("vector< ::std::string > x1;", Spaces); 21472 verifyFormat("Foo< int, Bar > x2;", Spaces); 21473 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 21474 21475 verifyFormat("static_cast< int >(arg);", Spaces); 21476 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 21477 verifyFormat("f< int, float >();", Spaces); 21478 verifyFormat("template <> g() {}", Spaces); 21479 verifyFormat("template < std::vector< int > > f() {}", Spaces); 21480 verifyFormat("std::function< void(int, int) > fct;", Spaces); 21481 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 21482 Spaces); 21483 21484 Spaces.Standard = FormatStyle::LS_Cpp03; 21485 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21486 verifyFormat("A< A< int > >();", Spaces); 21487 21488 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21489 verifyFormat("A<A<int> >();", Spaces); 21490 21491 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21492 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 21493 Spaces); 21494 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 21495 Spaces); 21496 21497 verifyFormat("A<A<int> >();", Spaces); 21498 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 21499 verifyFormat("A< A< int > >();", Spaces); 21500 21501 Spaces.Standard = FormatStyle::LS_Cpp11; 21502 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21503 verifyFormat("A< A< int > >();", Spaces); 21504 21505 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21506 verifyFormat("vector<::std::string> x4;", Spaces); 21507 verifyFormat("vector<int> x5;", Spaces); 21508 verifyFormat("Foo<int, Bar> x6;", Spaces); 21509 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21510 21511 verifyFormat("A<A<int>>();", Spaces); 21512 21513 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21514 verifyFormat("vector<::std::string> x4;", Spaces); 21515 verifyFormat("vector< ::std::string > x4;", Spaces); 21516 verifyFormat("vector<int> x5;", Spaces); 21517 verifyFormat("vector< int > x5;", Spaces); 21518 verifyFormat("Foo<int, Bar> x6;", Spaces); 21519 verifyFormat("Foo< int, Bar > x6;", Spaces); 21520 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21521 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 21522 21523 verifyFormat("A<A<int>>();", Spaces); 21524 verifyFormat("A< A< int > >();", Spaces); 21525 verifyFormat("A<A<int > >();", Spaces); 21526 verifyFormat("A< A< int>>();", Spaces); 21527 21528 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21529 verifyFormat("// clang-format off\n" 21530 "foo<<<1, 1>>>();\n" 21531 "// clang-format on\n", 21532 Spaces); 21533 verifyFormat("// clang-format off\n" 21534 "foo< < <1, 1> > >();\n" 21535 "// clang-format on\n", 21536 Spaces); 21537 } 21538 21539 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 21540 FormatStyle Style = getLLVMStyle(); 21541 Style.SpaceAfterTemplateKeyword = false; 21542 verifyFormat("template<int> void foo();", Style); 21543 } 21544 21545 TEST_F(FormatTest, TripleAngleBrackets) { 21546 verifyFormat("f<<<1, 1>>>();"); 21547 verifyFormat("f<<<1, 1, 1, s>>>();"); 21548 verifyFormat("f<<<a, b, c, d>>>();"); 21549 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 21550 verifyFormat("f<param><<<1, 1>>>();"); 21551 verifyFormat("f<1><<<1, 1>>>();"); 21552 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 21553 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21554 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 21555 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 21556 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 21557 } 21558 21559 TEST_F(FormatTest, MergeLessLessAtEnd) { 21560 verifyFormat("<<"); 21561 EXPECT_EQ("< < <", format("\\\n<<<")); 21562 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21563 "aaallvm::outs() <<"); 21564 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21565 "aaaallvm::outs()\n <<"); 21566 } 21567 21568 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 21569 std::string code = "#if A\n" 21570 "#if B\n" 21571 "a.\n" 21572 "#endif\n" 21573 " a = 1;\n" 21574 "#else\n" 21575 "#endif\n" 21576 "#if C\n" 21577 "#else\n" 21578 "#endif\n"; 21579 EXPECT_EQ(code, format(code)); 21580 } 21581 21582 TEST_F(FormatTest, HandleConflictMarkers) { 21583 // Git/SVN conflict markers. 21584 EXPECT_EQ("int a;\n" 21585 "void f() {\n" 21586 " callme(some(parameter1,\n" 21587 "<<<<<<< text by the vcs\n" 21588 " parameter2),\n" 21589 "||||||| text by the vcs\n" 21590 " parameter2),\n" 21591 " parameter3,\n" 21592 "======= text by the vcs\n" 21593 " parameter2, parameter3),\n" 21594 ">>>>>>> text by the vcs\n" 21595 " otherparameter);\n", 21596 format("int a;\n" 21597 "void f() {\n" 21598 " callme(some(parameter1,\n" 21599 "<<<<<<< text by the vcs\n" 21600 " parameter2),\n" 21601 "||||||| text by the vcs\n" 21602 " parameter2),\n" 21603 " parameter3,\n" 21604 "======= text by the vcs\n" 21605 " parameter2,\n" 21606 " parameter3),\n" 21607 ">>>>>>> text by the vcs\n" 21608 " otherparameter);\n")); 21609 21610 // Perforce markers. 21611 EXPECT_EQ("void f() {\n" 21612 " function(\n" 21613 ">>>> text by the vcs\n" 21614 " parameter,\n" 21615 "==== text by the vcs\n" 21616 " parameter,\n" 21617 "==== text by the vcs\n" 21618 " parameter,\n" 21619 "<<<< text by the vcs\n" 21620 " parameter);\n", 21621 format("void f() {\n" 21622 " function(\n" 21623 ">>>> text by the vcs\n" 21624 " parameter,\n" 21625 "==== text by the vcs\n" 21626 " parameter,\n" 21627 "==== text by the vcs\n" 21628 " parameter,\n" 21629 "<<<< text by the vcs\n" 21630 " parameter);\n")); 21631 21632 EXPECT_EQ("<<<<<<<\n" 21633 "|||||||\n" 21634 "=======\n" 21635 ">>>>>>>", 21636 format("<<<<<<<\n" 21637 "|||||||\n" 21638 "=======\n" 21639 ">>>>>>>")); 21640 21641 EXPECT_EQ("<<<<<<<\n" 21642 "|||||||\n" 21643 "int i;\n" 21644 "=======\n" 21645 ">>>>>>>", 21646 format("<<<<<<<\n" 21647 "|||||||\n" 21648 "int i;\n" 21649 "=======\n" 21650 ">>>>>>>")); 21651 21652 // FIXME: Handle parsing of macros around conflict markers correctly: 21653 EXPECT_EQ("#define Macro \\\n" 21654 "<<<<<<<\n" 21655 "Something \\\n" 21656 "|||||||\n" 21657 "Else \\\n" 21658 "=======\n" 21659 "Other \\\n" 21660 ">>>>>>>\n" 21661 " End int i;\n", 21662 format("#define Macro \\\n" 21663 "<<<<<<<\n" 21664 " Something \\\n" 21665 "|||||||\n" 21666 " Else \\\n" 21667 "=======\n" 21668 " Other \\\n" 21669 ">>>>>>>\n" 21670 " End\n" 21671 "int i;\n")); 21672 21673 verifyFormat(R"(==== 21674 #ifdef A 21675 a 21676 #else 21677 b 21678 #endif 21679 )"); 21680 } 21681 21682 TEST_F(FormatTest, DisableRegions) { 21683 EXPECT_EQ("int i;\n" 21684 "// clang-format off\n" 21685 " int j;\n" 21686 "// clang-format on\n" 21687 "int k;", 21688 format(" int i;\n" 21689 " // clang-format off\n" 21690 " int j;\n" 21691 " // clang-format on\n" 21692 " int k;")); 21693 EXPECT_EQ("int i;\n" 21694 "/* clang-format off */\n" 21695 " int j;\n" 21696 "/* clang-format on */\n" 21697 "int k;", 21698 format(" int i;\n" 21699 " /* clang-format off */\n" 21700 " int j;\n" 21701 " /* clang-format on */\n" 21702 " int k;")); 21703 21704 // Don't reflow comments within disabled regions. 21705 EXPECT_EQ("// clang-format off\n" 21706 "// long long long long long long line\n" 21707 "/* clang-format on */\n" 21708 "/* long long long\n" 21709 " * long long long\n" 21710 " * line */\n" 21711 "int i;\n" 21712 "/* clang-format off */\n" 21713 "/* long long long long long long line */\n", 21714 format("// clang-format off\n" 21715 "// long long long long long long line\n" 21716 "/* clang-format on */\n" 21717 "/* long long long long long long line */\n" 21718 "int i;\n" 21719 "/* clang-format off */\n" 21720 "/* long long long long long long line */\n", 21721 getLLVMStyleWithColumns(20))); 21722 } 21723 21724 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 21725 format("? ) ="); 21726 verifyNoCrash("#define a\\\n /**/}"); 21727 } 21728 21729 TEST_F(FormatTest, FormatsTableGenCode) { 21730 FormatStyle Style = getLLVMStyle(); 21731 Style.Language = FormatStyle::LK_TableGen; 21732 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 21733 } 21734 21735 TEST_F(FormatTest, ArrayOfTemplates) { 21736 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 21737 format("auto a = new unique_ptr<int > [ 10];")); 21738 21739 FormatStyle Spaces = getLLVMStyle(); 21740 Spaces.SpacesInSquareBrackets = true; 21741 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 21742 format("auto a = new unique_ptr<int > [10];", Spaces)); 21743 } 21744 21745 TEST_F(FormatTest, ArrayAsTemplateType) { 21746 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 21747 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 21748 21749 FormatStyle Spaces = getLLVMStyle(); 21750 Spaces.SpacesInSquareBrackets = true; 21751 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 21752 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 21753 } 21754 21755 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 21756 21757 TEST(FormatStyle, GetStyleWithEmptyFileName) { 21758 llvm::vfs::InMemoryFileSystem FS; 21759 auto Style1 = getStyle("file", "", "Google", "", &FS); 21760 ASSERT_TRUE((bool)Style1); 21761 ASSERT_EQ(*Style1, getGoogleStyle()); 21762 } 21763 21764 TEST(FormatStyle, GetStyleOfFile) { 21765 llvm::vfs::InMemoryFileSystem FS; 21766 // Test 1: format file in the same directory. 21767 ASSERT_TRUE( 21768 FS.addFile("/a/.clang-format", 0, 21769 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 21770 ASSERT_TRUE( 21771 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21772 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 21773 ASSERT_TRUE((bool)Style1); 21774 ASSERT_EQ(*Style1, getLLVMStyle()); 21775 21776 // Test 2.1: fallback to default. 21777 ASSERT_TRUE( 21778 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21779 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 21780 ASSERT_TRUE((bool)Style2); 21781 ASSERT_EQ(*Style2, getMozillaStyle()); 21782 21783 // Test 2.2: no format on 'none' fallback style. 21784 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 21785 ASSERT_TRUE((bool)Style2); 21786 ASSERT_EQ(*Style2, getNoStyle()); 21787 21788 // Test 2.3: format if config is found with no based style while fallback is 21789 // 'none'. 21790 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 21791 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 21792 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 21793 ASSERT_TRUE((bool)Style2); 21794 ASSERT_EQ(*Style2, getLLVMStyle()); 21795 21796 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 21797 Style2 = getStyle("{}", "a.h", "none", "", &FS); 21798 ASSERT_TRUE((bool)Style2); 21799 ASSERT_EQ(*Style2, getLLVMStyle()); 21800 21801 // Test 3: format file in parent directory. 21802 ASSERT_TRUE( 21803 FS.addFile("/c/.clang-format", 0, 21804 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 21805 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 21806 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21807 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 21808 ASSERT_TRUE((bool)Style3); 21809 ASSERT_EQ(*Style3, getGoogleStyle()); 21810 21811 // Test 4: error on invalid fallback style 21812 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 21813 ASSERT_FALSE((bool)Style4); 21814 llvm::consumeError(Style4.takeError()); 21815 21816 // Test 5: error on invalid yaml on command line 21817 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 21818 ASSERT_FALSE((bool)Style5); 21819 llvm::consumeError(Style5.takeError()); 21820 21821 // Test 6: error on invalid style 21822 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 21823 ASSERT_FALSE((bool)Style6); 21824 llvm::consumeError(Style6.takeError()); 21825 21826 // Test 7: found config file, error on parsing it 21827 ASSERT_TRUE( 21828 FS.addFile("/d/.clang-format", 0, 21829 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 21830 "InvalidKey: InvalidValue"))); 21831 ASSERT_TRUE( 21832 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21833 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 21834 ASSERT_FALSE((bool)Style7a); 21835 llvm::consumeError(Style7a.takeError()); 21836 21837 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 21838 ASSERT_TRUE((bool)Style7b); 21839 21840 // Test 8: inferred per-language defaults apply. 21841 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 21842 ASSERT_TRUE((bool)StyleTd); 21843 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 21844 21845 // Test 9.1.1: overwriting a file style, when no parent file exists with no 21846 // fallback style. 21847 ASSERT_TRUE(FS.addFile( 21848 "/e/sub/.clang-format", 0, 21849 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 21850 "ColumnLimit: 20"))); 21851 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 21852 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21853 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 21854 ASSERT_TRUE(static_cast<bool>(Style9)); 21855 ASSERT_EQ(*Style9, [] { 21856 auto Style = getNoStyle(); 21857 Style.ColumnLimit = 20; 21858 return Style; 21859 }()); 21860 21861 // Test 9.1.2: propagate more than one level with no parent file. 21862 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 21863 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21864 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 21865 llvm::MemoryBuffer::getMemBuffer( 21866 "BasedOnStyle: InheritParentConfig\n" 21867 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 21868 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 21869 21870 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 21871 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 21872 ASSERT_TRUE(static_cast<bool>(Style9)); 21873 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 21874 auto Style = getNoStyle(); 21875 Style.ColumnLimit = 20; 21876 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 21877 return Style; 21878 }()); 21879 21880 // Test 9.2: with LLVM fallback style 21881 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 21882 ASSERT_TRUE(static_cast<bool>(Style9)); 21883 ASSERT_EQ(*Style9, [] { 21884 auto Style = getLLVMStyle(); 21885 Style.ColumnLimit = 20; 21886 return Style; 21887 }()); 21888 21889 // Test 9.3: with a parent file 21890 ASSERT_TRUE( 21891 FS.addFile("/e/.clang-format", 0, 21892 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 21893 "UseTab: Always"))); 21894 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 21895 ASSERT_TRUE(static_cast<bool>(Style9)); 21896 ASSERT_EQ(*Style9, [] { 21897 auto Style = getGoogleStyle(); 21898 Style.ColumnLimit = 20; 21899 Style.UseTab = FormatStyle::UT_Always; 21900 return Style; 21901 }()); 21902 21903 // Test 9.4: propagate more than one level with a parent file. 21904 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 21905 auto Style = getGoogleStyle(); 21906 Style.ColumnLimit = 20; 21907 Style.UseTab = FormatStyle::UT_Always; 21908 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 21909 return Style; 21910 }(); 21911 21912 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 21913 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 21914 ASSERT_TRUE(static_cast<bool>(Style9)); 21915 ASSERT_EQ(*Style9, SubSubStyle); 21916 21917 // Test 9.5: use InheritParentConfig as style name 21918 Style9 = 21919 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 21920 ASSERT_TRUE(static_cast<bool>(Style9)); 21921 ASSERT_EQ(*Style9, SubSubStyle); 21922 21923 // Test 9.6: use command line style with inheritance 21924 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 21925 "none", "", &FS); 21926 ASSERT_TRUE(static_cast<bool>(Style9)); 21927 ASSERT_EQ(*Style9, SubSubStyle); 21928 21929 // Test 9.7: use command line style with inheritance and own config 21930 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 21931 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 21932 "/e/sub/code.cpp", "none", "", &FS); 21933 ASSERT_TRUE(static_cast<bool>(Style9)); 21934 ASSERT_EQ(*Style9, SubSubStyle); 21935 21936 // Test 9.8: use inheritance from a file without BasedOnStyle 21937 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 21938 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 21939 ASSERT_TRUE( 21940 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 21941 llvm::MemoryBuffer::getMemBuffer( 21942 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 21943 // Make sure we do not use the fallback style 21944 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 21945 ASSERT_TRUE(static_cast<bool>(Style9)); 21946 ASSERT_EQ(*Style9, [] { 21947 auto Style = getLLVMStyle(); 21948 Style.ColumnLimit = 123; 21949 return Style; 21950 }()); 21951 21952 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 21953 ASSERT_TRUE(static_cast<bool>(Style9)); 21954 ASSERT_EQ(*Style9, [] { 21955 auto Style = getLLVMStyle(); 21956 Style.ColumnLimit = 123; 21957 Style.IndentWidth = 7; 21958 return Style; 21959 }()); 21960 21961 // Test 9.9: use inheritance from a specific config file. 21962 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 21963 "none", "", &FS); 21964 ASSERT_TRUE(static_cast<bool>(Style9)); 21965 ASSERT_EQ(*Style9, SubSubStyle); 21966 } 21967 21968 TEST(FormatStyle, GetStyleOfSpecificFile) { 21969 llvm::vfs::InMemoryFileSystem FS; 21970 // Specify absolute path to a format file in a parent directory. 21971 ASSERT_TRUE( 21972 FS.addFile("/e/.clang-format", 0, 21973 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 21974 ASSERT_TRUE( 21975 FS.addFile("/e/explicit.clang-format", 0, 21976 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 21977 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 21978 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21979 auto Style = getStyle("file:/e/explicit.clang-format", 21980 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 21981 ASSERT_TRUE(static_cast<bool>(Style)); 21982 ASSERT_EQ(*Style, getGoogleStyle()); 21983 21984 // Specify relative path to a format file. 21985 ASSERT_TRUE( 21986 FS.addFile("../../e/explicit.clang-format", 0, 21987 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 21988 Style = getStyle("file:../../e/explicit.clang-format", 21989 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 21990 ASSERT_TRUE(static_cast<bool>(Style)); 21991 ASSERT_EQ(*Style, getGoogleStyle()); 21992 21993 // Specify path to a format file that does not exist. 21994 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 21995 "LLVM", "", &FS); 21996 ASSERT_FALSE(static_cast<bool>(Style)); 21997 llvm::consumeError(Style.takeError()); 21998 21999 // Specify path to a file on the filesystem. 22000 SmallString<128> FormatFilePath; 22001 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22002 "FormatFileTest", "tpl", FormatFilePath); 22003 EXPECT_FALSE((bool)ECF); 22004 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22005 EXPECT_FALSE((bool)ECF); 22006 FormatFileTest << "BasedOnStyle: Google\n"; 22007 FormatFileTest.close(); 22008 22009 SmallString<128> TestFilePath; 22010 std::error_code ECT = 22011 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22012 EXPECT_FALSE((bool)ECT); 22013 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22014 CodeFileTest << "int i;\n"; 22015 CodeFileTest.close(); 22016 22017 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22018 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22019 22020 llvm::sys::fs::remove(FormatFilePath.c_str()); 22021 llvm::sys::fs::remove(TestFilePath.c_str()); 22022 ASSERT_TRUE(static_cast<bool>(Style)); 22023 ASSERT_EQ(*Style, getGoogleStyle()); 22024 } 22025 22026 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22027 // Column limit is 20. 22028 std::string Code = "Type *a =\n" 22029 " new Type();\n" 22030 "g(iiiii, 0, jjjjj,\n" 22031 " 0, kkkkk, 0, mm);\n" 22032 "int bad = format ;"; 22033 std::string Expected = "auto a = new Type();\n" 22034 "g(iiiii, nullptr,\n" 22035 " jjjjj, nullptr,\n" 22036 " kkkkk, nullptr,\n" 22037 " mm);\n" 22038 "int bad = format ;"; 22039 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22040 tooling::Replacements Replaces = toReplacements( 22041 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22042 "auto "), 22043 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22044 "nullptr"), 22045 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22046 "nullptr"), 22047 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22048 "nullptr")}); 22049 22050 FormatStyle Style = getLLVMStyle(); 22051 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22052 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22053 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22054 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22055 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22056 EXPECT_TRUE(static_cast<bool>(Result)); 22057 EXPECT_EQ(Expected, *Result); 22058 } 22059 22060 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22061 std::string Code = "#include \"a.h\"\n" 22062 "#include \"c.h\"\n" 22063 "\n" 22064 "int main() {\n" 22065 " return 0;\n" 22066 "}"; 22067 std::string Expected = "#include \"a.h\"\n" 22068 "#include \"b.h\"\n" 22069 "#include \"c.h\"\n" 22070 "\n" 22071 "int main() {\n" 22072 " return 0;\n" 22073 "}"; 22074 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22075 tooling::Replacements Replaces = toReplacements( 22076 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22077 "#include \"b.h\"\n")}); 22078 22079 FormatStyle Style = getLLVMStyle(); 22080 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22081 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22082 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22083 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22084 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22085 EXPECT_TRUE(static_cast<bool>(Result)); 22086 EXPECT_EQ(Expected, *Result); 22087 } 22088 22089 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22090 EXPECT_EQ("using std::cin;\n" 22091 "using std::cout;", 22092 format("using std::cout;\n" 22093 "using std::cin;", 22094 getGoogleStyle())); 22095 } 22096 22097 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22098 FormatStyle Style = getLLVMStyle(); 22099 Style.Standard = FormatStyle::LS_Cpp03; 22100 // cpp03 recognize this string as identifier u8 and literal character 'a' 22101 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22102 } 22103 22104 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22105 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22106 // all modes, including C++11, C++14 and C++17 22107 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22108 } 22109 22110 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22111 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22112 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22113 } 22114 22115 TEST_F(FormatTest, StructuredBindings) { 22116 // Structured bindings is a C++17 feature. 22117 // all modes, including C++11, C++14 and C++17 22118 verifyFormat("auto [a, b] = f();"); 22119 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22120 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22121 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22122 EXPECT_EQ("auto const volatile [a, b] = f();", 22123 format("auto const volatile[a, b] = f();")); 22124 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22125 EXPECT_EQ("auto &[a, b, c] = f();", 22126 format("auto &[ a , b,c ] = f();")); 22127 EXPECT_EQ("auto &&[a, b, c] = f();", 22128 format("auto &&[ a , b,c ] = f();")); 22129 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22130 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22131 format("auto const volatile &&[a, b] = f();")); 22132 EXPECT_EQ("auto const &&[a, b] = f();", 22133 format("auto const && [a, b] = f();")); 22134 EXPECT_EQ("const auto &[a, b] = f();", 22135 format("const auto & [a, b] = f();")); 22136 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22137 format("const auto volatile &&[a, b] = f();")); 22138 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22139 format("volatile const auto &&[a, b] = f();")); 22140 EXPECT_EQ("const auto &&[a, b] = f();", 22141 format("const auto && [a, b] = f();")); 22142 22143 // Make sure we don't mistake structured bindings for lambdas. 22144 FormatStyle PointerMiddle = getLLVMStyle(); 22145 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22146 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22147 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22148 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22149 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22150 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22151 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22152 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22153 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22154 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22155 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22156 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22157 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22158 22159 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22160 format("for (const auto && [a, b] : some_range) {\n}")); 22161 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22162 format("for (const auto & [a, b] : some_range) {\n}")); 22163 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22164 format("for (const auto[a, b] : some_range) {\n}")); 22165 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22166 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22167 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22168 EXPECT_EQ("auto const &[x, y](expr);", 22169 format("auto const & [x,y] (expr);")); 22170 EXPECT_EQ("auto const &&[x, y](expr);", 22171 format("auto const && [x,y] (expr);")); 22172 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22173 EXPECT_EQ("auto const &[x, y]{expr};", 22174 format("auto const & [x,y] {expr};")); 22175 EXPECT_EQ("auto const &&[x, y]{expr};", 22176 format("auto const && [x,y] {expr};")); 22177 22178 FormatStyle Spaces = getLLVMStyle(); 22179 Spaces.SpacesInSquareBrackets = true; 22180 verifyFormat("auto [ a, b ] = f();", Spaces); 22181 verifyFormat("auto &&[ a, b ] = f();", Spaces); 22182 verifyFormat("auto &[ a, b ] = f();", Spaces); 22183 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 22184 verifyFormat("auto const &[ a, b ] = f();", Spaces); 22185 } 22186 22187 TEST_F(FormatTest, FileAndCode) { 22188 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 22189 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 22190 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 22191 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 22192 EXPECT_EQ(FormatStyle::LK_ObjC, 22193 guessLanguage("foo.h", "@interface Foo\n@end\n")); 22194 EXPECT_EQ( 22195 FormatStyle::LK_ObjC, 22196 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 22197 EXPECT_EQ(FormatStyle::LK_ObjC, 22198 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 22199 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 22200 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 22201 EXPECT_EQ(FormatStyle::LK_ObjC, 22202 guessLanguage("foo", "@interface Foo\n@end\n")); 22203 EXPECT_EQ(FormatStyle::LK_ObjC, 22204 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 22205 EXPECT_EQ( 22206 FormatStyle::LK_ObjC, 22207 guessLanguage("foo.h", 22208 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 22209 EXPECT_EQ( 22210 FormatStyle::LK_Cpp, 22211 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 22212 } 22213 22214 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 22215 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 22216 EXPECT_EQ(FormatStyle::LK_ObjC, 22217 guessLanguage("foo.h", "array[[calculator getIndex]];")); 22218 EXPECT_EQ(FormatStyle::LK_Cpp, 22219 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 22220 EXPECT_EQ( 22221 FormatStyle::LK_Cpp, 22222 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 22223 EXPECT_EQ(FormatStyle::LK_ObjC, 22224 guessLanguage("foo.h", "[[noreturn foo] bar];")); 22225 EXPECT_EQ(FormatStyle::LK_Cpp, 22226 guessLanguage("foo.h", "[[clang::fallthrough]];")); 22227 EXPECT_EQ(FormatStyle::LK_ObjC, 22228 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 22229 EXPECT_EQ(FormatStyle::LK_Cpp, 22230 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 22231 EXPECT_EQ(FormatStyle::LK_Cpp, 22232 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 22233 EXPECT_EQ(FormatStyle::LK_ObjC, 22234 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 22235 EXPECT_EQ(FormatStyle::LK_Cpp, 22236 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 22237 EXPECT_EQ( 22238 FormatStyle::LK_Cpp, 22239 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 22240 EXPECT_EQ( 22241 FormatStyle::LK_Cpp, 22242 guessLanguage("foo.h", 22243 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 22244 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 22245 } 22246 22247 TEST_F(FormatTest, GuessLanguageWithCaret) { 22248 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 22249 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 22250 EXPECT_EQ(FormatStyle::LK_ObjC, 22251 guessLanguage("foo.h", "int(^)(char, float);")); 22252 EXPECT_EQ(FormatStyle::LK_ObjC, 22253 guessLanguage("foo.h", "int(^foo)(char, float);")); 22254 EXPECT_EQ(FormatStyle::LK_ObjC, 22255 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 22256 EXPECT_EQ(FormatStyle::LK_ObjC, 22257 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 22258 EXPECT_EQ( 22259 FormatStyle::LK_ObjC, 22260 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 22261 } 22262 22263 TEST_F(FormatTest, GuessLanguageWithPragmas) { 22264 EXPECT_EQ(FormatStyle::LK_Cpp, 22265 guessLanguage("foo.h", "__pragma(warning(disable:))")); 22266 EXPECT_EQ(FormatStyle::LK_Cpp, 22267 guessLanguage("foo.h", "#pragma(warning(disable:))")); 22268 EXPECT_EQ(FormatStyle::LK_Cpp, 22269 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 22270 } 22271 22272 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 22273 // ASM symbolic names are identifiers that must be surrounded by [] without 22274 // space in between: 22275 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 22276 22277 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 22278 verifyFormat(R"(// 22279 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 22280 )"); 22281 22282 // A list of several ASM symbolic names. 22283 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 22284 22285 // ASM symbolic names in inline ASM with inputs and outputs. 22286 verifyFormat(R"(// 22287 asm("cmoveq %1, %2, %[result]" 22288 : [result] "=r"(result) 22289 : "r"(test), "r"(new), "[result]"(old)); 22290 )"); 22291 22292 // ASM symbolic names in inline ASM with no outputs. 22293 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 22294 } 22295 22296 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 22297 EXPECT_EQ(FormatStyle::LK_Cpp, 22298 guessLanguage("foo.h", "void f() {\n" 22299 " asm (\"mov %[e], %[d]\"\n" 22300 " : [d] \"=rm\" (d)\n" 22301 " [e] \"rm\" (*e));\n" 22302 "}")); 22303 EXPECT_EQ(FormatStyle::LK_Cpp, 22304 guessLanguage("foo.h", "void f() {\n" 22305 " _asm (\"mov %[e], %[d]\"\n" 22306 " : [d] \"=rm\" (d)\n" 22307 " [e] \"rm\" (*e));\n" 22308 "}")); 22309 EXPECT_EQ(FormatStyle::LK_Cpp, 22310 guessLanguage("foo.h", "void f() {\n" 22311 " __asm (\"mov %[e], %[d]\"\n" 22312 " : [d] \"=rm\" (d)\n" 22313 " [e] \"rm\" (*e));\n" 22314 "}")); 22315 EXPECT_EQ(FormatStyle::LK_Cpp, 22316 guessLanguage("foo.h", "void f() {\n" 22317 " __asm__ (\"mov %[e], %[d]\"\n" 22318 " : [d] \"=rm\" (d)\n" 22319 " [e] \"rm\" (*e));\n" 22320 "}")); 22321 EXPECT_EQ(FormatStyle::LK_Cpp, 22322 guessLanguage("foo.h", "void f() {\n" 22323 " asm (\"mov %[e], %[d]\"\n" 22324 " : [d] \"=rm\" (d),\n" 22325 " [e] \"rm\" (*e));\n" 22326 "}")); 22327 EXPECT_EQ(FormatStyle::LK_Cpp, 22328 guessLanguage("foo.h", "void f() {\n" 22329 " asm volatile (\"mov %[e], %[d]\"\n" 22330 " : [d] \"=rm\" (d)\n" 22331 " [e] \"rm\" (*e));\n" 22332 "}")); 22333 } 22334 22335 TEST_F(FormatTest, GuessLanguageWithChildLines) { 22336 EXPECT_EQ(FormatStyle::LK_Cpp, 22337 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 22338 EXPECT_EQ(FormatStyle::LK_ObjC, 22339 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 22340 EXPECT_EQ( 22341 FormatStyle::LK_Cpp, 22342 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 22343 EXPECT_EQ( 22344 FormatStyle::LK_ObjC, 22345 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 22346 } 22347 22348 TEST_F(FormatTest, TypenameMacros) { 22349 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 22350 22351 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 22352 FormatStyle Google = getGoogleStyleWithColumns(0); 22353 Google.TypenameMacros = TypenameMacros; 22354 verifyFormat("struct foo {\n" 22355 " int bar;\n" 22356 " TAILQ_ENTRY(a) bleh;\n" 22357 "};", 22358 Google); 22359 22360 FormatStyle Macros = getLLVMStyle(); 22361 Macros.TypenameMacros = TypenameMacros; 22362 22363 verifyFormat("STACK_OF(int) a;", Macros); 22364 verifyFormat("STACK_OF(int) *a;", Macros); 22365 verifyFormat("STACK_OF(int const *) *a;", Macros); 22366 verifyFormat("STACK_OF(int *const) *a;", Macros); 22367 verifyFormat("STACK_OF(int, string) a;", Macros); 22368 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 22369 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 22370 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 22371 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 22372 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 22373 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 22374 22375 Macros.PointerAlignment = FormatStyle::PAS_Left; 22376 verifyFormat("STACK_OF(int)* a;", Macros); 22377 verifyFormat("STACK_OF(int*)* a;", Macros); 22378 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 22379 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 22380 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 22381 } 22382 22383 TEST_F(FormatTest, AtomicQualifier) { 22384 // Check that we treate _Atomic as a type and not a function call 22385 FormatStyle Google = getGoogleStyleWithColumns(0); 22386 verifyFormat("struct foo {\n" 22387 " int a1;\n" 22388 " _Atomic(a) a2;\n" 22389 " _Atomic(_Atomic(int) *const) a3;\n" 22390 "};", 22391 Google); 22392 verifyFormat("_Atomic(uint64_t) a;"); 22393 verifyFormat("_Atomic(uint64_t) *a;"); 22394 verifyFormat("_Atomic(uint64_t const *) *a;"); 22395 verifyFormat("_Atomic(uint64_t *const) *a;"); 22396 verifyFormat("_Atomic(const uint64_t *) *a;"); 22397 verifyFormat("_Atomic(uint64_t) a;"); 22398 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 22399 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 22400 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 22401 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 22402 22403 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 22404 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 22405 FormatStyle Style = getLLVMStyle(); 22406 Style.PointerAlignment = FormatStyle::PAS_Left; 22407 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 22408 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 22409 verifyFormat("_Atomic(int)* a;", Style); 22410 verifyFormat("_Atomic(int*)* a;", Style); 22411 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 22412 22413 Style.SpacesInCStyleCastParentheses = true; 22414 Style.SpacesInParentheses = false; 22415 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 22416 Style.SpacesInCStyleCastParentheses = false; 22417 Style.SpacesInParentheses = true; 22418 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 22419 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 22420 } 22421 22422 TEST_F(FormatTest, AmbersandInLamda) { 22423 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 22424 FormatStyle AlignStyle = getLLVMStyle(); 22425 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 22426 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22427 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 22428 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22429 } 22430 22431 TEST_F(FormatTest, SpacesInConditionalStatement) { 22432 FormatStyle Spaces = getLLVMStyle(); 22433 Spaces.IfMacros.clear(); 22434 Spaces.IfMacros.push_back("MYIF"); 22435 Spaces.SpacesInConditionalStatement = true; 22436 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 22437 verifyFormat("if ( !a )\n return;", Spaces); 22438 verifyFormat("if ( a )\n return;", Spaces); 22439 verifyFormat("if constexpr ( a )\n return;", Spaces); 22440 verifyFormat("MYIF ( a )\n return;", Spaces); 22441 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 22442 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 22443 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 22444 verifyFormat("while ( a )\n return;", Spaces); 22445 verifyFormat("while ( (a && b) )\n return;", Spaces); 22446 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 22447 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 22448 // Check that space on the left of "::" is inserted as expected at beginning 22449 // of condition. 22450 verifyFormat("while ( ::func() )\n return;", Spaces); 22451 22452 // Check impact of ControlStatementsExceptControlMacros is honored. 22453 Spaces.SpaceBeforeParens = 22454 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 22455 verifyFormat("MYIF( a )\n return;", Spaces); 22456 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 22457 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 22458 } 22459 22460 TEST_F(FormatTest, AlternativeOperators) { 22461 // Test case for ensuring alternate operators are not 22462 // combined with their right most neighbour. 22463 verifyFormat("int a and b;"); 22464 verifyFormat("int a and_eq b;"); 22465 verifyFormat("int a bitand b;"); 22466 verifyFormat("int a bitor b;"); 22467 verifyFormat("int a compl b;"); 22468 verifyFormat("int a not b;"); 22469 verifyFormat("int a not_eq b;"); 22470 verifyFormat("int a or b;"); 22471 verifyFormat("int a xor b;"); 22472 verifyFormat("int a xor_eq b;"); 22473 verifyFormat("return this not_eq bitand other;"); 22474 verifyFormat("bool operator not_eq(const X bitand other)"); 22475 22476 verifyFormat("int a and 5;"); 22477 verifyFormat("int a and_eq 5;"); 22478 verifyFormat("int a bitand 5;"); 22479 verifyFormat("int a bitor 5;"); 22480 verifyFormat("int a compl 5;"); 22481 verifyFormat("int a not 5;"); 22482 verifyFormat("int a not_eq 5;"); 22483 verifyFormat("int a or 5;"); 22484 verifyFormat("int a xor 5;"); 22485 verifyFormat("int a xor_eq 5;"); 22486 22487 verifyFormat("int a compl(5);"); 22488 verifyFormat("int a not(5);"); 22489 22490 /* FIXME handle alternate tokens 22491 * https://en.cppreference.com/w/cpp/language/operator_alternative 22492 // alternative tokens 22493 verifyFormat("compl foo();"); // ~foo(); 22494 verifyFormat("foo() <%%>;"); // foo(); 22495 verifyFormat("void foo() <%%>;"); // void foo(){} 22496 verifyFormat("int a <:1:>;"); // int a[1];[ 22497 verifyFormat("%:define ABC abc"); // #define ABC abc 22498 verifyFormat("%:%:"); // ## 22499 */ 22500 } 22501 22502 TEST_F(FormatTest, STLWhileNotDefineChed) { 22503 verifyFormat("#if defined(while)\n" 22504 "#define while EMIT WARNING C4005\n" 22505 "#endif // while"); 22506 } 22507 22508 TEST_F(FormatTest, OperatorSpacing) { 22509 FormatStyle Style = getLLVMStyle(); 22510 Style.PointerAlignment = FormatStyle::PAS_Right; 22511 verifyFormat("Foo::operator*();", Style); 22512 verifyFormat("Foo::operator void *();", Style); 22513 verifyFormat("Foo::operator void **();", Style); 22514 verifyFormat("Foo::operator void *&();", Style); 22515 verifyFormat("Foo::operator void *&&();", Style); 22516 verifyFormat("Foo::operator void const *();", Style); 22517 verifyFormat("Foo::operator void const **();", Style); 22518 verifyFormat("Foo::operator void const *&();", Style); 22519 verifyFormat("Foo::operator void const *&&();", Style); 22520 verifyFormat("Foo::operator()(void *);", Style); 22521 verifyFormat("Foo::operator*(void *);", Style); 22522 verifyFormat("Foo::operator*();", Style); 22523 verifyFormat("Foo::operator**();", Style); 22524 verifyFormat("Foo::operator&();", Style); 22525 verifyFormat("Foo::operator<int> *();", Style); 22526 verifyFormat("Foo::operator<Foo> *();", Style); 22527 verifyFormat("Foo::operator<int> **();", Style); 22528 verifyFormat("Foo::operator<Foo> **();", Style); 22529 verifyFormat("Foo::operator<int> &();", Style); 22530 verifyFormat("Foo::operator<Foo> &();", Style); 22531 verifyFormat("Foo::operator<int> &&();", Style); 22532 verifyFormat("Foo::operator<Foo> &&();", Style); 22533 verifyFormat("Foo::operator<int> *&();", Style); 22534 verifyFormat("Foo::operator<Foo> *&();", Style); 22535 verifyFormat("Foo::operator<int> *&&();", Style); 22536 verifyFormat("Foo::operator<Foo> *&&();", Style); 22537 verifyFormat("operator*(int (*)(), class Foo);", Style); 22538 22539 verifyFormat("Foo::operator&();", Style); 22540 verifyFormat("Foo::operator void &();", Style); 22541 verifyFormat("Foo::operator void const &();", Style); 22542 verifyFormat("Foo::operator()(void &);", Style); 22543 verifyFormat("Foo::operator&(void &);", Style); 22544 verifyFormat("Foo::operator&();", Style); 22545 verifyFormat("operator&(int (&)(), class Foo);", Style); 22546 verifyFormat("operator&&(int (&)(), class Foo);", Style); 22547 22548 verifyFormat("Foo::operator&&();", Style); 22549 verifyFormat("Foo::operator**();", Style); 22550 verifyFormat("Foo::operator void &&();", Style); 22551 verifyFormat("Foo::operator void const &&();", Style); 22552 verifyFormat("Foo::operator()(void &&);", Style); 22553 verifyFormat("Foo::operator&&(void &&);", Style); 22554 verifyFormat("Foo::operator&&();", Style); 22555 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22556 verifyFormat("operator const nsTArrayRight<E> &()", Style); 22557 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 22558 Style); 22559 verifyFormat("operator void **()", Style); 22560 verifyFormat("operator const FooRight<Object> &()", Style); 22561 verifyFormat("operator const FooRight<Object> *()", Style); 22562 verifyFormat("operator const FooRight<Object> **()", Style); 22563 verifyFormat("operator const FooRight<Object> *&()", Style); 22564 verifyFormat("operator const FooRight<Object> *&&()", Style); 22565 22566 Style.PointerAlignment = FormatStyle::PAS_Left; 22567 verifyFormat("Foo::operator*();", Style); 22568 verifyFormat("Foo::operator**();", Style); 22569 verifyFormat("Foo::operator void*();", Style); 22570 verifyFormat("Foo::operator void**();", Style); 22571 verifyFormat("Foo::operator void*&();", Style); 22572 verifyFormat("Foo::operator void*&&();", Style); 22573 verifyFormat("Foo::operator void const*();", Style); 22574 verifyFormat("Foo::operator void const**();", Style); 22575 verifyFormat("Foo::operator void const*&();", Style); 22576 verifyFormat("Foo::operator void const*&&();", Style); 22577 verifyFormat("Foo::operator/*comment*/ void*();", Style); 22578 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 22579 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 22580 verifyFormat("Foo::operator()(void*);", Style); 22581 verifyFormat("Foo::operator*(void*);", Style); 22582 verifyFormat("Foo::operator*();", Style); 22583 verifyFormat("Foo::operator<int>*();", Style); 22584 verifyFormat("Foo::operator<Foo>*();", Style); 22585 verifyFormat("Foo::operator<int>**();", Style); 22586 verifyFormat("Foo::operator<Foo>**();", Style); 22587 verifyFormat("Foo::operator<Foo>*&();", Style); 22588 verifyFormat("Foo::operator<int>&();", Style); 22589 verifyFormat("Foo::operator<Foo>&();", Style); 22590 verifyFormat("Foo::operator<int>&&();", Style); 22591 verifyFormat("Foo::operator<Foo>&&();", Style); 22592 verifyFormat("Foo::operator<int>*&();", Style); 22593 verifyFormat("Foo::operator<Foo>*&();", Style); 22594 verifyFormat("operator*(int (*)(), class Foo);", Style); 22595 22596 verifyFormat("Foo::operator&();", Style); 22597 verifyFormat("Foo::operator void&();", Style); 22598 verifyFormat("Foo::operator void const&();", Style); 22599 verifyFormat("Foo::operator/*comment*/ void&();", Style); 22600 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 22601 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 22602 verifyFormat("Foo::operator()(void&);", Style); 22603 verifyFormat("Foo::operator&(void&);", Style); 22604 verifyFormat("Foo::operator&();", Style); 22605 verifyFormat("operator&(int (&)(), class Foo);", Style); 22606 verifyFormat("operator&(int (&&)(), class Foo);", Style); 22607 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22608 22609 verifyFormat("Foo::operator&&();", Style); 22610 verifyFormat("Foo::operator void&&();", Style); 22611 verifyFormat("Foo::operator void const&&();", Style); 22612 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 22613 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 22614 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 22615 verifyFormat("Foo::operator()(void&&);", Style); 22616 verifyFormat("Foo::operator&&(void&&);", Style); 22617 verifyFormat("Foo::operator&&();", Style); 22618 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22619 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 22620 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 22621 Style); 22622 verifyFormat("operator void**()", Style); 22623 verifyFormat("operator const FooLeft<Object>&()", Style); 22624 verifyFormat("operator const FooLeft<Object>*()", Style); 22625 verifyFormat("operator const FooLeft<Object>**()", Style); 22626 verifyFormat("operator const FooLeft<Object>*&()", Style); 22627 verifyFormat("operator const FooLeft<Object>*&&()", Style); 22628 22629 // PR45107 22630 verifyFormat("operator Vector<String>&();", Style); 22631 verifyFormat("operator const Vector<String>&();", Style); 22632 verifyFormat("operator foo::Bar*();", Style); 22633 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 22634 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 22635 Style); 22636 22637 Style.PointerAlignment = FormatStyle::PAS_Middle; 22638 verifyFormat("Foo::operator*();", Style); 22639 verifyFormat("Foo::operator void *();", Style); 22640 verifyFormat("Foo::operator()(void *);", Style); 22641 verifyFormat("Foo::operator*(void *);", Style); 22642 verifyFormat("Foo::operator*();", Style); 22643 verifyFormat("operator*(int (*)(), class Foo);", Style); 22644 22645 verifyFormat("Foo::operator&();", Style); 22646 verifyFormat("Foo::operator void &();", Style); 22647 verifyFormat("Foo::operator void const &();", Style); 22648 verifyFormat("Foo::operator()(void &);", Style); 22649 verifyFormat("Foo::operator&(void &);", Style); 22650 verifyFormat("Foo::operator&();", Style); 22651 verifyFormat("operator&(int (&)(), class Foo);", Style); 22652 22653 verifyFormat("Foo::operator&&();", Style); 22654 verifyFormat("Foo::operator void &&();", Style); 22655 verifyFormat("Foo::operator void const &&();", Style); 22656 verifyFormat("Foo::operator()(void &&);", Style); 22657 verifyFormat("Foo::operator&&(void &&);", Style); 22658 verifyFormat("Foo::operator&&();", Style); 22659 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22660 } 22661 22662 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 22663 FormatStyle Style = getLLVMStyle(); 22664 // PR46157 22665 verifyFormat("foo(operator+, -42);", Style); 22666 verifyFormat("foo(operator++, -42);", Style); 22667 verifyFormat("foo(operator--, -42);", Style); 22668 verifyFormat("foo(-42, operator--);", Style); 22669 verifyFormat("foo(-42, operator, );", Style); 22670 verifyFormat("foo(operator, , -42);", Style); 22671 } 22672 22673 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 22674 FormatStyle Style = getLLVMStyle(); 22675 Style.WhitespaceSensitiveMacros.push_back("FOO"); 22676 22677 // Don't use the helpers here, since 'mess up' will change the whitespace 22678 // and these are all whitespace sensitive by definition 22679 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 22680 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 22681 EXPECT_EQ( 22682 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 22683 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 22684 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 22685 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 22686 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 22687 " Still=Intentional);", 22688 format("FOO(String-ized&Messy+But,: :\n" 22689 " Still=Intentional);", 22690 Style)); 22691 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 22692 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 22693 " Still=Intentional);", 22694 format("FOO(String-ized=&Messy+But,: :\n" 22695 " Still=Intentional);", 22696 Style)); 22697 22698 Style.ColumnLimit = 21; 22699 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 22700 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 22701 } 22702 22703 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 22704 // These tests are not in NamespaceFixer because that doesn't 22705 // test its interaction with line wrapping 22706 FormatStyle Style = getLLVMStyleWithColumns(80); 22707 verifyFormat("namespace {\n" 22708 "int i;\n" 22709 "int j;\n" 22710 "} // namespace", 22711 Style); 22712 22713 verifyFormat("namespace AAA {\n" 22714 "int i;\n" 22715 "int j;\n" 22716 "} // namespace AAA", 22717 Style); 22718 22719 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 22720 "int i;\n" 22721 "int j;\n" 22722 "} // namespace Averyveryveryverylongnamespace", 22723 format("namespace Averyveryveryverylongnamespace {\n" 22724 "int i;\n" 22725 "int j;\n" 22726 "}", 22727 Style)); 22728 22729 EXPECT_EQ( 22730 "namespace " 22731 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22732 " went::mad::now {\n" 22733 "int i;\n" 22734 "int j;\n" 22735 "} // namespace\n" 22736 " // " 22737 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22738 "went::mad::now", 22739 format("namespace " 22740 "would::it::save::you::a::lot::of::time::if_::i::" 22741 "just::gave::up::and_::went::mad::now {\n" 22742 "int i;\n" 22743 "int j;\n" 22744 "}", 22745 Style)); 22746 22747 // This used to duplicate the comment again and again on subsequent runs 22748 EXPECT_EQ( 22749 "namespace " 22750 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22751 " went::mad::now {\n" 22752 "int i;\n" 22753 "int j;\n" 22754 "} // namespace\n" 22755 " // " 22756 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22757 "went::mad::now", 22758 format("namespace " 22759 "would::it::save::you::a::lot::of::time::if_::i::" 22760 "just::gave::up::and_::went::mad::now {\n" 22761 "int i;\n" 22762 "int j;\n" 22763 "} // namespace\n" 22764 " // " 22765 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 22766 "and_::went::mad::now", 22767 Style)); 22768 } 22769 22770 TEST_F(FormatTest, LikelyUnlikely) { 22771 FormatStyle Style = getLLVMStyle(); 22772 22773 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22774 " return 29;\n" 22775 "}", 22776 Style); 22777 22778 verifyFormat("if (argc > 5) [[likely]] {\n" 22779 " return 29;\n" 22780 "}", 22781 Style); 22782 22783 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22784 " return 29;\n" 22785 "} else [[likely]] {\n" 22786 " return 42;\n" 22787 "}\n", 22788 Style); 22789 22790 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22791 " return 29;\n" 22792 "} else if (argc > 10) [[likely]] {\n" 22793 " return 99;\n" 22794 "} else {\n" 22795 " return 42;\n" 22796 "}\n", 22797 Style); 22798 22799 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 22800 " return 29;\n" 22801 "}", 22802 Style); 22803 22804 verifyFormat("if (argc > 5) [[unlikely]]\n" 22805 " return 29;\n", 22806 Style); 22807 verifyFormat("if (argc > 5) [[likely]]\n" 22808 " return 29;\n", 22809 Style); 22810 22811 Style.AttributeMacros.push_back("UNLIKELY"); 22812 Style.AttributeMacros.push_back("LIKELY"); 22813 verifyFormat("if (argc > 5) UNLIKELY\n" 22814 " return 29;\n", 22815 Style); 22816 22817 verifyFormat("if (argc > 5) UNLIKELY {\n" 22818 " return 29;\n" 22819 "}", 22820 Style); 22821 verifyFormat("if (argc > 5) UNLIKELY {\n" 22822 " return 29;\n" 22823 "} else [[likely]] {\n" 22824 " return 42;\n" 22825 "}\n", 22826 Style); 22827 verifyFormat("if (argc > 5) UNLIKELY {\n" 22828 " return 29;\n" 22829 "} else LIKELY {\n" 22830 " return 42;\n" 22831 "}\n", 22832 Style); 22833 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22834 " return 29;\n" 22835 "} else LIKELY {\n" 22836 " return 42;\n" 22837 "}\n", 22838 Style); 22839 } 22840 22841 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 22842 verifyFormat("Constructor()\n" 22843 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 22844 " aaaa(aaaaaaaaaaaaaaaaaa, " 22845 "aaaaaaaaaaaaaaaaaat))"); 22846 verifyFormat("Constructor()\n" 22847 " : aaaaaaaaaaaaa(aaaaaa), " 22848 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 22849 22850 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 22851 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 22852 verifyFormat("Constructor()\n" 22853 " : aaaaaa(aaaaaa),\n" 22854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 22855 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 22856 StyleWithWhitespacePenalty); 22857 verifyFormat("Constructor()\n" 22858 " : aaaaaaaaaaaaa(aaaaaa), " 22859 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 22860 StyleWithWhitespacePenalty); 22861 } 22862 22863 TEST_F(FormatTest, LLVMDefaultStyle) { 22864 FormatStyle Style = getLLVMStyle(); 22865 verifyFormat("extern \"C\" {\n" 22866 "int foo();\n" 22867 "}", 22868 Style); 22869 } 22870 TEST_F(FormatTest, GNUDefaultStyle) { 22871 FormatStyle Style = getGNUStyle(); 22872 verifyFormat("extern \"C\"\n" 22873 "{\n" 22874 " int foo ();\n" 22875 "}", 22876 Style); 22877 } 22878 TEST_F(FormatTest, MozillaDefaultStyle) { 22879 FormatStyle Style = getMozillaStyle(); 22880 verifyFormat("extern \"C\"\n" 22881 "{\n" 22882 " int foo();\n" 22883 "}", 22884 Style); 22885 } 22886 TEST_F(FormatTest, GoogleDefaultStyle) { 22887 FormatStyle Style = getGoogleStyle(); 22888 verifyFormat("extern \"C\" {\n" 22889 "int foo();\n" 22890 "}", 22891 Style); 22892 } 22893 TEST_F(FormatTest, ChromiumDefaultStyle) { 22894 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 22895 verifyFormat("extern \"C\" {\n" 22896 "int foo();\n" 22897 "}", 22898 Style); 22899 } 22900 TEST_F(FormatTest, MicrosoftDefaultStyle) { 22901 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 22902 verifyFormat("extern \"C\"\n" 22903 "{\n" 22904 " int foo();\n" 22905 "}", 22906 Style); 22907 } 22908 TEST_F(FormatTest, WebKitDefaultStyle) { 22909 FormatStyle Style = getWebKitStyle(); 22910 verifyFormat("extern \"C\" {\n" 22911 "int foo();\n" 22912 "}", 22913 Style); 22914 } 22915 22916 TEST_F(FormatTest, ConceptsAndRequires) { 22917 FormatStyle Style = getLLVMStyle(); 22918 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 22919 22920 verifyFormat("template <typename T>\n" 22921 "concept Hashable = requires(T a) {\n" 22922 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 22923 "};", 22924 Style); 22925 verifyFormat("template <typename T>\n" 22926 "concept EqualityComparable = requires(T a, T b) {\n" 22927 " { a == b } -> bool;\n" 22928 "};", 22929 Style); 22930 verifyFormat("template <typename T>\n" 22931 "concept EqualityComparable = requires(T a, T b) {\n" 22932 " { a == b } -> bool;\n" 22933 " { a != b } -> bool;\n" 22934 "};", 22935 Style); 22936 verifyFormat("template <typename T>\n" 22937 "concept EqualityComparable = requires(T a, T b) {\n" 22938 " { a == b } -> bool;\n" 22939 " { a != b } -> bool;\n" 22940 "};", 22941 Style); 22942 22943 verifyFormat("template <typename It>\n" 22944 "requires Iterator<It>\n" 22945 "void sort(It begin, It end) {\n" 22946 " //....\n" 22947 "}", 22948 Style); 22949 22950 verifyFormat("template <typename T>\n" 22951 "concept Large = sizeof(T) > 10;", 22952 Style); 22953 22954 verifyFormat("template <typename T, typename U>\n" 22955 "concept FooableWith = requires(T t, U u) {\n" 22956 " typename T::foo_type;\n" 22957 " { t.foo(u) } -> typename T::foo_type;\n" 22958 " t++;\n" 22959 "};\n" 22960 "void doFoo(FooableWith<int> auto t) {\n" 22961 " t.foo(3);\n" 22962 "}", 22963 Style); 22964 verifyFormat("template <typename T>\n" 22965 "concept Context = sizeof(T) == 1;", 22966 Style); 22967 verifyFormat("template <typename T>\n" 22968 "concept Context = is_specialization_of_v<context, T>;", 22969 Style); 22970 verifyFormat("template <typename T>\n" 22971 "concept Node = std::is_object_v<T>;", 22972 Style); 22973 verifyFormat("template <typename T>\n" 22974 "concept Tree = true;", 22975 Style); 22976 22977 verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n" 22978 " //...\n" 22979 "}", 22980 Style); 22981 22982 verifyFormat( 22983 "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n" 22984 " //...\n" 22985 "}", 22986 Style); 22987 22988 verifyFormat( 22989 "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n" 22990 " //...\n" 22991 "}", 22992 Style); 22993 22994 verifyFormat("template <typename T>\n" 22995 "veryveryvery_long_return_type g(T i) requires Concept1<I> || " 22996 "Concept2<I> {\n" 22997 " //...\n" 22998 "}", 22999 Style); 23000 23001 verifyFormat("template <typename T>\n" 23002 "veryveryvery_long_return_type g(T i) requires Concept1<I> && " 23003 "Concept2<I> {\n" 23004 " //...\n" 23005 "}", 23006 Style); 23007 23008 verifyFormat( 23009 "template <typename T>\n" 23010 "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n" 23011 " //...\n" 23012 "}", 23013 Style); 23014 23015 verifyFormat( 23016 "template <typename T>\n" 23017 "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n" 23018 " //...\n" 23019 "}", 23020 Style); 23021 23022 verifyFormat("template <typename It>\n" 23023 "requires Foo<It>() && Bar<It> {\n" 23024 " //....\n" 23025 "}", 23026 Style); 23027 23028 verifyFormat("template <typename It>\n" 23029 "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n" 23030 " //....\n" 23031 "}", 23032 Style); 23033 23034 verifyFormat("template <typename It>\n" 23035 "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n" 23036 " //....\n" 23037 "}", 23038 Style); 23039 23040 verifyFormat( 23041 "template <typename It>\n" 23042 "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n" 23043 " //....\n" 23044 "}", 23045 Style); 23046 23047 Style.IndentRequires = true; 23048 verifyFormat("template <typename It>\n" 23049 " requires Iterator<It>\n" 23050 "void sort(It begin, It end) {\n" 23051 " //....\n" 23052 "}", 23053 Style); 23054 verifyFormat("template <std::size index_>\n" 23055 " requires(index_ < sizeof...(Children_))\n" 23056 "Tree auto &child() {\n" 23057 " // ...\n" 23058 "}", 23059 Style); 23060 23061 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 23062 verifyFormat("template <typename T>\n" 23063 "concept Hashable = requires (T a) {\n" 23064 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 23065 "};", 23066 Style); 23067 23068 verifyFormat("template <class T = void>\n" 23069 " requires EqualityComparable<T> || Same<T, void>\n" 23070 "struct equal_to;", 23071 Style); 23072 23073 verifyFormat("template <class T>\n" 23074 " requires requires {\n" 23075 " T{};\n" 23076 " T (int);\n" 23077 " }\n", 23078 Style); 23079 23080 Style.ColumnLimit = 78; 23081 verifyFormat("template <typename T>\n" 23082 "concept Context = Traits<typename T::traits_type> and\n" 23083 " Interface<typename T::interface_type> and\n" 23084 " Request<typename T::request_type> and\n" 23085 " Response<typename T::response_type> and\n" 23086 " ContextExtension<typename T::extension_type> and\n" 23087 " ::std::is_copy_constructable<T> and " 23088 "::std::is_move_constructable<T> and\n" 23089 " requires (T c) {\n" 23090 " { c.response; } -> Response;\n" 23091 "} and requires (T c) {\n" 23092 " { c.request; } -> Request;\n" 23093 "}\n", 23094 Style); 23095 23096 verifyFormat("template <typename T>\n" 23097 "concept Context = Traits<typename T::traits_type> or\n" 23098 " Interface<typename T::interface_type> or\n" 23099 " Request<typename T::request_type> or\n" 23100 " Response<typename T::response_type> or\n" 23101 " ContextExtension<typename T::extension_type> or\n" 23102 " ::std::is_copy_constructable<T> or " 23103 "::std::is_move_constructable<T> or\n" 23104 " requires (T c) {\n" 23105 " { c.response; } -> Response;\n" 23106 "} or requires (T c) {\n" 23107 " { c.request; } -> Request;\n" 23108 "}\n", 23109 Style); 23110 23111 verifyFormat("template <typename T>\n" 23112 "concept Context = Traits<typename T::traits_type> &&\n" 23113 " Interface<typename T::interface_type> &&\n" 23114 " Request<typename T::request_type> &&\n" 23115 " Response<typename T::response_type> &&\n" 23116 " ContextExtension<typename T::extension_type> &&\n" 23117 " ::std::is_copy_constructable<T> && " 23118 "::std::is_move_constructable<T> &&\n" 23119 " requires (T c) {\n" 23120 " { c.response; } -> Response;\n" 23121 "} && requires (T c) {\n" 23122 " { c.request; } -> Request;\n" 23123 "}\n", 23124 Style); 23125 23126 verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && " 23127 "Constraint2<T>;"); 23128 23129 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 23130 Style.BraceWrapping.AfterFunction = true; 23131 Style.BraceWrapping.AfterClass = true; 23132 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 23133 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 23134 verifyFormat("void Foo () requires (std::copyable<T>)\n" 23135 "{\n" 23136 " return\n" 23137 "}\n", 23138 Style); 23139 23140 verifyFormat("void Foo () requires std::copyable<T>\n" 23141 "{\n" 23142 " return\n" 23143 "}\n", 23144 Style); 23145 23146 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23147 " requires (std::invocable<F, std::invoke_result_t<Args>...>)\n" 23148 "struct constant;", 23149 Style); 23150 23151 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23152 " requires std::invocable<F, std::invoke_result_t<Args>...>\n" 23153 "struct constant;", 23154 Style); 23155 23156 verifyFormat("template <class T>\n" 23157 "class plane_with_very_very_very_long_name\n" 23158 "{\n" 23159 " constexpr plane_with_very_very_very_long_name () requires " 23160 "std::copyable<T>\n" 23161 " : plane_with_very_very_very_long_name (1)\n" 23162 " {\n" 23163 " }\n" 23164 "}\n", 23165 Style); 23166 23167 verifyFormat("template <class T>\n" 23168 "class plane_with_long_name\n" 23169 "{\n" 23170 " constexpr plane_with_long_name () requires std::copyable<T>\n" 23171 " : plane_with_long_name (1)\n" 23172 " {\n" 23173 " }\n" 23174 "}\n", 23175 Style); 23176 23177 Style.BreakBeforeConceptDeclarations = false; 23178 verifyFormat("template <typename T> concept Tree = true;", Style); 23179 23180 Style.IndentRequires = false; 23181 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23182 "requires (std::invocable<F, std::invoke_result_t<Args>...>) " 23183 "struct constant;", 23184 Style); 23185 } 23186 23187 TEST_F(FormatTest, StatementAttributeLikeMacros) { 23188 FormatStyle Style = getLLVMStyle(); 23189 StringRef Source = "void Foo::slot() {\n" 23190 " unsigned char MyChar = 'x';\n" 23191 " emit signal(MyChar);\n" 23192 " Q_EMIT signal(MyChar);\n" 23193 "}"; 23194 23195 EXPECT_EQ(Source, format(Source, Style)); 23196 23197 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 23198 EXPECT_EQ("void Foo::slot() {\n" 23199 " unsigned char MyChar = 'x';\n" 23200 " emit signal(MyChar);\n" 23201 " Q_EMIT signal(MyChar);\n" 23202 "}", 23203 format(Source, Style)); 23204 23205 Style.StatementAttributeLikeMacros.push_back("emit"); 23206 EXPECT_EQ(Source, format(Source, Style)); 23207 23208 Style.StatementAttributeLikeMacros = {}; 23209 EXPECT_EQ("void Foo::slot() {\n" 23210 " unsigned char MyChar = 'x';\n" 23211 " emit signal(MyChar);\n" 23212 " Q_EMIT signal(MyChar);\n" 23213 "}", 23214 format(Source, Style)); 23215 } 23216 23217 TEST_F(FormatTest, IndentAccessModifiers) { 23218 FormatStyle Style = getLLVMStyle(); 23219 Style.IndentAccessModifiers = true; 23220 // Members are *two* levels below the record; 23221 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 23222 verifyFormat("class C {\n" 23223 " int i;\n" 23224 "};\n", 23225 Style); 23226 verifyFormat("union C {\n" 23227 " int i;\n" 23228 " unsigned u;\n" 23229 "};\n", 23230 Style); 23231 // Access modifiers should be indented one level below the record. 23232 verifyFormat("class C {\n" 23233 " public:\n" 23234 " int i;\n" 23235 "};\n", 23236 Style); 23237 verifyFormat("struct S {\n" 23238 " private:\n" 23239 " class C {\n" 23240 " int j;\n" 23241 "\n" 23242 " public:\n" 23243 " C();\n" 23244 " };\n" 23245 "\n" 23246 " public:\n" 23247 " int i;\n" 23248 "};\n", 23249 Style); 23250 // Enumerations are not records and should be unaffected. 23251 Style.AllowShortEnumsOnASingleLine = false; 23252 verifyFormat("enum class E {\n" 23253 " A,\n" 23254 " B\n" 23255 "};\n", 23256 Style); 23257 // Test with a different indentation width; 23258 // also proves that the result is Style.AccessModifierOffset agnostic. 23259 Style.IndentWidth = 3; 23260 verifyFormat("class C {\n" 23261 " public:\n" 23262 " int i;\n" 23263 "};\n", 23264 Style); 23265 } 23266 23267 TEST_F(FormatTest, LimitlessStringsAndComments) { 23268 auto Style = getLLVMStyleWithColumns(0); 23269 constexpr StringRef Code = 23270 "/**\n" 23271 " * This is a multiline comment with quite some long lines, at least for " 23272 "the LLVM Style.\n" 23273 " * We will redo this with strings and line comments. Just to check if " 23274 "everything is working.\n" 23275 " */\n" 23276 "bool foo() {\n" 23277 " /* Single line multi line comment. */\n" 23278 " const std::string String = \"This is a multiline string with quite " 23279 "some long lines, at least for the LLVM Style.\"\n" 23280 " \"We already did it with multi line " 23281 "comments, and we will do it with line comments. Just to check if " 23282 "everything is working.\";\n" 23283 " // This is a line comment (block) with quite some long lines, at " 23284 "least for the LLVM Style.\n" 23285 " // We already did this with multi line comments and strings. Just to " 23286 "check if everything is working.\n" 23287 " const std::string SmallString = \"Hello World\";\n" 23288 " // Small line comment\n" 23289 " return String.size() > SmallString.size();\n" 23290 "}"; 23291 EXPECT_EQ(Code, format(Code, Style)); 23292 } 23293 23294 TEST_F(FormatTest, FormatDecayCopy) { 23295 // error cases from unit tests 23296 verifyFormat("foo(auto())"); 23297 verifyFormat("foo(auto{})"); 23298 verifyFormat("foo(auto({}))"); 23299 verifyFormat("foo(auto{{}})"); 23300 23301 verifyFormat("foo(auto(1))"); 23302 verifyFormat("foo(auto{1})"); 23303 verifyFormat("foo(new auto(1))"); 23304 verifyFormat("foo(new auto{1})"); 23305 verifyFormat("decltype(auto(1)) x;"); 23306 verifyFormat("decltype(auto{1}) x;"); 23307 verifyFormat("auto(x);"); 23308 verifyFormat("auto{x};"); 23309 verifyFormat("new auto{x};"); 23310 verifyFormat("auto{x} = y;"); 23311 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 23312 // the user's own fault 23313 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 23314 // clearly the user's own fault 23315 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 23316 } 23317 23318 TEST_F(FormatTest, Cpp20ModulesSupport) { 23319 FormatStyle Style = getLLVMStyle(); 23320 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 23321 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 23322 23323 verifyFormat("export import foo;", Style); 23324 verifyFormat("export import foo:bar;", Style); 23325 verifyFormat("export import foo.bar;", Style); 23326 verifyFormat("export import foo.bar:baz;", Style); 23327 verifyFormat("export import :bar;", Style); 23328 verifyFormat("export module foo:bar;", Style); 23329 verifyFormat("export module foo;", Style); 23330 verifyFormat("export module foo.bar;", Style); 23331 verifyFormat("export module foo.bar:baz;", Style); 23332 verifyFormat("export import <string_view>;", Style); 23333 23334 verifyFormat("export type_name var;", Style); 23335 verifyFormat("template <class T> export using A = B<T>;", Style); 23336 verifyFormat("export using A = B;", Style); 23337 verifyFormat("export int func() {\n" 23338 " foo();\n" 23339 "}", 23340 Style); 23341 verifyFormat("export struct {\n" 23342 " int foo;\n" 23343 "};", 23344 Style); 23345 verifyFormat("export {\n" 23346 " int foo;\n" 23347 "};", 23348 Style); 23349 verifyFormat("export export char const *hello() { return \"hello\"; }"); 23350 23351 verifyFormat("import bar;", Style); 23352 verifyFormat("import foo.bar;", Style); 23353 verifyFormat("import foo:bar;", Style); 23354 verifyFormat("import :bar;", Style); 23355 verifyFormat("import <ctime>;", Style); 23356 verifyFormat("import \"header\";", Style); 23357 23358 verifyFormat("module foo;", Style); 23359 verifyFormat("module foo:bar;", Style); 23360 verifyFormat("module foo.bar;", Style); 23361 verifyFormat("module;", Style); 23362 23363 verifyFormat("export namespace hi {\n" 23364 "const char *sayhi();\n" 23365 "}", 23366 Style); 23367 23368 verifyFormat("module :private;", Style); 23369 verifyFormat("import <foo/bar.h>;", Style); 23370 verifyFormat("import foo...bar;", Style); 23371 verifyFormat("import ..........;", Style); 23372 verifyFormat("module foo:private;", Style); 23373 verifyFormat("import a", Style); 23374 verifyFormat("module a", Style); 23375 verifyFormat("export import a", Style); 23376 verifyFormat("export module a", Style); 23377 23378 verifyFormat("import", Style); 23379 verifyFormat("module", Style); 23380 verifyFormat("export", Style); 23381 } 23382 23383 TEST_F(FormatTest, CoroutineForCoawait) { 23384 FormatStyle Style = getLLVMStyle(); 23385 verifyFormat("for co_await (auto x : range())\n ;"); 23386 verifyFormat("for (auto i : arr) {\n" 23387 "}", 23388 Style); 23389 verifyFormat("for co_await (auto i : arr) {\n" 23390 "}", 23391 Style); 23392 verifyFormat("for co_await (auto i : foo(T{})) {\n" 23393 "}", 23394 Style); 23395 } 23396 23397 TEST_F(FormatTest, CoroutineCoAwait) { 23398 verifyFormat("int x = co_await foo();"); 23399 verifyFormat("int x = (co_await foo());"); 23400 verifyFormat("co_await (42);"); 23401 verifyFormat("void operator co_await(int);"); 23402 verifyFormat("void operator co_await(a);"); 23403 verifyFormat("co_await a;"); 23404 verifyFormat("co_await missing_await_resume{};"); 23405 verifyFormat("co_await a; // comment"); 23406 verifyFormat("void test0() { co_await a; }"); 23407 verifyFormat("co_await co_await co_await foo();"); 23408 verifyFormat("co_await foo().bar();"); 23409 verifyFormat("co_await [this]() -> Task { co_return x; }"); 23410 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 23411 "foo(); }(x, y);"); 23412 23413 FormatStyle Style = getLLVMStyleWithColumns(40); 23414 verifyFormat("co_await [this](int a, int b) -> Task {\n" 23415 " co_return co_await foo();\n" 23416 "}(x, y);", 23417 Style); 23418 verifyFormat("co_await;"); 23419 } 23420 23421 TEST_F(FormatTest, CoroutineCoYield) { 23422 verifyFormat("int x = co_yield foo();"); 23423 verifyFormat("int x = (co_yield foo());"); 23424 verifyFormat("co_yield (42);"); 23425 verifyFormat("co_yield {42};"); 23426 verifyFormat("co_yield 42;"); 23427 verifyFormat("co_yield n++;"); 23428 verifyFormat("co_yield ++n;"); 23429 verifyFormat("co_yield;"); 23430 } 23431 23432 TEST_F(FormatTest, CoroutineCoReturn) { 23433 verifyFormat("co_return (42);"); 23434 verifyFormat("co_return;"); 23435 verifyFormat("co_return {};"); 23436 verifyFormat("co_return x;"); 23437 verifyFormat("co_return co_await foo();"); 23438 verifyFormat("co_return co_yield foo();"); 23439 } 23440 23441 TEST_F(FormatTest, EmptyShortBlock) { 23442 auto Style = getLLVMStyle(); 23443 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 23444 23445 verifyFormat("try {\n" 23446 " doA();\n" 23447 "} catch (Exception &e) {\n" 23448 " e.printStackTrace();\n" 23449 "}\n", 23450 Style); 23451 23452 verifyFormat("try {\n" 23453 " doA();\n" 23454 "} catch (Exception &e) {}\n", 23455 Style); 23456 } 23457 23458 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 23459 auto Style = getLLVMStyle(); 23460 23461 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 23462 verifyFormat("struct Y<[] { return 0; }> {};", Style); 23463 23464 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 23465 } 23466 23467 TEST_F(FormatTest, RemoveBraces) { 23468 FormatStyle Style = getLLVMStyle(); 23469 Style.RemoveBracesLLVM = true; 23470 23471 // The following eight test cases are fully-braced versions of the examples at 23472 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 23473 // statement-bodies-of-if-else-loop-statements". 23474 23475 // 1. Omit the braces, since the body is simple and clearly associated with 23476 // the if. 23477 verifyFormat("if (isa<FunctionDecl>(D))\n" 23478 " handleFunctionDecl(D);\n" 23479 "else if (isa<VarDecl>(D))\n" 23480 " handleVarDecl(D);", 23481 "if (isa<FunctionDecl>(D)) {\n" 23482 " handleFunctionDecl(D);\n" 23483 "} else if (isa<VarDecl>(D)) {\n" 23484 " handleVarDecl(D);\n" 23485 "}", 23486 Style); 23487 23488 // 2. Here we document the condition itself and not the body. 23489 verifyFormat("if (isa<VarDecl>(D)) {\n" 23490 " // It is necessary that we explain the situation with this\n" 23491 " // surprisingly long comment, so it would be unclear\n" 23492 " // without the braces whether the following statement is in\n" 23493 " // the scope of the `if`.\n" 23494 " // Because the condition is documented, we can't really\n" 23495 " // hoist this comment that applies to the body above the\n" 23496 " // if.\n" 23497 " handleOtherDecl(D);\n" 23498 "}", 23499 Style); 23500 23501 // 3. Use braces on the outer `if` to avoid a potential dangling else 23502 // situation. 23503 verifyFormat("if (isa<VarDecl>(D)) {\n" 23504 " for (auto *A : D.attrs())\n" 23505 " if (shouldProcessAttr(A))\n" 23506 " handleAttr(A);\n" 23507 "}", 23508 "if (isa<VarDecl>(D)) {\n" 23509 " for (auto *A : D.attrs()) {\n" 23510 " if (shouldProcessAttr(A)) {\n" 23511 " handleAttr(A);\n" 23512 " }\n" 23513 " }\n" 23514 "}", 23515 Style); 23516 23517 // 4. Use braces for the `if` block to keep it uniform with the else block. 23518 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23519 " handleFunctionDecl(D);\n" 23520 "} else {\n" 23521 " // In this else case, it is necessary that we explain the\n" 23522 " // situation with this surprisingly long comment, so it\n" 23523 " // would be unclear without the braces whether the\n" 23524 " // following statement is in the scope of the `if`.\n" 23525 " handleOtherDecl(D);\n" 23526 "}", 23527 Style); 23528 23529 // 5. This should also omit braces. The `for` loop contains only a single 23530 // statement, so it shouldn't have braces. The `if` also only contains a 23531 // single simple statement (the for loop), so it also should omit braces. 23532 verifyFormat("if (isa<FunctionDecl>(D))\n" 23533 " for (auto *A : D.attrs())\n" 23534 " handleAttr(A);", 23535 "if (isa<FunctionDecl>(D)) {\n" 23536 " for (auto *A : D.attrs()) {\n" 23537 " handleAttr(A);\n" 23538 " }\n" 23539 "}", 23540 Style); 23541 23542 // 6. Use braces for the outer `if` since the nested `for` is braced. 23543 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23544 " for (auto *A : D.attrs()) {\n" 23545 " // In this for loop body, it is necessary that we explain\n" 23546 " // the situation with this surprisingly long comment,\n" 23547 " // forcing braces on the `for` block.\n" 23548 " handleAttr(A);\n" 23549 " }\n" 23550 "}", 23551 Style); 23552 23553 // 7. Use braces on the outer block because there are more than two levels of 23554 // nesting. 23555 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23556 " for (auto *A : D.attrs())\n" 23557 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 23558 " handleAttrOnDecl(D, A, i);\n" 23559 "}", 23560 "if (isa<FunctionDecl>(D)) {\n" 23561 " for (auto *A : D.attrs()) {\n" 23562 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 23563 " handleAttrOnDecl(D, A, i);\n" 23564 " }\n" 23565 " }\n" 23566 "}", 23567 Style); 23568 23569 // 8. Use braces on the outer block because of a nested `if`, otherwise the 23570 // compiler would warn: `add explicit braces to avoid dangling else` 23571 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 23572 " if (shouldProcess(D))\n" 23573 " handleVarDecl(D);\n" 23574 " else\n" 23575 " markAsIgnored(D);\n" 23576 "}", 23577 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 23578 " if (shouldProcess(D)) {\n" 23579 " handleVarDecl(D);\n" 23580 " } else {\n" 23581 " markAsIgnored(D);\n" 23582 " }\n" 23583 "}", 23584 Style); 23585 23586 verifyFormat("if (a)\n" 23587 " b; // comment\n" 23588 "else if (c)\n" 23589 " d; /* comment */\n" 23590 "else\n" 23591 " e;", 23592 "if (a) {\n" 23593 " b; // comment\n" 23594 "} else if (c) {\n" 23595 " d; /* comment */\n" 23596 "} else {\n" 23597 " e;\n" 23598 "}", 23599 Style); 23600 23601 verifyFormat("if (a) {\n" 23602 " b;\n" 23603 " c;\n" 23604 "} else if (d) {\n" 23605 " e;\n" 23606 "}", 23607 Style); 23608 23609 verifyFormat("if (a) {\n" 23610 "#undef NDEBUG\n" 23611 " b;\n" 23612 "} else {\n" 23613 " c;\n" 23614 "}", 23615 Style); 23616 23617 verifyFormat("if (a) {\n" 23618 " // comment\n" 23619 "} else if (b) {\n" 23620 " c;\n" 23621 "}", 23622 Style); 23623 23624 verifyFormat("if (a) {\n" 23625 " b;\n" 23626 "} else {\n" 23627 " { c; }\n" 23628 "}", 23629 Style); 23630 23631 verifyFormat("if (a) {\n" 23632 " if (b) // comment\n" 23633 " c;\n" 23634 "} else if (d) {\n" 23635 " e;\n" 23636 "}", 23637 "if (a) {\n" 23638 " if (b) { // comment\n" 23639 " c;\n" 23640 " }\n" 23641 "} else if (d) {\n" 23642 " e;\n" 23643 "}", 23644 Style); 23645 23646 verifyFormat("if (a) {\n" 23647 " if (b) {\n" 23648 " c;\n" 23649 " // comment\n" 23650 " } else if (d) {\n" 23651 " e;\n" 23652 " }\n" 23653 "}", 23654 Style); 23655 23656 verifyFormat("if (a) {\n" 23657 " if (b)\n" 23658 " c;\n" 23659 "}", 23660 "if (a) {\n" 23661 " if (b) {\n" 23662 " c;\n" 23663 " }\n" 23664 "}", 23665 Style); 23666 23667 verifyFormat("if (a)\n" 23668 " if (b)\n" 23669 " c;\n" 23670 " else\n" 23671 " d;\n" 23672 "else\n" 23673 " e;", 23674 "if (a) {\n" 23675 " if (b) {\n" 23676 " c;\n" 23677 " } else {\n" 23678 " d;\n" 23679 " }\n" 23680 "} else {\n" 23681 " e;\n" 23682 "}", 23683 Style); 23684 23685 verifyFormat("if (a) {\n" 23686 " // comment\n" 23687 " if (b)\n" 23688 " c;\n" 23689 " else if (d)\n" 23690 " e;\n" 23691 "} else {\n" 23692 " g;\n" 23693 "}", 23694 "if (a) {\n" 23695 " // comment\n" 23696 " if (b) {\n" 23697 " c;\n" 23698 " } else if (d) {\n" 23699 " e;\n" 23700 " }\n" 23701 "} else {\n" 23702 " g;\n" 23703 "}", 23704 Style); 23705 23706 verifyFormat("if (a)\n" 23707 " b;\n" 23708 "else if (c)\n" 23709 " d;\n" 23710 "else\n" 23711 " e;", 23712 "if (a) {\n" 23713 " b;\n" 23714 "} else {\n" 23715 " if (c) {\n" 23716 " d;\n" 23717 " } else {\n" 23718 " e;\n" 23719 " }\n" 23720 "}", 23721 Style); 23722 23723 verifyFormat("if (a) {\n" 23724 " if (b)\n" 23725 " c;\n" 23726 " else if (d)\n" 23727 " e;\n" 23728 "} else {\n" 23729 " g;\n" 23730 "}", 23731 "if (a) {\n" 23732 " if (b)\n" 23733 " c;\n" 23734 " else {\n" 23735 " if (d)\n" 23736 " e;\n" 23737 " }\n" 23738 "} else {\n" 23739 " g;\n" 23740 "}", 23741 Style); 23742 23743 verifyFormat("if (a)\n" 23744 " b;\n" 23745 "else if (c)\n" 23746 " while (d)\n" 23747 " e;\n" 23748 "// comment", 23749 "if (a)\n" 23750 "{\n" 23751 " b;\n" 23752 "} else if (c) {\n" 23753 " while (d) {\n" 23754 " e;\n" 23755 " }\n" 23756 "}\n" 23757 "// comment", 23758 Style); 23759 23760 verifyFormat("if (a) {\n" 23761 " b;\n" 23762 "} else if (c) {\n" 23763 " d;\n" 23764 "} else {\n" 23765 " e;\n" 23766 " g;\n" 23767 "}", 23768 Style); 23769 23770 verifyFormat("if (a) {\n" 23771 " b;\n" 23772 "} else if (c) {\n" 23773 " d;\n" 23774 "} else {\n" 23775 " e;\n" 23776 "} // comment", 23777 Style); 23778 23779 verifyFormat("int abs = [](int i) {\n" 23780 " if (i >= 0)\n" 23781 " return i;\n" 23782 " return -i;\n" 23783 "};", 23784 "int abs = [](int i) {\n" 23785 " if (i >= 0) {\n" 23786 " return i;\n" 23787 " }\n" 23788 " return -i;\n" 23789 "};", 23790 Style); 23791 23792 Style.ColumnLimit = 20; 23793 23794 verifyFormat("if (a) {\n" 23795 " b = c + // 1 -\n" 23796 " d;\n" 23797 "}", 23798 Style); 23799 23800 verifyFormat("if (a) {\n" 23801 " b = c >= 0 ? d\n" 23802 " : e;\n" 23803 "}", 23804 "if (a) {\n" 23805 " b = c >= 0 ? d : e;\n" 23806 "}", 23807 Style); 23808 23809 verifyFormat("if (a)\n" 23810 " b = c > 0 ? d : e;", 23811 "if (a) {\n" 23812 " b = c > 0 ? d : e;\n" 23813 "}", 23814 Style); 23815 23816 Style.ColumnLimit = 0; 23817 23818 verifyFormat("if (a)\n" 23819 " b234567890223456789032345678904234567890 = " 23820 "c234567890223456789032345678904234567890;", 23821 "if (a) {\n" 23822 " b234567890223456789032345678904234567890 = " 23823 "c234567890223456789032345678904234567890;\n" 23824 "}", 23825 Style); 23826 } 23827 23828 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 23829 auto Style = getLLVMStyle(); 23830 23831 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 23832 "void functionDecl(int a, int b, int c);"; 23833 23834 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 23835 "paramF, paramG, paramH, paramI);\n" 23836 "void functionDecl(int argumentA, int argumentB, int " 23837 "argumentC, int argumentD, int argumentE);"; 23838 23839 verifyFormat(Short, Style); 23840 23841 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 23842 "paramF, paramG, paramH,\n" 23843 " paramI);\n" 23844 "void functionDecl(int argumentA, int argumentB, int " 23845 "argumentC, int argumentD,\n" 23846 " int argumentE);"; 23847 23848 verifyFormat(NoBreak, Medium, Style); 23849 verifyFormat(NoBreak, 23850 "functionCall(\n" 23851 " paramA,\n" 23852 " paramB,\n" 23853 " paramC,\n" 23854 " paramD,\n" 23855 " paramE,\n" 23856 " paramF,\n" 23857 " paramG,\n" 23858 " paramH,\n" 23859 " paramI\n" 23860 ");\n" 23861 "void functionDecl(\n" 23862 " int argumentA,\n" 23863 " int argumentB,\n" 23864 " int argumentC,\n" 23865 " int argumentD,\n" 23866 " int argumentE\n" 23867 ");", 23868 Style); 23869 23870 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 23871 " nestedLongFunctionCall(argument1, " 23872 "argument2, argument3,\n" 23873 " argument4, " 23874 "argument5));", 23875 Style); 23876 23877 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 23878 23879 verifyFormat(Short, Style); 23880 verifyFormat( 23881 "functionCall(\n" 23882 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 23883 "paramI\n" 23884 ");\n" 23885 "void functionDecl(\n" 23886 " int argumentA, int argumentB, int argumentC, int argumentD, int " 23887 "argumentE\n" 23888 ");", 23889 Medium, Style); 23890 23891 Style.AllowAllArgumentsOnNextLine = false; 23892 Style.AllowAllParametersOfDeclarationOnNextLine = false; 23893 23894 verifyFormat(Short, Style); 23895 verifyFormat( 23896 "functionCall(\n" 23897 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 23898 "paramI\n" 23899 ");\n" 23900 "void functionDecl(\n" 23901 " int argumentA, int argumentB, int argumentC, int argumentD, int " 23902 "argumentE\n" 23903 ");", 23904 Medium, Style); 23905 23906 Style.BinPackArguments = false; 23907 Style.BinPackParameters = false; 23908 23909 verifyFormat(Short, Style); 23910 23911 verifyFormat("functionCall(\n" 23912 " paramA,\n" 23913 " paramB,\n" 23914 " paramC,\n" 23915 " paramD,\n" 23916 " paramE,\n" 23917 " paramF,\n" 23918 " paramG,\n" 23919 " paramH,\n" 23920 " paramI\n" 23921 ");\n" 23922 "void functionDecl(\n" 23923 " int argumentA,\n" 23924 " int argumentB,\n" 23925 " int argumentC,\n" 23926 " int argumentD,\n" 23927 " int argumentE\n" 23928 ");", 23929 Medium, Style); 23930 23931 verifyFormat("outerFunctionCall(\n" 23932 " nestedFunctionCall(argument1),\n" 23933 " nestedLongFunctionCall(\n" 23934 " argument1,\n" 23935 " argument2,\n" 23936 " argument3,\n" 23937 " argument4,\n" 23938 " argument5\n" 23939 " )\n" 23940 ");", 23941 Style); 23942 23943 verifyFormat("int a = (int)b;", Style); 23944 verifyFormat("int a = (int)b;", 23945 "int a = (\n" 23946 " int\n" 23947 ") b;", 23948 Style); 23949 23950 verifyFormat("return (true);", Style); 23951 verifyFormat("return (true);", 23952 "return (\n" 23953 " true\n" 23954 ");", 23955 Style); 23956 23957 verifyFormat("void foo();", Style); 23958 verifyFormat("void foo();", 23959 "void foo(\n" 23960 ");", 23961 Style); 23962 23963 verifyFormat("void foo() {}", Style); 23964 verifyFormat("void foo() {}", 23965 "void foo(\n" 23966 ") {\n" 23967 "}", 23968 Style); 23969 23970 verifyFormat("auto string = std::string();", Style); 23971 verifyFormat("auto string = std::string();", 23972 "auto string = std::string(\n" 23973 ");", 23974 Style); 23975 23976 verifyFormat("void (*functionPointer)() = nullptr;", Style); 23977 verifyFormat("void (*functionPointer)() = nullptr;", 23978 "void (\n" 23979 " *functionPointer\n" 23980 ")\n" 23981 "(\n" 23982 ") = nullptr;", 23983 Style); 23984 } 23985 23986 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 23987 auto Style = getLLVMStyle(); 23988 23989 verifyFormat("if (foo()) {\n" 23990 " return;\n" 23991 "}", 23992 Style); 23993 23994 verifyFormat("if (quitelongarg !=\n" 23995 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 23996 "comment\n" 23997 " return;\n" 23998 "}", 23999 Style); 24000 24001 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24002 24003 verifyFormat("if (foo()) {\n" 24004 " return;\n" 24005 "}", 24006 Style); 24007 24008 verifyFormat("if (quitelongarg !=\n" 24009 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24010 "comment\n" 24011 " return;\n" 24012 "}", 24013 Style); 24014 } 24015 24016 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 24017 auto Style = getLLVMStyle(); 24018 24019 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24020 " doSomething();\n" 24021 "}", 24022 Style); 24023 24024 verifyFormat("for (int myReallyLongCountVariable = 0; " 24025 "myReallyLongCountVariable < count;\n" 24026 " myReallyLongCountVariable++) {\n" 24027 " doSomething();\n" 24028 "}", 24029 Style); 24030 24031 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24032 24033 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24034 " doSomething();\n" 24035 "}", 24036 Style); 24037 24038 verifyFormat("for (int myReallyLongCountVariable = 0; " 24039 "myReallyLongCountVariable < count;\n" 24040 " myReallyLongCountVariable++) {\n" 24041 " doSomething();\n" 24042 "}", 24043 Style); 24044 } 24045 24046 } // namespace 24047 } // namespace format 24048 } // namespace clang 24049