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 consteval {\n}"); 587 verifyFormat("if !consteval {\n}"); 588 verifyFormat("if not consteval {\n}"); 589 verifyFormat("if consteval {\n} else {\n}"); 590 verifyFormat("if !consteval {\n} else {\n}"); 591 verifyFormat("if consteval {\n" 592 " f();\n" 593 "}"); 594 verifyFormat("if !consteval {\n" 595 " f();\n" 596 "}"); 597 verifyFormat("if consteval {\n" 598 " f();\n" 599 "} else {\n" 600 " g();\n" 601 "}"); 602 verifyFormat("if CONSTEVAL {\n" 603 " f();\n" 604 "}"); 605 verifyFormat("if !CONSTEVAL {\n" 606 " f();\n" 607 "}"); 608 609 verifyFormat("if (a)\n" 610 " g();"); 611 verifyFormat("if (a) {\n" 612 " g()\n" 613 "};"); 614 verifyFormat("if (a)\n" 615 " g();\n" 616 "else\n" 617 " g();"); 618 verifyFormat("if (a) {\n" 619 " g();\n" 620 "} else\n" 621 " g();"); 622 verifyFormat("if (a)\n" 623 " g();\n" 624 "else {\n" 625 " g();\n" 626 "}"); 627 verifyFormat("if (a) {\n" 628 " g();\n" 629 "} else {\n" 630 " g();\n" 631 "}"); 632 verifyFormat("if (a)\n" 633 " g();\n" 634 "else if (b)\n" 635 " g();\n" 636 "else\n" 637 " g();"); 638 verifyFormat("if (a) {\n" 639 " g();\n" 640 "} else if (b)\n" 641 " g();\n" 642 "else\n" 643 " g();"); 644 verifyFormat("if (a)\n" 645 " g();\n" 646 "else if (b) {\n" 647 " g();\n" 648 "} else\n" 649 " g();"); 650 verifyFormat("if (a)\n" 651 " g();\n" 652 "else if (b)\n" 653 " g();\n" 654 "else {\n" 655 " g();\n" 656 "}"); 657 verifyFormat("if (a)\n" 658 " g();\n" 659 "else if (b) {\n" 660 " g();\n" 661 "} else {\n" 662 " g();\n" 663 "}"); 664 verifyFormat("if (a) {\n" 665 " g();\n" 666 "} else if (b) {\n" 667 " g();\n" 668 "} else {\n" 669 " g();\n" 670 "}"); 671 672 FormatStyle AllowsMergedIf = getLLVMStyle(); 673 AllowsMergedIf.IfMacros.push_back("MYIF"); 674 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 675 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 676 FormatStyle::SIS_WithoutElse; 677 verifyFormat("if (a)\n" 678 " // comment\n" 679 " f();", 680 AllowsMergedIf); 681 verifyFormat("{\n" 682 " if (a)\n" 683 " label:\n" 684 " f();\n" 685 "}", 686 AllowsMergedIf); 687 verifyFormat("#define A \\\n" 688 " if (a) \\\n" 689 " label: \\\n" 690 " f()", 691 AllowsMergedIf); 692 verifyFormat("if (a)\n" 693 " ;", 694 AllowsMergedIf); 695 verifyFormat("if (a)\n" 696 " if (b) return;", 697 AllowsMergedIf); 698 699 verifyFormat("if (a) // Can't merge this\n" 700 " f();\n", 701 AllowsMergedIf); 702 verifyFormat("if (a) /* still don't merge */\n" 703 " f();", 704 AllowsMergedIf); 705 verifyFormat("if (a) { // Never merge this\n" 706 " f();\n" 707 "}", 708 AllowsMergedIf); 709 verifyFormat("if (a) { /* Never merge this */\n" 710 " f();\n" 711 "}", 712 AllowsMergedIf); 713 verifyFormat("MYIF (a)\n" 714 " // comment\n" 715 " f();", 716 AllowsMergedIf); 717 verifyFormat("{\n" 718 " MYIF (a)\n" 719 " label:\n" 720 " f();\n" 721 "}", 722 AllowsMergedIf); 723 verifyFormat("#define A \\\n" 724 " MYIF (a) \\\n" 725 " label: \\\n" 726 " f()", 727 AllowsMergedIf); 728 verifyFormat("MYIF (a)\n" 729 " ;", 730 AllowsMergedIf); 731 verifyFormat("MYIF (a)\n" 732 " MYIF (b) return;", 733 AllowsMergedIf); 734 735 verifyFormat("MYIF (a) // Can't merge this\n" 736 " f();\n", 737 AllowsMergedIf); 738 verifyFormat("MYIF (a) /* still don't merge */\n" 739 " f();", 740 AllowsMergedIf); 741 verifyFormat("MYIF (a) { // Never merge this\n" 742 " f();\n" 743 "}", 744 AllowsMergedIf); 745 verifyFormat("MYIF (a) { /* Never merge this */\n" 746 " f();\n" 747 "}", 748 AllowsMergedIf); 749 750 AllowsMergedIf.ColumnLimit = 14; 751 // Where line-lengths matter, a 2-letter synonym that maintains line length. 752 // Not IF to avoid any confusion that IF is somehow special. 753 AllowsMergedIf.IfMacros.push_back("FI"); 754 verifyFormat("if (a) return;", AllowsMergedIf); 755 verifyFormat("if (aaaaaaaaa)\n" 756 " return;", 757 AllowsMergedIf); 758 verifyFormat("FI (a) return;", AllowsMergedIf); 759 verifyFormat("FI (aaaaaaaaa)\n" 760 " return;", 761 AllowsMergedIf); 762 763 AllowsMergedIf.ColumnLimit = 13; 764 verifyFormat("if (a)\n return;", AllowsMergedIf); 765 verifyFormat("FI (a)\n return;", AllowsMergedIf); 766 767 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 768 AllowsMergedIfElse.IfMacros.push_back("MYIF"); 769 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 770 FormatStyle::SIS_AllIfsAndElse; 771 verifyFormat("if (a)\n" 772 " // comment\n" 773 " f();\n" 774 "else\n" 775 " // comment\n" 776 " f();", 777 AllowsMergedIfElse); 778 verifyFormat("{\n" 779 " if (a)\n" 780 " label:\n" 781 " f();\n" 782 " else\n" 783 " label:\n" 784 " f();\n" 785 "}", 786 AllowsMergedIfElse); 787 verifyFormat("if (a)\n" 788 " ;\n" 789 "else\n" 790 " ;", 791 AllowsMergedIfElse); 792 verifyFormat("if (a) {\n" 793 "} else {\n" 794 "}", 795 AllowsMergedIfElse); 796 verifyFormat("if (a) return;\n" 797 "else if (b) return;\n" 798 "else return;", 799 AllowsMergedIfElse); 800 verifyFormat("if (a) {\n" 801 "} else return;", 802 AllowsMergedIfElse); 803 verifyFormat("if (a) {\n" 804 "} else if (b) return;\n" 805 "else return;", 806 AllowsMergedIfElse); 807 verifyFormat("if (a) return;\n" 808 "else if (b) {\n" 809 "} else return;", 810 AllowsMergedIfElse); 811 verifyFormat("if (a)\n" 812 " if (b) return;\n" 813 " else return;", 814 AllowsMergedIfElse); 815 verifyFormat("if constexpr (a)\n" 816 " if constexpr (b) return;\n" 817 " else if constexpr (c) return;\n" 818 " else return;", 819 AllowsMergedIfElse); 820 verifyFormat("MYIF (a)\n" 821 " // comment\n" 822 " f();\n" 823 "else\n" 824 " // comment\n" 825 " f();", 826 AllowsMergedIfElse); 827 verifyFormat("{\n" 828 " MYIF (a)\n" 829 " label:\n" 830 " f();\n" 831 " else\n" 832 " label:\n" 833 " f();\n" 834 "}", 835 AllowsMergedIfElse); 836 verifyFormat("MYIF (a)\n" 837 " ;\n" 838 "else\n" 839 " ;", 840 AllowsMergedIfElse); 841 verifyFormat("MYIF (a) {\n" 842 "} else {\n" 843 "}", 844 AllowsMergedIfElse); 845 verifyFormat("MYIF (a) return;\n" 846 "else MYIF (b) return;\n" 847 "else return;", 848 AllowsMergedIfElse); 849 verifyFormat("MYIF (a) {\n" 850 "} else return;", 851 AllowsMergedIfElse); 852 verifyFormat("MYIF (a) {\n" 853 "} else MYIF (b) return;\n" 854 "else return;", 855 AllowsMergedIfElse); 856 verifyFormat("MYIF (a) return;\n" 857 "else MYIF (b) {\n" 858 "} else return;", 859 AllowsMergedIfElse); 860 verifyFormat("MYIF (a)\n" 861 " MYIF (b) return;\n" 862 " else return;", 863 AllowsMergedIfElse); 864 verifyFormat("MYIF constexpr (a)\n" 865 " MYIF constexpr (b) return;\n" 866 " else MYIF constexpr (c) return;\n" 867 " else return;", 868 AllowsMergedIfElse); 869 } 870 871 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 872 FormatStyle AllowsMergedIf = getLLVMStyle(); 873 AllowsMergedIf.IfMacros.push_back("MYIF"); 874 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 875 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 876 FormatStyle::SIS_WithoutElse; 877 verifyFormat("if (a)\n" 878 " f();\n" 879 "else {\n" 880 " g();\n" 881 "}", 882 AllowsMergedIf); 883 verifyFormat("if (a)\n" 884 " f();\n" 885 "else\n" 886 " g();\n", 887 AllowsMergedIf); 888 889 verifyFormat("if (a) g();", AllowsMergedIf); 890 verifyFormat("if (a) {\n" 891 " g()\n" 892 "};", 893 AllowsMergedIf); 894 verifyFormat("if (a)\n" 895 " g();\n" 896 "else\n" 897 " g();", 898 AllowsMergedIf); 899 verifyFormat("if (a) {\n" 900 " g();\n" 901 "} else\n" 902 " g();", 903 AllowsMergedIf); 904 verifyFormat("if (a)\n" 905 " g();\n" 906 "else {\n" 907 " g();\n" 908 "}", 909 AllowsMergedIf); 910 verifyFormat("if (a) {\n" 911 " g();\n" 912 "} else {\n" 913 " g();\n" 914 "}", 915 AllowsMergedIf); 916 verifyFormat("if (a)\n" 917 " g();\n" 918 "else if (b)\n" 919 " g();\n" 920 "else\n" 921 " g();", 922 AllowsMergedIf); 923 verifyFormat("if (a) {\n" 924 " g();\n" 925 "} else if (b)\n" 926 " g();\n" 927 "else\n" 928 " g();", 929 AllowsMergedIf); 930 verifyFormat("if (a)\n" 931 " g();\n" 932 "else if (b) {\n" 933 " g();\n" 934 "} else\n" 935 " g();", 936 AllowsMergedIf); 937 verifyFormat("if (a)\n" 938 " g();\n" 939 "else if (b)\n" 940 " g();\n" 941 "else {\n" 942 " g();\n" 943 "}", 944 AllowsMergedIf); 945 verifyFormat("if (a)\n" 946 " g();\n" 947 "else if (b) {\n" 948 " g();\n" 949 "} else {\n" 950 " g();\n" 951 "}", 952 AllowsMergedIf); 953 verifyFormat("if (a) {\n" 954 " g();\n" 955 "} else if (b) {\n" 956 " g();\n" 957 "} else {\n" 958 " g();\n" 959 "}", 960 AllowsMergedIf); 961 verifyFormat("MYIF (a)\n" 962 " f();\n" 963 "else {\n" 964 " g();\n" 965 "}", 966 AllowsMergedIf); 967 verifyFormat("MYIF (a)\n" 968 " f();\n" 969 "else\n" 970 " g();\n", 971 AllowsMergedIf); 972 973 verifyFormat("MYIF (a) g();", AllowsMergedIf); 974 verifyFormat("MYIF (a) {\n" 975 " g()\n" 976 "};", 977 AllowsMergedIf); 978 verifyFormat("MYIF (a)\n" 979 " g();\n" 980 "else\n" 981 " g();", 982 AllowsMergedIf); 983 verifyFormat("MYIF (a) {\n" 984 " g();\n" 985 "} else\n" 986 " g();", 987 AllowsMergedIf); 988 verifyFormat("MYIF (a)\n" 989 " g();\n" 990 "else {\n" 991 " g();\n" 992 "}", 993 AllowsMergedIf); 994 verifyFormat("MYIF (a) {\n" 995 " g();\n" 996 "} else {\n" 997 " g();\n" 998 "}", 999 AllowsMergedIf); 1000 verifyFormat("MYIF (a)\n" 1001 " g();\n" 1002 "else MYIF (b)\n" 1003 " g();\n" 1004 "else\n" 1005 " g();", 1006 AllowsMergedIf); 1007 verifyFormat("MYIF (a)\n" 1008 " g();\n" 1009 "else if (b)\n" 1010 " g();\n" 1011 "else\n" 1012 " g();", 1013 AllowsMergedIf); 1014 verifyFormat("MYIF (a) {\n" 1015 " g();\n" 1016 "} else MYIF (b)\n" 1017 " g();\n" 1018 "else\n" 1019 " g();", 1020 AllowsMergedIf); 1021 verifyFormat("MYIF (a) {\n" 1022 " g();\n" 1023 "} else if (b)\n" 1024 " g();\n" 1025 "else\n" 1026 " g();", 1027 AllowsMergedIf); 1028 verifyFormat("MYIF (a)\n" 1029 " g();\n" 1030 "else MYIF (b) {\n" 1031 " g();\n" 1032 "} else\n" 1033 " g();", 1034 AllowsMergedIf); 1035 verifyFormat("MYIF (a)\n" 1036 " g();\n" 1037 "else if (b) {\n" 1038 " g();\n" 1039 "} else\n" 1040 " g();", 1041 AllowsMergedIf); 1042 verifyFormat("MYIF (a)\n" 1043 " g();\n" 1044 "else MYIF (b)\n" 1045 " g();\n" 1046 "else {\n" 1047 " g();\n" 1048 "}", 1049 AllowsMergedIf); 1050 verifyFormat("MYIF (a)\n" 1051 " g();\n" 1052 "else if (b)\n" 1053 " g();\n" 1054 "else {\n" 1055 " g();\n" 1056 "}", 1057 AllowsMergedIf); 1058 verifyFormat("MYIF (a)\n" 1059 " g();\n" 1060 "else MYIF (b) {\n" 1061 " g();\n" 1062 "} else {\n" 1063 " g();\n" 1064 "}", 1065 AllowsMergedIf); 1066 verifyFormat("MYIF (a)\n" 1067 " g();\n" 1068 "else if (b) {\n" 1069 " g();\n" 1070 "} else {\n" 1071 " g();\n" 1072 "}", 1073 AllowsMergedIf); 1074 verifyFormat("MYIF (a) {\n" 1075 " g();\n" 1076 "} else MYIF (b) {\n" 1077 " g();\n" 1078 "} else {\n" 1079 " g();\n" 1080 "}", 1081 AllowsMergedIf); 1082 verifyFormat("MYIF (a) {\n" 1083 " g();\n" 1084 "} else if (b) {\n" 1085 " g();\n" 1086 "} else {\n" 1087 " g();\n" 1088 "}", 1089 AllowsMergedIf); 1090 1091 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1092 FormatStyle::SIS_OnlyFirstIf; 1093 1094 verifyFormat("if (a) f();\n" 1095 "else {\n" 1096 " g();\n" 1097 "}", 1098 AllowsMergedIf); 1099 verifyFormat("if (a) f();\n" 1100 "else {\n" 1101 " if (a) f();\n" 1102 " else {\n" 1103 " g();\n" 1104 " }\n" 1105 " g();\n" 1106 "}", 1107 AllowsMergedIf); 1108 1109 verifyFormat("if (a) g();", AllowsMergedIf); 1110 verifyFormat("if (a) {\n" 1111 " g()\n" 1112 "};", 1113 AllowsMergedIf); 1114 verifyFormat("if (a) g();\n" 1115 "else\n" 1116 " g();", 1117 AllowsMergedIf); 1118 verifyFormat("if (a) {\n" 1119 " g();\n" 1120 "} else\n" 1121 " g();", 1122 AllowsMergedIf); 1123 verifyFormat("if (a) g();\n" 1124 "else {\n" 1125 " g();\n" 1126 "}", 1127 AllowsMergedIf); 1128 verifyFormat("if (a) {\n" 1129 " g();\n" 1130 "} else {\n" 1131 " g();\n" 1132 "}", 1133 AllowsMergedIf); 1134 verifyFormat("if (a) g();\n" 1135 "else if (b)\n" 1136 " g();\n" 1137 "else\n" 1138 " g();", 1139 AllowsMergedIf); 1140 verifyFormat("if (a) {\n" 1141 " g();\n" 1142 "} else if (b)\n" 1143 " g();\n" 1144 "else\n" 1145 " g();", 1146 AllowsMergedIf); 1147 verifyFormat("if (a) g();\n" 1148 "else if (b) {\n" 1149 " g();\n" 1150 "} else\n" 1151 " g();", 1152 AllowsMergedIf); 1153 verifyFormat("if (a) g();\n" 1154 "else if (b)\n" 1155 " g();\n" 1156 "else {\n" 1157 " g();\n" 1158 "}", 1159 AllowsMergedIf); 1160 verifyFormat("if (a) g();\n" 1161 "else if (b) {\n" 1162 " g();\n" 1163 "} else {\n" 1164 " g();\n" 1165 "}", 1166 AllowsMergedIf); 1167 verifyFormat("if (a) {\n" 1168 " g();\n" 1169 "} else if (b) {\n" 1170 " g();\n" 1171 "} else {\n" 1172 " g();\n" 1173 "}", 1174 AllowsMergedIf); 1175 verifyFormat("MYIF (a) f();\n" 1176 "else {\n" 1177 " g();\n" 1178 "}", 1179 AllowsMergedIf); 1180 verifyFormat("MYIF (a) f();\n" 1181 "else {\n" 1182 " if (a) f();\n" 1183 " else {\n" 1184 " g();\n" 1185 " }\n" 1186 " g();\n" 1187 "}", 1188 AllowsMergedIf); 1189 1190 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1191 verifyFormat("MYIF (a) {\n" 1192 " g()\n" 1193 "};", 1194 AllowsMergedIf); 1195 verifyFormat("MYIF (a) g();\n" 1196 "else\n" 1197 " g();", 1198 AllowsMergedIf); 1199 verifyFormat("MYIF (a) {\n" 1200 " g();\n" 1201 "} else\n" 1202 " g();", 1203 AllowsMergedIf); 1204 verifyFormat("MYIF (a) g();\n" 1205 "else {\n" 1206 " g();\n" 1207 "}", 1208 AllowsMergedIf); 1209 verifyFormat("MYIF (a) {\n" 1210 " g();\n" 1211 "} else {\n" 1212 " g();\n" 1213 "}", 1214 AllowsMergedIf); 1215 verifyFormat("MYIF (a) g();\n" 1216 "else MYIF (b)\n" 1217 " g();\n" 1218 "else\n" 1219 " g();", 1220 AllowsMergedIf); 1221 verifyFormat("MYIF (a) g();\n" 1222 "else if (b)\n" 1223 " g();\n" 1224 "else\n" 1225 " g();", 1226 AllowsMergedIf); 1227 verifyFormat("MYIF (a) {\n" 1228 " g();\n" 1229 "} else MYIF (b)\n" 1230 " g();\n" 1231 "else\n" 1232 " g();", 1233 AllowsMergedIf); 1234 verifyFormat("MYIF (a) {\n" 1235 " g();\n" 1236 "} else if (b)\n" 1237 " g();\n" 1238 "else\n" 1239 " g();", 1240 AllowsMergedIf); 1241 verifyFormat("MYIF (a) g();\n" 1242 "else MYIF (b) {\n" 1243 " g();\n" 1244 "} else\n" 1245 " g();", 1246 AllowsMergedIf); 1247 verifyFormat("MYIF (a) g();\n" 1248 "else if (b) {\n" 1249 " g();\n" 1250 "} else\n" 1251 " g();", 1252 AllowsMergedIf); 1253 verifyFormat("MYIF (a) g();\n" 1254 "else MYIF (b)\n" 1255 " g();\n" 1256 "else {\n" 1257 " g();\n" 1258 "}", 1259 AllowsMergedIf); 1260 verifyFormat("MYIF (a) g();\n" 1261 "else if (b)\n" 1262 " g();\n" 1263 "else {\n" 1264 " g();\n" 1265 "}", 1266 AllowsMergedIf); 1267 verifyFormat("MYIF (a) g();\n" 1268 "else MYIF (b) {\n" 1269 " g();\n" 1270 "} else {\n" 1271 " g();\n" 1272 "}", 1273 AllowsMergedIf); 1274 verifyFormat("MYIF (a) g();\n" 1275 "else if (b) {\n" 1276 " g();\n" 1277 "} else {\n" 1278 " g();\n" 1279 "}", 1280 AllowsMergedIf); 1281 verifyFormat("MYIF (a) {\n" 1282 " g();\n" 1283 "} else MYIF (b) {\n" 1284 " g();\n" 1285 "} else {\n" 1286 " g();\n" 1287 "}", 1288 AllowsMergedIf); 1289 verifyFormat("MYIF (a) {\n" 1290 " g();\n" 1291 "} else if (b) {\n" 1292 " g();\n" 1293 "} else {\n" 1294 " g();\n" 1295 "}", 1296 AllowsMergedIf); 1297 1298 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1299 FormatStyle::SIS_AllIfsAndElse; 1300 1301 verifyFormat("if (a) f();\n" 1302 "else {\n" 1303 " g();\n" 1304 "}", 1305 AllowsMergedIf); 1306 verifyFormat("if (a) f();\n" 1307 "else {\n" 1308 " if (a) f();\n" 1309 " else {\n" 1310 " g();\n" 1311 " }\n" 1312 " g();\n" 1313 "}", 1314 AllowsMergedIf); 1315 1316 verifyFormat("if (a) g();", AllowsMergedIf); 1317 verifyFormat("if (a) {\n" 1318 " g()\n" 1319 "};", 1320 AllowsMergedIf); 1321 verifyFormat("if (a) g();\n" 1322 "else g();", 1323 AllowsMergedIf); 1324 verifyFormat("if (a) {\n" 1325 " g();\n" 1326 "} else g();", 1327 AllowsMergedIf); 1328 verifyFormat("if (a) g();\n" 1329 "else {\n" 1330 " g();\n" 1331 "}", 1332 AllowsMergedIf); 1333 verifyFormat("if (a) {\n" 1334 " g();\n" 1335 "} else {\n" 1336 " g();\n" 1337 "}", 1338 AllowsMergedIf); 1339 verifyFormat("if (a) g();\n" 1340 "else if (b) g();\n" 1341 "else g();", 1342 AllowsMergedIf); 1343 verifyFormat("if (a) {\n" 1344 " g();\n" 1345 "} else if (b) g();\n" 1346 "else g();", 1347 AllowsMergedIf); 1348 verifyFormat("if (a) g();\n" 1349 "else if (b) {\n" 1350 " g();\n" 1351 "} else g();", 1352 AllowsMergedIf); 1353 verifyFormat("if (a) g();\n" 1354 "else if (b) g();\n" 1355 "else {\n" 1356 " g();\n" 1357 "}", 1358 AllowsMergedIf); 1359 verifyFormat("if (a) g();\n" 1360 "else if (b) {\n" 1361 " g();\n" 1362 "} else {\n" 1363 " g();\n" 1364 "}", 1365 AllowsMergedIf); 1366 verifyFormat("if (a) {\n" 1367 " g();\n" 1368 "} else if (b) {\n" 1369 " g();\n" 1370 "} else {\n" 1371 " g();\n" 1372 "}", 1373 AllowsMergedIf); 1374 verifyFormat("MYIF (a) f();\n" 1375 "else {\n" 1376 " g();\n" 1377 "}", 1378 AllowsMergedIf); 1379 verifyFormat("MYIF (a) f();\n" 1380 "else {\n" 1381 " if (a) f();\n" 1382 " else {\n" 1383 " g();\n" 1384 " }\n" 1385 " g();\n" 1386 "}", 1387 AllowsMergedIf); 1388 1389 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1390 verifyFormat("MYIF (a) {\n" 1391 " g()\n" 1392 "};", 1393 AllowsMergedIf); 1394 verifyFormat("MYIF (a) g();\n" 1395 "else g();", 1396 AllowsMergedIf); 1397 verifyFormat("MYIF (a) {\n" 1398 " g();\n" 1399 "} else g();", 1400 AllowsMergedIf); 1401 verifyFormat("MYIF (a) g();\n" 1402 "else {\n" 1403 " g();\n" 1404 "}", 1405 AllowsMergedIf); 1406 verifyFormat("MYIF (a) {\n" 1407 " g();\n" 1408 "} else {\n" 1409 " g();\n" 1410 "}", 1411 AllowsMergedIf); 1412 verifyFormat("MYIF (a) g();\n" 1413 "else MYIF (b) g();\n" 1414 "else g();", 1415 AllowsMergedIf); 1416 verifyFormat("MYIF (a) g();\n" 1417 "else if (b) g();\n" 1418 "else g();", 1419 AllowsMergedIf); 1420 verifyFormat("MYIF (a) {\n" 1421 " g();\n" 1422 "} else MYIF (b) g();\n" 1423 "else g();", 1424 AllowsMergedIf); 1425 verifyFormat("MYIF (a) {\n" 1426 " g();\n" 1427 "} else if (b) g();\n" 1428 "else g();", 1429 AllowsMergedIf); 1430 verifyFormat("MYIF (a) g();\n" 1431 "else MYIF (b) {\n" 1432 " g();\n" 1433 "} else g();", 1434 AllowsMergedIf); 1435 verifyFormat("MYIF (a) g();\n" 1436 "else if (b) {\n" 1437 " g();\n" 1438 "} else g();", 1439 AllowsMergedIf); 1440 verifyFormat("MYIF (a) g();\n" 1441 "else MYIF (b) g();\n" 1442 "else {\n" 1443 " g();\n" 1444 "}", 1445 AllowsMergedIf); 1446 verifyFormat("MYIF (a) g();\n" 1447 "else if (b) g();\n" 1448 "else {\n" 1449 " g();\n" 1450 "}", 1451 AllowsMergedIf); 1452 verifyFormat("MYIF (a) g();\n" 1453 "else MYIF (b) {\n" 1454 " g();\n" 1455 "} else {\n" 1456 " g();\n" 1457 "}", 1458 AllowsMergedIf); 1459 verifyFormat("MYIF (a) g();\n" 1460 "else if (b) {\n" 1461 " g();\n" 1462 "} else {\n" 1463 " g();\n" 1464 "}", 1465 AllowsMergedIf); 1466 verifyFormat("MYIF (a) {\n" 1467 " g();\n" 1468 "} else MYIF (b) {\n" 1469 " g();\n" 1470 "} else {\n" 1471 " g();\n" 1472 "}", 1473 AllowsMergedIf); 1474 verifyFormat("MYIF (a) {\n" 1475 " g();\n" 1476 "} else if (b) {\n" 1477 " g();\n" 1478 "} else {\n" 1479 " g();\n" 1480 "}", 1481 AllowsMergedIf); 1482 } 1483 1484 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 1485 FormatStyle AllowsMergedLoops = getLLVMStyle(); 1486 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 1487 verifyFormat("while (true) continue;", AllowsMergedLoops); 1488 verifyFormat("for (;;) continue;", AllowsMergedLoops); 1489 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 1490 verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops); 1491 verifyFormat("while (true)\n" 1492 " ;", 1493 AllowsMergedLoops); 1494 verifyFormat("for (;;)\n" 1495 " ;", 1496 AllowsMergedLoops); 1497 verifyFormat("for (;;)\n" 1498 " for (;;) continue;", 1499 AllowsMergedLoops); 1500 verifyFormat("for (;;)\n" 1501 " while (true) continue;", 1502 AllowsMergedLoops); 1503 verifyFormat("while (true)\n" 1504 " for (;;) continue;", 1505 AllowsMergedLoops); 1506 verifyFormat("BOOST_FOREACH (int &v, vec)\n" 1507 " for (;;) continue;", 1508 AllowsMergedLoops); 1509 verifyFormat("for (;;)\n" 1510 " BOOST_FOREACH (int &v, vec) continue;", 1511 AllowsMergedLoops); 1512 verifyFormat("for (;;) // Can't merge this\n" 1513 " continue;", 1514 AllowsMergedLoops); 1515 verifyFormat("for (;;) /* still don't merge */\n" 1516 " continue;", 1517 AllowsMergedLoops); 1518 verifyFormat("do a++;\n" 1519 "while (true);", 1520 AllowsMergedLoops); 1521 verifyFormat("do /* Don't merge */\n" 1522 " a++;\n" 1523 "while (true);", 1524 AllowsMergedLoops); 1525 verifyFormat("do // Don't merge\n" 1526 " a++;\n" 1527 "while (true);", 1528 AllowsMergedLoops); 1529 verifyFormat("do\n" 1530 " // Don't merge\n" 1531 " a++;\n" 1532 "while (true);", 1533 AllowsMergedLoops); 1534 // Without braces labels are interpreted differently. 1535 verifyFormat("{\n" 1536 " do\n" 1537 " label:\n" 1538 " a++;\n" 1539 " while (true);\n" 1540 "}", 1541 AllowsMergedLoops); 1542 } 1543 1544 TEST_F(FormatTest, FormatShortBracedStatements) { 1545 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1546 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false); 1547 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine, 1548 FormatStyle::SIS_Never); 1549 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false); 1550 EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false); 1551 verifyFormat("for (;;) {\n" 1552 " f();\n" 1553 "}"); 1554 verifyFormat("/*comment*/ for (;;) {\n" 1555 " f();\n" 1556 "}"); 1557 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1558 " f();\n" 1559 "}"); 1560 verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n" 1561 " f();\n" 1562 "}"); 1563 verifyFormat("while (true) {\n" 1564 " f();\n" 1565 "}"); 1566 verifyFormat("/*comment*/ while (true) {\n" 1567 " f();\n" 1568 "}"); 1569 verifyFormat("if (true) {\n" 1570 " f();\n" 1571 "}"); 1572 verifyFormat("/*comment*/ if (true) {\n" 1573 " f();\n" 1574 "}"); 1575 1576 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1577 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1578 // Not IF to avoid any confusion that IF is somehow special. 1579 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1580 AllowSimpleBracedStatements.ColumnLimit = 40; 1581 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1582 FormatStyle::SBS_Always; 1583 1584 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1585 FormatStyle::SIS_WithoutElse; 1586 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1587 1588 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1589 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1590 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1591 1592 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1593 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1594 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1595 verifyFormat("if consteval {}", AllowSimpleBracedStatements); 1596 verifyFormat("if !consteval {}", AllowSimpleBracedStatements); 1597 verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements); 1598 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1599 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1600 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1601 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1602 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1603 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1604 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1605 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1606 verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements); 1607 verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1608 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1609 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1610 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1611 verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements); 1612 verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1613 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1614 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1615 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1616 AllowSimpleBracedStatements); 1617 verifyFormat("if (true) {\n" 1618 " ffffffffffffffffffffffff();\n" 1619 "}", 1620 AllowSimpleBracedStatements); 1621 verifyFormat("if (true) {\n" 1622 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1623 "}", 1624 AllowSimpleBracedStatements); 1625 verifyFormat("if (true) { //\n" 1626 " f();\n" 1627 "}", 1628 AllowSimpleBracedStatements); 1629 verifyFormat("if (true) {\n" 1630 " f();\n" 1631 " f();\n" 1632 "}", 1633 AllowSimpleBracedStatements); 1634 verifyFormat("if (true) {\n" 1635 " f();\n" 1636 "} else {\n" 1637 " f();\n" 1638 "}", 1639 AllowSimpleBracedStatements); 1640 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1641 AllowSimpleBracedStatements); 1642 verifyFormat("MYIF (true) {\n" 1643 " ffffffffffffffffffffffff();\n" 1644 "}", 1645 AllowSimpleBracedStatements); 1646 verifyFormat("MYIF (true) {\n" 1647 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1648 "}", 1649 AllowSimpleBracedStatements); 1650 verifyFormat("MYIF (true) { //\n" 1651 " f();\n" 1652 "}", 1653 AllowSimpleBracedStatements); 1654 verifyFormat("MYIF (true) {\n" 1655 " f();\n" 1656 " f();\n" 1657 "}", 1658 AllowSimpleBracedStatements); 1659 verifyFormat("MYIF (true) {\n" 1660 " f();\n" 1661 "} else {\n" 1662 " f();\n" 1663 "}", 1664 AllowSimpleBracedStatements); 1665 1666 verifyFormat("struct A2 {\n" 1667 " int X;\n" 1668 "};", 1669 AllowSimpleBracedStatements); 1670 verifyFormat("typedef struct A2 {\n" 1671 " int X;\n" 1672 "} A2_t;", 1673 AllowSimpleBracedStatements); 1674 verifyFormat("template <int> struct A2 {\n" 1675 " struct B {};\n" 1676 "};", 1677 AllowSimpleBracedStatements); 1678 1679 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1680 FormatStyle::SIS_Never; 1681 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1682 verifyFormat("if (true) {\n" 1683 " f();\n" 1684 "}", 1685 AllowSimpleBracedStatements); 1686 verifyFormat("if (true) {\n" 1687 " f();\n" 1688 "} else {\n" 1689 " f();\n" 1690 "}", 1691 AllowSimpleBracedStatements); 1692 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1693 verifyFormat("MYIF (true) {\n" 1694 " f();\n" 1695 "}", 1696 AllowSimpleBracedStatements); 1697 verifyFormat("MYIF (true) {\n" 1698 " f();\n" 1699 "} else {\n" 1700 " f();\n" 1701 "}", 1702 AllowSimpleBracedStatements); 1703 1704 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1705 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1706 verifyFormat("while (true) {\n" 1707 " f();\n" 1708 "}", 1709 AllowSimpleBracedStatements); 1710 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1711 verifyFormat("for (;;) {\n" 1712 " f();\n" 1713 "}", 1714 AllowSimpleBracedStatements); 1715 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1716 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1717 " f();\n" 1718 "}", 1719 AllowSimpleBracedStatements); 1720 1721 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1722 FormatStyle::SIS_WithoutElse; 1723 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1724 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1725 FormatStyle::BWACS_Always; 1726 1727 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1728 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1729 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1730 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1731 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1732 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1733 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1734 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1735 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1736 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1737 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1738 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1739 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1740 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1741 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1742 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1743 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1744 AllowSimpleBracedStatements); 1745 verifyFormat("if (true)\n" 1746 "{\n" 1747 " ffffffffffffffffffffffff();\n" 1748 "}", 1749 AllowSimpleBracedStatements); 1750 verifyFormat("if (true)\n" 1751 "{\n" 1752 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1753 "}", 1754 AllowSimpleBracedStatements); 1755 verifyFormat("if (true)\n" 1756 "{ //\n" 1757 " f();\n" 1758 "}", 1759 AllowSimpleBracedStatements); 1760 verifyFormat("if (true)\n" 1761 "{\n" 1762 " f();\n" 1763 " f();\n" 1764 "}", 1765 AllowSimpleBracedStatements); 1766 verifyFormat("if (true)\n" 1767 "{\n" 1768 " f();\n" 1769 "} else\n" 1770 "{\n" 1771 " f();\n" 1772 "}", 1773 AllowSimpleBracedStatements); 1774 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1775 AllowSimpleBracedStatements); 1776 verifyFormat("MYIF (true)\n" 1777 "{\n" 1778 " ffffffffffffffffffffffff();\n" 1779 "}", 1780 AllowSimpleBracedStatements); 1781 verifyFormat("MYIF (true)\n" 1782 "{\n" 1783 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1784 "}", 1785 AllowSimpleBracedStatements); 1786 verifyFormat("MYIF (true)\n" 1787 "{ //\n" 1788 " f();\n" 1789 "}", 1790 AllowSimpleBracedStatements); 1791 verifyFormat("MYIF (true)\n" 1792 "{\n" 1793 " f();\n" 1794 " f();\n" 1795 "}", 1796 AllowSimpleBracedStatements); 1797 verifyFormat("MYIF (true)\n" 1798 "{\n" 1799 " f();\n" 1800 "} else\n" 1801 "{\n" 1802 " f();\n" 1803 "}", 1804 AllowSimpleBracedStatements); 1805 1806 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1807 FormatStyle::SIS_Never; 1808 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1809 verifyFormat("if (true)\n" 1810 "{\n" 1811 " f();\n" 1812 "}", 1813 AllowSimpleBracedStatements); 1814 verifyFormat("if (true)\n" 1815 "{\n" 1816 " f();\n" 1817 "} else\n" 1818 "{\n" 1819 " f();\n" 1820 "}", 1821 AllowSimpleBracedStatements); 1822 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1823 verifyFormat("MYIF (true)\n" 1824 "{\n" 1825 " f();\n" 1826 "}", 1827 AllowSimpleBracedStatements); 1828 verifyFormat("MYIF (true)\n" 1829 "{\n" 1830 " f();\n" 1831 "} else\n" 1832 "{\n" 1833 " f();\n" 1834 "}", 1835 AllowSimpleBracedStatements); 1836 1837 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1838 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1839 verifyFormat("while (true)\n" 1840 "{\n" 1841 " f();\n" 1842 "}", 1843 AllowSimpleBracedStatements); 1844 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1845 verifyFormat("for (;;)\n" 1846 "{\n" 1847 " f();\n" 1848 "}", 1849 AllowSimpleBracedStatements); 1850 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1851 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1852 "{\n" 1853 " f();\n" 1854 "}", 1855 AllowSimpleBracedStatements); 1856 } 1857 1858 TEST_F(FormatTest, UnderstandsMacros) { 1859 verifyFormat("#define A (parentheses)"); 1860 verifyFormat("/* comment */ #define A (parentheses)"); 1861 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1862 // Even the partial code should never be merged. 1863 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1864 "#", 1865 format("/* comment */ #define A (parentheses)\n" 1866 "#")); 1867 verifyFormat("/* comment */ #define A (parentheses)\n" 1868 "#\n"); 1869 verifyFormat("/* comment */ #define A (parentheses)\n" 1870 "#define B (parentheses)"); 1871 verifyFormat("#define true ((int)1)"); 1872 verifyFormat("#define and(x)"); 1873 verifyFormat("#define if(x) x"); 1874 verifyFormat("#define return(x) (x)"); 1875 verifyFormat("#define while(x) for (; x;)"); 1876 verifyFormat("#define xor(x) (^(x))"); 1877 verifyFormat("#define __except(x)"); 1878 verifyFormat("#define __try(x)"); 1879 1880 // https://llvm.org/PR54348. 1881 verifyFormat( 1882 "#define A" 1883 " " 1884 "\\\n" 1885 " class & {}"); 1886 1887 FormatStyle Style = getLLVMStyle(); 1888 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1889 Style.BraceWrapping.AfterFunction = true; 1890 // Test that a macro definition never gets merged with the following 1891 // definition. 1892 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1893 verifyFormat("#define AAA " 1894 " \\\n" 1895 " N " 1896 " \\\n" 1897 " {\n" 1898 "#define BBB }\n", 1899 Style); 1900 // verifyFormat("#define AAA N { //\n", Style); 1901 1902 verifyFormat("MACRO(return)"); 1903 verifyFormat("MACRO(co_await)"); 1904 verifyFormat("MACRO(co_return)"); 1905 verifyFormat("MACRO(co_yield)"); 1906 verifyFormat("MACRO(return, something)"); 1907 verifyFormat("MACRO(co_return, something)"); 1908 verifyFormat("MACRO(something##something)"); 1909 verifyFormat("MACRO(return##something)"); 1910 verifyFormat("MACRO(co_return##something)"); 1911 } 1912 1913 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1914 FormatStyle Style = getLLVMStyleWithColumns(60); 1915 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1916 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1917 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1918 EXPECT_EQ("#define A \\\n" 1919 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1920 " { \\\n" 1921 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1922 " }\n" 1923 "X;", 1924 format("#define A \\\n" 1925 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1926 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1927 " }\n" 1928 "X;", 1929 Style)); 1930 } 1931 1932 TEST_F(FormatTest, ParseIfElse) { 1933 verifyFormat("if (true)\n" 1934 " if (true)\n" 1935 " if (true)\n" 1936 " f();\n" 1937 " else\n" 1938 " g();\n" 1939 " else\n" 1940 " h();\n" 1941 "else\n" 1942 " i();"); 1943 verifyFormat("if (true)\n" 1944 " if (true)\n" 1945 " if (true) {\n" 1946 " if (true)\n" 1947 " f();\n" 1948 " } else {\n" 1949 " g();\n" 1950 " }\n" 1951 " else\n" 1952 " h();\n" 1953 "else {\n" 1954 " i();\n" 1955 "}"); 1956 verifyFormat("if (true)\n" 1957 " if constexpr (true)\n" 1958 " if (true) {\n" 1959 " if constexpr (true)\n" 1960 " f();\n" 1961 " } else {\n" 1962 " g();\n" 1963 " }\n" 1964 " else\n" 1965 " h();\n" 1966 "else {\n" 1967 " i();\n" 1968 "}"); 1969 verifyFormat("if (true)\n" 1970 " if CONSTEXPR (true)\n" 1971 " if (true) {\n" 1972 " if CONSTEXPR (true)\n" 1973 " f();\n" 1974 " } else {\n" 1975 " g();\n" 1976 " }\n" 1977 " else\n" 1978 " h();\n" 1979 "else {\n" 1980 " i();\n" 1981 "}"); 1982 verifyFormat("void f() {\n" 1983 " if (a) {\n" 1984 " } else {\n" 1985 " }\n" 1986 "}"); 1987 } 1988 1989 TEST_F(FormatTest, ElseIf) { 1990 verifyFormat("if (a) {\n} else if (b) {\n}"); 1991 verifyFormat("if (a)\n" 1992 " f();\n" 1993 "else if (b)\n" 1994 " g();\n" 1995 "else\n" 1996 " h();"); 1997 verifyFormat("if (a)\n" 1998 " f();\n" 1999 "else // comment\n" 2000 " if (b) {\n" 2001 " g();\n" 2002 " h();\n" 2003 " }"); 2004 verifyFormat("if constexpr (a)\n" 2005 " f();\n" 2006 "else if constexpr (b)\n" 2007 " g();\n" 2008 "else\n" 2009 " h();"); 2010 verifyFormat("if CONSTEXPR (a)\n" 2011 " f();\n" 2012 "else if CONSTEXPR (b)\n" 2013 " g();\n" 2014 "else\n" 2015 " h();"); 2016 verifyFormat("if (a) {\n" 2017 " f();\n" 2018 "}\n" 2019 "// or else ..\n" 2020 "else {\n" 2021 " g()\n" 2022 "}"); 2023 2024 verifyFormat("if (a) {\n" 2025 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2026 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2027 "}"); 2028 verifyFormat("if (a) {\n" 2029 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2030 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2031 "}"); 2032 verifyFormat("if (a) {\n" 2033 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2034 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2035 "}"); 2036 verifyFormat("if (a) {\n" 2037 "} else if (\n" 2038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2039 "}", 2040 getLLVMStyleWithColumns(62)); 2041 verifyFormat("if (a) {\n" 2042 "} else if constexpr (\n" 2043 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2044 "}", 2045 getLLVMStyleWithColumns(62)); 2046 verifyFormat("if (a) {\n" 2047 "} else if CONSTEXPR (\n" 2048 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2049 "}", 2050 getLLVMStyleWithColumns(62)); 2051 } 2052 2053 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2054 FormatStyle Style = getLLVMStyle(); 2055 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2056 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2057 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2058 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2059 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2060 verifyFormat("int *f1(int &a) const &;", Style); 2061 verifyFormat("int *f1(int &a) const & = 0;", Style); 2062 verifyFormat("int *a = f1();", Style); 2063 verifyFormat("int &b = f2();", Style); 2064 verifyFormat("int &&c = f3();", Style); 2065 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2066 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2067 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2068 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2069 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2070 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2071 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2072 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2073 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2074 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2075 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2076 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2077 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2078 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2079 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2080 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2081 verifyFormat( 2082 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2083 " res2 = [](int &a) { return 0000000000000; };", 2084 Style); 2085 2086 Style.AlignConsecutiveDeclarations.Enabled = true; 2087 verifyFormat("Const unsigned int *c;\n" 2088 "const unsigned int *d;\n" 2089 "Const unsigned int &e;\n" 2090 "const unsigned int &f;\n" 2091 "const unsigned &&g;\n" 2092 "Const unsigned h;", 2093 Style); 2094 2095 Style.PointerAlignment = FormatStyle::PAS_Left; 2096 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2097 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2098 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2099 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2100 verifyFormat("int* f1(int& a) const& = 0;", Style); 2101 verifyFormat("int* a = f1();", Style); 2102 verifyFormat("int& b = f2();", Style); 2103 verifyFormat("int&& c = f3();", Style); 2104 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2105 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2106 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2107 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2108 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2109 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2110 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2111 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2112 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2113 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2114 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2115 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2116 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2117 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2118 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2119 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2120 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2121 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2122 verifyFormat( 2123 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2124 " res2 = [](int& a) { return 0000000000000; };", 2125 Style); 2126 2127 Style.AlignConsecutiveDeclarations.Enabled = true; 2128 verifyFormat("Const unsigned int* c;\n" 2129 "const unsigned int* d;\n" 2130 "Const unsigned int& e;\n" 2131 "const unsigned int& f;\n" 2132 "const unsigned&& g;\n" 2133 "Const unsigned h;", 2134 Style); 2135 2136 Style.PointerAlignment = FormatStyle::PAS_Right; 2137 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2138 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2139 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2140 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2141 verifyFormat("int *a = f1();", Style); 2142 verifyFormat("int& b = f2();", Style); 2143 verifyFormat("int&& c = f3();", Style); 2144 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2145 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2146 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2147 2148 Style.AlignConsecutiveDeclarations.Enabled = true; 2149 verifyFormat("Const unsigned int *c;\n" 2150 "const unsigned int *d;\n" 2151 "Const unsigned int& e;\n" 2152 "const unsigned int& f;\n" 2153 "const unsigned g;\n" 2154 "Const unsigned h;", 2155 Style); 2156 2157 Style.PointerAlignment = FormatStyle::PAS_Left; 2158 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2159 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2160 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2161 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2162 verifyFormat("int* a = f1();", Style); 2163 verifyFormat("int & b = f2();", Style); 2164 verifyFormat("int && c = f3();", Style); 2165 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2166 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2167 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2168 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2169 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2170 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2171 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2172 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2173 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2174 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2175 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2176 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2177 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2178 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2179 verifyFormat( 2180 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2181 " res2 = [](int & a) { return 0000000000000; };", 2182 Style); 2183 2184 Style.AlignConsecutiveDeclarations.Enabled = true; 2185 verifyFormat("Const unsigned int* c;\n" 2186 "const unsigned int* d;\n" 2187 "Const unsigned int & e;\n" 2188 "const unsigned int & f;\n" 2189 "const unsigned && g;\n" 2190 "Const unsigned h;", 2191 Style); 2192 2193 Style.PointerAlignment = FormatStyle::PAS_Middle; 2194 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2195 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2196 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2197 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2198 verifyFormat("int * a = f1();", Style); 2199 verifyFormat("int &b = f2();", Style); 2200 verifyFormat("int &&c = f3();", Style); 2201 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2202 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2203 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2204 2205 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2206 // specifically handled 2207 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2208 } 2209 2210 TEST_F(FormatTest, FormatsForLoop) { 2211 verifyFormat( 2212 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2213 " ++VeryVeryLongLoopVariable)\n" 2214 " ;"); 2215 verifyFormat("for (;;)\n" 2216 " f();"); 2217 verifyFormat("for (;;) {\n}"); 2218 verifyFormat("for (;;) {\n" 2219 " f();\n" 2220 "}"); 2221 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2222 2223 verifyFormat( 2224 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2225 " E = UnwrappedLines.end();\n" 2226 " I != E; ++I) {\n}"); 2227 2228 verifyFormat( 2229 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2230 " ++IIIII) {\n}"); 2231 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2232 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2233 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2234 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2235 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2236 " E = FD->getDeclsInPrototypeScope().end();\n" 2237 " I != E; ++I) {\n}"); 2238 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2239 " I = Container.begin(),\n" 2240 " E = Container.end();\n" 2241 " I != E; ++I) {\n}", 2242 getLLVMStyleWithColumns(76)); 2243 2244 verifyFormat( 2245 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2246 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2247 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2248 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2249 " ++aaaaaaaaaaa) {\n}"); 2250 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2251 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2252 " ++i) {\n}"); 2253 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2254 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2255 "}"); 2256 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2257 " aaaaaaaaaa);\n" 2258 " iter; ++iter) {\n" 2259 "}"); 2260 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2261 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2262 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2263 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2264 2265 // These should not be formatted as Objective-C for-in loops. 2266 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2267 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2268 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2269 verifyFormat( 2270 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2271 2272 FormatStyle NoBinPacking = getLLVMStyle(); 2273 NoBinPacking.BinPackParameters = false; 2274 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2275 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2276 " aaaaaaaaaaaaaaaa,\n" 2277 " aaaaaaaaaaaaaaaa,\n" 2278 " aaaaaaaaaaaaaaaa);\n" 2279 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2280 "}", 2281 NoBinPacking); 2282 verifyFormat( 2283 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2284 " E = UnwrappedLines.end();\n" 2285 " I != E;\n" 2286 " ++I) {\n}", 2287 NoBinPacking); 2288 2289 FormatStyle AlignLeft = getLLVMStyle(); 2290 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2291 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2292 } 2293 2294 TEST_F(FormatTest, RangeBasedForLoops) { 2295 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2296 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2297 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2298 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2299 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2300 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2301 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2302 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2303 } 2304 2305 TEST_F(FormatTest, ForEachLoops) { 2306 FormatStyle Style = getLLVMStyle(); 2307 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2308 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2309 verifyFormat("void f() {\n" 2310 " for (;;) {\n" 2311 " }\n" 2312 " foreach (Item *item, itemlist) {\n" 2313 " }\n" 2314 " Q_FOREACH (Item *item, itemlist) {\n" 2315 " }\n" 2316 " BOOST_FOREACH (Item *item, itemlist) {\n" 2317 " }\n" 2318 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2319 "}", 2320 Style); 2321 verifyFormat("void f() {\n" 2322 " for (;;)\n" 2323 " int j = 1;\n" 2324 " Q_FOREACH (int v, vec)\n" 2325 " v *= 2;\n" 2326 " for (;;) {\n" 2327 " int j = 1;\n" 2328 " }\n" 2329 " Q_FOREACH (int v, vec) {\n" 2330 " v *= 2;\n" 2331 " }\n" 2332 "}", 2333 Style); 2334 2335 FormatStyle ShortBlocks = getLLVMStyle(); 2336 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2337 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2338 verifyFormat("void f() {\n" 2339 " for (;;)\n" 2340 " int j = 1;\n" 2341 " Q_FOREACH (int &v, vec)\n" 2342 " v *= 2;\n" 2343 " for (;;) {\n" 2344 " int j = 1;\n" 2345 " }\n" 2346 " Q_FOREACH (int &v, vec) {\n" 2347 " int j = 1;\n" 2348 " }\n" 2349 "}", 2350 ShortBlocks); 2351 2352 FormatStyle ShortLoops = getLLVMStyle(); 2353 ShortLoops.AllowShortLoopsOnASingleLine = true; 2354 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2355 verifyFormat("void f() {\n" 2356 " for (;;) int j = 1;\n" 2357 " Q_FOREACH (int &v, vec) int j = 1;\n" 2358 " for (;;) {\n" 2359 " int j = 1;\n" 2360 " }\n" 2361 " Q_FOREACH (int &v, vec) {\n" 2362 " int j = 1;\n" 2363 " }\n" 2364 "}", 2365 ShortLoops); 2366 2367 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2368 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2369 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2370 verifyFormat("void f() {\n" 2371 " for (;;) int j = 1;\n" 2372 " Q_FOREACH (int &v, vec) int j = 1;\n" 2373 " for (;;) { int j = 1; }\n" 2374 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2375 "}", 2376 ShortBlocksAndLoops); 2377 2378 Style.SpaceBeforeParens = 2379 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2380 verifyFormat("void f() {\n" 2381 " for (;;) {\n" 2382 " }\n" 2383 " foreach(Item *item, itemlist) {\n" 2384 " }\n" 2385 " Q_FOREACH(Item *item, itemlist) {\n" 2386 " }\n" 2387 " BOOST_FOREACH(Item *item, itemlist) {\n" 2388 " }\n" 2389 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2390 "}", 2391 Style); 2392 2393 // As function-like macros. 2394 verifyFormat("#define foreach(x, y)\n" 2395 "#define Q_FOREACH(x, y)\n" 2396 "#define BOOST_FOREACH(x, y)\n" 2397 "#define UNKNOWN_FOREACH(x, y)\n"); 2398 2399 // Not as function-like macros. 2400 verifyFormat("#define foreach (x, y)\n" 2401 "#define Q_FOREACH (x, y)\n" 2402 "#define BOOST_FOREACH (x, y)\n" 2403 "#define UNKNOWN_FOREACH (x, y)\n"); 2404 2405 // handle microsoft non standard extension 2406 verifyFormat("for each (char c in x->MyStringProperty)"); 2407 } 2408 2409 TEST_F(FormatTest, FormatsWhileLoop) { 2410 verifyFormat("while (true) {\n}"); 2411 verifyFormat("while (true)\n" 2412 " f();"); 2413 verifyFormat("while () {\n}"); 2414 verifyFormat("while () {\n" 2415 " f();\n" 2416 "}"); 2417 } 2418 2419 TEST_F(FormatTest, FormatsDoWhile) { 2420 verifyFormat("do {\n" 2421 " do_something();\n" 2422 "} while (something());"); 2423 verifyFormat("do\n" 2424 " do_something();\n" 2425 "while (something());"); 2426 } 2427 2428 TEST_F(FormatTest, FormatsSwitchStatement) { 2429 verifyFormat("switch (x) {\n" 2430 "case 1:\n" 2431 " f();\n" 2432 " break;\n" 2433 "case kFoo:\n" 2434 "case ns::kBar:\n" 2435 "case kBaz:\n" 2436 " break;\n" 2437 "default:\n" 2438 " g();\n" 2439 " break;\n" 2440 "}"); 2441 verifyFormat("switch (x) {\n" 2442 "case 1: {\n" 2443 " f();\n" 2444 " break;\n" 2445 "}\n" 2446 "case 2: {\n" 2447 " break;\n" 2448 "}\n" 2449 "}"); 2450 verifyFormat("switch (x) {\n" 2451 "case 1: {\n" 2452 " f();\n" 2453 " {\n" 2454 " g();\n" 2455 " h();\n" 2456 " }\n" 2457 " break;\n" 2458 "}\n" 2459 "}"); 2460 verifyFormat("switch (x) {\n" 2461 "case 1: {\n" 2462 " f();\n" 2463 " if (foo) {\n" 2464 " g();\n" 2465 " h();\n" 2466 " }\n" 2467 " break;\n" 2468 "}\n" 2469 "}"); 2470 verifyFormat("switch (x) {\n" 2471 "case 1: {\n" 2472 " f();\n" 2473 " g();\n" 2474 "} break;\n" 2475 "}"); 2476 verifyFormat("switch (test)\n" 2477 " ;"); 2478 verifyFormat("switch (x) {\n" 2479 "default: {\n" 2480 " // Do nothing.\n" 2481 "}\n" 2482 "}"); 2483 verifyFormat("switch (x) {\n" 2484 "// comment\n" 2485 "// if 1, do f()\n" 2486 "case 1:\n" 2487 " f();\n" 2488 "}"); 2489 verifyFormat("switch (x) {\n" 2490 "case 1:\n" 2491 " // Do amazing stuff\n" 2492 " {\n" 2493 " f();\n" 2494 " g();\n" 2495 " }\n" 2496 " break;\n" 2497 "}"); 2498 verifyFormat("#define A \\\n" 2499 " switch (x) { \\\n" 2500 " case a: \\\n" 2501 " foo = b; \\\n" 2502 " }", 2503 getLLVMStyleWithColumns(20)); 2504 verifyFormat("#define OPERATION_CASE(name) \\\n" 2505 " case OP_name: \\\n" 2506 " return operations::Operation##name\n", 2507 getLLVMStyleWithColumns(40)); 2508 verifyFormat("switch (x) {\n" 2509 "case 1:;\n" 2510 "default:;\n" 2511 " int i;\n" 2512 "}"); 2513 2514 verifyGoogleFormat("switch (x) {\n" 2515 " case 1:\n" 2516 " f();\n" 2517 " break;\n" 2518 " case kFoo:\n" 2519 " case ns::kBar:\n" 2520 " case kBaz:\n" 2521 " break;\n" 2522 " default:\n" 2523 " g();\n" 2524 " break;\n" 2525 "}"); 2526 verifyGoogleFormat("switch (x) {\n" 2527 " case 1: {\n" 2528 " f();\n" 2529 " break;\n" 2530 " }\n" 2531 "}"); 2532 verifyGoogleFormat("switch (test)\n" 2533 " ;"); 2534 2535 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2536 " case OP_name: \\\n" 2537 " return operations::Operation##name\n"); 2538 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2539 " // Get the correction operation class.\n" 2540 " switch (OpCode) {\n" 2541 " CASE(Add);\n" 2542 " CASE(Subtract);\n" 2543 " default:\n" 2544 " return operations::Unknown;\n" 2545 " }\n" 2546 "#undef OPERATION_CASE\n" 2547 "}"); 2548 verifyFormat("DEBUG({\n" 2549 " switch (x) {\n" 2550 " case A:\n" 2551 " f();\n" 2552 " break;\n" 2553 " // fallthrough\n" 2554 " case B:\n" 2555 " g();\n" 2556 " break;\n" 2557 " }\n" 2558 "});"); 2559 EXPECT_EQ("DEBUG({\n" 2560 " switch (x) {\n" 2561 " case A:\n" 2562 " f();\n" 2563 " break;\n" 2564 " // On B:\n" 2565 " case B:\n" 2566 " g();\n" 2567 " break;\n" 2568 " }\n" 2569 "});", 2570 format("DEBUG({\n" 2571 " switch (x) {\n" 2572 " case A:\n" 2573 " f();\n" 2574 " break;\n" 2575 " // On B:\n" 2576 " case B:\n" 2577 " g();\n" 2578 " break;\n" 2579 " }\n" 2580 "});", 2581 getLLVMStyle())); 2582 EXPECT_EQ("switch (n) {\n" 2583 "case 0: {\n" 2584 " return false;\n" 2585 "}\n" 2586 "default: {\n" 2587 " return true;\n" 2588 "}\n" 2589 "}", 2590 format("switch (n)\n" 2591 "{\n" 2592 "case 0: {\n" 2593 " return false;\n" 2594 "}\n" 2595 "default: {\n" 2596 " return true;\n" 2597 "}\n" 2598 "}", 2599 getLLVMStyle())); 2600 verifyFormat("switch (a) {\n" 2601 "case (b):\n" 2602 " return;\n" 2603 "}"); 2604 2605 verifyFormat("switch (a) {\n" 2606 "case some_namespace::\n" 2607 " some_constant:\n" 2608 " return;\n" 2609 "}", 2610 getLLVMStyleWithColumns(34)); 2611 2612 verifyFormat("switch (a) {\n" 2613 "[[likely]] case 1:\n" 2614 " return;\n" 2615 "}"); 2616 verifyFormat("switch (a) {\n" 2617 "[[likely]] [[other::likely]] case 1:\n" 2618 " return;\n" 2619 "}"); 2620 verifyFormat("switch (x) {\n" 2621 "case 1:\n" 2622 " return;\n" 2623 "[[likely]] case 2:\n" 2624 " return;\n" 2625 "}"); 2626 verifyFormat("switch (a) {\n" 2627 "case 1:\n" 2628 "[[likely]] case 2:\n" 2629 " return;\n" 2630 "}"); 2631 FormatStyle Attributes = getLLVMStyle(); 2632 Attributes.AttributeMacros.push_back("LIKELY"); 2633 Attributes.AttributeMacros.push_back("OTHER_LIKELY"); 2634 verifyFormat("switch (a) {\n" 2635 "LIKELY case b:\n" 2636 " return;\n" 2637 "}", 2638 Attributes); 2639 verifyFormat("switch (a) {\n" 2640 "LIKELY OTHER_LIKELY() case b:\n" 2641 " return;\n" 2642 "}", 2643 Attributes); 2644 verifyFormat("switch (a) {\n" 2645 "case 1:\n" 2646 " return;\n" 2647 "LIKELY case 2:\n" 2648 " return;\n" 2649 "}", 2650 Attributes); 2651 verifyFormat("switch (a) {\n" 2652 "case 1:\n" 2653 "LIKELY case 2:\n" 2654 " return;\n" 2655 "}", 2656 Attributes); 2657 2658 FormatStyle Style = getLLVMStyle(); 2659 Style.IndentCaseLabels = true; 2660 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2661 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2662 Style.BraceWrapping.AfterCaseLabel = true; 2663 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2664 EXPECT_EQ("switch (n)\n" 2665 "{\n" 2666 " case 0:\n" 2667 " {\n" 2668 " return false;\n" 2669 " }\n" 2670 " default:\n" 2671 " {\n" 2672 " return true;\n" 2673 " }\n" 2674 "}", 2675 format("switch (n) {\n" 2676 " case 0: {\n" 2677 " return false;\n" 2678 " }\n" 2679 " default: {\n" 2680 " return true;\n" 2681 " }\n" 2682 "}", 2683 Style)); 2684 Style.BraceWrapping.AfterCaseLabel = false; 2685 EXPECT_EQ("switch (n)\n" 2686 "{\n" 2687 " case 0: {\n" 2688 " return false;\n" 2689 " }\n" 2690 " default: {\n" 2691 " return true;\n" 2692 " }\n" 2693 "}", 2694 format("switch (n) {\n" 2695 " case 0:\n" 2696 " {\n" 2697 " return false;\n" 2698 " }\n" 2699 " default:\n" 2700 " {\n" 2701 " return true;\n" 2702 " }\n" 2703 "}", 2704 Style)); 2705 Style.IndentCaseLabels = false; 2706 Style.IndentCaseBlocks = true; 2707 EXPECT_EQ("switch (n)\n" 2708 "{\n" 2709 "case 0:\n" 2710 " {\n" 2711 " return false;\n" 2712 " }\n" 2713 "case 1:\n" 2714 " break;\n" 2715 "default:\n" 2716 " {\n" 2717 " return true;\n" 2718 " }\n" 2719 "}", 2720 format("switch (n) {\n" 2721 "case 0: {\n" 2722 " return false;\n" 2723 "}\n" 2724 "case 1:\n" 2725 " break;\n" 2726 "default: {\n" 2727 " return true;\n" 2728 "}\n" 2729 "}", 2730 Style)); 2731 Style.IndentCaseLabels = true; 2732 Style.IndentCaseBlocks = true; 2733 EXPECT_EQ("switch (n)\n" 2734 "{\n" 2735 " case 0:\n" 2736 " {\n" 2737 " return false;\n" 2738 " }\n" 2739 " case 1:\n" 2740 " break;\n" 2741 " default:\n" 2742 " {\n" 2743 " return true;\n" 2744 " }\n" 2745 "}", 2746 format("switch (n) {\n" 2747 "case 0: {\n" 2748 " return false;\n" 2749 "}\n" 2750 "case 1:\n" 2751 " break;\n" 2752 "default: {\n" 2753 " return true;\n" 2754 "}\n" 2755 "}", 2756 Style)); 2757 } 2758 2759 TEST_F(FormatTest, CaseRanges) { 2760 verifyFormat("switch (x) {\n" 2761 "case 'A' ... 'Z':\n" 2762 "case 1 ... 5:\n" 2763 "case a ... b:\n" 2764 " break;\n" 2765 "}"); 2766 } 2767 2768 TEST_F(FormatTest, ShortEnums) { 2769 FormatStyle Style = getLLVMStyle(); 2770 EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine); 2771 EXPECT_FALSE(Style.BraceWrapping.AfterEnum); 2772 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2773 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2774 Style.AllowShortEnumsOnASingleLine = false; 2775 verifyFormat("enum {\n" 2776 " A,\n" 2777 " B,\n" 2778 " C\n" 2779 "} ShortEnum1, ShortEnum2;", 2780 Style); 2781 verifyFormat("typedef enum {\n" 2782 " A,\n" 2783 " B,\n" 2784 " C\n" 2785 "} ShortEnum1, ShortEnum2;", 2786 Style); 2787 verifyFormat("enum {\n" 2788 " A,\n" 2789 "} ShortEnum1, ShortEnum2;", 2790 Style); 2791 verifyFormat("typedef enum {\n" 2792 " A,\n" 2793 "} ShortEnum1, ShortEnum2;", 2794 Style); 2795 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2796 Style.BraceWrapping.AfterEnum = true; 2797 verifyFormat("enum\n" 2798 "{\n" 2799 " A,\n" 2800 " B,\n" 2801 " C\n" 2802 "} ShortEnum1, ShortEnum2;", 2803 Style); 2804 verifyFormat("typedef enum\n" 2805 "{\n" 2806 " A,\n" 2807 " B,\n" 2808 " C\n" 2809 "} ShortEnum1, ShortEnum2;", 2810 Style); 2811 } 2812 2813 TEST_F(FormatTest, ShortCaseLabels) { 2814 FormatStyle Style = getLLVMStyle(); 2815 Style.AllowShortCaseLabelsOnASingleLine = true; 2816 verifyFormat("switch (a) {\n" 2817 "case 1: x = 1; break;\n" 2818 "case 2: return;\n" 2819 "case 3:\n" 2820 "case 4:\n" 2821 "case 5: return;\n" 2822 "case 6: // comment\n" 2823 " return;\n" 2824 "case 7:\n" 2825 " // comment\n" 2826 " return;\n" 2827 "case 8:\n" 2828 " x = 8; // comment\n" 2829 " break;\n" 2830 "default: y = 1; break;\n" 2831 "}", 2832 Style); 2833 verifyFormat("switch (a) {\n" 2834 "case 0: return; // comment\n" 2835 "case 1: break; // comment\n" 2836 "case 2: return;\n" 2837 "// comment\n" 2838 "case 3: return;\n" 2839 "// comment 1\n" 2840 "// comment 2\n" 2841 "// comment 3\n" 2842 "case 4: break; /* comment */\n" 2843 "case 5:\n" 2844 " // comment\n" 2845 " break;\n" 2846 "case 6: /* comment */ x = 1; break;\n" 2847 "case 7: x = /* comment */ 1; break;\n" 2848 "case 8:\n" 2849 " x = 1; /* comment */\n" 2850 " break;\n" 2851 "case 9:\n" 2852 " break; // comment line 1\n" 2853 " // comment line 2\n" 2854 "}", 2855 Style); 2856 EXPECT_EQ("switch (a) {\n" 2857 "case 1:\n" 2858 " x = 8;\n" 2859 " // fall through\n" 2860 "case 2: x = 8;\n" 2861 "// comment\n" 2862 "case 3:\n" 2863 " return; /* comment line 1\n" 2864 " * comment line 2 */\n" 2865 "case 4: i = 8;\n" 2866 "// something else\n" 2867 "#if FOO\n" 2868 "case 5: break;\n" 2869 "#endif\n" 2870 "}", 2871 format("switch (a) {\n" 2872 "case 1: x = 8;\n" 2873 " // fall through\n" 2874 "case 2:\n" 2875 " x = 8;\n" 2876 "// comment\n" 2877 "case 3:\n" 2878 " return; /* comment line 1\n" 2879 " * comment line 2 */\n" 2880 "case 4:\n" 2881 " i = 8;\n" 2882 "// something else\n" 2883 "#if FOO\n" 2884 "case 5: break;\n" 2885 "#endif\n" 2886 "}", 2887 Style)); 2888 EXPECT_EQ("switch (a) {\n" 2889 "case 0:\n" 2890 " return; // long long long long long long long long long long " 2891 "long long comment\n" 2892 " // line\n" 2893 "}", 2894 format("switch (a) {\n" 2895 "case 0: return; // long long long long long long long long " 2896 "long long long long comment line\n" 2897 "}", 2898 Style)); 2899 EXPECT_EQ("switch (a) {\n" 2900 "case 0:\n" 2901 " return; /* long long long long long long long long long long " 2902 "long long comment\n" 2903 " line */\n" 2904 "}", 2905 format("switch (a) {\n" 2906 "case 0: return; /* long long long long long long long long " 2907 "long long long long comment line */\n" 2908 "}", 2909 Style)); 2910 verifyFormat("switch (a) {\n" 2911 "#if FOO\n" 2912 "case 0: return 0;\n" 2913 "#endif\n" 2914 "}", 2915 Style); 2916 verifyFormat("switch (a) {\n" 2917 "case 1: {\n" 2918 "}\n" 2919 "case 2: {\n" 2920 " return;\n" 2921 "}\n" 2922 "case 3: {\n" 2923 " x = 1;\n" 2924 " return;\n" 2925 "}\n" 2926 "case 4:\n" 2927 " if (x)\n" 2928 " return;\n" 2929 "}", 2930 Style); 2931 Style.ColumnLimit = 21; 2932 verifyFormat("switch (a) {\n" 2933 "case 1: x = 1; break;\n" 2934 "case 2: return;\n" 2935 "case 3:\n" 2936 "case 4:\n" 2937 "case 5: return;\n" 2938 "default:\n" 2939 " y = 1;\n" 2940 " break;\n" 2941 "}", 2942 Style); 2943 Style.ColumnLimit = 80; 2944 Style.AllowShortCaseLabelsOnASingleLine = false; 2945 Style.IndentCaseLabels = true; 2946 EXPECT_EQ("switch (n) {\n" 2947 " default /*comments*/:\n" 2948 " return true;\n" 2949 " case 0:\n" 2950 " return false;\n" 2951 "}", 2952 format("switch (n) {\n" 2953 "default/*comments*/:\n" 2954 " return true;\n" 2955 "case 0:\n" 2956 " return false;\n" 2957 "}", 2958 Style)); 2959 Style.AllowShortCaseLabelsOnASingleLine = true; 2960 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2961 Style.BraceWrapping.AfterCaseLabel = true; 2962 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2963 EXPECT_EQ("switch (n)\n" 2964 "{\n" 2965 " case 0:\n" 2966 " {\n" 2967 " return false;\n" 2968 " }\n" 2969 " default:\n" 2970 " {\n" 2971 " return true;\n" 2972 " }\n" 2973 "}", 2974 format("switch (n) {\n" 2975 " case 0: {\n" 2976 " return false;\n" 2977 " }\n" 2978 " default:\n" 2979 " {\n" 2980 " return true;\n" 2981 " }\n" 2982 "}", 2983 Style)); 2984 } 2985 2986 TEST_F(FormatTest, FormatsLabels) { 2987 verifyFormat("void f() {\n" 2988 " some_code();\n" 2989 "test_label:\n" 2990 " some_other_code();\n" 2991 " {\n" 2992 " some_more_code();\n" 2993 " another_label:\n" 2994 " some_more_code();\n" 2995 " }\n" 2996 "}"); 2997 verifyFormat("{\n" 2998 " some_code();\n" 2999 "test_label:\n" 3000 " some_other_code();\n" 3001 "}"); 3002 verifyFormat("{\n" 3003 " some_code();\n" 3004 "test_label:;\n" 3005 " int i = 0;\n" 3006 "}"); 3007 FormatStyle Style = getLLVMStyle(); 3008 Style.IndentGotoLabels = false; 3009 verifyFormat("void f() {\n" 3010 " some_code();\n" 3011 "test_label:\n" 3012 " some_other_code();\n" 3013 " {\n" 3014 " some_more_code();\n" 3015 "another_label:\n" 3016 " some_more_code();\n" 3017 " }\n" 3018 "}", 3019 Style); 3020 verifyFormat("{\n" 3021 " some_code();\n" 3022 "test_label:\n" 3023 " some_other_code();\n" 3024 "}", 3025 Style); 3026 verifyFormat("{\n" 3027 " some_code();\n" 3028 "test_label:;\n" 3029 " int i = 0;\n" 3030 "}"); 3031 } 3032 3033 TEST_F(FormatTest, MultiLineControlStatements) { 3034 FormatStyle Style = getLLVMStyleWithColumns(20); 3035 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3036 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3037 // Short lines should keep opening brace on same line. 3038 EXPECT_EQ("if (foo) {\n" 3039 " bar();\n" 3040 "}", 3041 format("if(foo){bar();}", Style)); 3042 EXPECT_EQ("if (foo) {\n" 3043 " bar();\n" 3044 "} else {\n" 3045 " baz();\n" 3046 "}", 3047 format("if(foo){bar();}else{baz();}", Style)); 3048 EXPECT_EQ("if (foo && bar) {\n" 3049 " baz();\n" 3050 "}", 3051 format("if(foo&&bar){baz();}", Style)); 3052 EXPECT_EQ("if (foo) {\n" 3053 " bar();\n" 3054 "} else if (baz) {\n" 3055 " quux();\n" 3056 "}", 3057 format("if(foo){bar();}else if(baz){quux();}", Style)); 3058 EXPECT_EQ( 3059 "if (foo) {\n" 3060 " bar();\n" 3061 "} else if (baz) {\n" 3062 " quux();\n" 3063 "} else {\n" 3064 " foobar();\n" 3065 "}", 3066 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 3067 EXPECT_EQ("for (;;) {\n" 3068 " foo();\n" 3069 "}", 3070 format("for(;;){foo();}")); 3071 EXPECT_EQ("while (1) {\n" 3072 " foo();\n" 3073 "}", 3074 format("while(1){foo();}", Style)); 3075 EXPECT_EQ("switch (foo) {\n" 3076 "case bar:\n" 3077 " return;\n" 3078 "}", 3079 format("switch(foo){case bar:return;}", Style)); 3080 EXPECT_EQ("try {\n" 3081 " foo();\n" 3082 "} catch (...) {\n" 3083 " bar();\n" 3084 "}", 3085 format("try{foo();}catch(...){bar();}", Style)); 3086 EXPECT_EQ("do {\n" 3087 " foo();\n" 3088 "} while (bar &&\n" 3089 " baz);", 3090 format("do{foo();}while(bar&&baz);", Style)); 3091 // Long lines should put opening brace on new line. 3092 EXPECT_EQ("if (foo && bar &&\n" 3093 " baz)\n" 3094 "{\n" 3095 " quux();\n" 3096 "}", 3097 format("if(foo&&bar&&baz){quux();}", Style)); 3098 EXPECT_EQ("if (foo && bar &&\n" 3099 " baz)\n" 3100 "{\n" 3101 " quux();\n" 3102 "}", 3103 format("if (foo && bar &&\n" 3104 " baz) {\n" 3105 " quux();\n" 3106 "}", 3107 Style)); 3108 EXPECT_EQ("if (foo) {\n" 3109 " bar();\n" 3110 "} else if (baz ||\n" 3111 " quux)\n" 3112 "{\n" 3113 " foobar();\n" 3114 "}", 3115 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3116 EXPECT_EQ( 3117 "if (foo) {\n" 3118 " bar();\n" 3119 "} else if (baz ||\n" 3120 " quux)\n" 3121 "{\n" 3122 " foobar();\n" 3123 "} else {\n" 3124 " barbaz();\n" 3125 "}", 3126 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3127 Style)); 3128 EXPECT_EQ("for (int i = 0;\n" 3129 " i < 10; ++i)\n" 3130 "{\n" 3131 " foo();\n" 3132 "}", 3133 format("for(int i=0;i<10;++i){foo();}", Style)); 3134 EXPECT_EQ("foreach (int i,\n" 3135 " list)\n" 3136 "{\n" 3137 " foo();\n" 3138 "}", 3139 format("foreach(int i, list){foo();}", Style)); 3140 Style.ColumnLimit = 3141 40; // to concentrate at brace wrapping, not line wrap due to column limit 3142 EXPECT_EQ("foreach (int i, list) {\n" 3143 " foo();\n" 3144 "}", 3145 format("foreach(int i, list){foo();}", Style)); 3146 Style.ColumnLimit = 3147 20; // to concentrate at brace wrapping, not line wrap due to column limit 3148 EXPECT_EQ("while (foo || bar ||\n" 3149 " baz)\n" 3150 "{\n" 3151 " quux();\n" 3152 "}", 3153 format("while(foo||bar||baz){quux();}", Style)); 3154 EXPECT_EQ("switch (\n" 3155 " foo = barbaz)\n" 3156 "{\n" 3157 "case quux:\n" 3158 " return;\n" 3159 "}", 3160 format("switch(foo=barbaz){case quux:return;}", Style)); 3161 EXPECT_EQ("try {\n" 3162 " foo();\n" 3163 "} catch (\n" 3164 " Exception &bar)\n" 3165 "{\n" 3166 " baz();\n" 3167 "}", 3168 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3169 Style.ColumnLimit = 3170 40; // to concentrate at brace wrapping, not line wrap due to column limit 3171 EXPECT_EQ("try {\n" 3172 " foo();\n" 3173 "} catch (Exception &bar) {\n" 3174 " baz();\n" 3175 "}", 3176 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3177 Style.ColumnLimit = 3178 20; // to concentrate at brace wrapping, not line wrap due to column limit 3179 3180 Style.BraceWrapping.BeforeElse = true; 3181 EXPECT_EQ( 3182 "if (foo) {\n" 3183 " bar();\n" 3184 "}\n" 3185 "else if (baz ||\n" 3186 " quux)\n" 3187 "{\n" 3188 " foobar();\n" 3189 "}\n" 3190 "else {\n" 3191 " barbaz();\n" 3192 "}", 3193 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3194 Style)); 3195 3196 Style.BraceWrapping.BeforeCatch = true; 3197 EXPECT_EQ("try {\n" 3198 " foo();\n" 3199 "}\n" 3200 "catch (...) {\n" 3201 " baz();\n" 3202 "}", 3203 format("try{foo();}catch(...){baz();}", Style)); 3204 3205 Style.BraceWrapping.AfterFunction = true; 3206 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3207 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3208 Style.ColumnLimit = 80; 3209 verifyFormat("void shortfunction() { bar(); }", Style); 3210 3211 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3212 verifyFormat("void shortfunction()\n" 3213 "{\n" 3214 " bar();\n" 3215 "}", 3216 Style); 3217 } 3218 3219 TEST_F(FormatTest, BeforeWhile) { 3220 FormatStyle Style = getLLVMStyle(); 3221 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3222 3223 verifyFormat("do {\n" 3224 " foo();\n" 3225 "} while (1);", 3226 Style); 3227 Style.BraceWrapping.BeforeWhile = true; 3228 verifyFormat("do {\n" 3229 " foo();\n" 3230 "}\n" 3231 "while (1);", 3232 Style); 3233 } 3234 3235 //===----------------------------------------------------------------------===// 3236 // Tests for classes, namespaces, etc. 3237 //===----------------------------------------------------------------------===// 3238 3239 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3240 verifyFormat("class A {};"); 3241 } 3242 3243 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3244 verifyFormat("class A {\n" 3245 "public:\n" 3246 "public: // comment\n" 3247 "protected:\n" 3248 "private:\n" 3249 " void f() {}\n" 3250 "};"); 3251 verifyFormat("export class A {\n" 3252 "public:\n" 3253 "public: // comment\n" 3254 "protected:\n" 3255 "private:\n" 3256 " void f() {}\n" 3257 "};"); 3258 verifyGoogleFormat("class A {\n" 3259 " public:\n" 3260 " protected:\n" 3261 " private:\n" 3262 " void f() {}\n" 3263 "};"); 3264 verifyGoogleFormat("export class A {\n" 3265 " public:\n" 3266 " protected:\n" 3267 " private:\n" 3268 " void f() {}\n" 3269 "};"); 3270 verifyFormat("class A {\n" 3271 "public slots:\n" 3272 " void f1() {}\n" 3273 "public Q_SLOTS:\n" 3274 " void f2() {}\n" 3275 "protected slots:\n" 3276 " void f3() {}\n" 3277 "protected Q_SLOTS:\n" 3278 " void f4() {}\n" 3279 "private slots:\n" 3280 " void f5() {}\n" 3281 "private Q_SLOTS:\n" 3282 " void f6() {}\n" 3283 "signals:\n" 3284 " void g1();\n" 3285 "Q_SIGNALS:\n" 3286 " void g2();\n" 3287 "};"); 3288 3289 // Don't interpret 'signals' the wrong way. 3290 verifyFormat("signals.set();"); 3291 verifyFormat("for (Signals signals : f()) {\n}"); 3292 verifyFormat("{\n" 3293 " signals.set(); // This needs indentation.\n" 3294 "}"); 3295 verifyFormat("void f() {\n" 3296 "label:\n" 3297 " signals.baz();\n" 3298 "}"); 3299 verifyFormat("private[1];"); 3300 verifyFormat("testArray[public] = 1;"); 3301 verifyFormat("public();"); 3302 verifyFormat("myFunc(public);"); 3303 verifyFormat("std::vector<int> testVec = {private};"); 3304 verifyFormat("private.p = 1;"); 3305 verifyFormat("void function(private...){};"); 3306 verifyFormat("if (private && public)\n"); 3307 verifyFormat("private &= true;"); 3308 verifyFormat("int x = private * public;"); 3309 verifyFormat("public *= private;"); 3310 verifyFormat("int x = public + private;"); 3311 verifyFormat("private++;"); 3312 verifyFormat("++private;"); 3313 verifyFormat("public += private;"); 3314 verifyFormat("public = public - private;"); 3315 verifyFormat("public->foo();"); 3316 verifyFormat("private--;"); 3317 verifyFormat("--private;"); 3318 verifyFormat("public -= 1;"); 3319 verifyFormat("if (!private && !public)\n"); 3320 verifyFormat("public != private;"); 3321 verifyFormat("int x = public / private;"); 3322 verifyFormat("public /= 2;"); 3323 verifyFormat("public = public % 2;"); 3324 verifyFormat("public %= 2;"); 3325 verifyFormat("if (public < private)\n"); 3326 verifyFormat("public << private;"); 3327 verifyFormat("public <<= private;"); 3328 verifyFormat("if (public > private)\n"); 3329 verifyFormat("public >> private;"); 3330 verifyFormat("public >>= private;"); 3331 verifyFormat("public ^ private;"); 3332 verifyFormat("public ^= private;"); 3333 verifyFormat("public | private;"); 3334 verifyFormat("public |= private;"); 3335 verifyFormat("auto x = private ? 1 : 2;"); 3336 verifyFormat("if (public == private)\n"); 3337 verifyFormat("void foo(public, private)"); 3338 verifyFormat("public::foo();"); 3339 3340 verifyFormat("class A {\n" 3341 "public:\n" 3342 " std::unique_ptr<int *[]> b() { return nullptr; }\n" 3343 "\n" 3344 "private:\n" 3345 " int c;\n" 3346 "};"); 3347 } 3348 3349 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3350 EXPECT_EQ("class A {\n" 3351 "public:\n" 3352 " void f();\n" 3353 "\n" 3354 "private:\n" 3355 " void g() {}\n" 3356 " // test\n" 3357 "protected:\n" 3358 " int h;\n" 3359 "};", 3360 format("class A {\n" 3361 "public:\n" 3362 "void f();\n" 3363 "private:\n" 3364 "void g() {}\n" 3365 "// test\n" 3366 "protected:\n" 3367 "int h;\n" 3368 "};")); 3369 EXPECT_EQ("class A {\n" 3370 "protected:\n" 3371 "public:\n" 3372 " void f();\n" 3373 "};", 3374 format("class A {\n" 3375 "protected:\n" 3376 "\n" 3377 "public:\n" 3378 "\n" 3379 " void f();\n" 3380 "};")); 3381 3382 // Even ensure proper spacing inside macros. 3383 EXPECT_EQ("#define B \\\n" 3384 " class A { \\\n" 3385 " protected: \\\n" 3386 " public: \\\n" 3387 " void f(); \\\n" 3388 " };", 3389 format("#define B \\\n" 3390 " class A { \\\n" 3391 " protected: \\\n" 3392 " \\\n" 3393 " public: \\\n" 3394 " \\\n" 3395 " void f(); \\\n" 3396 " };", 3397 getGoogleStyle())); 3398 // But don't remove empty lines after macros ending in access specifiers. 3399 EXPECT_EQ("#define A private:\n" 3400 "\n" 3401 "int i;", 3402 format("#define A private:\n" 3403 "\n" 3404 "int i;")); 3405 } 3406 3407 TEST_F(FormatTest, FormatsClasses) { 3408 verifyFormat("class A : public B {};"); 3409 verifyFormat("class A : public ::B {};"); 3410 3411 verifyFormat( 3412 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3413 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3414 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3415 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3416 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3417 verifyFormat( 3418 "class A : public B, public C, public D, public E, public F {};"); 3419 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3420 " public C,\n" 3421 " public D,\n" 3422 " public E,\n" 3423 " public F,\n" 3424 " public G {};"); 3425 3426 verifyFormat("class\n" 3427 " ReallyReallyLongClassName {\n" 3428 " int i;\n" 3429 "};", 3430 getLLVMStyleWithColumns(32)); 3431 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3432 " aaaaaaaaaaaaaaaa> {};"); 3433 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3434 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3435 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3436 verifyFormat("template <class R, class C>\n" 3437 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3438 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3439 verifyFormat("class ::A::B {};"); 3440 } 3441 3442 TEST_F(FormatTest, BreakInheritanceStyle) { 3443 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3444 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3445 FormatStyle::BILS_BeforeComma; 3446 verifyFormat("class MyClass : public X {};", 3447 StyleWithInheritanceBreakBeforeComma); 3448 verifyFormat("class MyClass\n" 3449 " : public X\n" 3450 " , public Y {};", 3451 StyleWithInheritanceBreakBeforeComma); 3452 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3453 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3454 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3455 StyleWithInheritanceBreakBeforeComma); 3456 verifyFormat("struct aaaaaaaaaaaaa\n" 3457 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3458 " aaaaaaaaaaaaaaaa> {};", 3459 StyleWithInheritanceBreakBeforeComma); 3460 3461 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3462 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3463 FormatStyle::BILS_AfterColon; 3464 verifyFormat("class MyClass : public X {};", 3465 StyleWithInheritanceBreakAfterColon); 3466 verifyFormat("class MyClass : public X, public Y {};", 3467 StyleWithInheritanceBreakAfterColon); 3468 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3469 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3470 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3471 StyleWithInheritanceBreakAfterColon); 3472 verifyFormat("struct aaaaaaaaaaaaa :\n" 3473 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3474 " aaaaaaaaaaaaaaaa> {};", 3475 StyleWithInheritanceBreakAfterColon); 3476 3477 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3478 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3479 FormatStyle::BILS_AfterComma; 3480 verifyFormat("class MyClass : public X {};", 3481 StyleWithInheritanceBreakAfterComma); 3482 verifyFormat("class MyClass : public X,\n" 3483 " public Y {};", 3484 StyleWithInheritanceBreakAfterComma); 3485 verifyFormat( 3486 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3487 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3488 "{};", 3489 StyleWithInheritanceBreakAfterComma); 3490 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3491 " aaaaaaaaaaaaaaaa> {};", 3492 StyleWithInheritanceBreakAfterComma); 3493 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3494 " : public OnceBreak,\n" 3495 " public AlwaysBreak,\n" 3496 " EvenBasesFitInOneLine {};", 3497 StyleWithInheritanceBreakAfterComma); 3498 } 3499 3500 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3501 verifyFormat("class A {\n} a, b;"); 3502 verifyFormat("struct A {\n} a, b;"); 3503 verifyFormat("union A {\n} a, b;"); 3504 3505 verifyFormat("constexpr class A {\n} a, b;"); 3506 verifyFormat("constexpr struct A {\n} a, b;"); 3507 verifyFormat("constexpr union A {\n} a, b;"); 3508 3509 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3510 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3511 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3512 3513 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3514 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3515 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3516 3517 verifyFormat("namespace ns {\n" 3518 "class {\n" 3519 "} a, b;\n" 3520 "} // namespace ns"); 3521 verifyFormat("namespace ns {\n" 3522 "const class {\n" 3523 "} a, b;\n" 3524 "} // namespace ns"); 3525 verifyFormat("namespace ns {\n" 3526 "constexpr class C {\n" 3527 "} a, b;\n" 3528 "} // namespace ns"); 3529 verifyFormat("namespace ns {\n" 3530 "class { /* comment */\n" 3531 "} a, b;\n" 3532 "} // namespace ns"); 3533 verifyFormat("namespace ns {\n" 3534 "const class { /* comment */\n" 3535 "} a, b;\n" 3536 "} // namespace ns"); 3537 } 3538 3539 TEST_F(FormatTest, FormatsEnum) { 3540 verifyFormat("enum {\n" 3541 " Zero,\n" 3542 " One = 1,\n" 3543 " Two = One + 1,\n" 3544 " Three = (One + Two),\n" 3545 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3546 " Five = (One, Two, Three, Four, 5)\n" 3547 "};"); 3548 verifyGoogleFormat("enum {\n" 3549 " Zero,\n" 3550 " One = 1,\n" 3551 " Two = One + 1,\n" 3552 " Three = (One + Two),\n" 3553 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3554 " Five = (One, Two, Three, Four, 5)\n" 3555 "};"); 3556 verifyFormat("enum Enum {};"); 3557 verifyFormat("enum {};"); 3558 verifyFormat("enum X E {} d;"); 3559 verifyFormat("enum __attribute__((...)) E {} d;"); 3560 verifyFormat("enum __declspec__((...)) E {} d;"); 3561 verifyFormat("enum {\n" 3562 " Bar = Foo<int, int>::value\n" 3563 "};", 3564 getLLVMStyleWithColumns(30)); 3565 3566 verifyFormat("enum ShortEnum { A, B, C };"); 3567 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3568 3569 EXPECT_EQ("enum KeepEmptyLines {\n" 3570 " ONE,\n" 3571 "\n" 3572 " TWO,\n" 3573 "\n" 3574 " THREE\n" 3575 "}", 3576 format("enum KeepEmptyLines {\n" 3577 " ONE,\n" 3578 "\n" 3579 " TWO,\n" 3580 "\n" 3581 "\n" 3582 " THREE\n" 3583 "}")); 3584 verifyFormat("enum E { // comment\n" 3585 " ONE,\n" 3586 " TWO\n" 3587 "};\n" 3588 "int i;"); 3589 3590 FormatStyle EightIndent = getLLVMStyle(); 3591 EightIndent.IndentWidth = 8; 3592 verifyFormat("enum {\n" 3593 " VOID,\n" 3594 " CHAR,\n" 3595 " SHORT,\n" 3596 " INT,\n" 3597 " LONG,\n" 3598 " SIGNED,\n" 3599 " UNSIGNED,\n" 3600 " BOOL,\n" 3601 " FLOAT,\n" 3602 " DOUBLE,\n" 3603 " COMPLEX\n" 3604 "};", 3605 EightIndent); 3606 3607 // Not enums. 3608 verifyFormat("enum X f() {\n" 3609 " a();\n" 3610 " return 42;\n" 3611 "}"); 3612 verifyFormat("enum X Type::f() {\n" 3613 " a();\n" 3614 " return 42;\n" 3615 "}"); 3616 verifyFormat("enum ::X f() {\n" 3617 " a();\n" 3618 " return 42;\n" 3619 "}"); 3620 verifyFormat("enum ns::X f() {\n" 3621 " a();\n" 3622 " return 42;\n" 3623 "}"); 3624 } 3625 3626 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3627 verifyFormat("enum Type {\n" 3628 " One = 0; // These semicolons should be commas.\n" 3629 " Two = 1;\n" 3630 "};"); 3631 verifyFormat("namespace n {\n" 3632 "enum Type {\n" 3633 " One,\n" 3634 " Two, // missing };\n" 3635 " int i;\n" 3636 "}\n" 3637 "void g() {}"); 3638 } 3639 3640 TEST_F(FormatTest, FormatsEnumStruct) { 3641 verifyFormat("enum struct {\n" 3642 " Zero,\n" 3643 " One = 1,\n" 3644 " Two = One + 1,\n" 3645 " Three = (One + Two),\n" 3646 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3647 " Five = (One, Two, Three, Four, 5)\n" 3648 "};"); 3649 verifyFormat("enum struct Enum {};"); 3650 verifyFormat("enum struct {};"); 3651 verifyFormat("enum struct X E {} d;"); 3652 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3653 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3654 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3655 } 3656 3657 TEST_F(FormatTest, FormatsEnumClass) { 3658 verifyFormat("enum class {\n" 3659 " Zero,\n" 3660 " One = 1,\n" 3661 " Two = One + 1,\n" 3662 " Three = (One + Two),\n" 3663 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3664 " Five = (One, Two, Three, Four, 5)\n" 3665 "};"); 3666 verifyFormat("enum class Enum {};"); 3667 verifyFormat("enum class {};"); 3668 verifyFormat("enum class X E {} d;"); 3669 verifyFormat("enum class __attribute__((...)) E {} d;"); 3670 verifyFormat("enum class __declspec__((...)) E {} d;"); 3671 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3672 } 3673 3674 TEST_F(FormatTest, FormatsEnumTypes) { 3675 verifyFormat("enum X : int {\n" 3676 " A, // Force multiple lines.\n" 3677 " B\n" 3678 "};"); 3679 verifyFormat("enum X : int { A, B };"); 3680 verifyFormat("enum X : std::uint32_t { A, B };"); 3681 } 3682 3683 TEST_F(FormatTest, FormatsTypedefEnum) { 3684 FormatStyle Style = getLLVMStyleWithColumns(40); 3685 verifyFormat("typedef enum {} EmptyEnum;"); 3686 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3687 verifyFormat("typedef enum {\n" 3688 " ZERO = 0,\n" 3689 " ONE = 1,\n" 3690 " TWO = 2,\n" 3691 " THREE = 3\n" 3692 "} LongEnum;", 3693 Style); 3694 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3695 Style.BraceWrapping.AfterEnum = true; 3696 verifyFormat("typedef enum {} EmptyEnum;"); 3697 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3698 verifyFormat("typedef enum\n" 3699 "{\n" 3700 " ZERO = 0,\n" 3701 " ONE = 1,\n" 3702 " TWO = 2,\n" 3703 " THREE = 3\n" 3704 "} LongEnum;", 3705 Style); 3706 } 3707 3708 TEST_F(FormatTest, FormatsNSEnums) { 3709 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3710 verifyGoogleFormat( 3711 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3712 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3713 " // Information about someDecentlyLongValue.\n" 3714 " someDecentlyLongValue,\n" 3715 " // Information about anotherDecentlyLongValue.\n" 3716 " anotherDecentlyLongValue,\n" 3717 " // Information about aThirdDecentlyLongValue.\n" 3718 " aThirdDecentlyLongValue\n" 3719 "};"); 3720 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3721 " // Information about someDecentlyLongValue.\n" 3722 " someDecentlyLongValue,\n" 3723 " // Information about anotherDecentlyLongValue.\n" 3724 " anotherDecentlyLongValue,\n" 3725 " // Information about aThirdDecentlyLongValue.\n" 3726 " aThirdDecentlyLongValue\n" 3727 "};"); 3728 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3729 " a = 1,\n" 3730 " b = 2,\n" 3731 " c = 3,\n" 3732 "};"); 3733 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3734 " a = 1,\n" 3735 " b = 2,\n" 3736 " c = 3,\n" 3737 "};"); 3738 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3739 " a = 1,\n" 3740 " b = 2,\n" 3741 " c = 3,\n" 3742 "};"); 3743 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3744 " a = 1,\n" 3745 " b = 2,\n" 3746 " c = 3,\n" 3747 "};"); 3748 } 3749 3750 TEST_F(FormatTest, FormatsBitfields) { 3751 verifyFormat("struct Bitfields {\n" 3752 " unsigned sClass : 8;\n" 3753 " unsigned ValueKind : 2;\n" 3754 "};"); 3755 verifyFormat("struct A {\n" 3756 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3757 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3758 "};"); 3759 verifyFormat("struct MyStruct {\n" 3760 " uchar data;\n" 3761 " uchar : 8;\n" 3762 " uchar : 8;\n" 3763 " uchar other;\n" 3764 "};"); 3765 FormatStyle Style = getLLVMStyle(); 3766 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3767 verifyFormat("struct Bitfields {\n" 3768 " unsigned sClass:8;\n" 3769 " unsigned ValueKind:2;\n" 3770 " uchar other;\n" 3771 "};", 3772 Style); 3773 verifyFormat("struct A {\n" 3774 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3775 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3776 "};", 3777 Style); 3778 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3779 verifyFormat("struct Bitfields {\n" 3780 " unsigned sClass :8;\n" 3781 " unsigned ValueKind :2;\n" 3782 " uchar other;\n" 3783 "};", 3784 Style); 3785 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3786 verifyFormat("struct Bitfields {\n" 3787 " unsigned sClass: 8;\n" 3788 " unsigned ValueKind: 2;\n" 3789 " uchar other;\n" 3790 "};", 3791 Style); 3792 } 3793 3794 TEST_F(FormatTest, FormatsNamespaces) { 3795 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3796 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3797 3798 verifyFormat("namespace some_namespace {\n" 3799 "class A {};\n" 3800 "void f() { f(); }\n" 3801 "}", 3802 LLVMWithNoNamespaceFix); 3803 verifyFormat("#define M(x) x##x\n" 3804 "namespace M(x) {\n" 3805 "class A {};\n" 3806 "void f() { f(); }\n" 3807 "}", 3808 LLVMWithNoNamespaceFix); 3809 verifyFormat("#define M(x) x##x\n" 3810 "namespace N::inline M(x) {\n" 3811 "class A {};\n" 3812 "void f() { f(); }\n" 3813 "}", 3814 LLVMWithNoNamespaceFix); 3815 verifyFormat("#define M(x) x##x\n" 3816 "namespace M(x)::inline N {\n" 3817 "class A {};\n" 3818 "void f() { f(); }\n" 3819 "}", 3820 LLVMWithNoNamespaceFix); 3821 verifyFormat("#define M(x) x##x\n" 3822 "namespace N::M(x) {\n" 3823 "class A {};\n" 3824 "void f() { f(); }\n" 3825 "}", 3826 LLVMWithNoNamespaceFix); 3827 verifyFormat("#define M(x) x##x\n" 3828 "namespace M::N(x) {\n" 3829 "class A {};\n" 3830 "void f() { f(); }\n" 3831 "}", 3832 LLVMWithNoNamespaceFix); 3833 verifyFormat("namespace N::inline D {\n" 3834 "class A {};\n" 3835 "void f() { f(); }\n" 3836 "}", 3837 LLVMWithNoNamespaceFix); 3838 verifyFormat("namespace N::inline D::E {\n" 3839 "class A {};\n" 3840 "void f() { f(); }\n" 3841 "}", 3842 LLVMWithNoNamespaceFix); 3843 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3844 "class A {};\n" 3845 "void f() { f(); }\n" 3846 "}", 3847 LLVMWithNoNamespaceFix); 3848 verifyFormat("/* something */ namespace some_namespace {\n" 3849 "class A {};\n" 3850 "void f() { f(); }\n" 3851 "}", 3852 LLVMWithNoNamespaceFix); 3853 verifyFormat("namespace {\n" 3854 "class A {};\n" 3855 "void f() { f(); }\n" 3856 "}", 3857 LLVMWithNoNamespaceFix); 3858 verifyFormat("/* something */ namespace {\n" 3859 "class A {};\n" 3860 "void f() { f(); }\n" 3861 "}", 3862 LLVMWithNoNamespaceFix); 3863 verifyFormat("inline namespace X {\n" 3864 "class A {};\n" 3865 "void f() { f(); }\n" 3866 "}", 3867 LLVMWithNoNamespaceFix); 3868 verifyFormat("/* something */ inline namespace X {\n" 3869 "class A {};\n" 3870 "void f() { f(); }\n" 3871 "}", 3872 LLVMWithNoNamespaceFix); 3873 verifyFormat("export namespace X {\n" 3874 "class A {};\n" 3875 "void f() { f(); }\n" 3876 "}", 3877 LLVMWithNoNamespaceFix); 3878 verifyFormat("using namespace some_namespace;\n" 3879 "class A {};\n" 3880 "void f() { f(); }", 3881 LLVMWithNoNamespaceFix); 3882 3883 // This code is more common than we thought; if we 3884 // layout this correctly the semicolon will go into 3885 // its own line, which is undesirable. 3886 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3887 verifyFormat("namespace {\n" 3888 "class A {};\n" 3889 "};", 3890 LLVMWithNoNamespaceFix); 3891 3892 verifyFormat("namespace {\n" 3893 "int SomeVariable = 0; // comment\n" 3894 "} // namespace", 3895 LLVMWithNoNamespaceFix); 3896 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3897 "#define HEADER_GUARD\n" 3898 "namespace my_namespace {\n" 3899 "int i;\n" 3900 "} // my_namespace\n" 3901 "#endif // HEADER_GUARD", 3902 format("#ifndef HEADER_GUARD\n" 3903 " #define HEADER_GUARD\n" 3904 " namespace my_namespace {\n" 3905 "int i;\n" 3906 "} // my_namespace\n" 3907 "#endif // HEADER_GUARD", 3908 LLVMWithNoNamespaceFix)); 3909 3910 EXPECT_EQ("namespace A::B {\n" 3911 "class C {};\n" 3912 "}", 3913 format("namespace A::B {\n" 3914 "class C {};\n" 3915 "}", 3916 LLVMWithNoNamespaceFix)); 3917 3918 FormatStyle Style = getLLVMStyle(); 3919 Style.NamespaceIndentation = FormatStyle::NI_All; 3920 EXPECT_EQ("namespace out {\n" 3921 " int i;\n" 3922 " namespace in {\n" 3923 " int i;\n" 3924 " } // namespace in\n" 3925 "} // namespace out", 3926 format("namespace out {\n" 3927 "int i;\n" 3928 "namespace in {\n" 3929 "int i;\n" 3930 "} // namespace in\n" 3931 "} // namespace out", 3932 Style)); 3933 3934 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3935 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3936 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3937 FormatStyle::SFS_Inline; 3938 verifyFormat("namespace {\n" 3939 " void f() {\n" 3940 " return;\n" 3941 " }\n" 3942 "} // namespace\n", 3943 ShortInlineFunctions); 3944 verifyFormat("namespace { /* comment */\n" 3945 " void f() {\n" 3946 " return;\n" 3947 " }\n" 3948 "} // namespace\n", 3949 ShortInlineFunctions); 3950 verifyFormat("namespace { // comment\n" 3951 " void f() {\n" 3952 " return;\n" 3953 " }\n" 3954 "} // namespace\n", 3955 ShortInlineFunctions); 3956 verifyFormat("namespace {\n" 3957 " int some_int;\n" 3958 " void f() {\n" 3959 " return;\n" 3960 " }\n" 3961 "} // namespace\n", 3962 ShortInlineFunctions); 3963 verifyFormat("namespace interface {\n" 3964 " void f() {\n" 3965 " return;\n" 3966 " }\n" 3967 "} // namespace interface\n", 3968 ShortInlineFunctions); 3969 verifyFormat("namespace {\n" 3970 " class X {\n" 3971 " void f() { return; }\n" 3972 " };\n" 3973 "} // namespace\n", 3974 ShortInlineFunctions); 3975 verifyFormat("namespace {\n" 3976 " class X { /* comment */\n" 3977 " void f() { return; }\n" 3978 " };\n" 3979 "} // namespace\n", 3980 ShortInlineFunctions); 3981 verifyFormat("namespace {\n" 3982 " class X { // comment\n" 3983 " void f() { return; }\n" 3984 " };\n" 3985 "} // namespace\n", 3986 ShortInlineFunctions); 3987 verifyFormat("namespace {\n" 3988 " struct X {\n" 3989 " void f() { return; }\n" 3990 " };\n" 3991 "} // namespace\n", 3992 ShortInlineFunctions); 3993 verifyFormat("namespace {\n" 3994 " union X {\n" 3995 " void f() { return; }\n" 3996 " };\n" 3997 "} // namespace\n", 3998 ShortInlineFunctions); 3999 verifyFormat("extern \"C\" {\n" 4000 "void f() {\n" 4001 " return;\n" 4002 "}\n" 4003 "} // namespace\n", 4004 ShortInlineFunctions); 4005 verifyFormat("namespace {\n" 4006 " class X {\n" 4007 " void f() { return; }\n" 4008 " } x;\n" 4009 "} // namespace\n", 4010 ShortInlineFunctions); 4011 verifyFormat("namespace {\n" 4012 " [[nodiscard]] class X {\n" 4013 " void f() { return; }\n" 4014 " };\n" 4015 "} // namespace\n", 4016 ShortInlineFunctions); 4017 verifyFormat("namespace {\n" 4018 " static class X {\n" 4019 " void f() { return; }\n" 4020 " } x;\n" 4021 "} // namespace\n", 4022 ShortInlineFunctions); 4023 verifyFormat("namespace {\n" 4024 " constexpr class X {\n" 4025 " void f() { return; }\n" 4026 " } x;\n" 4027 "} // namespace\n", 4028 ShortInlineFunctions); 4029 4030 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4031 verifyFormat("extern \"C\" {\n" 4032 " void f() {\n" 4033 " return;\n" 4034 " }\n" 4035 "} // namespace\n", 4036 ShortInlineFunctions); 4037 4038 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4039 EXPECT_EQ("namespace out {\n" 4040 "int i;\n" 4041 "namespace in {\n" 4042 " int i;\n" 4043 "} // namespace in\n" 4044 "} // namespace out", 4045 format("namespace out {\n" 4046 "int i;\n" 4047 "namespace in {\n" 4048 "int i;\n" 4049 "} // namespace in\n" 4050 "} // namespace out", 4051 Style)); 4052 4053 Style.NamespaceIndentation = FormatStyle::NI_None; 4054 verifyFormat("template <class T>\n" 4055 "concept a_concept = X<>;\n" 4056 "namespace B {\n" 4057 "struct b_struct {};\n" 4058 "} // namespace B\n", 4059 Style); 4060 verifyFormat("template <int I>\n" 4061 "constexpr void foo()\n" 4062 " requires(I == 42)\n" 4063 "{}\n" 4064 "namespace ns {\n" 4065 "void foo() {}\n" 4066 "} // namespace ns\n", 4067 Style); 4068 } 4069 4070 TEST_F(FormatTest, NamespaceMacros) { 4071 FormatStyle Style = getLLVMStyle(); 4072 Style.NamespaceMacros.push_back("TESTSUITE"); 4073 4074 verifyFormat("TESTSUITE(A) {\n" 4075 "int foo();\n" 4076 "} // TESTSUITE(A)", 4077 Style); 4078 4079 verifyFormat("TESTSUITE(A, B) {\n" 4080 "int foo();\n" 4081 "} // TESTSUITE(A)", 4082 Style); 4083 4084 // Properly indent according to NamespaceIndentation style 4085 Style.NamespaceIndentation = FormatStyle::NI_All; 4086 verifyFormat("TESTSUITE(A) {\n" 4087 " int foo();\n" 4088 "} // TESTSUITE(A)", 4089 Style); 4090 verifyFormat("TESTSUITE(A) {\n" 4091 " namespace B {\n" 4092 " int foo();\n" 4093 " } // namespace B\n" 4094 "} // TESTSUITE(A)", 4095 Style); 4096 verifyFormat("namespace A {\n" 4097 " TESTSUITE(B) {\n" 4098 " int foo();\n" 4099 " } // TESTSUITE(B)\n" 4100 "} // namespace A", 4101 Style); 4102 4103 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4104 verifyFormat("TESTSUITE(A) {\n" 4105 "TESTSUITE(B) {\n" 4106 " int foo();\n" 4107 "} // TESTSUITE(B)\n" 4108 "} // TESTSUITE(A)", 4109 Style); 4110 verifyFormat("TESTSUITE(A) {\n" 4111 "namespace B {\n" 4112 " int foo();\n" 4113 "} // namespace B\n" 4114 "} // TESTSUITE(A)", 4115 Style); 4116 verifyFormat("namespace A {\n" 4117 "TESTSUITE(B) {\n" 4118 " int foo();\n" 4119 "} // TESTSUITE(B)\n" 4120 "} // namespace A", 4121 Style); 4122 4123 // Properly merge namespace-macros blocks in CompactNamespaces mode 4124 Style.NamespaceIndentation = FormatStyle::NI_None; 4125 Style.CompactNamespaces = true; 4126 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4127 "}} // TESTSUITE(A::B)", 4128 Style); 4129 4130 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4131 "}} // TESTSUITE(out::in)", 4132 format("TESTSUITE(out) {\n" 4133 "TESTSUITE(in) {\n" 4134 "} // TESTSUITE(in)\n" 4135 "} // TESTSUITE(out)", 4136 Style)); 4137 4138 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4139 "}} // TESTSUITE(out::in)", 4140 format("TESTSUITE(out) {\n" 4141 "TESTSUITE(in) {\n" 4142 "} // TESTSUITE(in)\n" 4143 "} // TESTSUITE(out)", 4144 Style)); 4145 4146 // Do not merge different namespaces/macros 4147 EXPECT_EQ("namespace out {\n" 4148 "TESTSUITE(in) {\n" 4149 "} // TESTSUITE(in)\n" 4150 "} // namespace out", 4151 format("namespace out {\n" 4152 "TESTSUITE(in) {\n" 4153 "} // TESTSUITE(in)\n" 4154 "} // namespace out", 4155 Style)); 4156 EXPECT_EQ("TESTSUITE(out) {\n" 4157 "namespace in {\n" 4158 "} // namespace in\n" 4159 "} // TESTSUITE(out)", 4160 format("TESTSUITE(out) {\n" 4161 "namespace in {\n" 4162 "} // namespace in\n" 4163 "} // TESTSUITE(out)", 4164 Style)); 4165 Style.NamespaceMacros.push_back("FOOBAR"); 4166 EXPECT_EQ("TESTSUITE(out) {\n" 4167 "FOOBAR(in) {\n" 4168 "} // FOOBAR(in)\n" 4169 "} // TESTSUITE(out)", 4170 format("TESTSUITE(out) {\n" 4171 "FOOBAR(in) {\n" 4172 "} // FOOBAR(in)\n" 4173 "} // TESTSUITE(out)", 4174 Style)); 4175 } 4176 4177 TEST_F(FormatTest, FormatsCompactNamespaces) { 4178 FormatStyle Style = getLLVMStyle(); 4179 Style.CompactNamespaces = true; 4180 Style.NamespaceMacros.push_back("TESTSUITE"); 4181 4182 verifyFormat("namespace A { namespace B {\n" 4183 "}} // namespace A::B", 4184 Style); 4185 4186 EXPECT_EQ("namespace out { namespace in {\n" 4187 "}} // namespace out::in", 4188 format("namespace out {\n" 4189 "namespace in {\n" 4190 "} // namespace in\n" 4191 "} // namespace out", 4192 Style)); 4193 4194 // Only namespaces which have both consecutive opening and end get compacted 4195 EXPECT_EQ("namespace out {\n" 4196 "namespace in1 {\n" 4197 "} // namespace in1\n" 4198 "namespace in2 {\n" 4199 "} // namespace in2\n" 4200 "} // namespace out", 4201 format("namespace out {\n" 4202 "namespace in1 {\n" 4203 "} // namespace in1\n" 4204 "namespace in2 {\n" 4205 "} // namespace in2\n" 4206 "} // namespace out", 4207 Style)); 4208 4209 EXPECT_EQ("namespace out {\n" 4210 "int i;\n" 4211 "namespace in {\n" 4212 "int j;\n" 4213 "} // namespace in\n" 4214 "int k;\n" 4215 "} // namespace out", 4216 format("namespace out { int i;\n" 4217 "namespace in { int j; } // namespace in\n" 4218 "int k; } // namespace out", 4219 Style)); 4220 4221 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4222 "}}} // namespace A::B::C\n", 4223 format("namespace A { namespace B {\n" 4224 "namespace C {\n" 4225 "}} // namespace B::C\n" 4226 "} // namespace A\n", 4227 Style)); 4228 4229 Style.ColumnLimit = 40; 4230 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4231 "namespace bbbbbbbbbb {\n" 4232 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4233 format("namespace aaaaaaaaaa {\n" 4234 "namespace bbbbbbbbbb {\n" 4235 "} // namespace bbbbbbbbbb\n" 4236 "} // namespace aaaaaaaaaa", 4237 Style)); 4238 4239 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4240 "namespace cccccc {\n" 4241 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4242 format("namespace aaaaaa {\n" 4243 "namespace bbbbbb {\n" 4244 "namespace cccccc {\n" 4245 "} // namespace cccccc\n" 4246 "} // namespace bbbbbb\n" 4247 "} // namespace aaaaaa", 4248 Style)); 4249 Style.ColumnLimit = 80; 4250 4251 // Extra semicolon after 'inner' closing brace prevents merging 4252 EXPECT_EQ("namespace out { namespace in {\n" 4253 "}; } // namespace out::in", 4254 format("namespace out {\n" 4255 "namespace in {\n" 4256 "}; // namespace in\n" 4257 "} // namespace out", 4258 Style)); 4259 4260 // Extra semicolon after 'outer' closing brace is conserved 4261 EXPECT_EQ("namespace out { namespace in {\n" 4262 "}}; // namespace out::in", 4263 format("namespace out {\n" 4264 "namespace in {\n" 4265 "} // namespace in\n" 4266 "}; // namespace out", 4267 Style)); 4268 4269 Style.NamespaceIndentation = FormatStyle::NI_All; 4270 EXPECT_EQ("namespace out { namespace in {\n" 4271 " int i;\n" 4272 "}} // namespace out::in", 4273 format("namespace out {\n" 4274 "namespace in {\n" 4275 "int i;\n" 4276 "} // namespace in\n" 4277 "} // namespace out", 4278 Style)); 4279 EXPECT_EQ("namespace out { namespace mid {\n" 4280 " namespace in {\n" 4281 " int j;\n" 4282 " } // namespace in\n" 4283 " int k;\n" 4284 "}} // namespace out::mid", 4285 format("namespace out { namespace mid {\n" 4286 "namespace in { int j; } // namespace in\n" 4287 "int k; }} // namespace out::mid", 4288 Style)); 4289 4290 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4291 EXPECT_EQ("namespace out { namespace in {\n" 4292 " int i;\n" 4293 "}} // namespace out::in", 4294 format("namespace out {\n" 4295 "namespace in {\n" 4296 "int i;\n" 4297 "} // namespace in\n" 4298 "} // namespace out", 4299 Style)); 4300 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4301 " int i;\n" 4302 "}}} // namespace out::mid::in", 4303 format("namespace out {\n" 4304 "namespace mid {\n" 4305 "namespace in {\n" 4306 "int i;\n" 4307 "} // namespace in\n" 4308 "} // namespace mid\n" 4309 "} // namespace out", 4310 Style)); 4311 4312 Style.CompactNamespaces = true; 4313 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4314 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4315 Style.BraceWrapping.BeforeLambdaBody = true; 4316 verifyFormat("namespace out { namespace in {\n" 4317 "}} // namespace out::in", 4318 Style); 4319 EXPECT_EQ("namespace out { namespace in {\n" 4320 "}} // namespace out::in", 4321 format("namespace out {\n" 4322 "namespace in {\n" 4323 "} // namespace in\n" 4324 "} // namespace out", 4325 Style)); 4326 } 4327 4328 TEST_F(FormatTest, FormatsExternC) { 4329 verifyFormat("extern \"C\" {\nint a;"); 4330 verifyFormat("extern \"C\" {}"); 4331 verifyFormat("extern \"C\" {\n" 4332 "int foo();\n" 4333 "}"); 4334 verifyFormat("extern \"C\" int foo() {}"); 4335 verifyFormat("extern \"C\" int foo();"); 4336 verifyFormat("extern \"C\" int foo() {\n" 4337 " int i = 42;\n" 4338 " return i;\n" 4339 "}"); 4340 4341 FormatStyle Style = getLLVMStyle(); 4342 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4343 Style.BraceWrapping.AfterFunction = true; 4344 verifyFormat("extern \"C\" int foo() {}", Style); 4345 verifyFormat("extern \"C\" int foo();", Style); 4346 verifyFormat("extern \"C\" int foo()\n" 4347 "{\n" 4348 " int i = 42;\n" 4349 " return i;\n" 4350 "}", 4351 Style); 4352 4353 Style.BraceWrapping.AfterExternBlock = true; 4354 Style.BraceWrapping.SplitEmptyRecord = false; 4355 verifyFormat("extern \"C\"\n" 4356 "{}", 4357 Style); 4358 verifyFormat("extern \"C\"\n" 4359 "{\n" 4360 " int foo();\n" 4361 "}", 4362 Style); 4363 } 4364 4365 TEST_F(FormatTest, IndentExternBlockStyle) { 4366 FormatStyle Style = getLLVMStyle(); 4367 Style.IndentWidth = 2; 4368 4369 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4370 verifyFormat("extern \"C\" { /*9*/\n" 4371 "}", 4372 Style); 4373 verifyFormat("extern \"C\" {\n" 4374 " int foo10();\n" 4375 "}", 4376 Style); 4377 4378 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4379 verifyFormat("extern \"C\" { /*11*/\n" 4380 "}", 4381 Style); 4382 verifyFormat("extern \"C\" {\n" 4383 "int foo12();\n" 4384 "}", 4385 Style); 4386 4387 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4388 Style.BraceWrapping.AfterExternBlock = true; 4389 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4390 verifyFormat("extern \"C\"\n" 4391 "{ /*13*/\n" 4392 "}", 4393 Style); 4394 verifyFormat("extern \"C\"\n{\n" 4395 " int foo14();\n" 4396 "}", 4397 Style); 4398 4399 Style.BraceWrapping.AfterExternBlock = false; 4400 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4401 verifyFormat("extern \"C\" { /*15*/\n" 4402 "}", 4403 Style); 4404 verifyFormat("extern \"C\" {\n" 4405 "int foo16();\n" 4406 "}", 4407 Style); 4408 4409 Style.BraceWrapping.AfterExternBlock = true; 4410 verifyFormat("extern \"C\"\n" 4411 "{ /*13*/\n" 4412 "}", 4413 Style); 4414 verifyFormat("extern \"C\"\n" 4415 "{\n" 4416 "int foo14();\n" 4417 "}", 4418 Style); 4419 4420 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4421 verifyFormat("extern \"C\"\n" 4422 "{ /*13*/\n" 4423 "}", 4424 Style); 4425 verifyFormat("extern \"C\"\n" 4426 "{\n" 4427 " int foo14();\n" 4428 "}", 4429 Style); 4430 } 4431 4432 TEST_F(FormatTest, FormatsInlineASM) { 4433 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4434 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4435 verifyFormat( 4436 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4437 " \"cpuid\\n\\t\"\n" 4438 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4439 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4440 " : \"a\"(value));"); 4441 EXPECT_EQ( 4442 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4443 " __asm {\n" 4444 " mov edx,[that] // vtable in edx\n" 4445 " mov eax,methodIndex\n" 4446 " call [edx][eax*4] // stdcall\n" 4447 " }\n" 4448 "}", 4449 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4450 " __asm {\n" 4451 " mov edx,[that] // vtable in edx\n" 4452 " mov eax,methodIndex\n" 4453 " call [edx][eax*4] // stdcall\n" 4454 " }\n" 4455 "}")); 4456 EXPECT_EQ("_asm {\n" 4457 " xor eax, eax;\n" 4458 " cpuid;\n" 4459 "}", 4460 format("_asm {\n" 4461 " xor eax, eax;\n" 4462 " cpuid;\n" 4463 "}")); 4464 verifyFormat("void function() {\n" 4465 " // comment\n" 4466 " asm(\"\");\n" 4467 "}"); 4468 EXPECT_EQ("__asm {\n" 4469 "}\n" 4470 "int i;", 4471 format("__asm {\n" 4472 "}\n" 4473 "int i;")); 4474 } 4475 4476 TEST_F(FormatTest, FormatTryCatch) { 4477 verifyFormat("try {\n" 4478 " throw a * b;\n" 4479 "} catch (int a) {\n" 4480 " // Do nothing.\n" 4481 "} catch (...) {\n" 4482 " exit(42);\n" 4483 "}"); 4484 4485 // Function-level try statements. 4486 verifyFormat("int f() try { return 4; } catch (...) {\n" 4487 " return 5;\n" 4488 "}"); 4489 verifyFormat("class A {\n" 4490 " int a;\n" 4491 " A() try : a(0) {\n" 4492 " } catch (...) {\n" 4493 " throw;\n" 4494 " }\n" 4495 "};\n"); 4496 verifyFormat("class A {\n" 4497 " int a;\n" 4498 " A() try : a(0), b{1} {\n" 4499 " } catch (...) {\n" 4500 " throw;\n" 4501 " }\n" 4502 "};\n"); 4503 verifyFormat("class A {\n" 4504 " int a;\n" 4505 " A() try : a(0), b{1}, c{2} {\n" 4506 " } catch (...) {\n" 4507 " throw;\n" 4508 " }\n" 4509 "};\n"); 4510 verifyFormat("class A {\n" 4511 " int a;\n" 4512 " A() try : a(0), b{1}, c{2} {\n" 4513 " { // New scope.\n" 4514 " }\n" 4515 " } catch (...) {\n" 4516 " throw;\n" 4517 " }\n" 4518 "};\n"); 4519 4520 // Incomplete try-catch blocks. 4521 verifyIncompleteFormat("try {} catch ("); 4522 } 4523 4524 TEST_F(FormatTest, FormatTryAsAVariable) { 4525 verifyFormat("int try;"); 4526 verifyFormat("int try, size;"); 4527 verifyFormat("try = foo();"); 4528 verifyFormat("if (try < size) {\n return true;\n}"); 4529 4530 verifyFormat("int catch;"); 4531 verifyFormat("int catch, size;"); 4532 verifyFormat("catch = foo();"); 4533 verifyFormat("if (catch < size) {\n return true;\n}"); 4534 4535 FormatStyle Style = getLLVMStyle(); 4536 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4537 Style.BraceWrapping.AfterFunction = true; 4538 Style.BraceWrapping.BeforeCatch = true; 4539 verifyFormat("try {\n" 4540 " int bar = 1;\n" 4541 "}\n" 4542 "catch (...) {\n" 4543 " int bar = 1;\n" 4544 "}", 4545 Style); 4546 verifyFormat("#if NO_EX\n" 4547 "try\n" 4548 "#endif\n" 4549 "{\n" 4550 "}\n" 4551 "#if NO_EX\n" 4552 "catch (...) {\n" 4553 "}", 4554 Style); 4555 verifyFormat("try /* abc */ {\n" 4556 " int bar = 1;\n" 4557 "}\n" 4558 "catch (...) {\n" 4559 " int bar = 1;\n" 4560 "}", 4561 Style); 4562 verifyFormat("try\n" 4563 "// abc\n" 4564 "{\n" 4565 " int bar = 1;\n" 4566 "}\n" 4567 "catch (...) {\n" 4568 " int bar = 1;\n" 4569 "}", 4570 Style); 4571 } 4572 4573 TEST_F(FormatTest, FormatSEHTryCatch) { 4574 verifyFormat("__try {\n" 4575 " int a = b * c;\n" 4576 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4577 " // Do nothing.\n" 4578 "}"); 4579 4580 verifyFormat("__try {\n" 4581 " int a = b * c;\n" 4582 "} __finally {\n" 4583 " // Do nothing.\n" 4584 "}"); 4585 4586 verifyFormat("DEBUG({\n" 4587 " __try {\n" 4588 " } __finally {\n" 4589 " }\n" 4590 "});\n"); 4591 } 4592 4593 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4594 verifyFormat("try {\n" 4595 " f();\n" 4596 "} catch {\n" 4597 " g();\n" 4598 "}"); 4599 verifyFormat("try {\n" 4600 " f();\n" 4601 "} catch (A a) MACRO(x) {\n" 4602 " g();\n" 4603 "} catch (B b) MACRO(x) {\n" 4604 " g();\n" 4605 "}"); 4606 } 4607 4608 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4609 FormatStyle Style = getLLVMStyle(); 4610 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4611 FormatStyle::BS_WebKit}) { 4612 Style.BreakBeforeBraces = BraceStyle; 4613 verifyFormat("try {\n" 4614 " // something\n" 4615 "} catch (...) {\n" 4616 " // something\n" 4617 "}", 4618 Style); 4619 } 4620 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4621 verifyFormat("try {\n" 4622 " // something\n" 4623 "}\n" 4624 "catch (...) {\n" 4625 " // something\n" 4626 "}", 4627 Style); 4628 verifyFormat("__try {\n" 4629 " // something\n" 4630 "}\n" 4631 "__finally {\n" 4632 " // something\n" 4633 "}", 4634 Style); 4635 verifyFormat("@try {\n" 4636 " // something\n" 4637 "}\n" 4638 "@finally {\n" 4639 " // something\n" 4640 "}", 4641 Style); 4642 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4643 verifyFormat("try\n" 4644 "{\n" 4645 " // something\n" 4646 "}\n" 4647 "catch (...)\n" 4648 "{\n" 4649 " // something\n" 4650 "}", 4651 Style); 4652 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4653 verifyFormat("try\n" 4654 " {\n" 4655 " // something white\n" 4656 " }\n" 4657 "catch (...)\n" 4658 " {\n" 4659 " // something white\n" 4660 " }", 4661 Style); 4662 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4663 verifyFormat("try\n" 4664 " {\n" 4665 " // something\n" 4666 " }\n" 4667 "catch (...)\n" 4668 " {\n" 4669 " // something\n" 4670 " }", 4671 Style); 4672 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4673 Style.BraceWrapping.BeforeCatch = true; 4674 verifyFormat("try {\n" 4675 " // something\n" 4676 "}\n" 4677 "catch (...) {\n" 4678 " // something\n" 4679 "}", 4680 Style); 4681 } 4682 4683 TEST_F(FormatTest, StaticInitializers) { 4684 verifyFormat("static SomeClass SC = {1, 'a'};"); 4685 4686 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4687 " 100000000, " 4688 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4689 4690 // Here, everything other than the "}" would fit on a line. 4691 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4692 " 10000000000000000000000000};"); 4693 EXPECT_EQ("S s = {a,\n" 4694 "\n" 4695 " b};", 4696 format("S s = {\n" 4697 " a,\n" 4698 "\n" 4699 " b\n" 4700 "};")); 4701 4702 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4703 // line. However, the formatting looks a bit off and this probably doesn't 4704 // happen often in practice. 4705 verifyFormat("static int Variable[1] = {\n" 4706 " {1000000000000000000000000000000000000}};", 4707 getLLVMStyleWithColumns(40)); 4708 } 4709 4710 TEST_F(FormatTest, DesignatedInitializers) { 4711 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4712 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4713 " .bbbbbbbbbb = 2,\n" 4714 " .cccccccccc = 3,\n" 4715 " .dddddddddd = 4,\n" 4716 " .eeeeeeeeee = 5};"); 4717 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4718 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4719 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4720 " .ccccccccccccccccccccccccccc = 3,\n" 4721 " .ddddddddddddddddddddddddddd = 4,\n" 4722 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4723 4724 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4725 4726 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4727 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4728 " [2] = bbbbbbbbbb,\n" 4729 " [3] = cccccccccc,\n" 4730 " [4] = dddddddddd,\n" 4731 " [5] = eeeeeeeeee};"); 4732 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4733 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4734 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4735 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4736 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4737 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4738 } 4739 4740 TEST_F(FormatTest, NestedStaticInitializers) { 4741 verifyFormat("static A x = {{{}}};\n"); 4742 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4743 " {init1, init2, init3, init4}}};", 4744 getLLVMStyleWithColumns(50)); 4745 4746 verifyFormat("somes Status::global_reps[3] = {\n" 4747 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4748 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4749 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4750 getLLVMStyleWithColumns(60)); 4751 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4752 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4753 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4754 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4755 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4756 " {rect.fRight - rect.fLeft, rect.fBottom - " 4757 "rect.fTop}};"); 4758 4759 verifyFormat( 4760 "SomeArrayOfSomeType a = {\n" 4761 " {{1, 2, 3},\n" 4762 " {1, 2, 3},\n" 4763 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4764 " 333333333333333333333333333333},\n" 4765 " {1, 2, 3},\n" 4766 " {1, 2, 3}}};"); 4767 verifyFormat( 4768 "SomeArrayOfSomeType a = {\n" 4769 " {{1, 2, 3}},\n" 4770 " {{1, 2, 3}},\n" 4771 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4772 " 333333333333333333333333333333}},\n" 4773 " {{1, 2, 3}},\n" 4774 " {{1, 2, 3}}};"); 4775 4776 verifyFormat("struct {\n" 4777 " unsigned bit;\n" 4778 " const char *const name;\n" 4779 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4780 " {kOsWin, \"Windows\"},\n" 4781 " {kOsLinux, \"Linux\"},\n" 4782 " {kOsCrOS, \"Chrome OS\"}};"); 4783 verifyFormat("struct {\n" 4784 " unsigned bit;\n" 4785 " const char *const name;\n" 4786 "} kBitsToOs[] = {\n" 4787 " {kOsMac, \"Mac\"},\n" 4788 " {kOsWin, \"Windows\"},\n" 4789 " {kOsLinux, \"Linux\"},\n" 4790 " {kOsCrOS, \"Chrome OS\"},\n" 4791 "};"); 4792 } 4793 4794 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4795 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4796 " \\\n" 4797 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4798 } 4799 4800 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4801 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4802 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4803 4804 // Do break defaulted and deleted functions. 4805 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4806 " default;", 4807 getLLVMStyleWithColumns(40)); 4808 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4809 " delete;", 4810 getLLVMStyleWithColumns(40)); 4811 } 4812 4813 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4814 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4815 getLLVMStyleWithColumns(40)); 4816 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4817 getLLVMStyleWithColumns(40)); 4818 EXPECT_EQ("#define Q \\\n" 4819 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4820 " \"aaaaaaaa.cpp\"", 4821 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4822 getLLVMStyleWithColumns(40))); 4823 } 4824 4825 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4826 EXPECT_EQ("# 123 \"A string literal\"", 4827 format(" # 123 \"A string literal\"")); 4828 } 4829 4830 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4831 EXPECT_EQ("#;", format("#;")); 4832 verifyFormat("#\n;\n;\n;"); 4833 } 4834 4835 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4836 EXPECT_EQ("#line 42 \"test\"\n", 4837 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4838 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4839 getLLVMStyleWithColumns(12))); 4840 } 4841 4842 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4843 EXPECT_EQ("#line 42 \"test\"", 4844 format("# \\\n line \\\n 42 \\\n \"test\"")); 4845 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4846 } 4847 4848 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4849 verifyFormat("#define A \\x20"); 4850 verifyFormat("#define A \\ x20"); 4851 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4852 verifyFormat("#define A ''"); 4853 verifyFormat("#define A ''qqq"); 4854 verifyFormat("#define A `qqq"); 4855 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4856 EXPECT_EQ("const char *c = STRINGIFY(\n" 4857 "\\na : b);", 4858 format("const char * c = STRINGIFY(\n" 4859 "\\na : b);")); 4860 4861 verifyFormat("a\r\\"); 4862 verifyFormat("a\v\\"); 4863 verifyFormat("a\f\\"); 4864 } 4865 4866 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4867 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4868 style.IndentWidth = 4; 4869 style.PPIndentWidth = 1; 4870 4871 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4872 verifyFormat("#ifdef __linux__\n" 4873 "void foo() {\n" 4874 " int x = 0;\n" 4875 "}\n" 4876 "#define FOO\n" 4877 "#endif\n" 4878 "void bar() {\n" 4879 " int y = 0;\n" 4880 "}\n", 4881 style); 4882 4883 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4884 verifyFormat("#ifdef __linux__\n" 4885 "void foo() {\n" 4886 " int x = 0;\n" 4887 "}\n" 4888 "# define FOO foo\n" 4889 "#endif\n" 4890 "void bar() {\n" 4891 " int y = 0;\n" 4892 "}\n", 4893 style); 4894 4895 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4896 verifyFormat("#ifdef __linux__\n" 4897 "void foo() {\n" 4898 " int x = 0;\n" 4899 "}\n" 4900 " #define FOO foo\n" 4901 "#endif\n" 4902 "void bar() {\n" 4903 " int y = 0;\n" 4904 "}\n", 4905 style); 4906 } 4907 4908 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4909 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4910 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4911 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4912 // FIXME: We never break before the macro name. 4913 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4914 4915 verifyFormat("#define A A\n#define A A"); 4916 verifyFormat("#define A(X) A\n#define A A"); 4917 4918 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4919 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4920 } 4921 4922 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4923 EXPECT_EQ("// somecomment\n" 4924 "#include \"a.h\"\n" 4925 "#define A( \\\n" 4926 " A, B)\n" 4927 "#include \"b.h\"\n" 4928 "// somecomment\n", 4929 format(" // somecomment\n" 4930 " #include \"a.h\"\n" 4931 "#define A(A,\\\n" 4932 " B)\n" 4933 " #include \"b.h\"\n" 4934 " // somecomment\n", 4935 getLLVMStyleWithColumns(13))); 4936 } 4937 4938 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4939 4940 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4941 EXPECT_EQ("#define A \\\n" 4942 " c; \\\n" 4943 " e;\n" 4944 "f;", 4945 format("#define A c; e;\n" 4946 "f;", 4947 getLLVMStyleWithColumns(14))); 4948 } 4949 4950 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4951 4952 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4953 EXPECT_EQ("int x,\n" 4954 "#define A\n" 4955 " y;", 4956 format("int x,\n#define A\ny;")); 4957 } 4958 4959 TEST_F(FormatTest, HashInMacroDefinition) { 4960 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4961 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4962 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4963 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4964 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4965 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4966 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4967 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4968 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4969 verifyFormat("#define A \\\n" 4970 " { \\\n" 4971 " f(#c); \\\n" 4972 " }", 4973 getLLVMStyleWithColumns(11)); 4974 4975 verifyFormat("#define A(X) \\\n" 4976 " void function##X()", 4977 getLLVMStyleWithColumns(22)); 4978 4979 verifyFormat("#define A(a, b, c) \\\n" 4980 " void a##b##c()", 4981 getLLVMStyleWithColumns(22)); 4982 4983 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4984 } 4985 4986 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4987 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4988 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4989 4990 FormatStyle Style = getLLVMStyle(); 4991 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4992 verifyFormat("#define true ((foo)1)", Style); 4993 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4994 verifyFormat("#define false((foo)0)", Style); 4995 } 4996 4997 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4998 EXPECT_EQ("#define A b;", format("#define A \\\n" 4999 " \\\n" 5000 " b;", 5001 getLLVMStyleWithColumns(25))); 5002 EXPECT_EQ("#define A \\\n" 5003 " \\\n" 5004 " a; \\\n" 5005 " b;", 5006 format("#define A \\\n" 5007 " \\\n" 5008 " a; \\\n" 5009 " b;", 5010 getLLVMStyleWithColumns(11))); 5011 EXPECT_EQ("#define A \\\n" 5012 " a; \\\n" 5013 " \\\n" 5014 " b;", 5015 format("#define A \\\n" 5016 " a; \\\n" 5017 " \\\n" 5018 " b;", 5019 getLLVMStyleWithColumns(11))); 5020 } 5021 5022 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5023 verifyIncompleteFormat("#define A :"); 5024 verifyFormat("#define SOMECASES \\\n" 5025 " case 1: \\\n" 5026 " case 2\n", 5027 getLLVMStyleWithColumns(20)); 5028 verifyFormat("#define MACRO(a) \\\n" 5029 " if (a) \\\n" 5030 " f(); \\\n" 5031 " else \\\n" 5032 " g()", 5033 getLLVMStyleWithColumns(18)); 5034 verifyFormat("#define A template <typename T>"); 5035 verifyIncompleteFormat("#define STR(x) #x\n" 5036 "f(STR(this_is_a_string_literal{));"); 5037 verifyFormat("#pragma omp threadprivate( \\\n" 5038 " y)), // expected-warning", 5039 getLLVMStyleWithColumns(28)); 5040 verifyFormat("#d, = };"); 5041 verifyFormat("#if \"a"); 5042 verifyIncompleteFormat("({\n" 5043 "#define b \\\n" 5044 " } \\\n" 5045 " a\n" 5046 "a", 5047 getLLVMStyleWithColumns(15)); 5048 verifyFormat("#define A \\\n" 5049 " { \\\n" 5050 " {\n" 5051 "#define B \\\n" 5052 " } \\\n" 5053 " }", 5054 getLLVMStyleWithColumns(15)); 5055 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5056 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5057 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5058 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5059 } 5060 5061 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5062 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5063 EXPECT_EQ("class A : public QObject {\n" 5064 " Q_OBJECT\n" 5065 "\n" 5066 " A() {}\n" 5067 "};", 5068 format("class A : public QObject {\n" 5069 " Q_OBJECT\n" 5070 "\n" 5071 " A() {\n}\n" 5072 "} ;")); 5073 EXPECT_EQ("MACRO\n" 5074 "/*static*/ int i;", 5075 format("MACRO\n" 5076 " /*static*/ int i;")); 5077 EXPECT_EQ("SOME_MACRO\n" 5078 "namespace {\n" 5079 "void f();\n" 5080 "} // namespace", 5081 format("SOME_MACRO\n" 5082 " namespace {\n" 5083 "void f( );\n" 5084 "} // namespace")); 5085 // Only if the identifier contains at least 5 characters. 5086 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5087 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5088 // Only if everything is upper case. 5089 EXPECT_EQ("class A : public QObject {\n" 5090 " Q_Object A() {}\n" 5091 "};", 5092 format("class A : public QObject {\n" 5093 " Q_Object\n" 5094 " A() {\n}\n" 5095 "} ;")); 5096 5097 // Only if the next line can actually start an unwrapped line. 5098 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5099 format("SOME_WEIRD_LOG_MACRO\n" 5100 "<< SomeThing;")); 5101 5102 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5103 "(n, buffers))\n", 5104 getChromiumStyle(FormatStyle::LK_Cpp)); 5105 5106 // See PR41483 5107 EXPECT_EQ("/**/ FOO(a)\n" 5108 "FOO(b)", 5109 format("/**/ FOO(a)\n" 5110 "FOO(b)")); 5111 } 5112 5113 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5114 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5115 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5116 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5117 "class X {};\n" 5118 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5119 "int *createScopDetectionPass() { return 0; }", 5120 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5121 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5122 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5123 " class X {};\n" 5124 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5125 " int *createScopDetectionPass() { return 0; }")); 5126 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5127 // braces, so that inner block is indented one level more. 5128 EXPECT_EQ("int q() {\n" 5129 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5130 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5131 " IPC_END_MESSAGE_MAP()\n" 5132 "}", 5133 format("int q() {\n" 5134 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5135 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5136 " IPC_END_MESSAGE_MAP()\n" 5137 "}")); 5138 5139 // Same inside macros. 5140 EXPECT_EQ("#define LIST(L) \\\n" 5141 " L(A) \\\n" 5142 " L(B) \\\n" 5143 " L(C)", 5144 format("#define LIST(L) \\\n" 5145 " L(A) \\\n" 5146 " L(B) \\\n" 5147 " L(C)", 5148 getGoogleStyle())); 5149 5150 // These must not be recognized as macros. 5151 EXPECT_EQ("int q() {\n" 5152 " f(x);\n" 5153 " f(x) {}\n" 5154 " f(x)->g();\n" 5155 " f(x)->*g();\n" 5156 " f(x).g();\n" 5157 " f(x) = x;\n" 5158 " f(x) += x;\n" 5159 " f(x) -= x;\n" 5160 " f(x) *= x;\n" 5161 " f(x) /= x;\n" 5162 " f(x) %= x;\n" 5163 " f(x) &= x;\n" 5164 " f(x) |= x;\n" 5165 " f(x) ^= x;\n" 5166 " f(x) >>= x;\n" 5167 " f(x) <<= x;\n" 5168 " f(x)[y].z();\n" 5169 " LOG(INFO) << x;\n" 5170 " ifstream(x) >> x;\n" 5171 "}\n", 5172 format("int q() {\n" 5173 " f(x)\n;\n" 5174 " f(x)\n {}\n" 5175 " f(x)\n->g();\n" 5176 " f(x)\n->*g();\n" 5177 " f(x)\n.g();\n" 5178 " f(x)\n = x;\n" 5179 " f(x)\n += x;\n" 5180 " f(x)\n -= x;\n" 5181 " f(x)\n *= x;\n" 5182 " f(x)\n /= x;\n" 5183 " f(x)\n %= x;\n" 5184 " f(x)\n &= x;\n" 5185 " f(x)\n |= x;\n" 5186 " f(x)\n ^= x;\n" 5187 " f(x)\n >>= x;\n" 5188 " f(x)\n <<= x;\n" 5189 " f(x)\n[y].z();\n" 5190 " LOG(INFO)\n << x;\n" 5191 " ifstream(x)\n >> x;\n" 5192 "}\n")); 5193 EXPECT_EQ("int q() {\n" 5194 " F(x)\n" 5195 " if (1) {\n" 5196 " }\n" 5197 " F(x)\n" 5198 " while (1) {\n" 5199 " }\n" 5200 " F(x)\n" 5201 " G(x);\n" 5202 " F(x)\n" 5203 " try {\n" 5204 " Q();\n" 5205 " } catch (...) {\n" 5206 " }\n" 5207 "}\n", 5208 format("int q() {\n" 5209 "F(x)\n" 5210 "if (1) {}\n" 5211 "F(x)\n" 5212 "while (1) {}\n" 5213 "F(x)\n" 5214 "G(x);\n" 5215 "F(x)\n" 5216 "try { Q(); } catch (...) {}\n" 5217 "}\n")); 5218 EXPECT_EQ("class A {\n" 5219 " A() : t(0) {}\n" 5220 " A(int i) noexcept() : {}\n" 5221 " A(X x)\n" // FIXME: function-level try blocks are broken. 5222 " try : t(0) {\n" 5223 " } catch (...) {\n" 5224 " }\n" 5225 "};", 5226 format("class A {\n" 5227 " A()\n : t(0) {}\n" 5228 " A(int i)\n noexcept() : {}\n" 5229 " A(X x)\n" 5230 " try : t(0) {} catch (...) {}\n" 5231 "};")); 5232 FormatStyle Style = getLLVMStyle(); 5233 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5234 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5235 Style.BraceWrapping.AfterFunction = true; 5236 EXPECT_EQ("void f()\n" 5237 "try\n" 5238 "{\n" 5239 "}", 5240 format("void f() try {\n" 5241 "}", 5242 Style)); 5243 EXPECT_EQ("class SomeClass {\n" 5244 "public:\n" 5245 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5246 "};", 5247 format("class SomeClass {\n" 5248 "public:\n" 5249 " SomeClass()\n" 5250 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5251 "};")); 5252 EXPECT_EQ("class SomeClass {\n" 5253 "public:\n" 5254 " SomeClass()\n" 5255 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5256 "};", 5257 format("class SomeClass {\n" 5258 "public:\n" 5259 " SomeClass()\n" 5260 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5261 "};", 5262 getLLVMStyleWithColumns(40))); 5263 5264 verifyFormat("MACRO(>)"); 5265 5266 // Some macros contain an implicit semicolon. 5267 Style = getLLVMStyle(); 5268 Style.StatementMacros.push_back("FOO"); 5269 verifyFormat("FOO(a) int b = 0;"); 5270 verifyFormat("FOO(a)\n" 5271 "int b = 0;", 5272 Style); 5273 verifyFormat("FOO(a);\n" 5274 "int b = 0;", 5275 Style); 5276 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5277 "int b = 0;", 5278 Style); 5279 verifyFormat("FOO()\n" 5280 "int b = 0;", 5281 Style); 5282 verifyFormat("FOO\n" 5283 "int b = 0;", 5284 Style); 5285 verifyFormat("void f() {\n" 5286 " FOO(a)\n" 5287 " return a;\n" 5288 "}", 5289 Style); 5290 verifyFormat("FOO(a)\n" 5291 "FOO(b)", 5292 Style); 5293 verifyFormat("int a = 0;\n" 5294 "FOO(b)\n" 5295 "int c = 0;", 5296 Style); 5297 verifyFormat("int a = 0;\n" 5298 "int x = FOO(a)\n" 5299 "int b = 0;", 5300 Style); 5301 verifyFormat("void foo(int a) { FOO(a) }\n" 5302 "uint32_t bar() {}", 5303 Style); 5304 } 5305 5306 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5307 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5308 5309 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5310 ZeroColumn); 5311 } 5312 5313 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5314 verifyFormat("#define A \\\n" 5315 " f({ \\\n" 5316 " g(); \\\n" 5317 " });", 5318 getLLVMStyleWithColumns(11)); 5319 } 5320 5321 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5322 FormatStyle Style = getLLVMStyleWithColumns(40); 5323 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5324 verifyFormat("#ifdef _WIN32\n" 5325 "#define A 0\n" 5326 "#ifdef VAR2\n" 5327 "#define B 1\n" 5328 "#include <someheader.h>\n" 5329 "#define MACRO \\\n" 5330 " some_very_long_func_aaaaaaaaaa();\n" 5331 "#endif\n" 5332 "#else\n" 5333 "#define A 1\n" 5334 "#endif", 5335 Style); 5336 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5337 verifyFormat("#ifdef _WIN32\n" 5338 "# define A 0\n" 5339 "# ifdef VAR2\n" 5340 "# define B 1\n" 5341 "# include <someheader.h>\n" 5342 "# define MACRO \\\n" 5343 " some_very_long_func_aaaaaaaaaa();\n" 5344 "# endif\n" 5345 "#else\n" 5346 "# define A 1\n" 5347 "#endif", 5348 Style); 5349 verifyFormat("#if A\n" 5350 "# define MACRO \\\n" 5351 " void a(int x) { \\\n" 5352 " b(); \\\n" 5353 " c(); \\\n" 5354 " d(); \\\n" 5355 " e(); \\\n" 5356 " f(); \\\n" 5357 " }\n" 5358 "#endif", 5359 Style); 5360 // Comments before include guard. 5361 verifyFormat("// file comment\n" 5362 "// file comment\n" 5363 "#ifndef HEADER_H\n" 5364 "#define HEADER_H\n" 5365 "code();\n" 5366 "#endif", 5367 Style); 5368 // Test with include guards. 5369 verifyFormat("#ifndef HEADER_H\n" 5370 "#define HEADER_H\n" 5371 "code();\n" 5372 "#endif", 5373 Style); 5374 // Include guards must have a #define with the same variable immediately 5375 // after #ifndef. 5376 verifyFormat("#ifndef NOT_GUARD\n" 5377 "# define FOO\n" 5378 "code();\n" 5379 "#endif", 5380 Style); 5381 5382 // Include guards must cover the entire file. 5383 verifyFormat("code();\n" 5384 "code();\n" 5385 "#ifndef NOT_GUARD\n" 5386 "# define NOT_GUARD\n" 5387 "code();\n" 5388 "#endif", 5389 Style); 5390 verifyFormat("#ifndef NOT_GUARD\n" 5391 "# define NOT_GUARD\n" 5392 "code();\n" 5393 "#endif\n" 5394 "code();", 5395 Style); 5396 // Test with trailing blank lines. 5397 verifyFormat("#ifndef HEADER_H\n" 5398 "#define HEADER_H\n" 5399 "code();\n" 5400 "#endif\n", 5401 Style); 5402 // Include guards don't have #else. 5403 verifyFormat("#ifndef NOT_GUARD\n" 5404 "# define NOT_GUARD\n" 5405 "code();\n" 5406 "#else\n" 5407 "#endif", 5408 Style); 5409 verifyFormat("#ifndef NOT_GUARD\n" 5410 "# define NOT_GUARD\n" 5411 "code();\n" 5412 "#elif FOO\n" 5413 "#endif", 5414 Style); 5415 // Non-identifier #define after potential include guard. 5416 verifyFormat("#ifndef FOO\n" 5417 "# define 1\n" 5418 "#endif\n", 5419 Style); 5420 // #if closes past last non-preprocessor line. 5421 verifyFormat("#ifndef FOO\n" 5422 "#define FOO\n" 5423 "#if 1\n" 5424 "int i;\n" 5425 "# define A 0\n" 5426 "#endif\n" 5427 "#endif\n", 5428 Style); 5429 // Don't crash if there is an #elif directive without a condition. 5430 verifyFormat("#if 1\n" 5431 "int x;\n" 5432 "#elif\n" 5433 "int y;\n" 5434 "#else\n" 5435 "int z;\n" 5436 "#endif", 5437 Style); 5438 // FIXME: This doesn't handle the case where there's code between the 5439 // #ifndef and #define but all other conditions hold. This is because when 5440 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5441 // previous code line yet, so we can't detect it. 5442 EXPECT_EQ("#ifndef NOT_GUARD\n" 5443 "code();\n" 5444 "#define NOT_GUARD\n" 5445 "code();\n" 5446 "#endif", 5447 format("#ifndef NOT_GUARD\n" 5448 "code();\n" 5449 "# define NOT_GUARD\n" 5450 "code();\n" 5451 "#endif", 5452 Style)); 5453 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5454 // be outside an include guard. Examples are #pragma once and 5455 // #pragma GCC diagnostic, or anything else that does not change the meaning 5456 // of the file if it's included multiple times. 5457 EXPECT_EQ("#ifdef WIN32\n" 5458 "# pragma once\n" 5459 "#endif\n" 5460 "#ifndef HEADER_H\n" 5461 "# define HEADER_H\n" 5462 "code();\n" 5463 "#endif", 5464 format("#ifdef WIN32\n" 5465 "# pragma once\n" 5466 "#endif\n" 5467 "#ifndef HEADER_H\n" 5468 "#define HEADER_H\n" 5469 "code();\n" 5470 "#endif", 5471 Style)); 5472 // FIXME: This does not detect when there is a single non-preprocessor line 5473 // in front of an include-guard-like structure where other conditions hold 5474 // because ScopedLineState hides the line. 5475 EXPECT_EQ("code();\n" 5476 "#ifndef HEADER_H\n" 5477 "#define HEADER_H\n" 5478 "code();\n" 5479 "#endif", 5480 format("code();\n" 5481 "#ifndef HEADER_H\n" 5482 "# define HEADER_H\n" 5483 "code();\n" 5484 "#endif", 5485 Style)); 5486 // Keep comments aligned with #, otherwise indent comments normally. These 5487 // tests cannot use verifyFormat because messUp manipulates leading 5488 // whitespace. 5489 { 5490 const char *Expected = "" 5491 "void f() {\n" 5492 "#if 1\n" 5493 "// Preprocessor aligned.\n" 5494 "# define A 0\n" 5495 " // Code. Separated by blank line.\n" 5496 "\n" 5497 "# define B 0\n" 5498 " // Code. Not aligned with #\n" 5499 "# define C 0\n" 5500 "#endif"; 5501 const char *ToFormat = "" 5502 "void f() {\n" 5503 "#if 1\n" 5504 "// Preprocessor aligned.\n" 5505 "# define A 0\n" 5506 "// Code. Separated by blank line.\n" 5507 "\n" 5508 "# define B 0\n" 5509 " // Code. Not aligned with #\n" 5510 "# define C 0\n" 5511 "#endif"; 5512 EXPECT_EQ(Expected, format(ToFormat, Style)); 5513 EXPECT_EQ(Expected, format(Expected, Style)); 5514 } 5515 // Keep block quotes aligned. 5516 { 5517 const char *Expected = "" 5518 "void f() {\n" 5519 "#if 1\n" 5520 "/* Preprocessor aligned. */\n" 5521 "# define A 0\n" 5522 " /* Code. Separated by blank line. */\n" 5523 "\n" 5524 "# define B 0\n" 5525 " /* Code. Not aligned with # */\n" 5526 "# define C 0\n" 5527 "#endif"; 5528 const char *ToFormat = "" 5529 "void f() {\n" 5530 "#if 1\n" 5531 "/* Preprocessor aligned. */\n" 5532 "# define A 0\n" 5533 "/* Code. Separated by blank line. */\n" 5534 "\n" 5535 "# define B 0\n" 5536 " /* Code. Not aligned with # */\n" 5537 "# define C 0\n" 5538 "#endif"; 5539 EXPECT_EQ(Expected, format(ToFormat, Style)); 5540 EXPECT_EQ(Expected, format(Expected, Style)); 5541 } 5542 // Keep comments aligned with un-indented directives. 5543 { 5544 const char *Expected = "" 5545 "void f() {\n" 5546 "// Preprocessor aligned.\n" 5547 "#define A 0\n" 5548 " // Code. Separated by blank line.\n" 5549 "\n" 5550 "#define B 0\n" 5551 " // Code. Not aligned with #\n" 5552 "#define C 0\n"; 5553 const char *ToFormat = "" 5554 "void f() {\n" 5555 "// Preprocessor aligned.\n" 5556 "#define A 0\n" 5557 "// Code. Separated by blank line.\n" 5558 "\n" 5559 "#define B 0\n" 5560 " // Code. Not aligned with #\n" 5561 "#define C 0\n"; 5562 EXPECT_EQ(Expected, format(ToFormat, Style)); 5563 EXPECT_EQ(Expected, format(Expected, Style)); 5564 } 5565 // Test AfterHash with tabs. 5566 { 5567 FormatStyle Tabbed = Style; 5568 Tabbed.UseTab = FormatStyle::UT_Always; 5569 Tabbed.IndentWidth = 8; 5570 Tabbed.TabWidth = 8; 5571 verifyFormat("#ifdef _WIN32\n" 5572 "#\tdefine A 0\n" 5573 "#\tifdef VAR2\n" 5574 "#\t\tdefine B 1\n" 5575 "#\t\tinclude <someheader.h>\n" 5576 "#\t\tdefine MACRO \\\n" 5577 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5578 "#\tendif\n" 5579 "#else\n" 5580 "#\tdefine A 1\n" 5581 "#endif", 5582 Tabbed); 5583 } 5584 5585 // Regression test: Multiline-macro inside include guards. 5586 verifyFormat("#ifndef HEADER_H\n" 5587 "#define HEADER_H\n" 5588 "#define A() \\\n" 5589 " int i; \\\n" 5590 " int j;\n" 5591 "#endif // HEADER_H", 5592 getLLVMStyleWithColumns(20)); 5593 5594 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5595 // Basic before hash indent tests 5596 verifyFormat("#ifdef _WIN32\n" 5597 " #define A 0\n" 5598 " #ifdef VAR2\n" 5599 " #define B 1\n" 5600 " #include <someheader.h>\n" 5601 " #define MACRO \\\n" 5602 " some_very_long_func_aaaaaaaaaa();\n" 5603 " #endif\n" 5604 "#else\n" 5605 " #define A 1\n" 5606 "#endif", 5607 Style); 5608 verifyFormat("#if A\n" 5609 " #define MACRO \\\n" 5610 " void a(int x) { \\\n" 5611 " b(); \\\n" 5612 " c(); \\\n" 5613 " d(); \\\n" 5614 " e(); \\\n" 5615 " f(); \\\n" 5616 " }\n" 5617 "#endif", 5618 Style); 5619 // Keep comments aligned with indented directives. These 5620 // tests cannot use verifyFormat because messUp manipulates leading 5621 // whitespace. 5622 { 5623 const char *Expected = "void f() {\n" 5624 "// Aligned to preprocessor.\n" 5625 "#if 1\n" 5626 " // Aligned to code.\n" 5627 " int a;\n" 5628 " #if 1\n" 5629 " // Aligned to preprocessor.\n" 5630 " #define A 0\n" 5631 " // Aligned to code.\n" 5632 " int b;\n" 5633 " #endif\n" 5634 "#endif\n" 5635 "}"; 5636 const char *ToFormat = "void f() {\n" 5637 "// Aligned to preprocessor.\n" 5638 "#if 1\n" 5639 "// Aligned to code.\n" 5640 "int a;\n" 5641 "#if 1\n" 5642 "// Aligned to preprocessor.\n" 5643 "#define A 0\n" 5644 "// Aligned to code.\n" 5645 "int b;\n" 5646 "#endif\n" 5647 "#endif\n" 5648 "}"; 5649 EXPECT_EQ(Expected, format(ToFormat, Style)); 5650 EXPECT_EQ(Expected, format(Expected, Style)); 5651 } 5652 { 5653 const char *Expected = "void f() {\n" 5654 "/* Aligned to preprocessor. */\n" 5655 "#if 1\n" 5656 " /* Aligned to code. */\n" 5657 " int a;\n" 5658 " #if 1\n" 5659 " /* Aligned to preprocessor. */\n" 5660 " #define A 0\n" 5661 " /* Aligned to code. */\n" 5662 " int b;\n" 5663 " #endif\n" 5664 "#endif\n" 5665 "}"; 5666 const char *ToFormat = "void f() {\n" 5667 "/* Aligned to preprocessor. */\n" 5668 "#if 1\n" 5669 "/* Aligned to code. */\n" 5670 "int a;\n" 5671 "#if 1\n" 5672 "/* Aligned to preprocessor. */\n" 5673 "#define A 0\n" 5674 "/* Aligned to code. */\n" 5675 "int b;\n" 5676 "#endif\n" 5677 "#endif\n" 5678 "}"; 5679 EXPECT_EQ(Expected, format(ToFormat, Style)); 5680 EXPECT_EQ(Expected, format(Expected, Style)); 5681 } 5682 5683 // Test single comment before preprocessor 5684 verifyFormat("// Comment\n" 5685 "\n" 5686 "#if 1\n" 5687 "#endif", 5688 Style); 5689 } 5690 5691 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5692 verifyFormat("{\n { a #c; }\n}"); 5693 } 5694 5695 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5696 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5697 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5698 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5699 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5700 } 5701 5702 TEST_F(FormatTest, EscapedNewlines) { 5703 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5704 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5705 format("#define A \\\nint i;\\\n int j;", Narrow)); 5706 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5707 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5708 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5709 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5710 5711 FormatStyle AlignLeft = getLLVMStyle(); 5712 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5713 EXPECT_EQ("#define MACRO(x) \\\n" 5714 "private: \\\n" 5715 " int x(int a);\n", 5716 format("#define MACRO(x) \\\n" 5717 "private: \\\n" 5718 " int x(int a);\n", 5719 AlignLeft)); 5720 5721 // CRLF line endings 5722 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5723 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5724 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5725 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5726 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5727 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5728 EXPECT_EQ("#define MACRO(x) \\\r\n" 5729 "private: \\\r\n" 5730 " int x(int a);\r\n", 5731 format("#define MACRO(x) \\\r\n" 5732 "private: \\\r\n" 5733 " int x(int a);\r\n", 5734 AlignLeft)); 5735 5736 FormatStyle DontAlign = getLLVMStyle(); 5737 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5738 DontAlign.MaxEmptyLinesToKeep = 3; 5739 // FIXME: can't use verifyFormat here because the newline before 5740 // "public:" is not inserted the first time it's reformatted 5741 EXPECT_EQ("#define A \\\n" 5742 " class Foo { \\\n" 5743 " void bar(); \\\n" 5744 "\\\n" 5745 "\\\n" 5746 "\\\n" 5747 " public: \\\n" 5748 " void baz(); \\\n" 5749 " };", 5750 format("#define A \\\n" 5751 " class Foo { \\\n" 5752 " void bar(); \\\n" 5753 "\\\n" 5754 "\\\n" 5755 "\\\n" 5756 " public: \\\n" 5757 " void baz(); \\\n" 5758 " };", 5759 DontAlign)); 5760 } 5761 5762 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5763 verifyFormat("#define A \\\n" 5764 " int v( \\\n" 5765 " a); \\\n" 5766 " int i;", 5767 getLLVMStyleWithColumns(11)); 5768 } 5769 5770 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5771 EXPECT_EQ( 5772 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5773 " \\\n" 5774 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5775 "\n" 5776 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5777 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5778 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5779 "\\\n" 5780 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5781 " \n" 5782 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5783 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5784 } 5785 5786 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5787 EXPECT_EQ("int\n" 5788 "#define A\n" 5789 " a;", 5790 format("int\n#define A\na;")); 5791 verifyFormat("functionCallTo(\n" 5792 " someOtherFunction(\n" 5793 " withSomeParameters, whichInSequence,\n" 5794 " areLongerThanALine(andAnotherCall,\n" 5795 "#define A B\n" 5796 " withMoreParamters,\n" 5797 " whichStronglyInfluenceTheLayout),\n" 5798 " andMoreParameters),\n" 5799 " trailing);", 5800 getLLVMStyleWithColumns(69)); 5801 verifyFormat("Foo::Foo()\n" 5802 "#ifdef BAR\n" 5803 " : baz(0)\n" 5804 "#endif\n" 5805 "{\n" 5806 "}"); 5807 verifyFormat("void f() {\n" 5808 " if (true)\n" 5809 "#ifdef A\n" 5810 " f(42);\n" 5811 " x();\n" 5812 "#else\n" 5813 " g();\n" 5814 " x();\n" 5815 "#endif\n" 5816 "}"); 5817 verifyFormat("void f(param1, param2,\n" 5818 " param3,\n" 5819 "#ifdef A\n" 5820 " param4(param5,\n" 5821 "#ifdef A1\n" 5822 " param6,\n" 5823 "#ifdef A2\n" 5824 " param7),\n" 5825 "#else\n" 5826 " param8),\n" 5827 " param9,\n" 5828 "#endif\n" 5829 " param10,\n" 5830 "#endif\n" 5831 " param11)\n" 5832 "#else\n" 5833 " param12)\n" 5834 "#endif\n" 5835 "{\n" 5836 " x();\n" 5837 "}", 5838 getLLVMStyleWithColumns(28)); 5839 verifyFormat("#if 1\n" 5840 "int i;"); 5841 verifyFormat("#if 1\n" 5842 "#endif\n" 5843 "#if 1\n" 5844 "#else\n" 5845 "#endif\n"); 5846 verifyFormat("DEBUG({\n" 5847 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5848 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5849 "});\n" 5850 "#if a\n" 5851 "#else\n" 5852 "#endif"); 5853 5854 verifyIncompleteFormat("void f(\n" 5855 "#if A\n" 5856 ");\n" 5857 "#else\n" 5858 "#endif"); 5859 } 5860 5861 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5862 verifyFormat("#endif\n" 5863 "#if B"); 5864 } 5865 5866 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5867 FormatStyle SingleLine = getLLVMStyle(); 5868 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5869 verifyFormat("#if 0\n" 5870 "#elif 1\n" 5871 "#endif\n" 5872 "void foo() {\n" 5873 " if (test) foo2();\n" 5874 "}", 5875 SingleLine); 5876 } 5877 5878 TEST_F(FormatTest, LayoutBlockInsideParens) { 5879 verifyFormat("functionCall({ int i; });"); 5880 verifyFormat("functionCall({\n" 5881 " int i;\n" 5882 " int j;\n" 5883 "});"); 5884 verifyFormat("functionCall(\n" 5885 " {\n" 5886 " int i;\n" 5887 " int j;\n" 5888 " },\n" 5889 " aaaa, bbbb, cccc);"); 5890 verifyFormat("functionA(functionB({\n" 5891 " int i;\n" 5892 " int j;\n" 5893 " }),\n" 5894 " aaaa, bbbb, cccc);"); 5895 verifyFormat("functionCall(\n" 5896 " {\n" 5897 " int i;\n" 5898 " int j;\n" 5899 " },\n" 5900 " aaaa, bbbb, // comment\n" 5901 " cccc);"); 5902 verifyFormat("functionA(functionB({\n" 5903 " int i;\n" 5904 " int j;\n" 5905 " }),\n" 5906 " aaaa, bbbb, // comment\n" 5907 " cccc);"); 5908 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5909 verifyFormat("functionCall(aaaa, bbbb, {\n" 5910 " int i;\n" 5911 " int j;\n" 5912 "});"); 5913 verifyFormat( 5914 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5915 " {\n" 5916 " int i; // break\n" 5917 " },\n" 5918 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5919 " ccccccccccccccccc));"); 5920 verifyFormat("DEBUG({\n" 5921 " if (a)\n" 5922 " f();\n" 5923 "});"); 5924 } 5925 5926 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5927 EXPECT_EQ("SOME_MACRO { int i; }\n" 5928 "int i;", 5929 format(" SOME_MACRO {int i;} int i;")); 5930 } 5931 5932 TEST_F(FormatTest, LayoutNestedBlocks) { 5933 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5934 " struct s {\n" 5935 " int i;\n" 5936 " };\n" 5937 " s kBitsToOs[] = {{10}};\n" 5938 " for (int i = 0; i < 10; ++i)\n" 5939 " return;\n" 5940 "}"); 5941 verifyFormat("call(parameter, {\n" 5942 " something();\n" 5943 " // Comment using all columns.\n" 5944 " somethingelse();\n" 5945 "});", 5946 getLLVMStyleWithColumns(40)); 5947 verifyFormat("DEBUG( //\n" 5948 " { f(); }, a);"); 5949 verifyFormat("DEBUG( //\n" 5950 " {\n" 5951 " f(); //\n" 5952 " },\n" 5953 " a);"); 5954 5955 EXPECT_EQ("call(parameter, {\n" 5956 " something();\n" 5957 " // Comment too\n" 5958 " // looooooooooong.\n" 5959 " somethingElse();\n" 5960 "});", 5961 format("call(parameter, {\n" 5962 " something();\n" 5963 " // Comment too looooooooooong.\n" 5964 " somethingElse();\n" 5965 "});", 5966 getLLVMStyleWithColumns(29))); 5967 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5968 EXPECT_EQ("DEBUG({ // comment\n" 5969 " int i;\n" 5970 "});", 5971 format("DEBUG({ // comment\n" 5972 "int i;\n" 5973 "});")); 5974 EXPECT_EQ("DEBUG({\n" 5975 " int i;\n" 5976 "\n" 5977 " // comment\n" 5978 " int j;\n" 5979 "});", 5980 format("DEBUG({\n" 5981 " int i;\n" 5982 "\n" 5983 " // comment\n" 5984 " int j;\n" 5985 "});")); 5986 5987 verifyFormat("DEBUG({\n" 5988 " if (a)\n" 5989 " return;\n" 5990 "});"); 5991 verifyGoogleFormat("DEBUG({\n" 5992 " if (a) return;\n" 5993 "});"); 5994 FormatStyle Style = getGoogleStyle(); 5995 Style.ColumnLimit = 45; 5996 verifyFormat("Debug(\n" 5997 " aaaaa,\n" 5998 " {\n" 5999 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 6000 " },\n" 6001 " a);", 6002 Style); 6003 6004 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 6005 6006 verifyNoCrash("^{v^{a}}"); 6007 } 6008 6009 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6010 EXPECT_EQ("#define MACRO() \\\n" 6011 " Debug(aaa, /* force line break */ \\\n" 6012 " { \\\n" 6013 " int i; \\\n" 6014 " int j; \\\n" 6015 " })", 6016 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6017 " { int i; int j; })", 6018 getGoogleStyle())); 6019 6020 EXPECT_EQ("#define A \\\n" 6021 " [] { \\\n" 6022 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6023 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6024 " }", 6025 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6026 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6027 getGoogleStyle())); 6028 } 6029 6030 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6031 EXPECT_EQ("{}", format("{}")); 6032 verifyFormat("enum E {};"); 6033 verifyFormat("enum E {}"); 6034 FormatStyle Style = getLLVMStyle(); 6035 Style.SpaceInEmptyBlock = true; 6036 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6037 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6038 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6039 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6040 Style.BraceWrapping.BeforeElse = false; 6041 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6042 verifyFormat("if (a)\n" 6043 "{\n" 6044 "} else if (b)\n" 6045 "{\n" 6046 "} else\n" 6047 "{ }", 6048 Style); 6049 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6050 verifyFormat("if (a) {\n" 6051 "} else if (b) {\n" 6052 "} else {\n" 6053 "}", 6054 Style); 6055 Style.BraceWrapping.BeforeElse = true; 6056 verifyFormat("if (a) { }\n" 6057 "else if (b) { }\n" 6058 "else { }", 6059 Style); 6060 } 6061 6062 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6063 FormatStyle Style = getLLVMStyle(); 6064 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6065 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6066 verifyFormat("FOO_BEGIN\n" 6067 " FOO_ENTRY\n" 6068 "FOO_END", 6069 Style); 6070 verifyFormat("FOO_BEGIN\n" 6071 " NESTED_FOO_BEGIN\n" 6072 " NESTED_FOO_ENTRY\n" 6073 " NESTED_FOO_END\n" 6074 "FOO_END", 6075 Style); 6076 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6077 " int x;\n" 6078 " x = 1;\n" 6079 "FOO_END(Baz)", 6080 Style); 6081 } 6082 6083 //===----------------------------------------------------------------------===// 6084 // Line break tests. 6085 //===----------------------------------------------------------------------===// 6086 6087 TEST_F(FormatTest, PreventConfusingIndents) { 6088 verifyFormat( 6089 "void f() {\n" 6090 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6091 " parameter, parameter, parameter)),\n" 6092 " SecondLongCall(parameter));\n" 6093 "}"); 6094 verifyFormat( 6095 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6096 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6097 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6098 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6099 verifyFormat( 6100 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6101 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6102 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6103 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6104 verifyFormat( 6105 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6106 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6107 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6108 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6109 verifyFormat("int a = bbbb && ccc &&\n" 6110 " fffff(\n" 6111 "#define A Just forcing a new line\n" 6112 " ddd);"); 6113 } 6114 6115 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6116 verifyFormat( 6117 "bool aaaaaaa =\n" 6118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6119 " bbbbbbbb();"); 6120 verifyFormat( 6121 "bool aaaaaaa =\n" 6122 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6123 " bbbbbbbb();"); 6124 6125 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6126 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6127 " ccccccccc == ddddddddddd;"); 6128 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6129 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6130 " ccccccccc == ddddddddddd;"); 6131 verifyFormat( 6132 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6133 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6134 " ccccccccc == ddddddddddd;"); 6135 6136 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6137 " aaaaaa) &&\n" 6138 " bbbbbb && cccccc;"); 6139 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6140 " aaaaaa) >>\n" 6141 " bbbbbb;"); 6142 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6143 " SourceMgr.getSpellingColumnNumber(\n" 6144 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6145 " 1);"); 6146 6147 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6148 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6149 " cccccc) {\n}"); 6150 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6151 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6152 " cccccc) {\n}"); 6153 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6154 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6155 " cccccc) {\n}"); 6156 verifyFormat("b = a &&\n" 6157 " // Comment\n" 6158 " b.c && d;"); 6159 6160 // If the LHS of a comparison is not a binary expression itself, the 6161 // additional linebreak confuses many people. 6162 verifyFormat( 6163 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6164 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6165 "}"); 6166 verifyFormat( 6167 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6168 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6169 "}"); 6170 verifyFormat( 6171 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6172 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6173 "}"); 6174 verifyFormat( 6175 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6176 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6177 "}"); 6178 // Even explicit parentheses stress the precedence enough to make the 6179 // additional break unnecessary. 6180 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6181 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6182 "}"); 6183 // This cases is borderline, but with the indentation it is still readable. 6184 verifyFormat( 6185 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6186 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6187 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6188 "}", 6189 getLLVMStyleWithColumns(75)); 6190 6191 // If the LHS is a binary expression, we should still use the additional break 6192 // as otherwise the formatting hides the operator precedence. 6193 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6194 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6195 " 5) {\n" 6196 "}"); 6197 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6199 " 5) {\n" 6200 "}"); 6201 6202 FormatStyle OnePerLine = getLLVMStyle(); 6203 OnePerLine.BinPackParameters = false; 6204 verifyFormat( 6205 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6207 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6208 OnePerLine); 6209 6210 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6211 " .aaa(aaaaaaaaaaaaa) *\n" 6212 " aaaaaaa +\n" 6213 " aaaaaaa;", 6214 getLLVMStyleWithColumns(40)); 6215 } 6216 6217 TEST_F(FormatTest, ExpressionIndentation) { 6218 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6219 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6220 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6222 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6223 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6224 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6225 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6226 " ccccccccccccccccccccccccccccccccccccccccc;"); 6227 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6229 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6230 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6231 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6232 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6233 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6234 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6235 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6236 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6237 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6238 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6239 verifyFormat("if () {\n" 6240 "} else if (aaaaa && bbbbb > // break\n" 6241 " ccccc) {\n" 6242 "}"); 6243 verifyFormat("if () {\n" 6244 "} else if constexpr (aaaaa && bbbbb > // break\n" 6245 " ccccc) {\n" 6246 "}"); 6247 verifyFormat("if () {\n" 6248 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6249 " ccccc) {\n" 6250 "}"); 6251 verifyFormat("if () {\n" 6252 "} else if (aaaaa &&\n" 6253 " bbbbb > // break\n" 6254 " ccccc &&\n" 6255 " ddddd) {\n" 6256 "}"); 6257 6258 // Presence of a trailing comment used to change indentation of b. 6259 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6260 " b;\n" 6261 "return aaaaaaaaaaaaaaaaaaa +\n" 6262 " b; //", 6263 getLLVMStyleWithColumns(30)); 6264 } 6265 6266 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6267 // Not sure what the best system is here. Like this, the LHS can be found 6268 // immediately above an operator (everything with the same or a higher 6269 // indent). The RHS is aligned right of the operator and so compasses 6270 // everything until something with the same indent as the operator is found. 6271 // FIXME: Is this a good system? 6272 FormatStyle Style = getLLVMStyle(); 6273 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6274 verifyFormat( 6275 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6276 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6277 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6278 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6279 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6280 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6281 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6282 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6283 " > ccccccccccccccccccccccccccccccccccccccccc;", 6284 Style); 6285 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6286 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6287 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6288 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6289 Style); 6290 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6291 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6292 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6293 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6294 Style); 6295 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6296 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6297 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6298 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6299 Style); 6300 verifyFormat("if () {\n" 6301 "} else if (aaaaa\n" 6302 " && bbbbb // break\n" 6303 " > ccccc) {\n" 6304 "}", 6305 Style); 6306 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6307 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6308 Style); 6309 verifyFormat("return (a)\n" 6310 " // comment\n" 6311 " + b;", 6312 Style); 6313 verifyFormat( 6314 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6315 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6316 " + cc;", 6317 Style); 6318 6319 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6320 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6321 Style); 6322 6323 // Forced by comments. 6324 verifyFormat( 6325 "unsigned ContentSize =\n" 6326 " sizeof(int16_t) // DWARF ARange version number\n" 6327 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6328 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6329 " + sizeof(int8_t); // Segment Size (in bytes)"); 6330 6331 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6332 " == boost::fusion::at_c<1>(iiii).second;", 6333 Style); 6334 6335 Style.ColumnLimit = 60; 6336 verifyFormat("zzzzzzzzzz\n" 6337 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6338 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6339 Style); 6340 6341 Style.ColumnLimit = 80; 6342 Style.IndentWidth = 4; 6343 Style.TabWidth = 4; 6344 Style.UseTab = FormatStyle::UT_Always; 6345 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6346 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6347 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6348 "\t&& (someOtherLongishConditionPart1\n" 6349 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6350 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6351 "(someOtherLongishConditionPart1 || " 6352 "someOtherEvenLongerNestedConditionPart2);", 6353 Style)); 6354 } 6355 6356 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6357 FormatStyle Style = getLLVMStyle(); 6358 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6359 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6360 6361 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6362 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6363 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6364 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6365 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6366 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6367 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6368 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6369 " > ccccccccccccccccccccccccccccccccccccccccc;", 6370 Style); 6371 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6372 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6373 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6374 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6375 Style); 6376 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6377 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6378 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6379 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6380 Style); 6381 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6382 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6383 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6384 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6385 Style); 6386 verifyFormat("if () {\n" 6387 "} else if (aaaaa\n" 6388 " && bbbbb // break\n" 6389 " > ccccc) {\n" 6390 "}", 6391 Style); 6392 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6393 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6394 Style); 6395 verifyFormat("return (a)\n" 6396 " // comment\n" 6397 " + b;", 6398 Style); 6399 verifyFormat( 6400 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6401 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6402 " + cc;", 6403 Style); 6404 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6405 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6406 " : 3333333333333333;", 6407 Style); 6408 verifyFormat( 6409 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6410 " : ccccccccccccccc ? dddddddddddddddddd\n" 6411 " : eeeeeeeeeeeeeeeeee)\n" 6412 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6413 " : 3333333333333333;", 6414 Style); 6415 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6416 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6417 Style); 6418 6419 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6420 " == boost::fusion::at_c<1>(iiii).second;", 6421 Style); 6422 6423 Style.ColumnLimit = 60; 6424 verifyFormat("zzzzzzzzzzzzz\n" 6425 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6426 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6427 Style); 6428 6429 // Forced by comments. 6430 Style.ColumnLimit = 80; 6431 verifyFormat( 6432 "unsigned ContentSize\n" 6433 " = sizeof(int16_t) // DWARF ARange version number\n" 6434 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6435 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6436 " + sizeof(int8_t); // Segment Size (in bytes)", 6437 Style); 6438 6439 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6440 verifyFormat( 6441 "unsigned ContentSize =\n" 6442 " sizeof(int16_t) // DWARF ARange version number\n" 6443 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6444 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6445 " + sizeof(int8_t); // Segment Size (in bytes)", 6446 Style); 6447 6448 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6449 verifyFormat( 6450 "unsigned ContentSize =\n" 6451 " sizeof(int16_t) // DWARF ARange version number\n" 6452 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6453 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6454 " + sizeof(int8_t); // Segment Size (in bytes)", 6455 Style); 6456 } 6457 6458 TEST_F(FormatTest, EnforcedOperatorWraps) { 6459 // Here we'd like to wrap after the || operators, but a comment is forcing an 6460 // earlier wrap. 6461 verifyFormat("bool x = aaaaa //\n" 6462 " || bbbbb\n" 6463 " //\n" 6464 " || cccc;"); 6465 } 6466 6467 TEST_F(FormatTest, NoOperandAlignment) { 6468 FormatStyle Style = getLLVMStyle(); 6469 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6470 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6471 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6472 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6473 Style); 6474 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6475 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6476 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6477 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6478 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6479 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6480 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6481 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6482 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6483 " > ccccccccccccccccccccccccccccccccccccccccc;", 6484 Style); 6485 6486 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6487 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6488 " + cc;", 6489 Style); 6490 verifyFormat("int a = aa\n" 6491 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6492 " * cccccccccccccccccccccccccccccccccccc;\n", 6493 Style); 6494 6495 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6496 verifyFormat("return (a > b\n" 6497 " // comment1\n" 6498 " // comment2\n" 6499 " || c);", 6500 Style); 6501 } 6502 6503 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6504 FormatStyle Style = getLLVMStyle(); 6505 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6506 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6507 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6508 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6509 Style); 6510 } 6511 6512 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6513 FormatStyle Style = getLLVMStyleWithColumns(40); 6514 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6515 Style.BinPackArguments = false; 6516 verifyFormat("void test() {\n" 6517 " someFunction(\n" 6518 " this + argument + is + quite\n" 6519 " + long + so + it + gets + wrapped\n" 6520 " + but + remains + bin - packed);\n" 6521 "}", 6522 Style); 6523 verifyFormat("void test() {\n" 6524 " someFunction(arg1,\n" 6525 " this + argument + is\n" 6526 " + quite + long + so\n" 6527 " + it + gets + wrapped\n" 6528 " + but + remains + bin\n" 6529 " - packed,\n" 6530 " arg3);\n" 6531 "}", 6532 Style); 6533 verifyFormat("void test() {\n" 6534 " someFunction(\n" 6535 " arg1,\n" 6536 " this + argument + has\n" 6537 " + anotherFunc(nested,\n" 6538 " calls + whose\n" 6539 " + arguments\n" 6540 " + are + also\n" 6541 " + wrapped,\n" 6542 " in + addition)\n" 6543 " + to + being + bin - packed,\n" 6544 " arg3);\n" 6545 "}", 6546 Style); 6547 6548 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6549 verifyFormat("void test() {\n" 6550 " someFunction(\n" 6551 " arg1,\n" 6552 " this + argument + has +\n" 6553 " anotherFunc(nested,\n" 6554 " calls + whose +\n" 6555 " arguments +\n" 6556 " are + also +\n" 6557 " wrapped,\n" 6558 " in + addition) +\n" 6559 " to + being + bin - packed,\n" 6560 " arg3);\n" 6561 "}", 6562 Style); 6563 } 6564 6565 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6566 auto Style = getLLVMStyleWithColumns(45); 6567 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6568 verifyFormat("bool b =\n" 6569 " is_default_constructible_v<hash<T>> and\n" 6570 " is_copy_constructible_v<hash<T>> and\n" 6571 " is_move_constructible_v<hash<T>> and\n" 6572 " is_copy_assignable_v<hash<T>> and\n" 6573 " is_move_assignable_v<hash<T>> and\n" 6574 " is_destructible_v<hash<T>> and\n" 6575 " is_swappable_v<hash<T>> and\n" 6576 " is_callable_v<hash<T>(T)>;", 6577 Style); 6578 6579 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6580 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6581 " and is_copy_constructible_v<hash<T>>\n" 6582 " and is_move_constructible_v<hash<T>>\n" 6583 " and is_copy_assignable_v<hash<T>>\n" 6584 " and is_move_assignable_v<hash<T>>\n" 6585 " and is_destructible_v<hash<T>>\n" 6586 " and is_swappable_v<hash<T>>\n" 6587 " and is_callable_v<hash<T>(T)>;", 6588 Style); 6589 6590 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6591 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6592 " and is_copy_constructible_v<hash<T>>\n" 6593 " and is_move_constructible_v<hash<T>>\n" 6594 " and is_copy_assignable_v<hash<T>>\n" 6595 " and is_move_assignable_v<hash<T>>\n" 6596 " and is_destructible_v<hash<T>>\n" 6597 " and is_swappable_v<hash<T>>\n" 6598 " and is_callable_v<hash<T>(T)>;", 6599 Style); 6600 } 6601 6602 TEST_F(FormatTest, ConstructorInitializers) { 6603 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6604 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6605 getLLVMStyleWithColumns(45)); 6606 verifyFormat("Constructor()\n" 6607 " : Inttializer(FitsOnTheLine) {}", 6608 getLLVMStyleWithColumns(44)); 6609 verifyFormat("Constructor()\n" 6610 " : Inttializer(FitsOnTheLine) {}", 6611 getLLVMStyleWithColumns(43)); 6612 6613 verifyFormat("template <typename T>\n" 6614 "Constructor() : Initializer(FitsOnTheLine) {}", 6615 getLLVMStyleWithColumns(45)); 6616 6617 verifyFormat( 6618 "SomeClass::Constructor()\n" 6619 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6620 6621 verifyFormat( 6622 "SomeClass::Constructor()\n" 6623 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6624 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6625 verifyFormat( 6626 "SomeClass::Constructor()\n" 6627 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6628 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6629 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6630 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6631 " : aaaaaaaaaa(aaaaaa) {}"); 6632 6633 verifyFormat("Constructor()\n" 6634 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6635 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6636 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6637 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6638 6639 verifyFormat("Constructor()\n" 6640 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6641 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6642 6643 verifyFormat("Constructor(int Parameter = 0)\n" 6644 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6645 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6646 verifyFormat("Constructor()\n" 6647 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6648 "}", 6649 getLLVMStyleWithColumns(60)); 6650 verifyFormat("Constructor()\n" 6651 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6652 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6653 6654 // Here a line could be saved by splitting the second initializer onto two 6655 // lines, but that is not desirable. 6656 verifyFormat("Constructor()\n" 6657 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6658 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6659 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6660 6661 FormatStyle OnePerLine = getLLVMStyle(); 6662 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6663 verifyFormat("MyClass::MyClass()\n" 6664 " : a(a),\n" 6665 " b(b),\n" 6666 " c(c) {}", 6667 OnePerLine); 6668 verifyFormat("MyClass::MyClass()\n" 6669 " : a(a), // comment\n" 6670 " b(b),\n" 6671 " c(c) {}", 6672 OnePerLine); 6673 verifyFormat("MyClass::MyClass(int a)\n" 6674 " : b(a), // comment\n" 6675 " c(a + 1) { // lined up\n" 6676 "}", 6677 OnePerLine); 6678 verifyFormat("Constructor()\n" 6679 " : a(b, b, b) {}", 6680 OnePerLine); 6681 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6682 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6683 verifyFormat("SomeClass::Constructor()\n" 6684 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6685 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6686 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6687 OnePerLine); 6688 verifyFormat("SomeClass::Constructor()\n" 6689 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6690 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6691 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6692 OnePerLine); 6693 verifyFormat("MyClass::MyClass(int var)\n" 6694 " : some_var_(var), // 4 space indent\n" 6695 " some_other_var_(var + 1) { // lined up\n" 6696 "}", 6697 OnePerLine); 6698 verifyFormat("Constructor()\n" 6699 " : aaaaa(aaaaaa),\n" 6700 " aaaaa(aaaaaa),\n" 6701 " aaaaa(aaaaaa),\n" 6702 " aaaaa(aaaaaa),\n" 6703 " aaaaa(aaaaaa) {}", 6704 OnePerLine); 6705 verifyFormat("Constructor()\n" 6706 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6707 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6708 OnePerLine); 6709 OnePerLine.BinPackParameters = false; 6710 verifyFormat( 6711 "Constructor()\n" 6712 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6713 " aaaaaaaaaaa().aaa(),\n" 6714 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6715 OnePerLine); 6716 OnePerLine.ColumnLimit = 60; 6717 verifyFormat("Constructor()\n" 6718 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6719 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6720 OnePerLine); 6721 6722 EXPECT_EQ("Constructor()\n" 6723 " : // Comment forcing unwanted break.\n" 6724 " aaaa(aaaa) {}", 6725 format("Constructor() :\n" 6726 " // Comment forcing unwanted break.\n" 6727 " aaaa(aaaa) {}")); 6728 } 6729 6730 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6731 FormatStyle Style = getLLVMStyleWithColumns(60); 6732 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6733 Style.BinPackParameters = false; 6734 6735 for (int i = 0; i < 4; ++i) { 6736 // Test all combinations of parameters that should not have an effect. 6737 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6738 Style.AllowAllArgumentsOnNextLine = i & 2; 6739 6740 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6741 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6742 verifyFormat("Constructor()\n" 6743 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6744 Style); 6745 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6746 6747 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6748 verifyFormat("Constructor()\n" 6749 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6750 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6751 Style); 6752 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6753 6754 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6755 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6756 verifyFormat("Constructor()\n" 6757 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6758 Style); 6759 6760 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6761 verifyFormat("Constructor()\n" 6762 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6763 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6764 Style); 6765 6766 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6767 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6768 verifyFormat("Constructor() :\n" 6769 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6770 Style); 6771 6772 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6773 verifyFormat("Constructor() :\n" 6774 " aaaaaaaaaaaaaaaaaa(a),\n" 6775 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6776 Style); 6777 } 6778 6779 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6780 // AllowAllConstructorInitializersOnNextLine in all 6781 // BreakConstructorInitializers modes 6782 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6783 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6784 verifyFormat("SomeClassWithALongName::Constructor(\n" 6785 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6786 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6787 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6788 Style); 6789 6790 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6791 verifyFormat("SomeClassWithALongName::Constructor(\n" 6792 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6793 " int bbbbbbbbbbbbb,\n" 6794 " int cccccccccccccccc)\n" 6795 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6796 Style); 6797 6798 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6799 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6800 verifyFormat("SomeClassWithALongName::Constructor(\n" 6801 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6802 " int bbbbbbbbbbbbb)\n" 6803 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6804 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6805 Style); 6806 6807 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6808 6809 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6810 verifyFormat("SomeClassWithALongName::Constructor(\n" 6811 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6812 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6813 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6814 Style); 6815 6816 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6817 verifyFormat("SomeClassWithALongName::Constructor(\n" 6818 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6819 " int bbbbbbbbbbbbb,\n" 6820 " int cccccccccccccccc)\n" 6821 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6822 Style); 6823 6824 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6825 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6826 verifyFormat("SomeClassWithALongName::Constructor(\n" 6827 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6828 " int bbbbbbbbbbbbb)\n" 6829 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6830 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6831 Style); 6832 6833 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6834 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6835 verifyFormat("SomeClassWithALongName::Constructor(\n" 6836 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6837 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6838 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6839 Style); 6840 6841 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6842 verifyFormat("SomeClassWithALongName::Constructor(\n" 6843 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6844 " int bbbbbbbbbbbbb,\n" 6845 " int cccccccccccccccc) :\n" 6846 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6847 Style); 6848 6849 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6850 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6851 verifyFormat("SomeClassWithALongName::Constructor(\n" 6852 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6853 " int bbbbbbbbbbbbb) :\n" 6854 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6855 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6856 Style); 6857 } 6858 6859 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6860 FormatStyle Style = getLLVMStyleWithColumns(60); 6861 Style.BinPackArguments = false; 6862 for (int i = 0; i < 4; ++i) { 6863 // Test all combinations of parameters that should not have an effect. 6864 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6865 Style.PackConstructorInitializers = 6866 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6867 6868 Style.AllowAllArgumentsOnNextLine = true; 6869 verifyFormat("void foo() {\n" 6870 " FunctionCallWithReallyLongName(\n" 6871 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6872 "}", 6873 Style); 6874 Style.AllowAllArgumentsOnNextLine = false; 6875 verifyFormat("void foo() {\n" 6876 " FunctionCallWithReallyLongName(\n" 6877 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6878 " bbbbbbbbbbbb);\n" 6879 "}", 6880 Style); 6881 6882 Style.AllowAllArgumentsOnNextLine = true; 6883 verifyFormat("void foo() {\n" 6884 " auto VariableWithReallyLongName = {\n" 6885 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6886 "}", 6887 Style); 6888 Style.AllowAllArgumentsOnNextLine = false; 6889 verifyFormat("void foo() {\n" 6890 " auto VariableWithReallyLongName = {\n" 6891 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6892 " bbbbbbbbbbbb};\n" 6893 "}", 6894 Style); 6895 } 6896 6897 // This parameter should not affect declarations. 6898 Style.BinPackParameters = false; 6899 Style.AllowAllArgumentsOnNextLine = false; 6900 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6901 verifyFormat("void FunctionCallWithReallyLongName(\n" 6902 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6903 Style); 6904 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6905 verifyFormat("void FunctionCallWithReallyLongName(\n" 6906 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6907 " int bbbbbbbbbbbb);", 6908 Style); 6909 } 6910 6911 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6912 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6913 // and BAS_Align. 6914 FormatStyle Style = getLLVMStyleWithColumns(35); 6915 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6916 "void functionDecl(int A, int B, int C);"; 6917 Style.AllowAllArgumentsOnNextLine = false; 6918 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6919 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6920 " paramC);\n" 6921 "void functionDecl(int A, int B,\n" 6922 " int C);"), 6923 format(Input, Style)); 6924 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6925 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6926 " paramC);\n" 6927 "void functionDecl(int A, int B,\n" 6928 " int C);"), 6929 format(Input, Style)); 6930 // However, BAS_AlwaysBreak should take precedence over 6931 // AllowAllArgumentsOnNextLine. 6932 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6933 EXPECT_EQ(StringRef("functionCall(\n" 6934 " paramA, paramB, paramC);\n" 6935 "void functionDecl(\n" 6936 " int A, int B, int C);"), 6937 format(Input, Style)); 6938 6939 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6940 // first argument. 6941 Style.AllowAllArgumentsOnNextLine = true; 6942 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6943 EXPECT_EQ(StringRef("functionCall(\n" 6944 " paramA, paramB, paramC);\n" 6945 "void functionDecl(\n" 6946 " int A, int B, int C);"), 6947 format(Input, Style)); 6948 // It wouldn't fit on one line with aligned parameters so this setting 6949 // doesn't change anything for BAS_Align. 6950 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6951 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6952 " paramC);\n" 6953 "void functionDecl(int A, int B,\n" 6954 " int C);"), 6955 format(Input, Style)); 6956 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6957 EXPECT_EQ(StringRef("functionCall(\n" 6958 " paramA, paramB, paramC);\n" 6959 "void functionDecl(\n" 6960 " int A, int B, int C);"), 6961 format(Input, Style)); 6962 } 6963 6964 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6965 FormatStyle Style = getLLVMStyle(); 6966 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6967 6968 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6969 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6970 getStyleWithColumns(Style, 45)); 6971 verifyFormat("Constructor() :\n" 6972 " Initializer(FitsOnTheLine) {}", 6973 getStyleWithColumns(Style, 44)); 6974 verifyFormat("Constructor() :\n" 6975 " Initializer(FitsOnTheLine) {}", 6976 getStyleWithColumns(Style, 43)); 6977 6978 verifyFormat("template <typename T>\n" 6979 "Constructor() : Initializer(FitsOnTheLine) {}", 6980 getStyleWithColumns(Style, 50)); 6981 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6982 verifyFormat( 6983 "SomeClass::Constructor() :\n" 6984 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6985 Style); 6986 6987 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6988 verifyFormat( 6989 "SomeClass::Constructor() :\n" 6990 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6991 Style); 6992 6993 verifyFormat( 6994 "SomeClass::Constructor() :\n" 6995 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6996 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6997 Style); 6998 verifyFormat( 6999 "SomeClass::Constructor() :\n" 7000 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7001 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7002 Style); 7003 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7004 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 7005 " aaaaaaaaaa(aaaaaa) {}", 7006 Style); 7007 7008 verifyFormat("Constructor() :\n" 7009 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7010 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7011 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7012 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7013 Style); 7014 7015 verifyFormat("Constructor() :\n" 7016 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7017 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7018 Style); 7019 7020 verifyFormat("Constructor(int Parameter = 0) :\n" 7021 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7022 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7023 Style); 7024 verifyFormat("Constructor() :\n" 7025 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7026 "}", 7027 getStyleWithColumns(Style, 60)); 7028 verifyFormat("Constructor() :\n" 7029 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7030 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7031 Style); 7032 7033 // Here a line could be saved by splitting the second initializer onto two 7034 // lines, but that is not desirable. 7035 verifyFormat("Constructor() :\n" 7036 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7037 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7038 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7039 Style); 7040 7041 FormatStyle OnePerLine = Style; 7042 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7043 verifyFormat("SomeClass::Constructor() :\n" 7044 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7045 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7046 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7047 OnePerLine); 7048 verifyFormat("SomeClass::Constructor() :\n" 7049 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7050 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7051 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7052 OnePerLine); 7053 verifyFormat("MyClass::MyClass(int var) :\n" 7054 " some_var_(var), // 4 space indent\n" 7055 " some_other_var_(var + 1) { // lined up\n" 7056 "}", 7057 OnePerLine); 7058 verifyFormat("Constructor() :\n" 7059 " aaaaa(aaaaaa),\n" 7060 " aaaaa(aaaaaa),\n" 7061 " aaaaa(aaaaaa),\n" 7062 " aaaaa(aaaaaa),\n" 7063 " aaaaa(aaaaaa) {}", 7064 OnePerLine); 7065 verifyFormat("Constructor() :\n" 7066 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7067 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7068 OnePerLine); 7069 OnePerLine.BinPackParameters = false; 7070 verifyFormat("Constructor() :\n" 7071 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7072 " aaaaaaaaaaa().aaa(),\n" 7073 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7074 OnePerLine); 7075 OnePerLine.ColumnLimit = 60; 7076 verifyFormat("Constructor() :\n" 7077 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7078 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7079 OnePerLine); 7080 7081 EXPECT_EQ("Constructor() :\n" 7082 " // Comment forcing unwanted break.\n" 7083 " aaaa(aaaa) {}", 7084 format("Constructor() :\n" 7085 " // Comment forcing unwanted break.\n" 7086 " aaaa(aaaa) {}", 7087 Style)); 7088 7089 Style.ColumnLimit = 0; 7090 verifyFormat("SomeClass::Constructor() :\n" 7091 " a(a) {}", 7092 Style); 7093 verifyFormat("SomeClass::Constructor() noexcept :\n" 7094 " a(a) {}", 7095 Style); 7096 verifyFormat("SomeClass::Constructor() :\n" 7097 " a(a), b(b), c(c) {}", 7098 Style); 7099 verifyFormat("SomeClass::Constructor() :\n" 7100 " a(a) {\n" 7101 " foo();\n" 7102 " bar();\n" 7103 "}", 7104 Style); 7105 7106 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7107 verifyFormat("SomeClass::Constructor() :\n" 7108 " a(a), b(b), c(c) {\n" 7109 "}", 7110 Style); 7111 verifyFormat("SomeClass::Constructor() :\n" 7112 " a(a) {\n" 7113 "}", 7114 Style); 7115 7116 Style.ColumnLimit = 80; 7117 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7118 Style.ConstructorInitializerIndentWidth = 2; 7119 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7120 verifyFormat("SomeClass::Constructor() :\n" 7121 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7122 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7123 Style); 7124 7125 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7126 // well 7127 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7128 verifyFormat( 7129 "class SomeClass\n" 7130 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7131 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7132 Style); 7133 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7134 verifyFormat( 7135 "class SomeClass\n" 7136 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7137 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7138 Style); 7139 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7140 verifyFormat( 7141 "class SomeClass :\n" 7142 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7143 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7144 Style); 7145 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7146 verifyFormat( 7147 "class SomeClass\n" 7148 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7149 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7150 Style); 7151 } 7152 7153 #ifndef EXPENSIVE_CHECKS 7154 // Expensive checks enables libstdc++ checking which includes validating the 7155 // state of ranges used in std::priority_queue - this blows out the 7156 // runtime/scalability of the function and makes this test unacceptably slow. 7157 TEST_F(FormatTest, MemoizationTests) { 7158 // This breaks if the memoization lookup does not take \c Indent and 7159 // \c LastSpace into account. 7160 verifyFormat( 7161 "extern CFRunLoopTimerRef\n" 7162 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7163 " CFTimeInterval interval, CFOptionFlags flags,\n" 7164 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7165 " CFRunLoopTimerContext *context) {}"); 7166 7167 // Deep nesting somewhat works around our memoization. 7168 verifyFormat( 7169 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7170 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7171 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7172 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7173 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7174 getLLVMStyleWithColumns(65)); 7175 verifyFormat( 7176 "aaaaa(\n" 7177 " aaaaa,\n" 7178 " aaaaa(\n" 7179 " aaaaa,\n" 7180 " aaaaa(\n" 7181 " aaaaa,\n" 7182 " aaaaa(\n" 7183 " aaaaa,\n" 7184 " aaaaa(\n" 7185 " aaaaa,\n" 7186 " aaaaa(\n" 7187 " aaaaa,\n" 7188 " aaaaa(\n" 7189 " aaaaa,\n" 7190 " aaaaa(\n" 7191 " aaaaa,\n" 7192 " aaaaa(\n" 7193 " aaaaa,\n" 7194 " aaaaa(\n" 7195 " aaaaa,\n" 7196 " aaaaa(\n" 7197 " aaaaa,\n" 7198 " aaaaa(\n" 7199 " aaaaa,\n" 7200 " aaaaa))))))))))));", 7201 getLLVMStyleWithColumns(65)); 7202 verifyFormat( 7203 "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" 7204 " a),\n" 7205 " a),\n" 7206 " a),\n" 7207 " a),\n" 7208 " a),\n" 7209 " a),\n" 7210 " a),\n" 7211 " a),\n" 7212 " a),\n" 7213 " a),\n" 7214 " a),\n" 7215 " a),\n" 7216 " a),\n" 7217 " a),\n" 7218 " a),\n" 7219 " a),\n" 7220 " a)", 7221 getLLVMStyleWithColumns(65)); 7222 7223 // This test takes VERY long when memoization is broken. 7224 FormatStyle OnePerLine = getLLVMStyle(); 7225 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7226 OnePerLine.BinPackParameters = false; 7227 std::string input = "Constructor()\n" 7228 " : aaaa(a,\n"; 7229 for (unsigned i = 0, e = 80; i != e; ++i) 7230 input += " a,\n"; 7231 input += " a) {}"; 7232 verifyFormat(input, OnePerLine); 7233 } 7234 #endif 7235 7236 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7237 verifyFormat( 7238 "void f() {\n" 7239 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7240 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7241 " f();\n" 7242 "}"); 7243 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7244 " Intervals[i - 1].getRange().getLast()) {\n}"); 7245 } 7246 7247 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7248 // Principially, we break function declarations in a certain order: 7249 // 1) break amongst arguments. 7250 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7251 " Cccccccccccccc cccccccccccccc);"); 7252 verifyFormat("template <class TemplateIt>\n" 7253 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7254 " TemplateIt *stop) {}"); 7255 7256 // 2) break after return type. 7257 verifyFormat( 7258 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7259 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7260 getGoogleStyle()); 7261 7262 // 3) break after (. 7263 verifyFormat( 7264 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7265 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7266 getGoogleStyle()); 7267 7268 // 4) break before after nested name specifiers. 7269 verifyFormat( 7270 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7271 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7272 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7273 getGoogleStyle()); 7274 7275 // However, there are exceptions, if a sufficient amount of lines can be 7276 // saved. 7277 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7278 // more adjusting. 7279 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7280 " Cccccccccccccc cccccccccc,\n" 7281 " Cccccccccccccc cccccccccc,\n" 7282 " Cccccccccccccc cccccccccc,\n" 7283 " Cccccccccccccc cccccccccc);"); 7284 verifyFormat( 7285 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7286 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7287 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7288 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7289 getGoogleStyle()); 7290 verifyFormat( 7291 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7292 " Cccccccccccccc cccccccccc,\n" 7293 " Cccccccccccccc cccccccccc,\n" 7294 " Cccccccccccccc cccccccccc,\n" 7295 " Cccccccccccccc cccccccccc,\n" 7296 " Cccccccccccccc cccccccccc,\n" 7297 " Cccccccccccccc cccccccccc);"); 7298 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7299 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7300 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7301 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7302 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7303 7304 // Break after multi-line parameters. 7305 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7306 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7308 " bbbb bbbb);"); 7309 verifyFormat("void SomeLoooooooooooongFunction(\n" 7310 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7311 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7312 " int bbbbbbbbbbbbb);"); 7313 7314 // Treat overloaded operators like other functions. 7315 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7316 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7317 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7318 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7319 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7320 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7321 verifyGoogleFormat( 7322 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7323 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7324 verifyGoogleFormat( 7325 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7326 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7327 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7328 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7329 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7330 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7331 verifyGoogleFormat( 7332 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7333 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7334 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7335 verifyGoogleFormat("template <typename T>\n" 7336 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7337 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7338 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7339 7340 FormatStyle Style = getLLVMStyle(); 7341 Style.PointerAlignment = FormatStyle::PAS_Left; 7342 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7343 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7344 Style); 7345 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7346 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7347 Style); 7348 } 7349 7350 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7351 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7352 // Prefer keeping `::` followed by `operator` together. 7353 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7354 "ccccccccc::operator++() {\n" 7355 " stuff();\n" 7356 "}", 7357 format("const aaaa::bbbbbbb\n" 7358 "&ccccccccc::operator++() { stuff(); }", 7359 getLLVMStyleWithColumns(40))); 7360 } 7361 7362 TEST_F(FormatTest, TrailingReturnType) { 7363 verifyFormat("auto foo() -> int;\n"); 7364 // correct trailing return type spacing 7365 verifyFormat("auto operator->() -> int;\n"); 7366 verifyFormat("auto operator++(int) -> int;\n"); 7367 7368 verifyFormat("struct S {\n" 7369 " auto bar() const -> int;\n" 7370 "};"); 7371 verifyFormat("template <size_t Order, typename T>\n" 7372 "auto load_img(const std::string &filename)\n" 7373 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7374 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7375 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7376 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7377 verifyFormat("template <typename T>\n" 7378 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7379 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7380 7381 // Not trailing return types. 7382 verifyFormat("void f() { auto a = b->c(); }"); 7383 verifyFormat("auto a = p->foo();"); 7384 verifyFormat("int a = p->foo();"); 7385 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7386 } 7387 7388 TEST_F(FormatTest, DeductionGuides) { 7389 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7390 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7391 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7392 verifyFormat( 7393 "template <class... T>\n" 7394 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7395 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7396 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7397 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7398 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7399 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7400 verifyFormat("template <class T> x() -> x<1>;"); 7401 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7402 7403 // Ensure not deduction guides. 7404 verifyFormat("c()->f<int>();"); 7405 verifyFormat("x()->foo<1>;"); 7406 verifyFormat("x = p->foo<3>();"); 7407 verifyFormat("x()->x<1>();"); 7408 verifyFormat("x()->x<1>;"); 7409 } 7410 7411 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7412 // Avoid breaking before trailing 'const' or other trailing annotations, if 7413 // they are not function-like. 7414 FormatStyle Style = getGoogleStyleWithColumns(47); 7415 verifyFormat("void someLongFunction(\n" 7416 " int someLoooooooooooooongParameter) const {\n}", 7417 getLLVMStyleWithColumns(47)); 7418 verifyFormat("LoooooongReturnType\n" 7419 "someLoooooooongFunction() const {}", 7420 getLLVMStyleWithColumns(47)); 7421 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7422 " const {}", 7423 Style); 7424 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7425 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7426 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7427 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7428 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7429 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7430 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7431 " aaaaaaaaaaa aaaaa) const override;"); 7432 verifyGoogleFormat( 7433 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7434 " const override;"); 7435 7436 // Even if the first parameter has to be wrapped. 7437 verifyFormat("void someLongFunction(\n" 7438 " int someLongParameter) const {}", 7439 getLLVMStyleWithColumns(46)); 7440 verifyFormat("void someLongFunction(\n" 7441 " int someLongParameter) const {}", 7442 Style); 7443 verifyFormat("void someLongFunction(\n" 7444 " int someLongParameter) override {}", 7445 Style); 7446 verifyFormat("void someLongFunction(\n" 7447 " int someLongParameter) OVERRIDE {}", 7448 Style); 7449 verifyFormat("void someLongFunction(\n" 7450 " int someLongParameter) final {}", 7451 Style); 7452 verifyFormat("void someLongFunction(\n" 7453 " int someLongParameter) FINAL {}", 7454 Style); 7455 verifyFormat("void someLongFunction(\n" 7456 " int parameter) const override {}", 7457 Style); 7458 7459 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7460 verifyFormat("void someLongFunction(\n" 7461 " int someLongParameter) const\n" 7462 "{\n" 7463 "}", 7464 Style); 7465 7466 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7467 verifyFormat("void someLongFunction(\n" 7468 " int someLongParameter) const\n" 7469 " {\n" 7470 " }", 7471 Style); 7472 7473 // Unless these are unknown annotations. 7474 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7475 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7476 " LONG_AND_UGLY_ANNOTATION;"); 7477 7478 // Breaking before function-like trailing annotations is fine to keep them 7479 // close to their arguments. 7480 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7481 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7482 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7483 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7484 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7485 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7486 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7487 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7488 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7489 7490 verifyFormat( 7491 "void aaaaaaaaaaaaaaaaaa()\n" 7492 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7493 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7494 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7495 " __attribute__((unused));"); 7496 verifyGoogleFormat( 7497 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7498 " GUARDED_BY(aaaaaaaaaaaa);"); 7499 verifyGoogleFormat( 7500 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7501 " GUARDED_BY(aaaaaaaaaaaa);"); 7502 verifyGoogleFormat( 7503 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7504 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7505 verifyGoogleFormat( 7506 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7507 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7508 } 7509 7510 TEST_F(FormatTest, FunctionAnnotations) { 7511 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7512 "int OldFunction(const string ¶meter) {}"); 7513 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7514 "string OldFunction(const string ¶meter) {}"); 7515 verifyFormat("template <typename T>\n" 7516 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7517 "string OldFunction(const string ¶meter) {}"); 7518 7519 // Not function annotations. 7520 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7521 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7522 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7523 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7524 verifyFormat("MACRO(abc).function() // wrap\n" 7525 " << abc;"); 7526 verifyFormat("MACRO(abc)->function() // wrap\n" 7527 " << abc;"); 7528 verifyFormat("MACRO(abc)::function() // wrap\n" 7529 " << abc;"); 7530 } 7531 7532 TEST_F(FormatTest, BreaksDesireably) { 7533 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7534 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7535 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7536 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7537 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7538 "}"); 7539 7540 verifyFormat( 7541 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7542 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7543 7544 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7545 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7546 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7547 7548 verifyFormat( 7549 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7550 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7551 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7552 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7553 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7554 7555 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7556 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7557 7558 verifyFormat( 7559 "void f() {\n" 7560 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7561 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7562 "}"); 7563 verifyFormat( 7564 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7565 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7566 verifyFormat( 7567 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7568 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7569 verifyFormat( 7570 "aaaaaa(aaa,\n" 7571 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7572 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7573 " aaaa);"); 7574 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7575 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7576 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7577 7578 // Indent consistently independent of call expression and unary operator. 7579 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7580 " dddddddddddddddddddddddddddddd));"); 7581 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7582 " dddddddddddddddddddddddddddddd));"); 7583 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7584 " dddddddddddddddddddddddddddddd));"); 7585 7586 // This test case breaks on an incorrect memoization, i.e. an optimization not 7587 // taking into account the StopAt value. 7588 verifyFormat( 7589 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7590 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7591 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7592 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7593 7594 verifyFormat("{\n {\n {\n" 7595 " Annotation.SpaceRequiredBefore =\n" 7596 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7597 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7598 " }\n }\n}"); 7599 7600 // Break on an outer level if there was a break on an inner level. 7601 EXPECT_EQ("f(g(h(a, // comment\n" 7602 " b, c),\n" 7603 " d, e),\n" 7604 " x, y);", 7605 format("f(g(h(a, // comment\n" 7606 " b, c), d, e), x, y);")); 7607 7608 // Prefer breaking similar line breaks. 7609 verifyFormat( 7610 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7611 " NSTrackingMouseEnteredAndExited |\n" 7612 " NSTrackingActiveAlways;"); 7613 } 7614 7615 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7616 FormatStyle NoBinPacking = getGoogleStyle(); 7617 NoBinPacking.BinPackParameters = false; 7618 NoBinPacking.BinPackArguments = true; 7619 verifyFormat("void f() {\n" 7620 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7621 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7622 "}", 7623 NoBinPacking); 7624 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7625 " int aaaaaaaaaaaaaaaaaaaa,\n" 7626 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7627 NoBinPacking); 7628 7629 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7630 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7631 " vector<int> bbbbbbbbbbbbbbb);", 7632 NoBinPacking); 7633 // FIXME: This behavior difference is probably not wanted. However, currently 7634 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7635 // template arguments from BreakBeforeParameter being set because of the 7636 // one-per-line formatting. 7637 verifyFormat( 7638 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7639 " aaaaaaaaaa> aaaaaaaaaa);", 7640 NoBinPacking); 7641 verifyFormat( 7642 "void fffffffffff(\n" 7643 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7644 " aaaaaaaaaa);"); 7645 } 7646 7647 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7648 FormatStyle NoBinPacking = getGoogleStyle(); 7649 NoBinPacking.BinPackParameters = false; 7650 NoBinPacking.BinPackArguments = false; 7651 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7652 " aaaaaaaaaaaaaaaaaaaa,\n" 7653 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7654 NoBinPacking); 7655 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7656 " aaaaaaaaaaaaa,\n" 7657 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7658 NoBinPacking); 7659 verifyFormat( 7660 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7661 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7663 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7664 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7665 NoBinPacking); 7666 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7667 " .aaaaaaaaaaaaaaaaaa();", 7668 NoBinPacking); 7669 verifyFormat("void f() {\n" 7670 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7671 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7672 "}", 7673 NoBinPacking); 7674 7675 verifyFormat( 7676 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7677 " aaaaaaaaaaaa,\n" 7678 " aaaaaaaaaaaa);", 7679 NoBinPacking); 7680 verifyFormat( 7681 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7682 " ddddddddddddddddddddddddddddd),\n" 7683 " test);", 7684 NoBinPacking); 7685 7686 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7687 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7688 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7689 " aaaaaaaaaaaaaaaaaa;", 7690 NoBinPacking); 7691 verifyFormat("a(\"a\"\n" 7692 " \"a\",\n" 7693 " a);"); 7694 7695 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7696 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7697 " aaaaaaaaa,\n" 7698 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7699 NoBinPacking); 7700 verifyFormat( 7701 "void f() {\n" 7702 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7703 " .aaaaaaa();\n" 7704 "}", 7705 NoBinPacking); 7706 verifyFormat( 7707 "template <class SomeType, class SomeOtherType>\n" 7708 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7709 NoBinPacking); 7710 } 7711 7712 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7713 FormatStyle Style = getLLVMStyleWithColumns(15); 7714 Style.ExperimentalAutoDetectBinPacking = true; 7715 EXPECT_EQ("aaa(aaaa,\n" 7716 " aaaa,\n" 7717 " aaaa);\n" 7718 "aaa(aaaa,\n" 7719 " aaaa,\n" 7720 " aaaa);", 7721 format("aaa(aaaa,\n" // one-per-line 7722 " aaaa,\n" 7723 " aaaa );\n" 7724 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7725 Style)); 7726 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7727 " aaaa);\n" 7728 "aaa(aaaa, aaaa,\n" 7729 " aaaa);", 7730 format("aaa(aaaa, aaaa,\n" // bin-packed 7731 " aaaa );\n" 7732 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7733 Style)); 7734 } 7735 7736 TEST_F(FormatTest, FormatsBuilderPattern) { 7737 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7738 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7739 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7740 " .StartsWith(\".init\", ORDER_INIT)\n" 7741 " .StartsWith(\".fini\", ORDER_FINI)\n" 7742 " .StartsWith(\".hash\", ORDER_HASH)\n" 7743 " .Default(ORDER_TEXT);\n"); 7744 7745 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7746 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7747 verifyFormat("aaaaaaa->aaaaaaa\n" 7748 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7749 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7750 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7751 verifyFormat( 7752 "aaaaaaa->aaaaaaa\n" 7753 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7754 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7755 verifyFormat( 7756 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7757 " aaaaaaaaaaaaaa);"); 7758 verifyFormat( 7759 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7760 " aaaaaa->aaaaaaaaaaaa()\n" 7761 " ->aaaaaaaaaaaaaaaa(\n" 7762 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7763 " ->aaaaaaaaaaaaaaaaa();"); 7764 verifyGoogleFormat( 7765 "void f() {\n" 7766 " someo->Add((new util::filetools::Handler(dir))\n" 7767 " ->OnEvent1(NewPermanentCallback(\n" 7768 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7769 " ->OnEvent2(NewPermanentCallback(\n" 7770 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7771 " ->OnEvent3(NewPermanentCallback(\n" 7772 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7773 " ->OnEvent5(NewPermanentCallback(\n" 7774 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7775 " ->OnEvent6(NewPermanentCallback(\n" 7776 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7777 "}"); 7778 7779 verifyFormat( 7780 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7781 verifyFormat("aaaaaaaaaaaaaaa()\n" 7782 " .aaaaaaaaaaaaaaa()\n" 7783 " .aaaaaaaaaaaaaaa()\n" 7784 " .aaaaaaaaaaaaaaa()\n" 7785 " .aaaaaaaaaaaaaaa();"); 7786 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7787 " .aaaaaaaaaaaaaaa()\n" 7788 " .aaaaaaaaaaaaaaa()\n" 7789 " .aaaaaaaaaaaaaaa();"); 7790 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7791 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7792 " .aaaaaaaaaaaaaaa();"); 7793 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7794 " ->aaaaaaaaaaaaaae(0)\n" 7795 " ->aaaaaaaaaaaaaaa();"); 7796 7797 // Don't linewrap after very short segments. 7798 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7799 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7800 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7801 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7802 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7803 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7804 verifyFormat("aaa()\n" 7805 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7806 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7807 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7808 7809 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7810 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7811 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7812 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7813 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7814 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7815 7816 // Prefer not to break after empty parentheses. 7817 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7818 " First->LastNewlineOffset);"); 7819 7820 // Prefer not to create "hanging" indents. 7821 verifyFormat( 7822 "return !soooooooooooooome_map\n" 7823 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7824 " .second;"); 7825 verifyFormat( 7826 "return aaaaaaaaaaaaaaaa\n" 7827 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7828 " .aaaa(aaaaaaaaaaaaaa);"); 7829 // No hanging indent here. 7830 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7831 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7832 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7833 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7834 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7835 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7836 getLLVMStyleWithColumns(60)); 7837 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7838 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7839 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7840 getLLVMStyleWithColumns(59)); 7841 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7842 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7843 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7844 7845 // Dont break if only closing statements before member call 7846 verifyFormat("test() {\n" 7847 " ([]() -> {\n" 7848 " int b = 32;\n" 7849 " return 3;\n" 7850 " }).foo();\n" 7851 "}"); 7852 verifyFormat("test() {\n" 7853 " (\n" 7854 " []() -> {\n" 7855 " int b = 32;\n" 7856 " return 3;\n" 7857 " },\n" 7858 " foo, bar)\n" 7859 " .foo();\n" 7860 "}"); 7861 verifyFormat("test() {\n" 7862 " ([]() -> {\n" 7863 " int b = 32;\n" 7864 " return 3;\n" 7865 " })\n" 7866 " .foo()\n" 7867 " .bar();\n" 7868 "}"); 7869 verifyFormat("test() {\n" 7870 " ([]() -> {\n" 7871 " int b = 32;\n" 7872 " return 3;\n" 7873 " })\n" 7874 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7875 " \"bbbb\");\n" 7876 "}", 7877 getLLVMStyleWithColumns(30)); 7878 } 7879 7880 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7881 verifyFormat( 7882 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7883 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7884 verifyFormat( 7885 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7886 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7887 7888 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7889 " ccccccccccccccccccccccccc) {\n}"); 7890 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7891 " ccccccccccccccccccccccccc) {\n}"); 7892 7893 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7894 " ccccccccccccccccccccccccc) {\n}"); 7895 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7896 " ccccccccccccccccccccccccc) {\n}"); 7897 7898 verifyFormat( 7899 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7900 " ccccccccccccccccccccccccc) {\n}"); 7901 verifyFormat( 7902 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7903 " ccccccccccccccccccccccccc) {\n}"); 7904 7905 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7906 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7907 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7908 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7909 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7910 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7911 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7912 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7913 7914 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7915 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7916 " aaaaaaaaaaaaaaa != aa) {\n}"); 7917 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7918 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7919 " aaaaaaaaaaaaaaa != aa) {\n}"); 7920 } 7921 7922 TEST_F(FormatTest, BreaksAfterAssignments) { 7923 verifyFormat( 7924 "unsigned Cost =\n" 7925 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7926 " SI->getPointerAddressSpaceee());\n"); 7927 verifyFormat( 7928 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7929 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7930 7931 verifyFormat( 7932 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7933 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7934 verifyFormat("unsigned OriginalStartColumn =\n" 7935 " SourceMgr.getSpellingColumnNumber(\n" 7936 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7937 " 1;"); 7938 } 7939 7940 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7941 FormatStyle Style = getLLVMStyle(); 7942 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7943 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7944 Style); 7945 7946 Style.PenaltyBreakAssignment = 20; 7947 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7948 " cccccccccccccccccccccccccc;", 7949 Style); 7950 } 7951 7952 TEST_F(FormatTest, AlignsAfterAssignments) { 7953 verifyFormat( 7954 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7955 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7956 verifyFormat( 7957 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7958 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7959 verifyFormat( 7960 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7961 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7962 verifyFormat( 7963 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7964 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7965 verifyFormat( 7966 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7967 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7968 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7969 } 7970 7971 TEST_F(FormatTest, AlignsAfterReturn) { 7972 verifyFormat( 7973 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7974 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7975 verifyFormat( 7976 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7977 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7978 verifyFormat( 7979 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7980 " aaaaaaaaaaaaaaaaaaaaaa();"); 7981 verifyFormat( 7982 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7983 " aaaaaaaaaaaaaaaaaaaaaa());"); 7984 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7985 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7986 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7988 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7989 verifyFormat("return\n" 7990 " // true if code is one of a or b.\n" 7991 " code == a || code == b;"); 7992 } 7993 7994 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7995 verifyFormat( 7996 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7997 " aaaaaaaaa aaaaaaa) {}"); 7998 verifyFormat( 7999 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8000 " aaaaaaaaaaa aaaaaaaaa);"); 8001 verifyFormat( 8002 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8003 " aaaaaaaaaaaaaaaaaaaaa));"); 8004 FormatStyle Style = getLLVMStyle(); 8005 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8006 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8007 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8008 Style); 8009 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8010 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8011 Style); 8012 verifyFormat("SomeLongVariableName->someFunction(\n" 8013 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8014 Style); 8015 verifyFormat( 8016 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8017 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8018 Style); 8019 verifyFormat( 8020 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8021 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8022 Style); 8023 verifyFormat( 8024 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8025 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8026 Style); 8027 8028 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8029 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8030 " b));", 8031 Style); 8032 8033 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8034 Style.BinPackArguments = false; 8035 Style.BinPackParameters = false; 8036 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8037 " aaaaaaaaaaa aaaaaaaa,\n" 8038 " aaaaaaaaa aaaaaaa,\n" 8039 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8040 Style); 8041 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8042 " aaaaaaaaaaa aaaaaaaaa,\n" 8043 " aaaaaaaaaaa aaaaaaaaa,\n" 8044 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8045 Style); 8046 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8047 " aaaaaaaaaaaaaaa,\n" 8048 " aaaaaaaaaaaaaaaaaaaaa,\n" 8049 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8050 Style); 8051 verifyFormat( 8052 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8053 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8054 Style); 8055 verifyFormat( 8056 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8057 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8058 Style); 8059 verifyFormat( 8060 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8061 " aaaaaaaaaaaaaaaaaaaaa(\n" 8062 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8063 " aaaaaaaaaaaaaaaa);", 8064 Style); 8065 verifyFormat( 8066 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8067 " aaaaaaaaaaaaaaaaaaaaa(\n" 8068 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8069 " aaaaaaaaaaaaaaaa);", 8070 Style); 8071 } 8072 8073 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8074 FormatStyle Style = getLLVMStyleWithColumns(40); 8075 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8076 " bbbbbbbbbbbbbbbbbbbbbb);", 8077 Style); 8078 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8079 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8080 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8081 " bbbbbbbbbbbbbbbbbbbbbb);", 8082 Style); 8083 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8084 Style.AlignOperands = FormatStyle::OAS_Align; 8085 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8086 " bbbbbbbbbbbbbbbbbbbbbb);", 8087 Style); 8088 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8089 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8090 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8091 " bbbbbbbbbbbbbbbbbbbbbb);", 8092 Style); 8093 } 8094 8095 TEST_F(FormatTest, BreaksConditionalExpressions) { 8096 verifyFormat( 8097 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8098 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8099 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8100 verifyFormat( 8101 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8102 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8103 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8104 verifyFormat( 8105 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8106 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8107 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8108 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8109 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8110 verifyFormat( 8111 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8112 " : aaaaaaaaaaaaa);"); 8113 verifyFormat( 8114 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8115 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8116 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8117 " aaaaaaaaaaaaa);"); 8118 verifyFormat( 8119 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8120 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8121 " aaaaaaaaaaaaa);"); 8122 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8123 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8125 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8126 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8127 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8128 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8129 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8130 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8131 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8132 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8133 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8134 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8136 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8137 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8138 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8139 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8140 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8141 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8142 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8143 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8144 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8145 " : aaaaaaaaaaaaaaaa;"); 8146 verifyFormat( 8147 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8148 " ? aaaaaaaaaaaaaaa\n" 8149 " : aaaaaaaaaaaaaaa;"); 8150 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8151 " aaaaaaaaa\n" 8152 " ? b\n" 8153 " : c);"); 8154 verifyFormat("return aaaa == bbbb\n" 8155 " // comment\n" 8156 " ? aaaa\n" 8157 " : bbbb;"); 8158 verifyFormat("unsigned Indent =\n" 8159 " format(TheLine.First,\n" 8160 " IndentForLevel[TheLine.Level] >= 0\n" 8161 " ? IndentForLevel[TheLine.Level]\n" 8162 " : TheLine * 2,\n" 8163 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8164 getLLVMStyleWithColumns(60)); 8165 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8166 " ? aaaaaaaaaaaaaaa\n" 8167 " : bbbbbbbbbbbbbbb //\n" 8168 " ? ccccccccccccccc\n" 8169 " : ddddddddddddddd;"); 8170 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8171 " ? aaaaaaaaaaaaaaa\n" 8172 " : (bbbbbbbbbbbbbbb //\n" 8173 " ? ccccccccccccccc\n" 8174 " : ddddddddddddddd);"); 8175 verifyFormat( 8176 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8177 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8178 " aaaaaaaaaaaaaaaaaaaaa +\n" 8179 " aaaaaaaaaaaaaaaaaaaaa\n" 8180 " : aaaaaaaaaa;"); 8181 verifyFormat( 8182 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8183 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8184 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8185 8186 FormatStyle NoBinPacking = getLLVMStyle(); 8187 NoBinPacking.BinPackArguments = false; 8188 verifyFormat( 8189 "void f() {\n" 8190 " g(aaa,\n" 8191 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8192 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8193 " ? aaaaaaaaaaaaaaa\n" 8194 " : aaaaaaaaaaaaaaa);\n" 8195 "}", 8196 NoBinPacking); 8197 verifyFormat( 8198 "void f() {\n" 8199 " g(aaa,\n" 8200 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8201 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8202 " ?: aaaaaaaaaaaaaaa);\n" 8203 "}", 8204 NoBinPacking); 8205 8206 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8207 " // comment.\n" 8208 " ccccccccccccccccccccccccccccccccccccccc\n" 8209 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8210 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8211 8212 // Assignments in conditional expressions. Apparently not uncommon :-(. 8213 verifyFormat("return a != b\n" 8214 " // comment\n" 8215 " ? a = b\n" 8216 " : a = b;"); 8217 verifyFormat("return a != b\n" 8218 " // comment\n" 8219 " ? a = a != b\n" 8220 " // comment\n" 8221 " ? a = b\n" 8222 " : a\n" 8223 " : a;\n"); 8224 verifyFormat("return a != b\n" 8225 " // comment\n" 8226 " ? a\n" 8227 " : a = a != b\n" 8228 " // comment\n" 8229 " ? a = b\n" 8230 " : a;"); 8231 8232 // Chained conditionals 8233 FormatStyle Style = getLLVMStyleWithColumns(70); 8234 Style.AlignOperands = FormatStyle::OAS_Align; 8235 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8236 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8237 " : 3333333333333333;", 8238 Style); 8239 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8240 " : bbbbbbbbbb ? 2222222222222222\n" 8241 " : 3333333333333333;", 8242 Style); 8243 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8244 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8245 " : 3333333333333333;", 8246 Style); 8247 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8248 " : bbbbbbbbbbbbbb ? 222222\n" 8249 " : 333333;", 8250 Style); 8251 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8252 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8253 " : cccccccccccccc ? 3333333333333333\n" 8254 " : 4444444444444444;", 8255 Style); 8256 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8257 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8258 " : 3333333333333333;", 8259 Style); 8260 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8261 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8262 " : (aaa ? bbb : ccc);", 8263 Style); 8264 verifyFormat( 8265 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8266 " : cccccccccccccccccc)\n" 8267 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8268 " : 3333333333333333;", 8269 Style); 8270 verifyFormat( 8271 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8272 " : cccccccccccccccccc)\n" 8273 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8274 " : 3333333333333333;", 8275 Style); 8276 verifyFormat( 8277 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8278 " : dddddddddddddddddd)\n" 8279 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8280 " : 3333333333333333;", 8281 Style); 8282 verifyFormat( 8283 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8284 " : dddddddddddddddddd)\n" 8285 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8286 " : 3333333333333333;", 8287 Style); 8288 verifyFormat( 8289 "return aaaaaaaaa ? 1111111111111111\n" 8290 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8291 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8292 " : dddddddddddddddddd)\n", 8293 Style); 8294 verifyFormat( 8295 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8296 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8297 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8298 " : cccccccccccccccccc);", 8299 Style); 8300 verifyFormat( 8301 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8302 " : ccccccccccccccc ? dddddddddddddddddd\n" 8303 " : eeeeeeeeeeeeeeeeee)\n" 8304 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8305 " : 3333333333333333;", 8306 Style); 8307 verifyFormat( 8308 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8309 " : ccccccccccccccc ? dddddddddddddddddd\n" 8310 " : eeeeeeeeeeeeeeeeee)\n" 8311 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8312 " : 3333333333333333;", 8313 Style); 8314 verifyFormat( 8315 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8316 " : cccccccccccc ? dddddddddddddddddd\n" 8317 " : eeeeeeeeeeeeeeeeee)\n" 8318 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8319 " : 3333333333333333;", 8320 Style); 8321 verifyFormat( 8322 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8323 " : cccccccccccccccccc\n" 8324 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8325 " : 3333333333333333;", 8326 Style); 8327 verifyFormat( 8328 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8329 " : cccccccccccccccc ? dddddddddddddddddd\n" 8330 " : eeeeeeeeeeeeeeeeee\n" 8331 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8332 " : 3333333333333333;", 8333 Style); 8334 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8335 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8336 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8337 " : eeeeeeeeeeeeeeeeee)\n" 8338 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8339 " : 3333333333333333;", 8340 Style); 8341 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8342 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8343 " : cccccccccccccccc ? dddddddddddddddddd\n" 8344 " : eeeeeeeeeeeeeeeeee\n" 8345 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8346 " : 3333333333333333;", 8347 Style); 8348 8349 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8350 Style.BreakBeforeTernaryOperators = false; 8351 // FIXME: Aligning the question marks is weird given DontAlign. 8352 // Consider disabling this alignment in this case. Also check whether this 8353 // will render the adjustment from https://reviews.llvm.org/D82199 8354 // unnecessary. 8355 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8356 " bbbb ? cccccccccccccccccc :\n" 8357 " ddddd;\n", 8358 Style); 8359 8360 EXPECT_EQ( 8361 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8362 " /*\n" 8363 " */\n" 8364 " function() {\n" 8365 " try {\n" 8366 " return JJJJJJJJJJJJJJ(\n" 8367 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8368 " }\n" 8369 " } :\n" 8370 " function() {};", 8371 format( 8372 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8373 " /*\n" 8374 " */\n" 8375 " function() {\n" 8376 " try {\n" 8377 " return JJJJJJJJJJJJJJ(\n" 8378 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8379 " }\n" 8380 " } :\n" 8381 " function() {};", 8382 getGoogleStyle(FormatStyle::LK_JavaScript))); 8383 } 8384 8385 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8386 FormatStyle Style = getLLVMStyleWithColumns(70); 8387 Style.BreakBeforeTernaryOperators = false; 8388 verifyFormat( 8389 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8390 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8391 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8392 Style); 8393 verifyFormat( 8394 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8395 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8396 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8397 Style); 8398 verifyFormat( 8399 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8400 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8401 Style); 8402 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8403 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8404 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8405 Style); 8406 verifyFormat( 8407 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8408 " aaaaaaaaaaaaa);", 8409 Style); 8410 verifyFormat( 8411 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8412 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8413 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8414 " aaaaaaaaaaaaa);", 8415 Style); 8416 verifyFormat( 8417 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8418 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8419 " aaaaaaaaaaaaa);", 8420 Style); 8421 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8422 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8423 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8424 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8425 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8426 Style); 8427 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8428 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8429 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8430 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8431 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8432 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8433 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8434 Style); 8435 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8436 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8437 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8438 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8439 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8440 Style); 8441 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8442 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8443 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8444 Style); 8445 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8446 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8447 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8448 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8449 Style); 8450 verifyFormat( 8451 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8452 " aaaaaaaaaaaaaaa :\n" 8453 " aaaaaaaaaaaaaaa;", 8454 Style); 8455 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8456 " aaaaaaaaa ?\n" 8457 " b :\n" 8458 " c);", 8459 Style); 8460 verifyFormat("unsigned Indent =\n" 8461 " format(TheLine.First,\n" 8462 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8463 " IndentForLevel[TheLine.Level] :\n" 8464 " TheLine * 2,\n" 8465 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8466 Style); 8467 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8468 " aaaaaaaaaaaaaaa :\n" 8469 " bbbbbbbbbbbbbbb ? //\n" 8470 " ccccccccccccccc :\n" 8471 " ddddddddddddddd;", 8472 Style); 8473 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8474 " aaaaaaaaaaaaaaa :\n" 8475 " (bbbbbbbbbbbbbbb ? //\n" 8476 " ccccccccccccccc :\n" 8477 " ddddddddddddddd);", 8478 Style); 8479 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8480 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8481 " ccccccccccccccccccccccccccc;", 8482 Style); 8483 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8484 " aaaaa :\n" 8485 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8486 Style); 8487 8488 // Chained conditionals 8489 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8490 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8491 " 3333333333333333;", 8492 Style); 8493 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8494 " bbbbbbbbbb ? 2222222222222222 :\n" 8495 " 3333333333333333;", 8496 Style); 8497 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8498 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8499 " 3333333333333333;", 8500 Style); 8501 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8502 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8503 " 333333;", 8504 Style); 8505 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8506 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8507 " cccccccccccccccc ? 3333333333333333 :\n" 8508 " 4444444444444444;", 8509 Style); 8510 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8511 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8512 " 3333333333333333;", 8513 Style); 8514 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8515 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8516 " (aaa ? bbb : ccc);", 8517 Style); 8518 verifyFormat( 8519 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8520 " cccccccccccccccccc) :\n" 8521 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8522 " 3333333333333333;", 8523 Style); 8524 verifyFormat( 8525 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8526 " cccccccccccccccccc) :\n" 8527 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8528 " 3333333333333333;", 8529 Style); 8530 verifyFormat( 8531 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8532 " dddddddddddddddddd) :\n" 8533 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8534 " 3333333333333333;", 8535 Style); 8536 verifyFormat( 8537 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8538 " dddddddddddddddddd) :\n" 8539 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8540 " 3333333333333333;", 8541 Style); 8542 verifyFormat( 8543 "return aaaaaaaaa ? 1111111111111111 :\n" 8544 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8545 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8546 " dddddddddddddddddd)\n", 8547 Style); 8548 verifyFormat( 8549 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8550 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8551 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8552 " cccccccccccccccccc);", 8553 Style); 8554 verifyFormat( 8555 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8556 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8557 " eeeeeeeeeeeeeeeeee) :\n" 8558 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8559 " 3333333333333333;", 8560 Style); 8561 verifyFormat( 8562 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8563 " ccccccccccccc ? dddddddddddddddddd :\n" 8564 " eeeeeeeeeeeeeeeeee) :\n" 8565 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8566 " 3333333333333333;", 8567 Style); 8568 verifyFormat( 8569 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8570 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8571 " eeeeeeeeeeeeeeeeee) :\n" 8572 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8573 " 3333333333333333;", 8574 Style); 8575 verifyFormat( 8576 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8577 " cccccccccccccccccc :\n" 8578 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8579 " 3333333333333333;", 8580 Style); 8581 verifyFormat( 8582 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8583 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8584 " eeeeeeeeeeeeeeeeee :\n" 8585 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8586 " 3333333333333333;", 8587 Style); 8588 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8589 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8590 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8591 " eeeeeeeeeeeeeeeeee) :\n" 8592 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8593 " 3333333333333333;", 8594 Style); 8595 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8596 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8597 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8598 " eeeeeeeeeeeeeeeeee :\n" 8599 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8600 " 3333333333333333;", 8601 Style); 8602 } 8603 8604 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8605 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8606 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8607 verifyFormat("bool a = true, b = false;"); 8608 8609 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8610 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8611 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8612 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8613 verifyFormat( 8614 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8615 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8616 " d = e && f;"); 8617 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8618 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8619 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8620 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8621 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8622 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8623 8624 FormatStyle Style = getGoogleStyle(); 8625 Style.PointerAlignment = FormatStyle::PAS_Left; 8626 Style.DerivePointerAlignment = false; 8627 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8628 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8629 " *b = bbbbbbbbbbbbbbbbbbb;", 8630 Style); 8631 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8632 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8633 Style); 8634 verifyFormat("vector<int*> a, b;", Style); 8635 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8636 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8637 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8638 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8639 Style); 8640 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8641 Style); 8642 verifyFormat( 8643 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8644 Style); 8645 8646 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8647 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8648 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8649 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8650 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8651 Style); 8652 } 8653 8654 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8655 verifyFormat("arr[foo ? bar : baz];"); 8656 verifyFormat("f()[foo ? bar : baz];"); 8657 verifyFormat("(a + b)[foo ? bar : baz];"); 8658 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8659 } 8660 8661 TEST_F(FormatTest, AlignsStringLiterals) { 8662 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8663 " \"short literal\");"); 8664 verifyFormat( 8665 "looooooooooooooooooooooooongFunction(\n" 8666 " \"short literal\"\n" 8667 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8668 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8669 " \" string literals\",\n" 8670 " and, other, parameters);"); 8671 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8672 " \"5678\";", 8673 format("fun + \"1243\" /* comment */\n" 8674 " \"5678\";", 8675 getLLVMStyleWithColumns(28))); 8676 EXPECT_EQ( 8677 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8678 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8679 " \"aaaaaaaaaaaaaaaa\";", 8680 format("aaaaaa =" 8681 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8682 "aaaaaaaaaaaaaaaaaaaaa\" " 8683 "\"aaaaaaaaaaaaaaaa\";")); 8684 verifyFormat("a = a + \"a\"\n" 8685 " \"a\"\n" 8686 " \"a\";"); 8687 verifyFormat("f(\"a\", \"b\"\n" 8688 " \"c\");"); 8689 8690 verifyFormat( 8691 "#define LL_FORMAT \"ll\"\n" 8692 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8693 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8694 8695 verifyFormat("#define A(X) \\\n" 8696 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8697 " \"ccccc\"", 8698 getLLVMStyleWithColumns(23)); 8699 verifyFormat("#define A \"def\"\n" 8700 "f(\"abc\" A \"ghi\"\n" 8701 " \"jkl\");"); 8702 8703 verifyFormat("f(L\"a\"\n" 8704 " L\"b\");"); 8705 verifyFormat("#define A(X) \\\n" 8706 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8707 " L\"ccccc\"", 8708 getLLVMStyleWithColumns(25)); 8709 8710 verifyFormat("f(@\"a\"\n" 8711 " @\"b\");"); 8712 verifyFormat("NSString s = @\"a\"\n" 8713 " @\"b\"\n" 8714 " @\"c\";"); 8715 verifyFormat("NSString s = @\"a\"\n" 8716 " \"b\"\n" 8717 " \"c\";"); 8718 } 8719 8720 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8721 FormatStyle Style = getLLVMStyle(); 8722 // No declarations or definitions should be moved to own line. 8723 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8724 verifyFormat("class A {\n" 8725 " int f() { return 1; }\n" 8726 " int g();\n" 8727 "};\n" 8728 "int f() { return 1; }\n" 8729 "int g();\n", 8730 Style); 8731 8732 // All declarations and definitions should have the return type moved to its 8733 // own line. 8734 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8735 Style.TypenameMacros = {"LIST"}; 8736 verifyFormat("SomeType\n" 8737 "funcdecl(LIST(uint64_t));", 8738 Style); 8739 verifyFormat("class E {\n" 8740 " int\n" 8741 " f() {\n" 8742 " return 1;\n" 8743 " }\n" 8744 " int\n" 8745 " g();\n" 8746 "};\n" 8747 "int\n" 8748 "f() {\n" 8749 " return 1;\n" 8750 "}\n" 8751 "int\n" 8752 "g();\n", 8753 Style); 8754 8755 // Top-level definitions, and no kinds of declarations should have the 8756 // return type moved to its own line. 8757 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8758 verifyFormat("class B {\n" 8759 " int f() { return 1; }\n" 8760 " int g();\n" 8761 "};\n" 8762 "int\n" 8763 "f() {\n" 8764 " return 1;\n" 8765 "}\n" 8766 "int g();\n", 8767 Style); 8768 8769 // Top-level definitions and declarations should have the return type moved 8770 // to its own line. 8771 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8772 verifyFormat("class C {\n" 8773 " int f() { return 1; }\n" 8774 " int g();\n" 8775 "};\n" 8776 "int\n" 8777 "f() {\n" 8778 " return 1;\n" 8779 "}\n" 8780 "int\n" 8781 "g();\n", 8782 Style); 8783 8784 // All definitions should have the return type moved to its own line, but no 8785 // kinds of declarations. 8786 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8787 verifyFormat("class D {\n" 8788 " int\n" 8789 " f() {\n" 8790 " return 1;\n" 8791 " }\n" 8792 " int g();\n" 8793 "};\n" 8794 "int\n" 8795 "f() {\n" 8796 " return 1;\n" 8797 "}\n" 8798 "int g();\n", 8799 Style); 8800 verifyFormat("const char *\n" 8801 "f(void) {\n" // Break here. 8802 " return \"\";\n" 8803 "}\n" 8804 "const char *bar(void);\n", // No break here. 8805 Style); 8806 verifyFormat("template <class T>\n" 8807 "T *\n" 8808 "f(T &c) {\n" // Break here. 8809 " return NULL;\n" 8810 "}\n" 8811 "template <class T> T *f(T &c);\n", // No break here. 8812 Style); 8813 verifyFormat("class C {\n" 8814 " int\n" 8815 " operator+() {\n" 8816 " return 1;\n" 8817 " }\n" 8818 " int\n" 8819 " operator()() {\n" 8820 " return 1;\n" 8821 " }\n" 8822 "};\n", 8823 Style); 8824 verifyFormat("void\n" 8825 "A::operator()() {}\n" 8826 "void\n" 8827 "A::operator>>() {}\n" 8828 "void\n" 8829 "A::operator+() {}\n" 8830 "void\n" 8831 "A::operator*() {}\n" 8832 "void\n" 8833 "A::operator->() {}\n" 8834 "void\n" 8835 "A::operator void *() {}\n" 8836 "void\n" 8837 "A::operator void &() {}\n" 8838 "void\n" 8839 "A::operator void &&() {}\n" 8840 "void\n" 8841 "A::operator char *() {}\n" 8842 "void\n" 8843 "A::operator[]() {}\n" 8844 "void\n" 8845 "A::operator!() {}\n" 8846 "void\n" 8847 "A::operator**() {}\n" 8848 "void\n" 8849 "A::operator<Foo> *() {}\n" 8850 "void\n" 8851 "A::operator<Foo> **() {}\n" 8852 "void\n" 8853 "A::operator<Foo> &() {}\n" 8854 "void\n" 8855 "A::operator void **() {}\n", 8856 Style); 8857 verifyFormat("constexpr auto\n" 8858 "operator()() const -> reference {}\n" 8859 "constexpr auto\n" 8860 "operator>>() const -> reference {}\n" 8861 "constexpr auto\n" 8862 "operator+() const -> reference {}\n" 8863 "constexpr auto\n" 8864 "operator*() const -> reference {}\n" 8865 "constexpr auto\n" 8866 "operator->() const -> reference {}\n" 8867 "constexpr auto\n" 8868 "operator++() const -> reference {}\n" 8869 "constexpr auto\n" 8870 "operator void *() const -> reference {}\n" 8871 "constexpr auto\n" 8872 "operator void **() const -> reference {}\n" 8873 "constexpr auto\n" 8874 "operator void *() const -> reference {}\n" 8875 "constexpr auto\n" 8876 "operator void &() const -> reference {}\n" 8877 "constexpr auto\n" 8878 "operator void &&() const -> reference {}\n" 8879 "constexpr auto\n" 8880 "operator char *() const -> reference {}\n" 8881 "constexpr auto\n" 8882 "operator!() const -> reference {}\n" 8883 "constexpr auto\n" 8884 "operator[]() const -> reference {}\n", 8885 Style); 8886 verifyFormat("void *operator new(std::size_t s);", // No break here. 8887 Style); 8888 verifyFormat("void *\n" 8889 "operator new(std::size_t s) {}", 8890 Style); 8891 verifyFormat("void *\n" 8892 "operator delete[](void *ptr) {}", 8893 Style); 8894 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8895 verifyFormat("const char *\n" 8896 "f(void)\n" // Break here. 8897 "{\n" 8898 " return \"\";\n" 8899 "}\n" 8900 "const char *bar(void);\n", // No break here. 8901 Style); 8902 verifyFormat("template <class T>\n" 8903 "T *\n" // Problem here: no line break 8904 "f(T &c)\n" // Break here. 8905 "{\n" 8906 " return NULL;\n" 8907 "}\n" 8908 "template <class T> T *f(T &c);\n", // No break here. 8909 Style); 8910 verifyFormat("int\n" 8911 "foo(A<bool> a)\n" 8912 "{\n" 8913 " return a;\n" 8914 "}\n", 8915 Style); 8916 verifyFormat("int\n" 8917 "foo(A<8> a)\n" 8918 "{\n" 8919 " return a;\n" 8920 "}\n", 8921 Style); 8922 verifyFormat("int\n" 8923 "foo(A<B<bool>, 8> a)\n" 8924 "{\n" 8925 " return a;\n" 8926 "}\n", 8927 Style); 8928 verifyFormat("int\n" 8929 "foo(A<B<8>, bool> a)\n" 8930 "{\n" 8931 " return a;\n" 8932 "}\n", 8933 Style); 8934 verifyFormat("int\n" 8935 "foo(A<B<bool>, bool> a)\n" 8936 "{\n" 8937 " return a;\n" 8938 "}\n", 8939 Style); 8940 verifyFormat("int\n" 8941 "foo(A<B<8>, 8> a)\n" 8942 "{\n" 8943 " return a;\n" 8944 "}\n", 8945 Style); 8946 8947 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8948 Style.BraceWrapping.AfterFunction = true; 8949 verifyFormat("int f(i);\n" // No break here. 8950 "int\n" // Break here. 8951 "f(i)\n" 8952 "{\n" 8953 " return i + 1;\n" 8954 "}\n" 8955 "int\n" // Break here. 8956 "f(i)\n" 8957 "{\n" 8958 " return i + 1;\n" 8959 "};", 8960 Style); 8961 verifyFormat("int f(a, b, c);\n" // No break here. 8962 "int\n" // Break here. 8963 "f(a, b, c)\n" // Break here. 8964 "short a, b;\n" 8965 "float c;\n" 8966 "{\n" 8967 " return a + b < c;\n" 8968 "}\n" 8969 "int\n" // Break here. 8970 "f(a, b, c)\n" // Break here. 8971 "short a, b;\n" 8972 "float c;\n" 8973 "{\n" 8974 " return a + b < c;\n" 8975 "};", 8976 Style); 8977 verifyFormat("byte *\n" // Break here. 8978 "f(a)\n" // Break here. 8979 "byte a[];\n" 8980 "{\n" 8981 " return a;\n" 8982 "}", 8983 Style); 8984 verifyFormat("bool f(int a, int) override;\n" 8985 "Bar g(int a, Bar) final;\n" 8986 "Bar h(a, Bar) final;", 8987 Style); 8988 verifyFormat("int\n" 8989 "f(a)", 8990 Style); 8991 verifyFormat("bool\n" 8992 "f(size_t = 0, bool b = false)\n" 8993 "{\n" 8994 " return !b;\n" 8995 "}", 8996 Style); 8997 8998 // The return breaking style doesn't affect: 8999 // * function and object definitions with attribute-like macros 9000 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9001 " ABSL_GUARDED_BY(mutex) = {};", 9002 getGoogleStyleWithColumns(40)); 9003 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9004 " ABSL_GUARDED_BY(mutex); // comment", 9005 getGoogleStyleWithColumns(40)); 9006 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9007 " ABSL_GUARDED_BY(mutex1)\n" 9008 " ABSL_GUARDED_BY(mutex2);", 9009 getGoogleStyleWithColumns(40)); 9010 verifyFormat("Tttttt f(int a, int b)\n" 9011 " ABSL_GUARDED_BY(mutex1)\n" 9012 " ABSL_GUARDED_BY(mutex2);", 9013 getGoogleStyleWithColumns(40)); 9014 // * typedefs 9015 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9016 9017 Style = getGNUStyle(); 9018 9019 // Test for comments at the end of function declarations. 9020 verifyFormat("void\n" 9021 "foo (int a, /*abc*/ int b) // def\n" 9022 "{\n" 9023 "}\n", 9024 Style); 9025 9026 verifyFormat("void\n" 9027 "foo (int a, /* abc */ int b) /* def */\n" 9028 "{\n" 9029 "}\n", 9030 Style); 9031 9032 // Definitions that should not break after return type 9033 verifyFormat("void foo (int a, int b); // def\n", Style); 9034 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9035 verifyFormat("void foo (int a, int b);\n", Style); 9036 } 9037 9038 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9039 FormatStyle NoBreak = getLLVMStyle(); 9040 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9041 FormatStyle Break = getLLVMStyle(); 9042 Break.AlwaysBreakBeforeMultilineStrings = true; 9043 verifyFormat("aaaa = \"bbbb\"\n" 9044 " \"cccc\";", 9045 NoBreak); 9046 verifyFormat("aaaa =\n" 9047 " \"bbbb\"\n" 9048 " \"cccc\";", 9049 Break); 9050 verifyFormat("aaaa(\"bbbb\"\n" 9051 " \"cccc\");", 9052 NoBreak); 9053 verifyFormat("aaaa(\n" 9054 " \"bbbb\"\n" 9055 " \"cccc\");", 9056 Break); 9057 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9058 " \"cccc\");", 9059 NoBreak); 9060 verifyFormat("aaaa(qqq,\n" 9061 " \"bbbb\"\n" 9062 " \"cccc\");", 9063 Break); 9064 verifyFormat("aaaa(qqq,\n" 9065 " L\"bbbb\"\n" 9066 " L\"cccc\");", 9067 Break); 9068 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9069 " \"bbbb\"));", 9070 Break); 9071 verifyFormat("string s = someFunction(\n" 9072 " \"abc\"\n" 9073 " \"abc\");", 9074 Break); 9075 9076 // As we break before unary operators, breaking right after them is bad. 9077 verifyFormat("string foo = abc ? \"x\"\n" 9078 " \"blah blah blah blah blah blah\"\n" 9079 " : \"y\";", 9080 Break); 9081 9082 // Don't break if there is no column gain. 9083 verifyFormat("f(\"aaaa\"\n" 9084 " \"bbbb\");", 9085 Break); 9086 9087 // Treat literals with escaped newlines like multi-line string literals. 9088 EXPECT_EQ("x = \"a\\\n" 9089 "b\\\n" 9090 "c\";", 9091 format("x = \"a\\\n" 9092 "b\\\n" 9093 "c\";", 9094 NoBreak)); 9095 EXPECT_EQ("xxxx =\n" 9096 " \"a\\\n" 9097 "b\\\n" 9098 "c\";", 9099 format("xxxx = \"a\\\n" 9100 "b\\\n" 9101 "c\";", 9102 Break)); 9103 9104 EXPECT_EQ("NSString *const kString =\n" 9105 " @\"aaaa\"\n" 9106 " @\"bbbb\";", 9107 format("NSString *const kString = @\"aaaa\"\n" 9108 "@\"bbbb\";", 9109 Break)); 9110 9111 Break.ColumnLimit = 0; 9112 verifyFormat("const char *hello = \"hello llvm\";", Break); 9113 } 9114 9115 TEST_F(FormatTest, AlignsPipes) { 9116 verifyFormat( 9117 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9118 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9119 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9120 verifyFormat( 9121 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9122 " << aaaaaaaaaaaaaaaaaaaa;"); 9123 verifyFormat( 9124 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9125 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9126 verifyFormat( 9127 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9128 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9129 verifyFormat( 9130 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9131 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9132 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9133 verifyFormat( 9134 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9135 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9136 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9137 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9138 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9139 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9140 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9141 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9142 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9143 verifyFormat( 9144 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9145 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9146 verifyFormat( 9147 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9148 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9149 9150 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9151 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9152 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9153 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9154 " aaaaaaaaaaaaaaaaaaaaa)\n" 9155 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9156 verifyFormat("LOG_IF(aaa == //\n" 9157 " bbb)\n" 9158 " << a << b;"); 9159 9160 // But sometimes, breaking before the first "<<" is desirable. 9161 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9162 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9163 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9164 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9165 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9166 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9167 " << BEF << IsTemplate << Description << E->getType();"); 9168 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9169 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9170 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9171 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9172 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9174 " << aaa;"); 9175 9176 verifyFormat( 9177 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9178 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9179 9180 // Incomplete string literal. 9181 EXPECT_EQ("llvm::errs() << \"\n" 9182 " << a;", 9183 format("llvm::errs() << \"\n<<a;")); 9184 9185 verifyFormat("void f() {\n" 9186 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9187 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9188 "}"); 9189 9190 // Handle 'endl'. 9191 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9192 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9193 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9194 9195 // Handle '\n'. 9196 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9197 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9198 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9199 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9200 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9201 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9202 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9203 } 9204 9205 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9206 verifyFormat("return out << \"somepacket = {\\n\"\n" 9207 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9208 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9209 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9210 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9211 " << \"}\";"); 9212 9213 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9214 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9215 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9216 verifyFormat( 9217 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9218 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9219 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9220 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9221 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9222 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9223 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9224 verifyFormat( 9225 "void f() {\n" 9226 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9227 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9228 "}"); 9229 9230 // Breaking before the first "<<" is generally not desirable. 9231 verifyFormat( 9232 "llvm::errs()\n" 9233 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9234 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9235 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9236 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9237 getLLVMStyleWithColumns(70)); 9238 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9239 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9240 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9241 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9242 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9243 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9244 getLLVMStyleWithColumns(70)); 9245 9246 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9247 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9248 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9249 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9250 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9251 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9252 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9253 " (aaaa + aaaa);", 9254 getLLVMStyleWithColumns(40)); 9255 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9256 " (aaaaaaa + aaaaa));", 9257 getLLVMStyleWithColumns(40)); 9258 verifyFormat( 9259 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9260 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9261 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9262 } 9263 9264 TEST_F(FormatTest, UnderstandsEquals) { 9265 verifyFormat( 9266 "aaaaaaaaaaaaaaaaa =\n" 9267 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9268 verifyFormat( 9269 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9270 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9271 verifyFormat( 9272 "if (a) {\n" 9273 " f();\n" 9274 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9275 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9276 "}"); 9277 9278 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9279 " 100000000 + 10000000) {\n}"); 9280 } 9281 9282 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9283 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9284 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9285 9286 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9287 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9288 9289 verifyFormat( 9290 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9291 " Parameter2);"); 9292 9293 verifyFormat( 9294 "ShortObject->shortFunction(\n" 9295 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9296 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9297 9298 verifyFormat("loooooooooooooongFunction(\n" 9299 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9300 9301 verifyFormat( 9302 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9303 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9304 9305 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9306 " .WillRepeatedly(Return(SomeValue));"); 9307 verifyFormat("void f() {\n" 9308 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9309 " .Times(2)\n" 9310 " .WillRepeatedly(Return(SomeValue));\n" 9311 "}"); 9312 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9313 " ccccccccccccccccccccccc);"); 9314 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9316 " .aaaaa(aaaaa),\n" 9317 " aaaaaaaaaaaaaaaaaaaaa);"); 9318 verifyFormat("void f() {\n" 9319 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9320 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9321 "}"); 9322 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9324 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9325 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9326 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9327 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9328 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9329 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9330 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9331 "}"); 9332 9333 // Here, it is not necessary to wrap at "." or "->". 9334 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9335 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9336 verifyFormat( 9337 "aaaaaaaaaaa->aaaaaaaaa(\n" 9338 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9339 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9340 9341 verifyFormat( 9342 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9343 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9344 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9345 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9346 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9347 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9348 9349 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9350 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9351 " .a();"); 9352 9353 FormatStyle NoBinPacking = getLLVMStyle(); 9354 NoBinPacking.BinPackParameters = false; 9355 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9356 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9357 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9358 " aaaaaaaaaaaaaaaaaaa,\n" 9359 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9360 NoBinPacking); 9361 9362 // If there is a subsequent call, change to hanging indentation. 9363 verifyFormat( 9364 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9365 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9366 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9367 verifyFormat( 9368 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9369 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9370 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9371 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9372 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9373 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9374 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9375 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9376 } 9377 9378 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9379 verifyFormat("template <typename T>\n" 9380 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9381 verifyFormat("template <typename T>\n" 9382 "// T should be one of {A, B}.\n" 9383 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9384 verifyFormat( 9385 "template <typename T>\n" 9386 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9387 verifyFormat("template <typename T>\n" 9388 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9389 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9390 verifyFormat( 9391 "template <typename T>\n" 9392 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9393 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9394 verifyFormat( 9395 "template <typename T>\n" 9396 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9397 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9398 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9399 verifyFormat("template <typename T>\n" 9400 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9401 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9402 verifyFormat( 9403 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9404 " typename T4 = char>\n" 9405 "void f();"); 9406 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9407 " template <typename> class cccccccccccccccccccccc,\n" 9408 " typename ddddddddddddd>\n" 9409 "class C {};"); 9410 verifyFormat( 9411 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9412 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9413 9414 verifyFormat("void f() {\n" 9415 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9416 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9417 "}"); 9418 9419 verifyFormat("template <typename T> class C {};"); 9420 verifyFormat("template <typename T> void f();"); 9421 verifyFormat("template <typename T> void f() {}"); 9422 verifyFormat( 9423 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9424 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9425 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9426 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9427 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9428 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9429 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9430 getLLVMStyleWithColumns(72)); 9431 EXPECT_EQ("static_cast<A< //\n" 9432 " B> *>(\n" 9433 "\n" 9434 ");", 9435 format("static_cast<A<//\n" 9436 " B>*>(\n" 9437 "\n" 9438 " );")); 9439 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9440 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9441 9442 FormatStyle AlwaysBreak = getLLVMStyle(); 9443 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9444 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9445 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9446 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9447 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9448 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9449 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9450 verifyFormat("template <template <typename> class Fooooooo,\n" 9451 " template <typename> class Baaaaaaar>\n" 9452 "struct C {};", 9453 AlwaysBreak); 9454 verifyFormat("template <typename T> // T can be A, B or C.\n" 9455 "struct C {};", 9456 AlwaysBreak); 9457 verifyFormat("template <enum E> class A {\n" 9458 "public:\n" 9459 " E *f();\n" 9460 "};"); 9461 9462 FormatStyle NeverBreak = getLLVMStyle(); 9463 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9464 verifyFormat("template <typename T> class C {};", NeverBreak); 9465 verifyFormat("template <typename T> void f();", NeverBreak); 9466 verifyFormat("template <typename T> void f() {}", NeverBreak); 9467 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9468 "bbbbbbbbbbbbbbbbbbbb) {}", 9469 NeverBreak); 9470 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9471 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9472 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9473 NeverBreak); 9474 verifyFormat("template <template <typename> class Fooooooo,\n" 9475 " template <typename> class Baaaaaaar>\n" 9476 "struct C {};", 9477 NeverBreak); 9478 verifyFormat("template <typename T> // T can be A, B or C.\n" 9479 "struct C {};", 9480 NeverBreak); 9481 verifyFormat("template <enum E> class A {\n" 9482 "public:\n" 9483 " E *f();\n" 9484 "};", 9485 NeverBreak); 9486 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9487 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9488 "bbbbbbbbbbbbbbbbbbbb) {}", 9489 NeverBreak); 9490 } 9491 9492 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9493 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9494 Style.ColumnLimit = 60; 9495 EXPECT_EQ("// Baseline - no comments.\n" 9496 "template <\n" 9497 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9498 "void f() {}", 9499 format("// Baseline - no comments.\n" 9500 "template <\n" 9501 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9502 "void f() {}", 9503 Style)); 9504 9505 EXPECT_EQ("template <\n" 9506 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9507 "void f() {}", 9508 format("template <\n" 9509 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9510 "void f() {}", 9511 Style)); 9512 9513 EXPECT_EQ( 9514 "template <\n" 9515 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9516 "void f() {}", 9517 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9518 "void f() {}", 9519 Style)); 9520 9521 EXPECT_EQ( 9522 "template <\n" 9523 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9524 " // multiline\n" 9525 "void f() {}", 9526 format("template <\n" 9527 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9528 " // multiline\n" 9529 "void f() {}", 9530 Style)); 9531 9532 EXPECT_EQ( 9533 "template <typename aaaaaaaaaa<\n" 9534 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9535 "void f() {}", 9536 format( 9537 "template <\n" 9538 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9539 "void f() {}", 9540 Style)); 9541 } 9542 9543 TEST_F(FormatTest, WrapsTemplateParameters) { 9544 FormatStyle Style = getLLVMStyle(); 9545 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9546 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9547 verifyFormat( 9548 "template <typename... a> struct q {};\n" 9549 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9550 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9551 " y;", 9552 Style); 9553 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9554 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9555 verifyFormat( 9556 "template <typename... a> struct r {};\n" 9557 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9558 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9559 " y;", 9560 Style); 9561 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9562 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9563 verifyFormat("template <typename... a> struct s {};\n" 9564 "extern s<\n" 9565 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9566 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9567 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9568 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9569 " y;", 9570 Style); 9571 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9572 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9573 verifyFormat("template <typename... a> struct t {};\n" 9574 "extern t<\n" 9575 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9576 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9577 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9578 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9579 " y;", 9580 Style); 9581 } 9582 9583 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9584 verifyFormat( 9585 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9586 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9587 verifyFormat( 9588 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9589 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9590 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9591 9592 // FIXME: Should we have the extra indent after the second break? 9593 verifyFormat( 9594 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9595 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9596 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9597 9598 verifyFormat( 9599 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9600 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9601 9602 // Breaking at nested name specifiers is generally not desirable. 9603 verifyFormat( 9604 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9605 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9606 9607 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9608 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9609 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9610 " aaaaaaaaaaaaaaaaaaaaa);", 9611 getLLVMStyleWithColumns(74)); 9612 9613 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9614 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9615 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9616 } 9617 9618 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9619 verifyFormat("A<int> a;"); 9620 verifyFormat("A<A<A<int>>> a;"); 9621 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9622 verifyFormat("bool x = a < 1 || 2 > a;"); 9623 verifyFormat("bool x = 5 < f<int>();"); 9624 verifyFormat("bool x = f<int>() > 5;"); 9625 verifyFormat("bool x = 5 < a<int>::x;"); 9626 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9627 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9628 9629 verifyGoogleFormat("A<A<int>> a;"); 9630 verifyGoogleFormat("A<A<A<int>>> a;"); 9631 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9632 verifyGoogleFormat("A<A<int> > a;"); 9633 verifyGoogleFormat("A<A<A<int> > > a;"); 9634 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9635 verifyGoogleFormat("A<::A<int>> a;"); 9636 verifyGoogleFormat("A<::A> a;"); 9637 verifyGoogleFormat("A< ::A> a;"); 9638 verifyGoogleFormat("A< ::A<int> > a;"); 9639 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9640 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9641 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9642 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9643 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9644 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9645 9646 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9647 9648 // template closer followed by a token that starts with > or = 9649 verifyFormat("bool b = a<1> > 1;"); 9650 verifyFormat("bool b = a<1> >= 1;"); 9651 verifyFormat("int i = a<1> >> 1;"); 9652 FormatStyle Style = getLLVMStyle(); 9653 Style.SpaceBeforeAssignmentOperators = false; 9654 verifyFormat("bool b= a<1> == 1;", Style); 9655 verifyFormat("a<int> = 1;", Style); 9656 verifyFormat("a<int> >>= 1;", Style); 9657 9658 verifyFormat("test < a | b >> c;"); 9659 verifyFormat("test<test<a | b>> c;"); 9660 verifyFormat("test >> a >> b;"); 9661 verifyFormat("test << a >> b;"); 9662 9663 verifyFormat("f<int>();"); 9664 verifyFormat("template <typename T> void f() {}"); 9665 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9666 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9667 "sizeof(char)>::type>;"); 9668 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9669 verifyFormat("f(a.operator()<A>());"); 9670 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9671 " .template operator()<A>());", 9672 getLLVMStyleWithColumns(35)); 9673 verifyFormat("bool_constant<a && noexcept(f())>"); 9674 verifyFormat("bool_constant<a || noexcept(f())>"); 9675 9676 // Not template parameters. 9677 verifyFormat("return a < b && c > d;"); 9678 verifyFormat("void f() {\n" 9679 " while (a < b && c > d) {\n" 9680 " }\n" 9681 "}"); 9682 verifyFormat("template <typename... Types>\n" 9683 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9684 9685 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9686 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9687 getLLVMStyleWithColumns(60)); 9688 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9689 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9690 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9691 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9692 } 9693 9694 TEST_F(FormatTest, UnderstandsShiftOperators) { 9695 verifyFormat("if (i < x >> 1)"); 9696 verifyFormat("while (i < x >> 1)"); 9697 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9698 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9699 verifyFormat( 9700 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9701 verifyFormat("Foo.call<Bar<Function>>()"); 9702 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9703 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9704 "++i, v = v >> 1)"); 9705 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9706 } 9707 9708 TEST_F(FormatTest, BitshiftOperatorWidth) { 9709 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9710 " bar */", 9711 format("int a=1<<2; /* foo\n" 9712 " bar */")); 9713 9714 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9715 " bar */", 9716 format("int b =256>>1 ; /* foo\n" 9717 " bar */")); 9718 } 9719 9720 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9721 verifyFormat("COMPARE(a, ==, b);"); 9722 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9723 } 9724 9725 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9726 verifyFormat("int A::*x;"); 9727 verifyFormat("int (S::*func)(void *);"); 9728 verifyFormat("void f() { int (S::*func)(void *); }"); 9729 verifyFormat("typedef bool *(Class::*Member)() const;"); 9730 verifyFormat("void f() {\n" 9731 " (a->*f)();\n" 9732 " a->*x;\n" 9733 " (a.*f)();\n" 9734 " ((*a).*f)();\n" 9735 " a.*x;\n" 9736 "}"); 9737 verifyFormat("void f() {\n" 9738 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9739 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9740 "}"); 9741 verifyFormat( 9742 "(aaaaaaaaaa->*bbbbbbb)(\n" 9743 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9744 FormatStyle Style = getLLVMStyle(); 9745 Style.PointerAlignment = FormatStyle::PAS_Left; 9746 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9747 } 9748 9749 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9750 verifyFormat("int a = -2;"); 9751 verifyFormat("f(-1, -2, -3);"); 9752 verifyFormat("a[-1] = 5;"); 9753 verifyFormat("int a = 5 + -2;"); 9754 verifyFormat("if (i == -1) {\n}"); 9755 verifyFormat("if (i != -1) {\n}"); 9756 verifyFormat("if (i > -1) {\n}"); 9757 verifyFormat("if (i < -1) {\n}"); 9758 verifyFormat("++(a->f());"); 9759 verifyFormat("--(a->f());"); 9760 verifyFormat("(a->f())++;"); 9761 verifyFormat("a[42]++;"); 9762 verifyFormat("if (!(a->f())) {\n}"); 9763 verifyFormat("if (!+i) {\n}"); 9764 verifyFormat("~&a;"); 9765 verifyFormat("for (x = 0; -10 < x; --x) {\n}"); 9766 verifyFormat("sizeof -x"); 9767 verifyFormat("sizeof +x"); 9768 verifyFormat("sizeof *x"); 9769 verifyFormat("sizeof &x"); 9770 verifyFormat("delete +x;"); 9771 verifyFormat("co_await +x;"); 9772 verifyFormat("case *x:"); 9773 verifyFormat("case &x:"); 9774 9775 verifyFormat("a-- > b;"); 9776 verifyFormat("b ? -a : c;"); 9777 verifyFormat("n * sizeof char16;"); 9778 verifyFormat("n * alignof char16;", getGoogleStyle()); 9779 verifyFormat("sizeof(char);"); 9780 verifyFormat("alignof(char);", getGoogleStyle()); 9781 9782 verifyFormat("return -1;"); 9783 verifyFormat("throw -1;"); 9784 verifyFormat("switch (a) {\n" 9785 "case -1:\n" 9786 " break;\n" 9787 "}"); 9788 verifyFormat("#define X -1"); 9789 verifyFormat("#define X -kConstant"); 9790 9791 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9792 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9793 9794 verifyFormat("int a = /* confusing comment */ -1;"); 9795 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9796 verifyFormat("int a = i /* confusing comment */++;"); 9797 9798 verifyFormat("co_yield -1;"); 9799 verifyFormat("co_return -1;"); 9800 9801 // Check that * is not treated as a binary operator when we set 9802 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9803 FormatStyle PASLeftStyle = getLLVMStyle(); 9804 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9805 verifyFormat("co_return *a;", PASLeftStyle); 9806 verifyFormat("co_await *a;", PASLeftStyle); 9807 verifyFormat("co_yield *a", PASLeftStyle); 9808 verifyFormat("return *a;", PASLeftStyle); 9809 } 9810 9811 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9812 verifyFormat("if (!aaaaaaaaaa( // break\n" 9813 " aaaaa)) {\n" 9814 "}"); 9815 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9816 " aaaaa));"); 9817 verifyFormat("*aaa = aaaaaaa( // break\n" 9818 " bbbbbb);"); 9819 } 9820 9821 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9822 verifyFormat("bool operator<();"); 9823 verifyFormat("bool operator>();"); 9824 verifyFormat("bool operator=();"); 9825 verifyFormat("bool operator==();"); 9826 verifyFormat("bool operator!=();"); 9827 verifyFormat("int operator+();"); 9828 verifyFormat("int operator++();"); 9829 verifyFormat("int operator++(int) volatile noexcept;"); 9830 verifyFormat("bool operator,();"); 9831 verifyFormat("bool operator();"); 9832 verifyFormat("bool operator()();"); 9833 verifyFormat("bool operator[]();"); 9834 verifyFormat("operator bool();"); 9835 verifyFormat("operator int();"); 9836 verifyFormat("operator void *();"); 9837 verifyFormat("operator SomeType<int>();"); 9838 verifyFormat("operator SomeType<int, int>();"); 9839 verifyFormat("operator SomeType<SomeType<int>>();"); 9840 verifyFormat("operator< <>();"); 9841 verifyFormat("operator<< <>();"); 9842 verifyFormat("< <>"); 9843 9844 verifyFormat("void *operator new(std::size_t size);"); 9845 verifyFormat("void *operator new[](std::size_t size);"); 9846 verifyFormat("void operator delete(void *ptr);"); 9847 verifyFormat("void operator delete[](void *ptr);"); 9848 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9849 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9850 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9851 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9852 9853 verifyFormat( 9854 "ostream &operator<<(ostream &OutputStream,\n" 9855 " SomeReallyLongType WithSomeReallyLongValue);"); 9856 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9857 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9858 " return left.group < right.group;\n" 9859 "}"); 9860 verifyFormat("SomeType &operator=(const SomeType &S);"); 9861 verifyFormat("f.template operator()<int>();"); 9862 9863 verifyGoogleFormat("operator void*();"); 9864 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9865 verifyGoogleFormat("operator ::A();"); 9866 9867 verifyFormat("using A::operator+;"); 9868 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9869 "int i;"); 9870 9871 // Calling an operator as a member function. 9872 verifyFormat("void f() { a.operator*(); }"); 9873 verifyFormat("void f() { a.operator*(b & b); }"); 9874 verifyFormat("void f() { a->operator&(a * b); }"); 9875 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9876 // TODO: Calling an operator as a non-member function is hard to distinguish. 9877 // https://llvm.org/PR50629 9878 // verifyFormat("void f() { operator*(a & a); }"); 9879 // verifyFormat("void f() { operator&(a, b * b); }"); 9880 9881 verifyFormat("::operator delete(foo);"); 9882 verifyFormat("::operator new(n * sizeof(foo));"); 9883 verifyFormat("foo() { ::operator delete(foo); }"); 9884 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9885 } 9886 9887 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9888 verifyFormat("void A::b() && {}"); 9889 verifyFormat("void A::b() &&noexcept {}"); 9890 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9891 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9892 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9893 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9894 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9895 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9896 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9897 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9898 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9899 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9900 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9901 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9902 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9903 verifyFormat("void Fn(T const &) const &;"); 9904 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9905 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9906 verifyFormat("template <typename T>\n" 9907 "void F(T) && = delete;", 9908 getGoogleStyle()); 9909 verifyFormat("template <typename T> void operator=(T) &;"); 9910 verifyFormat("template <typename T> void operator=(T) const &;"); 9911 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9912 verifyFormat("template <typename T> void operator=(T) & = default;"); 9913 verifyFormat("template <typename T> void operator=(T) &&;"); 9914 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9915 verifyFormat("template <typename T> void operator=(T) & {}"); 9916 verifyFormat("template <typename T> void operator=(T) && {}"); 9917 9918 FormatStyle AlignLeft = getLLVMStyle(); 9919 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9920 verifyFormat("void A::b() && {}", AlignLeft); 9921 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9922 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9923 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9924 AlignLeft); 9925 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9926 AlignLeft); 9927 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9928 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9929 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9930 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9931 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9932 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9933 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9934 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9935 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9936 AlignLeft); 9937 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 9938 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 9939 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9940 AlignLeft); 9941 verifyFormat("template <typename T> void operator=(T) & = default;", 9942 AlignLeft); 9943 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9944 verifyFormat("template <typename T> void operator=(T) && = delete;", 9945 AlignLeft); 9946 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9947 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9948 9949 FormatStyle AlignMiddle = getLLVMStyle(); 9950 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9951 verifyFormat("void A::b() && {}", AlignMiddle); 9952 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9953 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9954 AlignMiddle); 9955 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9956 AlignMiddle); 9957 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9958 AlignMiddle); 9959 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9960 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9961 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9962 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9963 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9964 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9965 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9966 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9967 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9968 AlignMiddle); 9969 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 9970 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 9971 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9972 AlignMiddle); 9973 verifyFormat("template <typename T> void operator=(T) & = default;", 9974 AlignMiddle); 9975 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 9976 verifyFormat("template <typename T> void operator=(T) && = delete;", 9977 AlignMiddle); 9978 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 9979 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 9980 9981 FormatStyle Spaces = getLLVMStyle(); 9982 Spaces.SpacesInCStyleCastParentheses = true; 9983 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9984 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9985 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9986 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9987 9988 Spaces.SpacesInCStyleCastParentheses = false; 9989 Spaces.SpacesInParentheses = true; 9990 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9991 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9992 Spaces); 9993 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9994 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9995 9996 FormatStyle BreakTemplate = getLLVMStyle(); 9997 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9998 9999 verifyFormat("struct f {\n" 10000 " template <class T>\n" 10001 " int &foo(const std::string &str) &noexcept {}\n" 10002 "};", 10003 BreakTemplate); 10004 10005 verifyFormat("struct f {\n" 10006 " template <class T>\n" 10007 " int &foo(const std::string &str) &&noexcept {}\n" 10008 "};", 10009 BreakTemplate); 10010 10011 verifyFormat("struct f {\n" 10012 " template <class T>\n" 10013 " int &foo(const std::string &str) const &noexcept {}\n" 10014 "};", 10015 BreakTemplate); 10016 10017 verifyFormat("struct f {\n" 10018 " template <class T>\n" 10019 " int &foo(const std::string &str) const &noexcept {}\n" 10020 "};", 10021 BreakTemplate); 10022 10023 verifyFormat("struct f {\n" 10024 " template <class T>\n" 10025 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10026 "};", 10027 BreakTemplate); 10028 10029 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10030 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10031 FormatStyle::BTDS_Yes; 10032 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10033 10034 verifyFormat("struct f {\n" 10035 " template <class T>\n" 10036 " int& foo(const std::string& str) & noexcept {}\n" 10037 "};", 10038 AlignLeftBreakTemplate); 10039 10040 verifyFormat("struct f {\n" 10041 " template <class T>\n" 10042 " int& foo(const std::string& str) && noexcept {}\n" 10043 "};", 10044 AlignLeftBreakTemplate); 10045 10046 verifyFormat("struct f {\n" 10047 " template <class T>\n" 10048 " int& foo(const std::string& str) const& noexcept {}\n" 10049 "};", 10050 AlignLeftBreakTemplate); 10051 10052 verifyFormat("struct f {\n" 10053 " template <class T>\n" 10054 " int& foo(const std::string& str) const&& noexcept {}\n" 10055 "};", 10056 AlignLeftBreakTemplate); 10057 10058 verifyFormat("struct f {\n" 10059 " template <class T>\n" 10060 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10061 "};", 10062 AlignLeftBreakTemplate); 10063 10064 // The `&` in `Type&` should not be confused with a trailing `&` of 10065 // DEPRECATED(reason) member function. 10066 verifyFormat("struct f {\n" 10067 " template <class T>\n" 10068 " DEPRECATED(reason)\n" 10069 " Type &foo(arguments) {}\n" 10070 "};", 10071 BreakTemplate); 10072 10073 verifyFormat("struct f {\n" 10074 " template <class T>\n" 10075 " DEPRECATED(reason)\n" 10076 " Type& foo(arguments) {}\n" 10077 "};", 10078 AlignLeftBreakTemplate); 10079 10080 verifyFormat("void (*foopt)(int) = &func;"); 10081 10082 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10083 DerivePointerAlignment.DerivePointerAlignment = true; 10084 // There's always a space between the function and its trailing qualifiers. 10085 // This isn't evidence for PAS_Right (or for PAS_Left). 10086 std::string Prefix = "void a() &;\n" 10087 "void b() &;\n"; 10088 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10089 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10090 // Same if the function is an overloaded operator, and with &&. 10091 Prefix = "void operator()() &&;\n" 10092 "void operator()() &&;\n"; 10093 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10094 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10095 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10096 Prefix = "void a() const &;\n" 10097 "void b() const &;\n"; 10098 EXPECT_EQ(Prefix + "int *x;", 10099 format(Prefix + "int* x;", DerivePointerAlignment)); 10100 } 10101 10102 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10103 verifyFormat("void f() {\n" 10104 " A *a = new A;\n" 10105 " A *a = new (placement) A;\n" 10106 " delete a;\n" 10107 " delete (A *)a;\n" 10108 "}"); 10109 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10110 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10111 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10112 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10113 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10114 verifyFormat("delete[] h->p;"); 10115 verifyFormat("delete[] (void *)p;"); 10116 10117 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10118 verifyFormat("void operator new(void *foo) ATTRIB;"); 10119 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10120 verifyFormat("void operator delete(void *ptr) noexcept;"); 10121 10122 EXPECT_EQ("void new(link p);\n" 10123 "void delete(link p);\n", 10124 format("void new (link p);\n" 10125 "void delete (link p);\n")); 10126 } 10127 10128 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10129 verifyFormat("int *f(int *a) {}"); 10130 verifyFormat("int main(int argc, char **argv) {}"); 10131 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10132 verifyIndependentOfContext("f(a, *a);"); 10133 verifyFormat("void g() { f(*a); }"); 10134 verifyIndependentOfContext("int a = b * 10;"); 10135 verifyIndependentOfContext("int a = 10 * b;"); 10136 verifyIndependentOfContext("int a = b * c;"); 10137 verifyIndependentOfContext("int a += b * c;"); 10138 verifyIndependentOfContext("int a -= b * c;"); 10139 verifyIndependentOfContext("int a *= b * c;"); 10140 verifyIndependentOfContext("int a /= b * c;"); 10141 verifyIndependentOfContext("int a = *b;"); 10142 verifyIndependentOfContext("int a = *b * c;"); 10143 verifyIndependentOfContext("int a = b * *c;"); 10144 verifyIndependentOfContext("int a = b * (10);"); 10145 verifyIndependentOfContext("S << b * (10);"); 10146 verifyIndependentOfContext("return 10 * b;"); 10147 verifyIndependentOfContext("return *b * *c;"); 10148 verifyIndependentOfContext("return a & ~b;"); 10149 verifyIndependentOfContext("f(b ? *c : *d);"); 10150 verifyIndependentOfContext("int a = b ? *c : *d;"); 10151 verifyIndependentOfContext("*b = a;"); 10152 verifyIndependentOfContext("a * ~b;"); 10153 verifyIndependentOfContext("a * !b;"); 10154 verifyIndependentOfContext("a * +b;"); 10155 verifyIndependentOfContext("a * -b;"); 10156 verifyIndependentOfContext("a * ++b;"); 10157 verifyIndependentOfContext("a * --b;"); 10158 verifyIndependentOfContext("a[4] * b;"); 10159 verifyIndependentOfContext("a[a * a] = 1;"); 10160 verifyIndependentOfContext("f() * b;"); 10161 verifyIndependentOfContext("a * [self dostuff];"); 10162 verifyIndependentOfContext("int x = a * (a + b);"); 10163 verifyIndependentOfContext("(a *)(a + b);"); 10164 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10165 verifyIndependentOfContext("int *pa = (int *)&a;"); 10166 verifyIndependentOfContext("return sizeof(int **);"); 10167 verifyIndependentOfContext("return sizeof(int ******);"); 10168 verifyIndependentOfContext("return (int **&)a;"); 10169 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10170 verifyFormat("void f(Type (*parameter)[10]) {}"); 10171 verifyFormat("void f(Type (¶meter)[10]) {}"); 10172 verifyGoogleFormat("return sizeof(int**);"); 10173 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10174 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10175 verifyFormat("auto a = [](int **&, int ***) {};"); 10176 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10177 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10178 verifyFormat("[](const decltype(*a) &value) {}"); 10179 verifyFormat("[](const typeof(*a) &value) {}"); 10180 verifyFormat("[](const _Atomic(a *) &value) {}"); 10181 verifyFormat("[](const __underlying_type(a) &value) {}"); 10182 verifyFormat("decltype(a * b) F();"); 10183 verifyFormat("typeof(a * b) F();"); 10184 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10185 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10186 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10187 verifyIndependentOfContext("int i{a * b};"); 10188 verifyIndependentOfContext("aaa && aaa->f();"); 10189 verifyIndependentOfContext("int x = ~*p;"); 10190 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10191 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10192 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10193 verifyFormat("void f() { f(a, c * d); }"); 10194 verifyFormat("void f() { f(new a(), c * d); }"); 10195 verifyFormat("void f(const MyOverride &override);"); 10196 verifyFormat("void f(const MyFinal &final);"); 10197 verifyIndependentOfContext("bool a = f() && override.f();"); 10198 verifyIndependentOfContext("bool a = f() && final.f();"); 10199 10200 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10201 10202 verifyIndependentOfContext("A<int *> a;"); 10203 verifyIndependentOfContext("A<int **> a;"); 10204 verifyIndependentOfContext("A<int *, int *> a;"); 10205 verifyIndependentOfContext("A<int *[]> a;"); 10206 verifyIndependentOfContext( 10207 "const char *const p = reinterpret_cast<const char *const>(q);"); 10208 verifyIndependentOfContext("A<int **, int **> a;"); 10209 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10210 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10211 verifyFormat("for (; a && b;) {\n}"); 10212 verifyFormat("bool foo = true && [] { return false; }();"); 10213 10214 verifyFormat( 10215 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10216 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10217 10218 verifyGoogleFormat("int const* a = &b;"); 10219 verifyGoogleFormat("**outparam = 1;"); 10220 verifyGoogleFormat("*outparam = a * b;"); 10221 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10222 verifyGoogleFormat("A<int*> a;"); 10223 verifyGoogleFormat("A<int**> a;"); 10224 verifyGoogleFormat("A<int*, int*> a;"); 10225 verifyGoogleFormat("A<int**, int**> a;"); 10226 verifyGoogleFormat("f(b ? *c : *d);"); 10227 verifyGoogleFormat("int a = b ? *c : *d;"); 10228 verifyGoogleFormat("Type* t = **x;"); 10229 verifyGoogleFormat("Type* t = *++*x;"); 10230 verifyGoogleFormat("*++*x;"); 10231 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10232 verifyGoogleFormat("Type* t = x++ * y;"); 10233 verifyGoogleFormat( 10234 "const char* const p = reinterpret_cast<const char* const>(q);"); 10235 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10236 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10237 verifyGoogleFormat("template <typename T>\n" 10238 "void f(int i = 0, SomeType** temps = NULL);"); 10239 10240 FormatStyle Left = getLLVMStyle(); 10241 Left.PointerAlignment = FormatStyle::PAS_Left; 10242 verifyFormat("x = *a(x) = *a(y);", Left); 10243 verifyFormat("for (;; *a = b) {\n}", Left); 10244 verifyFormat("return *this += 1;", Left); 10245 verifyFormat("throw *x;", Left); 10246 verifyFormat("delete *x;", Left); 10247 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10248 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10249 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10250 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10251 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10252 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10253 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10254 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10255 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10256 10257 verifyIndependentOfContext("a = *(x + y);"); 10258 verifyIndependentOfContext("a = &(x + y);"); 10259 verifyIndependentOfContext("*(x + y).call();"); 10260 verifyIndependentOfContext("&(x + y)->call();"); 10261 verifyFormat("void f() { &(*I).first; }"); 10262 10263 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10264 verifyFormat("f(* /* confusing comment */ foo);"); 10265 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10266 verifyFormat("void foo(int * // this is the first paramters\n" 10267 " ,\n" 10268 " int second);"); 10269 verifyFormat("double term = a * // first\n" 10270 " b;"); 10271 verifyFormat( 10272 "int *MyValues = {\n" 10273 " *A, // Operator detection might be confused by the '{'\n" 10274 " *BB // Operator detection might be confused by previous comment\n" 10275 "};"); 10276 10277 verifyIndependentOfContext("if (int *a = &b)"); 10278 verifyIndependentOfContext("if (int &a = *b)"); 10279 verifyIndependentOfContext("if (a & b[i])"); 10280 verifyIndependentOfContext("if constexpr (a & b[i])"); 10281 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10282 verifyIndependentOfContext("if (a * (b * c))"); 10283 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10284 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10285 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10286 verifyIndependentOfContext("if (*b[i])"); 10287 verifyIndependentOfContext("if (int *a = (&b))"); 10288 verifyIndependentOfContext("while (int *a = &b)"); 10289 verifyIndependentOfContext("while (a * (b * c))"); 10290 verifyIndependentOfContext("size = sizeof *a;"); 10291 verifyIndependentOfContext("if (a && (b = c))"); 10292 verifyFormat("void f() {\n" 10293 " for (const int &v : Values) {\n" 10294 " }\n" 10295 "}"); 10296 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10297 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10298 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10299 10300 verifyFormat("#define A (!a * b)"); 10301 verifyFormat("#define MACRO \\\n" 10302 " int *i = a * b; \\\n" 10303 " void f(a *b);", 10304 getLLVMStyleWithColumns(19)); 10305 10306 verifyIndependentOfContext("A = new SomeType *[Length];"); 10307 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10308 verifyIndependentOfContext("T **t = new T *;"); 10309 verifyIndependentOfContext("T **t = new T *();"); 10310 verifyGoogleFormat("A = new SomeType*[Length]();"); 10311 verifyGoogleFormat("A = new SomeType*[Length];"); 10312 verifyGoogleFormat("T** t = new T*;"); 10313 verifyGoogleFormat("T** t = new T*();"); 10314 10315 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10316 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10317 verifyFormat("template <bool a, bool b> " 10318 "typename t::if<x && y>::type f() {}"); 10319 verifyFormat("template <int *y> f() {}"); 10320 verifyFormat("vector<int *> v;"); 10321 verifyFormat("vector<int *const> v;"); 10322 verifyFormat("vector<int *const **const *> v;"); 10323 verifyFormat("vector<int *volatile> v;"); 10324 verifyFormat("vector<a *_Nonnull> v;"); 10325 verifyFormat("vector<a *_Nullable> v;"); 10326 verifyFormat("vector<a *_Null_unspecified> v;"); 10327 verifyFormat("vector<a *__ptr32> v;"); 10328 verifyFormat("vector<a *__ptr64> v;"); 10329 verifyFormat("vector<a *__capability> v;"); 10330 FormatStyle TypeMacros = getLLVMStyle(); 10331 TypeMacros.TypenameMacros = {"LIST"}; 10332 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10333 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10334 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10335 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10336 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10337 10338 FormatStyle CustomQualifier = getLLVMStyle(); 10339 // Add identifiers that should not be parsed as a qualifier by default. 10340 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10341 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10342 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10343 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10344 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10345 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10346 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10347 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10348 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10349 verifyFormat("vector<a * _NotAQualifier> v;"); 10350 verifyFormat("vector<a * __not_a_qualifier> v;"); 10351 verifyFormat("vector<a * b> v;"); 10352 verifyFormat("foo<b && false>();"); 10353 verifyFormat("foo<b & 1>();"); 10354 verifyFormat("foo<b & (1)>();"); 10355 verifyFormat("foo<b & (~0)>();"); 10356 verifyFormat("foo<b & (true)>();"); 10357 verifyFormat("foo<b & ((1))>();"); 10358 verifyFormat("foo<b & (/*comment*/ 1)>();"); 10359 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10360 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10361 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10362 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10363 verifyFormat( 10364 "template <class T, class = typename std::enable_if<\n" 10365 " std::is_integral<T>::value &&\n" 10366 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10367 "void F();", 10368 getLLVMStyleWithColumns(70)); 10369 verifyFormat("template <class T,\n" 10370 " class = typename std::enable_if<\n" 10371 " std::is_integral<T>::value &&\n" 10372 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10373 " class U>\n" 10374 "void F();", 10375 getLLVMStyleWithColumns(70)); 10376 verifyFormat( 10377 "template <class T,\n" 10378 " class = typename ::std::enable_if<\n" 10379 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10380 "void F();", 10381 getGoogleStyleWithColumns(68)); 10382 10383 verifyIndependentOfContext("MACRO(int *i);"); 10384 verifyIndependentOfContext("MACRO(auto *a);"); 10385 verifyIndependentOfContext("MACRO(const A *a);"); 10386 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10387 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10388 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10389 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10390 verifyIndependentOfContext("MACRO(A *const a);"); 10391 verifyIndependentOfContext("MACRO(A *restrict a);"); 10392 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10393 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10394 verifyIndependentOfContext("MACRO(A *volatile a);"); 10395 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10396 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10397 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10398 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10399 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10400 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10401 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10402 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10403 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10404 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10405 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10406 verifyIndependentOfContext("MACRO(A *__capability);"); 10407 verifyIndependentOfContext("MACRO(A &__capability);"); 10408 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10409 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10410 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10411 // a type declaration: 10412 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10413 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10414 // Also check that TypenameMacros prevents parsing it as multiplication: 10415 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10416 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10417 10418 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10419 verifyFormat("void f() { f(float{1}, a * a); }"); 10420 verifyFormat("void f() { f(float(1), a * a); }"); 10421 10422 verifyFormat("f((void (*)(int))g);"); 10423 verifyFormat("f((void (&)(int))g);"); 10424 verifyFormat("f((void (^)(int))g);"); 10425 10426 // FIXME: Is there a way to make this work? 10427 // verifyIndependentOfContext("MACRO(A *a);"); 10428 verifyFormat("MACRO(A &B);"); 10429 verifyFormat("MACRO(A *B);"); 10430 verifyFormat("void f() { MACRO(A * B); }"); 10431 verifyFormat("void f() { MACRO(A & B); }"); 10432 10433 // This lambda was mis-formatted after D88956 (treating it as a binop): 10434 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10435 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10436 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10437 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10438 10439 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10440 verifyFormat("return options != nullptr && operator==(*options);"); 10441 10442 EXPECT_EQ("#define OP(x) \\\n" 10443 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10444 " return s << a.DebugString(); \\\n" 10445 " }", 10446 format("#define OP(x) \\\n" 10447 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10448 " return s << a.DebugString(); \\\n" 10449 " }", 10450 getLLVMStyleWithColumns(50))); 10451 10452 // FIXME: We cannot handle this case yet; we might be able to figure out that 10453 // foo<x> d > v; doesn't make sense. 10454 verifyFormat("foo<a<b && c> d> v;"); 10455 10456 FormatStyle PointerMiddle = getLLVMStyle(); 10457 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10458 verifyFormat("delete *x;", PointerMiddle); 10459 verifyFormat("int * x;", PointerMiddle); 10460 verifyFormat("int *[] x;", PointerMiddle); 10461 verifyFormat("template <int * y> f() {}", PointerMiddle); 10462 verifyFormat("int * f(int * a) {}", PointerMiddle); 10463 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10464 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10465 verifyFormat("A<int *> a;", PointerMiddle); 10466 verifyFormat("A<int **> a;", PointerMiddle); 10467 verifyFormat("A<int *, int *> a;", PointerMiddle); 10468 verifyFormat("A<int *[]> a;", PointerMiddle); 10469 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10470 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10471 verifyFormat("T ** t = new T *;", PointerMiddle); 10472 10473 // Member function reference qualifiers aren't binary operators. 10474 verifyFormat("string // break\n" 10475 "operator()() & {}"); 10476 verifyFormat("string // break\n" 10477 "operator()() && {}"); 10478 verifyGoogleFormat("template <typename T>\n" 10479 "auto x() & -> int {}"); 10480 10481 // Should be binary operators when used as an argument expression (overloaded 10482 // operator invoked as a member function). 10483 verifyFormat("void f() { a.operator()(a * a); }"); 10484 verifyFormat("void f() { a->operator()(a & a); }"); 10485 verifyFormat("void f() { a.operator()(*a & *a); }"); 10486 verifyFormat("void f() { a->operator()(*a * *a); }"); 10487 10488 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10489 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10490 } 10491 10492 TEST_F(FormatTest, UnderstandsAttributes) { 10493 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10494 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10495 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10496 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10497 FormatStyle AfterType = getLLVMStyle(); 10498 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10499 verifyFormat("__attribute__((nodebug)) void\n" 10500 "foo() {}\n", 10501 AfterType); 10502 verifyFormat("__unused void\n" 10503 "foo() {}", 10504 AfterType); 10505 10506 FormatStyle CustomAttrs = getLLVMStyle(); 10507 CustomAttrs.AttributeMacros.push_back("__unused"); 10508 CustomAttrs.AttributeMacros.push_back("__attr1"); 10509 CustomAttrs.AttributeMacros.push_back("__attr2"); 10510 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10511 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10512 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10513 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10514 // Check that it is parsed as a multiplication without AttributeMacros and 10515 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10516 verifyFormat("vector<SomeType * __attr1> v;"); 10517 verifyFormat("vector<SomeType __attr1 *> v;"); 10518 verifyFormat("vector<SomeType __attr1 *const> v;"); 10519 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10520 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10521 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10522 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10523 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10524 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10525 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10526 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10527 10528 // Check that these are not parsed as function declarations: 10529 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10530 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10531 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10532 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10533 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10534 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10535 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10536 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10537 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10538 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10539 } 10540 10541 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10542 // Check that qualifiers on pointers don't break parsing of casts. 10543 verifyFormat("x = (foo *const)*v;"); 10544 verifyFormat("x = (foo *volatile)*v;"); 10545 verifyFormat("x = (foo *restrict)*v;"); 10546 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10547 verifyFormat("x = (foo *_Nonnull)*v;"); 10548 verifyFormat("x = (foo *_Nullable)*v;"); 10549 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10550 verifyFormat("x = (foo *_Nonnull)*v;"); 10551 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10552 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10553 verifyFormat("x = (foo *__ptr32)*v;"); 10554 verifyFormat("x = (foo *__ptr64)*v;"); 10555 verifyFormat("x = (foo *__capability)*v;"); 10556 10557 // Check that we handle multiple trailing qualifiers and skip them all to 10558 // determine that the expression is a cast to a pointer type. 10559 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10560 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10561 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10562 StringRef AllQualifiers = 10563 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10564 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10565 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10566 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10567 10568 // Also check that address-of is not parsed as a binary bitwise-and: 10569 verifyFormat("x = (foo *const)&v;"); 10570 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10571 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10572 10573 // Check custom qualifiers: 10574 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10575 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10576 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10577 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10578 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10579 CustomQualifier); 10580 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10581 CustomQualifier); 10582 10583 // Check that unknown identifiers result in binary operator parsing: 10584 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10585 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10586 } 10587 10588 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10589 verifyFormat("SomeType s [[unused]] (InitValue);"); 10590 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10591 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10592 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10593 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10594 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10595 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10596 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10597 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10598 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10599 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10600 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10601 10602 // Make sure we do not mistake attributes for array subscripts. 10603 verifyFormat("int a() {}\n" 10604 "[[unused]] int b() {}\n"); 10605 verifyFormat("NSArray *arr;\n" 10606 "arr[[Foo() bar]];"); 10607 10608 // On the other hand, we still need to correctly find array subscripts. 10609 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10610 10611 // Make sure that we do not mistake Objective-C method inside array literals 10612 // as attributes, even if those method names are also keywords. 10613 verifyFormat("@[ [foo bar] ];"); 10614 verifyFormat("@[ [NSArray class] ];"); 10615 verifyFormat("@[ [foo enum] ];"); 10616 10617 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10618 10619 // Make sure we do not parse attributes as lambda introducers. 10620 FormatStyle MultiLineFunctions = getLLVMStyle(); 10621 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10622 verifyFormat("[[unused]] int b() {\n" 10623 " return 42;\n" 10624 "}\n", 10625 MultiLineFunctions); 10626 } 10627 10628 TEST_F(FormatTest, AttributeClass) { 10629 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10630 verifyFormat("class S {\n" 10631 " S(S&&) = default;\n" 10632 "};", 10633 Style); 10634 verifyFormat("class [[nodiscard]] S {\n" 10635 " S(S&&) = default;\n" 10636 "};", 10637 Style); 10638 verifyFormat("class __attribute((maybeunused)) S {\n" 10639 " S(S&&) = default;\n" 10640 "};", 10641 Style); 10642 verifyFormat("struct S {\n" 10643 " S(S&&) = default;\n" 10644 "};", 10645 Style); 10646 verifyFormat("struct [[nodiscard]] S {\n" 10647 " S(S&&) = default;\n" 10648 "};", 10649 Style); 10650 } 10651 10652 TEST_F(FormatTest, AttributesAfterMacro) { 10653 FormatStyle Style = getLLVMStyle(); 10654 verifyFormat("MACRO;\n" 10655 "__attribute__((maybe_unused)) int foo() {\n" 10656 " //...\n" 10657 "}"); 10658 10659 verifyFormat("MACRO;\n" 10660 "[[nodiscard]] int foo() {\n" 10661 " //...\n" 10662 "}"); 10663 10664 EXPECT_EQ("MACRO\n\n" 10665 "__attribute__((maybe_unused)) int foo() {\n" 10666 " //...\n" 10667 "}", 10668 format("MACRO\n\n" 10669 "__attribute__((maybe_unused)) int foo() {\n" 10670 " //...\n" 10671 "}")); 10672 10673 EXPECT_EQ("MACRO\n\n" 10674 "[[nodiscard]] int foo() {\n" 10675 " //...\n" 10676 "}", 10677 format("MACRO\n\n" 10678 "[[nodiscard]] int foo() {\n" 10679 " //...\n" 10680 "}")); 10681 } 10682 10683 TEST_F(FormatTest, AttributePenaltyBreaking) { 10684 FormatStyle Style = getLLVMStyle(); 10685 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10686 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10687 Style); 10688 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10689 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10690 Style); 10691 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10692 "shared_ptr<ALongTypeName> &C d) {\n}", 10693 Style); 10694 } 10695 10696 TEST_F(FormatTest, UnderstandsEllipsis) { 10697 FormatStyle Style = getLLVMStyle(); 10698 verifyFormat("int printf(const char *fmt, ...);"); 10699 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10700 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10701 10702 verifyFormat("template <int *...PP> a;", Style); 10703 10704 Style.PointerAlignment = FormatStyle::PAS_Left; 10705 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10706 10707 verifyFormat("template <int*... PP> a;", Style); 10708 10709 Style.PointerAlignment = FormatStyle::PAS_Middle; 10710 verifyFormat("template <int *... PP> a;", Style); 10711 } 10712 10713 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10714 EXPECT_EQ("int *a;\n" 10715 "int *a;\n" 10716 "int *a;", 10717 format("int *a;\n" 10718 "int* a;\n" 10719 "int *a;", 10720 getGoogleStyle())); 10721 EXPECT_EQ("int* a;\n" 10722 "int* a;\n" 10723 "int* a;", 10724 format("int* a;\n" 10725 "int* a;\n" 10726 "int *a;", 10727 getGoogleStyle())); 10728 EXPECT_EQ("int *a;\n" 10729 "int *a;\n" 10730 "int *a;", 10731 format("int *a;\n" 10732 "int * a;\n" 10733 "int * a;", 10734 getGoogleStyle())); 10735 EXPECT_EQ("auto x = [] {\n" 10736 " int *a;\n" 10737 " int *a;\n" 10738 " int *a;\n" 10739 "};", 10740 format("auto x=[]{int *a;\n" 10741 "int * a;\n" 10742 "int * a;};", 10743 getGoogleStyle())); 10744 } 10745 10746 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10747 verifyFormat("int f(int &&a) {}"); 10748 verifyFormat("int f(int a, char &&b) {}"); 10749 verifyFormat("void f() { int &&a = b; }"); 10750 verifyGoogleFormat("int f(int a, char&& b) {}"); 10751 verifyGoogleFormat("void f() { int&& a = b; }"); 10752 10753 verifyIndependentOfContext("A<int &&> a;"); 10754 verifyIndependentOfContext("A<int &&, int &&> a;"); 10755 verifyGoogleFormat("A<int&&> a;"); 10756 verifyGoogleFormat("A<int&&, int&&> a;"); 10757 10758 // Not rvalue references: 10759 verifyFormat("template <bool B, bool C> class A {\n" 10760 " static_assert(B && C, \"Something is wrong\");\n" 10761 "};"); 10762 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10763 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10764 verifyFormat("#define A(a, b) (a && b)"); 10765 } 10766 10767 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10768 verifyFormat("void f() {\n" 10769 " x[aaaaaaaaa -\n" 10770 " b] = 23;\n" 10771 "}", 10772 getLLVMStyleWithColumns(15)); 10773 } 10774 10775 TEST_F(FormatTest, FormatsCasts) { 10776 verifyFormat("Type *A = static_cast<Type *>(P);"); 10777 verifyFormat("static_cast<Type *>(P);"); 10778 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10779 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10780 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10781 // Check that static_cast<...>(...) does not require the next token to be on 10782 // the same line. 10783 verifyFormat("some_loooong_output << something_something__ << " 10784 "static_cast<const void *>(R)\n" 10785 " << something;"); 10786 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10787 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10788 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10789 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10790 verifyFormat("Type *A = (Type *)P;"); 10791 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10792 verifyFormat("int a = (int)(2.0f);"); 10793 verifyFormat("int a = (int)2.0f;"); 10794 verifyFormat("x[(int32)y];"); 10795 verifyFormat("x = (int32)y;"); 10796 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10797 verifyFormat("int a = (int)*b;"); 10798 verifyFormat("int a = (int)2.0f;"); 10799 verifyFormat("int a = (int)~0;"); 10800 verifyFormat("int a = (int)++a;"); 10801 verifyFormat("int a = (int)sizeof(int);"); 10802 verifyFormat("int a = (int)+2;"); 10803 verifyFormat("my_int a = (my_int)2.0f;"); 10804 verifyFormat("my_int a = (my_int)sizeof(int);"); 10805 verifyFormat("return (my_int)aaa;"); 10806 verifyFormat("#define x ((int)-1)"); 10807 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10808 verifyFormat("#define p(q) ((int *)&q)"); 10809 verifyFormat("fn(a)(b) + 1;"); 10810 10811 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10812 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10813 verifyFormat("my_int a = (my_int)~0;"); 10814 verifyFormat("my_int a = (my_int)++a;"); 10815 verifyFormat("my_int a = (my_int)-2;"); 10816 verifyFormat("my_int a = (my_int)1;"); 10817 verifyFormat("my_int a = (my_int *)1;"); 10818 verifyFormat("my_int a = (const my_int)-1;"); 10819 verifyFormat("my_int a = (const my_int *)-1;"); 10820 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10821 verifyFormat("my_int a = (ns::my_int)-2;"); 10822 verifyFormat("case (my_int)ONE:"); 10823 verifyFormat("auto x = (X)this;"); 10824 // Casts in Obj-C style calls used to not be recognized as such. 10825 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10826 10827 // FIXME: single value wrapped with paren will be treated as cast. 10828 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10829 10830 verifyFormat("{ (void)F; }"); 10831 10832 // Don't break after a cast's 10833 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10834 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10835 " bbbbbbbbbbbbbbbbbbbbbb);"); 10836 10837 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10838 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10839 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10840 verifyFormat("bool *y = (bool *)(void *)(x);"); 10841 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10842 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10843 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10844 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10845 10846 // These are not casts. 10847 verifyFormat("void f(int *) {}"); 10848 verifyFormat("f(foo)->b;"); 10849 verifyFormat("f(foo).b;"); 10850 verifyFormat("f(foo)(b);"); 10851 verifyFormat("f(foo)[b];"); 10852 verifyFormat("[](foo) { return 4; }(bar);"); 10853 verifyFormat("(*funptr)(foo)[4];"); 10854 verifyFormat("funptrs[4](foo)[4];"); 10855 verifyFormat("void f(int *);"); 10856 verifyFormat("void f(int *) = 0;"); 10857 verifyFormat("void f(SmallVector<int>) {}"); 10858 verifyFormat("void f(SmallVector<int>);"); 10859 verifyFormat("void f(SmallVector<int>) = 0;"); 10860 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10861 verifyFormat("int a = sizeof(int) * b;"); 10862 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10863 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10864 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10865 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10866 10867 // These are not casts, but at some point were confused with casts. 10868 verifyFormat("virtual void foo(int *) override;"); 10869 verifyFormat("virtual void foo(char &) const;"); 10870 verifyFormat("virtual void foo(int *a, char *) const;"); 10871 verifyFormat("int a = sizeof(int *) + b;"); 10872 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10873 verifyFormat("bool b = f(g<int>) && c;"); 10874 verifyFormat("typedef void (*f)(int i) func;"); 10875 verifyFormat("void operator++(int) noexcept;"); 10876 verifyFormat("void operator++(int &) noexcept;"); 10877 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10878 "&) noexcept;"); 10879 verifyFormat( 10880 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10881 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10882 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10883 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10884 verifyFormat("void operator delete(foo &) noexcept;"); 10885 verifyFormat("void operator delete(foo) noexcept;"); 10886 verifyFormat("void operator delete(int) noexcept;"); 10887 verifyFormat("void operator delete(int &) noexcept;"); 10888 verifyFormat("void operator delete(int &) volatile noexcept;"); 10889 verifyFormat("void operator delete(int &) const"); 10890 verifyFormat("void operator delete(int &) = default"); 10891 verifyFormat("void operator delete(int &) = delete"); 10892 verifyFormat("void operator delete(int &) [[noreturn]]"); 10893 verifyFormat("void operator delete(int &) throw();"); 10894 verifyFormat("void operator delete(int &) throw(int);"); 10895 verifyFormat("auto operator delete(int &) -> int;"); 10896 verifyFormat("auto operator delete(int &) override"); 10897 verifyFormat("auto operator delete(int &) final"); 10898 10899 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10900 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10901 // FIXME: The indentation here is not ideal. 10902 verifyFormat( 10903 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10904 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10905 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10906 } 10907 10908 TEST_F(FormatTest, FormatsFunctionTypes) { 10909 verifyFormat("A<bool()> a;"); 10910 verifyFormat("A<SomeType()> a;"); 10911 verifyFormat("A<void (*)(int, std::string)> a;"); 10912 verifyFormat("A<void *(int)>;"); 10913 verifyFormat("void *(*a)(int *, SomeType *);"); 10914 verifyFormat("int (*func)(void *);"); 10915 verifyFormat("void f() { int (*func)(void *); }"); 10916 verifyFormat("template <class CallbackClass>\n" 10917 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10918 10919 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10920 verifyGoogleFormat("void* (*a)(int);"); 10921 verifyGoogleFormat( 10922 "template <class CallbackClass>\n" 10923 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10924 10925 // Other constructs can look somewhat like function types: 10926 verifyFormat("A<sizeof(*x)> a;"); 10927 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10928 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10929 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10930 verifyFormat("int x = f(&h)();"); 10931 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10932 verifyFormat("std::function<\n" 10933 " LooooooooooongTemplatedType<\n" 10934 " SomeType>*(\n" 10935 " LooooooooooooooooongType type)>\n" 10936 " function;", 10937 getGoogleStyleWithColumns(40)); 10938 } 10939 10940 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10941 verifyFormat("A (*foo_)[6];"); 10942 verifyFormat("vector<int> (*foo_)[6];"); 10943 } 10944 10945 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10946 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10947 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10948 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10949 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10950 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10951 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10952 10953 // Different ways of ()-initializiation. 10954 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10955 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10956 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10957 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10958 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10959 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10960 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10961 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10962 10963 // Lambdas should not confuse the variable declaration heuristic. 10964 verifyFormat("LooooooooooooooooongType\n" 10965 " variable(nullptr, [](A *a) {});", 10966 getLLVMStyleWithColumns(40)); 10967 } 10968 10969 TEST_F(FormatTest, BreaksLongDeclarations) { 10970 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10971 " AnotherNameForTheLongType;"); 10972 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10973 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10974 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10975 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10976 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10977 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10978 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10979 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10980 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10981 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10982 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10983 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10984 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10985 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10986 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10987 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10988 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10989 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10990 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10991 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10992 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10993 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10994 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10995 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10996 FormatStyle Indented = getLLVMStyle(); 10997 Indented.IndentWrappedFunctionNames = true; 10998 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10999 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 11000 Indented); 11001 verifyFormat( 11002 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11003 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11004 Indented); 11005 verifyFormat( 11006 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11007 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11008 Indented); 11009 verifyFormat( 11010 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11011 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11012 Indented); 11013 11014 // FIXME: Without the comment, this breaks after "(". 11015 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 11016 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 11017 getGoogleStyle()); 11018 11019 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 11020 " int LoooooooooooooooooooongParam2) {}"); 11021 verifyFormat( 11022 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 11023 " SourceLocation L, IdentifierIn *II,\n" 11024 " Type *T) {}"); 11025 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 11026 "ReallyReaaallyLongFunctionName(\n" 11027 " const std::string &SomeParameter,\n" 11028 " const SomeType<string, SomeOtherTemplateParameter>\n" 11029 " &ReallyReallyLongParameterName,\n" 11030 " const SomeType<string, SomeOtherTemplateParameter>\n" 11031 " &AnotherLongParameterName) {}"); 11032 verifyFormat("template <typename A>\n" 11033 "SomeLoooooooooooooooooooooongType<\n" 11034 " typename some_namespace::SomeOtherType<A>::Type>\n" 11035 "Function() {}"); 11036 11037 verifyGoogleFormat( 11038 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11039 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11040 verifyGoogleFormat( 11041 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11042 " SourceLocation L) {}"); 11043 verifyGoogleFormat( 11044 "some_namespace::LongReturnType\n" 11045 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11046 " int first_long_parameter, int second_parameter) {}"); 11047 11048 verifyGoogleFormat("template <typename T>\n" 11049 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11050 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11051 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11052 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11053 11054 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11055 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11056 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11057 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11058 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11059 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11060 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11061 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11062 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11063 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11064 11065 verifyFormat("template <typename T> // Templates on own line.\n" 11066 "static int // Some comment.\n" 11067 "MyFunction(int a);", 11068 getLLVMStyle()); 11069 } 11070 11071 TEST_F(FormatTest, FormatsAccessModifiers) { 11072 FormatStyle Style = getLLVMStyle(); 11073 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11074 FormatStyle::ELBAMS_LogicalBlock); 11075 verifyFormat("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 Style); 11086 verifyFormat("struct foo {\n" 11087 "private:\n" 11088 " void f() {}\n" 11089 "\n" 11090 "private:\n" 11091 " int i;\n" 11092 "\n" 11093 "protected:\n" 11094 " int j;\n" 11095 "};\n", 11096 "struct foo {\n" 11097 "private:\n" 11098 " void f() {}\n" 11099 "private:\n" 11100 " int i;\n" 11101 "protected:\n" 11102 " int j;\n" 11103 "};\n", 11104 Style); 11105 verifyFormat("struct foo { /* comment */\n" 11106 "private:\n" 11107 " int i;\n" 11108 " // comment\n" 11109 "private:\n" 11110 " int j;\n" 11111 "};\n", 11112 Style); 11113 verifyFormat("struct foo {\n" 11114 "#ifdef FOO\n" 11115 "#endif\n" 11116 "private:\n" 11117 " int i;\n" 11118 "#ifdef FOO\n" 11119 "private:\n" 11120 "#endif\n" 11121 " int j;\n" 11122 "};\n", 11123 Style); 11124 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11125 verifyFormat("struct foo {\n" 11126 "private:\n" 11127 " void f() {}\n" 11128 "private:\n" 11129 " int i;\n" 11130 "protected:\n" 11131 " int j;\n" 11132 "};\n", 11133 Style); 11134 verifyFormat("struct foo {\n" 11135 "private:\n" 11136 " void f() {}\n" 11137 "private:\n" 11138 " int i;\n" 11139 "protected:\n" 11140 " int j;\n" 11141 "};\n", 11142 "struct foo {\n" 11143 "\n" 11144 "private:\n" 11145 " void f() {}\n" 11146 "\n" 11147 "private:\n" 11148 " int i;\n" 11149 "\n" 11150 "protected:\n" 11151 " int j;\n" 11152 "};\n", 11153 Style); 11154 verifyFormat("struct foo { /* comment */\n" 11155 "private:\n" 11156 " int i;\n" 11157 " // comment\n" 11158 "private:\n" 11159 " int j;\n" 11160 "};\n", 11161 "struct foo { /* comment */\n" 11162 "\n" 11163 "private:\n" 11164 " int i;\n" 11165 " // comment\n" 11166 "\n" 11167 "private:\n" 11168 " int j;\n" 11169 "};\n", 11170 Style); 11171 verifyFormat("struct foo {\n" 11172 "#ifdef FOO\n" 11173 "#endif\n" 11174 "private:\n" 11175 " int i;\n" 11176 "#ifdef FOO\n" 11177 "private:\n" 11178 "#endif\n" 11179 " int j;\n" 11180 "};\n", 11181 "struct foo {\n" 11182 "#ifdef FOO\n" 11183 "#endif\n" 11184 "\n" 11185 "private:\n" 11186 " int i;\n" 11187 "#ifdef FOO\n" 11188 "\n" 11189 "private:\n" 11190 "#endif\n" 11191 " int j;\n" 11192 "};\n", 11193 Style); 11194 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11195 verifyFormat("struct foo {\n" 11196 "private:\n" 11197 " void f() {}\n" 11198 "\n" 11199 "private:\n" 11200 " int i;\n" 11201 "\n" 11202 "protected:\n" 11203 " int j;\n" 11204 "};\n", 11205 Style); 11206 verifyFormat("struct foo {\n" 11207 "private:\n" 11208 " void f() {}\n" 11209 "\n" 11210 "private:\n" 11211 " int i;\n" 11212 "\n" 11213 "protected:\n" 11214 " int j;\n" 11215 "};\n", 11216 "struct foo {\n" 11217 "private:\n" 11218 " void f() {}\n" 11219 "private:\n" 11220 " int i;\n" 11221 "protected:\n" 11222 " int j;\n" 11223 "};\n", 11224 Style); 11225 verifyFormat("struct foo { /* comment */\n" 11226 "private:\n" 11227 " int i;\n" 11228 " // comment\n" 11229 "\n" 11230 "private:\n" 11231 " int j;\n" 11232 "};\n", 11233 "struct foo { /* comment */\n" 11234 "private:\n" 11235 " int i;\n" 11236 " // comment\n" 11237 "\n" 11238 "private:\n" 11239 " int j;\n" 11240 "};\n", 11241 Style); 11242 verifyFormat("struct foo {\n" 11243 "#ifdef FOO\n" 11244 "#endif\n" 11245 "\n" 11246 "private:\n" 11247 " int i;\n" 11248 "#ifdef FOO\n" 11249 "\n" 11250 "private:\n" 11251 "#endif\n" 11252 " int j;\n" 11253 "};\n", 11254 "struct foo {\n" 11255 "#ifdef FOO\n" 11256 "#endif\n" 11257 "private:\n" 11258 " int i;\n" 11259 "#ifdef FOO\n" 11260 "private:\n" 11261 "#endif\n" 11262 " int j;\n" 11263 "};\n", 11264 Style); 11265 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11266 EXPECT_EQ("struct foo {\n" 11267 "\n" 11268 "private:\n" 11269 " void f() {}\n" 11270 "\n" 11271 "private:\n" 11272 " int i;\n" 11273 "\n" 11274 "protected:\n" 11275 " int j;\n" 11276 "};\n", 11277 format("struct foo {\n" 11278 "\n" 11279 "private:\n" 11280 " void f() {}\n" 11281 "\n" 11282 "private:\n" 11283 " int i;\n" 11284 "\n" 11285 "protected:\n" 11286 " int j;\n" 11287 "};\n", 11288 Style)); 11289 verifyFormat("struct foo {\n" 11290 "private:\n" 11291 " void f() {}\n" 11292 "private:\n" 11293 " int i;\n" 11294 "protected:\n" 11295 " int j;\n" 11296 "};\n", 11297 Style); 11298 EXPECT_EQ("struct foo { /* comment */\n" 11299 "\n" 11300 "private:\n" 11301 " int i;\n" 11302 " // comment\n" 11303 "\n" 11304 "private:\n" 11305 " int j;\n" 11306 "};\n", 11307 format("struct foo { /* comment */\n" 11308 "\n" 11309 "private:\n" 11310 " int i;\n" 11311 " // comment\n" 11312 "\n" 11313 "private:\n" 11314 " int j;\n" 11315 "};\n", 11316 Style)); 11317 verifyFormat("struct foo { /* comment */\n" 11318 "private:\n" 11319 " int i;\n" 11320 " // comment\n" 11321 "private:\n" 11322 " int j;\n" 11323 "};\n", 11324 Style); 11325 EXPECT_EQ("struct foo {\n" 11326 "#ifdef FOO\n" 11327 "#endif\n" 11328 "\n" 11329 "private:\n" 11330 " int i;\n" 11331 "#ifdef FOO\n" 11332 "\n" 11333 "private:\n" 11334 "#endif\n" 11335 " int j;\n" 11336 "};\n", 11337 format("struct foo {\n" 11338 "#ifdef FOO\n" 11339 "#endif\n" 11340 "\n" 11341 "private:\n" 11342 " int i;\n" 11343 "#ifdef FOO\n" 11344 "\n" 11345 "private:\n" 11346 "#endif\n" 11347 " int j;\n" 11348 "};\n", 11349 Style)); 11350 verifyFormat("struct foo {\n" 11351 "#ifdef FOO\n" 11352 "#endif\n" 11353 "private:\n" 11354 " int i;\n" 11355 "#ifdef FOO\n" 11356 "private:\n" 11357 "#endif\n" 11358 " int j;\n" 11359 "};\n", 11360 Style); 11361 11362 FormatStyle NoEmptyLines = getLLVMStyle(); 11363 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11364 verifyFormat("struct foo {\n" 11365 "private:\n" 11366 " void f() {}\n" 11367 "\n" 11368 "private:\n" 11369 " int i;\n" 11370 "\n" 11371 "public:\n" 11372 "protected:\n" 11373 " int j;\n" 11374 "};\n", 11375 NoEmptyLines); 11376 11377 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11378 verifyFormat("struct foo {\n" 11379 "private:\n" 11380 " void f() {}\n" 11381 "private:\n" 11382 " int i;\n" 11383 "public:\n" 11384 "protected:\n" 11385 " int j;\n" 11386 "};\n", 11387 NoEmptyLines); 11388 11389 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11390 verifyFormat("struct foo {\n" 11391 "private:\n" 11392 " void f() {}\n" 11393 "\n" 11394 "private:\n" 11395 " int i;\n" 11396 "\n" 11397 "public:\n" 11398 "\n" 11399 "protected:\n" 11400 " int j;\n" 11401 "};\n", 11402 NoEmptyLines); 11403 } 11404 11405 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11406 11407 FormatStyle Style = getLLVMStyle(); 11408 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11409 verifyFormat("struct foo {\n" 11410 "private:\n" 11411 " void f() {}\n" 11412 "\n" 11413 "private:\n" 11414 " int i;\n" 11415 "\n" 11416 "protected:\n" 11417 " int j;\n" 11418 "};\n", 11419 Style); 11420 11421 // Check if lines are removed. 11422 verifyFormat("struct foo {\n" 11423 "private:\n" 11424 " void f() {}\n" 11425 "\n" 11426 "private:\n" 11427 " int i;\n" 11428 "\n" 11429 "protected:\n" 11430 " int j;\n" 11431 "};\n", 11432 "struct foo {\n" 11433 "private:\n" 11434 "\n" 11435 " void f() {}\n" 11436 "\n" 11437 "private:\n" 11438 "\n" 11439 " int i;\n" 11440 "\n" 11441 "protected:\n" 11442 "\n" 11443 " int j;\n" 11444 "};\n", 11445 Style); 11446 11447 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11448 verifyFormat("struct foo {\n" 11449 "private:\n" 11450 "\n" 11451 " void f() {}\n" 11452 "\n" 11453 "private:\n" 11454 "\n" 11455 " int i;\n" 11456 "\n" 11457 "protected:\n" 11458 "\n" 11459 " int j;\n" 11460 "};\n", 11461 Style); 11462 11463 // Check if lines are added. 11464 verifyFormat("struct foo {\n" 11465 "private:\n" 11466 "\n" 11467 " void f() {}\n" 11468 "\n" 11469 "private:\n" 11470 "\n" 11471 " int i;\n" 11472 "\n" 11473 "protected:\n" 11474 "\n" 11475 " int j;\n" 11476 "};\n", 11477 "struct foo {\n" 11478 "private:\n" 11479 " void f() {}\n" 11480 "\n" 11481 "private:\n" 11482 " int i;\n" 11483 "\n" 11484 "protected:\n" 11485 " int j;\n" 11486 "};\n", 11487 Style); 11488 11489 // Leave tests rely on the code layout, test::messUp can not be used. 11490 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11491 Style.MaxEmptyLinesToKeep = 0u; 11492 verifyFormat("struct foo {\n" 11493 "private:\n" 11494 " void f() {}\n" 11495 "\n" 11496 "private:\n" 11497 " int i;\n" 11498 "\n" 11499 "protected:\n" 11500 " int j;\n" 11501 "};\n", 11502 Style); 11503 11504 // Check if MaxEmptyLinesToKeep is respected. 11505 EXPECT_EQ("struct foo {\n" 11506 "private:\n" 11507 " void f() {}\n" 11508 "\n" 11509 "private:\n" 11510 " int i;\n" 11511 "\n" 11512 "protected:\n" 11513 " int j;\n" 11514 "};\n", 11515 format("struct foo {\n" 11516 "private:\n" 11517 "\n\n\n" 11518 " void f() {}\n" 11519 "\n" 11520 "private:\n" 11521 "\n\n\n" 11522 " int i;\n" 11523 "\n" 11524 "protected:\n" 11525 "\n\n\n" 11526 " int j;\n" 11527 "};\n", 11528 Style)); 11529 11530 Style.MaxEmptyLinesToKeep = 1u; 11531 EXPECT_EQ("struct foo {\n" 11532 "private:\n" 11533 "\n" 11534 " void f() {}\n" 11535 "\n" 11536 "private:\n" 11537 "\n" 11538 " int i;\n" 11539 "\n" 11540 "protected:\n" 11541 "\n" 11542 " int j;\n" 11543 "};\n", 11544 format("struct foo {\n" 11545 "private:\n" 11546 "\n" 11547 " void f() {}\n" 11548 "\n" 11549 "private:\n" 11550 "\n" 11551 " int i;\n" 11552 "\n" 11553 "protected:\n" 11554 "\n" 11555 " int j;\n" 11556 "};\n", 11557 Style)); 11558 // Check if no lines are kept. 11559 EXPECT_EQ("struct foo {\n" 11560 "private:\n" 11561 " void f() {}\n" 11562 "\n" 11563 "private:\n" 11564 " int i;\n" 11565 "\n" 11566 "protected:\n" 11567 " int j;\n" 11568 "};\n", 11569 format("struct foo {\n" 11570 "private:\n" 11571 " void f() {}\n" 11572 "\n" 11573 "private:\n" 11574 " int i;\n" 11575 "\n" 11576 "protected:\n" 11577 " int j;\n" 11578 "};\n", 11579 Style)); 11580 // Check if MaxEmptyLinesToKeep is respected. 11581 EXPECT_EQ("struct foo {\n" 11582 "private:\n" 11583 "\n" 11584 " void f() {}\n" 11585 "\n" 11586 "private:\n" 11587 "\n" 11588 " int i;\n" 11589 "\n" 11590 "protected:\n" 11591 "\n" 11592 " int j;\n" 11593 "};\n", 11594 format("struct foo {\n" 11595 "private:\n" 11596 "\n\n\n" 11597 " void f() {}\n" 11598 "\n" 11599 "private:\n" 11600 "\n\n\n" 11601 " int i;\n" 11602 "\n" 11603 "protected:\n" 11604 "\n\n\n" 11605 " int j;\n" 11606 "};\n", 11607 Style)); 11608 11609 Style.MaxEmptyLinesToKeep = 10u; 11610 EXPECT_EQ("struct foo {\n" 11611 "private:\n" 11612 "\n\n\n" 11613 " void f() {}\n" 11614 "\n" 11615 "private:\n" 11616 "\n\n\n" 11617 " int i;\n" 11618 "\n" 11619 "protected:\n" 11620 "\n\n\n" 11621 " int j;\n" 11622 "};\n", 11623 format("struct foo {\n" 11624 "private:\n" 11625 "\n\n\n" 11626 " void f() {}\n" 11627 "\n" 11628 "private:\n" 11629 "\n\n\n" 11630 " int i;\n" 11631 "\n" 11632 "protected:\n" 11633 "\n\n\n" 11634 " int j;\n" 11635 "};\n", 11636 Style)); 11637 11638 // Test with comments. 11639 Style = getLLVMStyle(); 11640 verifyFormat("struct foo {\n" 11641 "private:\n" 11642 " // comment\n" 11643 " void f() {}\n" 11644 "\n" 11645 "private: /* comment */\n" 11646 " int i;\n" 11647 "};\n", 11648 Style); 11649 verifyFormat("struct foo {\n" 11650 "private:\n" 11651 " // comment\n" 11652 " void f() {}\n" 11653 "\n" 11654 "private: /* comment */\n" 11655 " int i;\n" 11656 "};\n", 11657 "struct foo {\n" 11658 "private:\n" 11659 "\n" 11660 " // comment\n" 11661 " void f() {}\n" 11662 "\n" 11663 "private: /* comment */\n" 11664 "\n" 11665 " int i;\n" 11666 "};\n", 11667 Style); 11668 11669 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11670 verifyFormat("struct foo {\n" 11671 "private:\n" 11672 "\n" 11673 " // comment\n" 11674 " void f() {}\n" 11675 "\n" 11676 "private: /* comment */\n" 11677 "\n" 11678 " int i;\n" 11679 "};\n", 11680 "struct foo {\n" 11681 "private:\n" 11682 " // comment\n" 11683 " void f() {}\n" 11684 "\n" 11685 "private: /* comment */\n" 11686 " int i;\n" 11687 "};\n", 11688 Style); 11689 verifyFormat("struct foo {\n" 11690 "private:\n" 11691 "\n" 11692 " // comment\n" 11693 " void f() {}\n" 11694 "\n" 11695 "private: /* comment */\n" 11696 "\n" 11697 " int i;\n" 11698 "};\n", 11699 Style); 11700 11701 // Test with preprocessor defines. 11702 Style = getLLVMStyle(); 11703 verifyFormat("struct foo {\n" 11704 "private:\n" 11705 "#ifdef FOO\n" 11706 "#endif\n" 11707 " void f() {}\n" 11708 "};\n", 11709 Style); 11710 verifyFormat("struct foo {\n" 11711 "private:\n" 11712 "#ifdef FOO\n" 11713 "#endif\n" 11714 " void f() {}\n" 11715 "};\n", 11716 "struct foo {\n" 11717 "private:\n" 11718 "\n" 11719 "#ifdef FOO\n" 11720 "#endif\n" 11721 " void f() {}\n" 11722 "};\n", 11723 Style); 11724 11725 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11726 verifyFormat("struct foo {\n" 11727 "private:\n" 11728 "\n" 11729 "#ifdef FOO\n" 11730 "#endif\n" 11731 " void f() {}\n" 11732 "};\n", 11733 "struct foo {\n" 11734 "private:\n" 11735 "#ifdef FOO\n" 11736 "#endif\n" 11737 " void f() {}\n" 11738 "};\n", 11739 Style); 11740 verifyFormat("struct foo {\n" 11741 "private:\n" 11742 "\n" 11743 "#ifdef FOO\n" 11744 "#endif\n" 11745 " void f() {}\n" 11746 "};\n", 11747 Style); 11748 } 11749 11750 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11751 // Combined tests of EmptyLineAfterAccessModifier and 11752 // EmptyLineBeforeAccessModifier. 11753 FormatStyle Style = getLLVMStyle(); 11754 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11755 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11756 verifyFormat("struct foo {\n" 11757 "private:\n" 11758 "\n" 11759 "protected:\n" 11760 "};\n", 11761 Style); 11762 11763 Style.MaxEmptyLinesToKeep = 10u; 11764 // Both remove all new lines. 11765 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11766 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11767 verifyFormat("struct foo {\n" 11768 "private:\n" 11769 "protected:\n" 11770 "};\n", 11771 "struct foo {\n" 11772 "private:\n" 11773 "\n\n\n" 11774 "protected:\n" 11775 "};\n", 11776 Style); 11777 11778 // Leave tests rely on the code layout, test::messUp can not be used. 11779 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11780 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11781 Style.MaxEmptyLinesToKeep = 10u; 11782 EXPECT_EQ("struct foo {\n" 11783 "private:\n" 11784 "\n\n\n" 11785 "protected:\n" 11786 "};\n", 11787 format("struct foo {\n" 11788 "private:\n" 11789 "\n\n\n" 11790 "protected:\n" 11791 "};\n", 11792 Style)); 11793 Style.MaxEmptyLinesToKeep = 3u; 11794 EXPECT_EQ("struct foo {\n" 11795 "private:\n" 11796 "\n\n\n" 11797 "protected:\n" 11798 "};\n", 11799 format("struct foo {\n" 11800 "private:\n" 11801 "\n\n\n" 11802 "protected:\n" 11803 "};\n", 11804 Style)); 11805 Style.MaxEmptyLinesToKeep = 1u; 11806 EXPECT_EQ("struct foo {\n" 11807 "private:\n" 11808 "\n\n\n" 11809 "protected:\n" 11810 "};\n", 11811 format("struct foo {\n" 11812 "private:\n" 11813 "\n\n\n" 11814 "protected:\n" 11815 "};\n", 11816 Style)); // Based on new lines in original document and not 11817 // on the setting. 11818 11819 Style.MaxEmptyLinesToKeep = 10u; 11820 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11821 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11822 // Newlines are kept if they are greater than zero, 11823 // test::messUp removes all new lines which changes the logic 11824 EXPECT_EQ("struct foo {\n" 11825 "private:\n" 11826 "\n\n\n" 11827 "protected:\n" 11828 "};\n", 11829 format("struct foo {\n" 11830 "private:\n" 11831 "\n\n\n" 11832 "protected:\n" 11833 "};\n", 11834 Style)); 11835 11836 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11837 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11838 // test::messUp removes all new lines which changes the logic 11839 EXPECT_EQ("struct foo {\n" 11840 "private:\n" 11841 "\n\n\n" 11842 "protected:\n" 11843 "};\n", 11844 format("struct foo {\n" 11845 "private:\n" 11846 "\n\n\n" 11847 "protected:\n" 11848 "};\n", 11849 Style)); 11850 11851 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11852 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11853 EXPECT_EQ("struct foo {\n" 11854 "private:\n" 11855 "\n\n\n" 11856 "protected:\n" 11857 "};\n", 11858 format("struct foo {\n" 11859 "private:\n" 11860 "\n\n\n" 11861 "protected:\n" 11862 "};\n", 11863 Style)); // test::messUp removes all new lines which changes 11864 // the logic. 11865 11866 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11867 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11868 verifyFormat("struct foo {\n" 11869 "private:\n" 11870 "protected:\n" 11871 "};\n", 11872 "struct foo {\n" 11873 "private:\n" 11874 "\n\n\n" 11875 "protected:\n" 11876 "};\n", 11877 Style); 11878 11879 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11880 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11881 EXPECT_EQ("struct foo {\n" 11882 "private:\n" 11883 "\n\n\n" 11884 "protected:\n" 11885 "};\n", 11886 format("struct foo {\n" 11887 "private:\n" 11888 "\n\n\n" 11889 "protected:\n" 11890 "};\n", 11891 Style)); // test::messUp removes all new lines which changes 11892 // the logic. 11893 11894 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11895 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11896 verifyFormat("struct foo {\n" 11897 "private:\n" 11898 "protected:\n" 11899 "};\n", 11900 "struct foo {\n" 11901 "private:\n" 11902 "\n\n\n" 11903 "protected:\n" 11904 "};\n", 11905 Style); 11906 11907 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11908 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11909 verifyFormat("struct foo {\n" 11910 "private:\n" 11911 "protected:\n" 11912 "};\n", 11913 "struct foo {\n" 11914 "private:\n" 11915 "\n\n\n" 11916 "protected:\n" 11917 "};\n", 11918 Style); 11919 11920 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11921 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11922 verifyFormat("struct foo {\n" 11923 "private:\n" 11924 "protected:\n" 11925 "};\n", 11926 "struct foo {\n" 11927 "private:\n" 11928 "\n\n\n" 11929 "protected:\n" 11930 "};\n", 11931 Style); 11932 11933 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11934 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11935 verifyFormat("struct foo {\n" 11936 "private:\n" 11937 "protected:\n" 11938 "};\n", 11939 "struct foo {\n" 11940 "private:\n" 11941 "\n\n\n" 11942 "protected:\n" 11943 "};\n", 11944 Style); 11945 } 11946 11947 TEST_F(FormatTest, FormatsArrays) { 11948 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11949 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11950 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11951 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11952 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11953 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11954 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11955 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11956 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11957 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11958 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11959 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11960 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11961 verifyFormat( 11962 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11963 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11964 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11965 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11966 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11967 11968 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11969 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11970 verifyFormat( 11971 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11972 " .aaaaaaa[0]\n" 11973 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11974 verifyFormat("a[::b::c];"); 11975 11976 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11977 11978 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11979 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11980 } 11981 11982 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11983 verifyFormat("(a)->b();"); 11984 verifyFormat("--a;"); 11985 } 11986 11987 TEST_F(FormatTest, HandlesIncludeDirectives) { 11988 verifyFormat("#include <string>\n" 11989 "#include <a/b/c.h>\n" 11990 "#include \"a/b/string\"\n" 11991 "#include \"string.h\"\n" 11992 "#include \"string.h\"\n" 11993 "#include <a-a>\n" 11994 "#include < path with space >\n" 11995 "#include_next <test.h>" 11996 "#include \"abc.h\" // this is included for ABC\n" 11997 "#include \"some long include\" // with a comment\n" 11998 "#include \"some very long include path\"\n" 11999 "#include <some/very/long/include/path>\n", 12000 getLLVMStyleWithColumns(35)); 12001 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 12002 EXPECT_EQ("#include <a>", format("#include<a>")); 12003 12004 verifyFormat("#import <string>"); 12005 verifyFormat("#import <a/b/c.h>"); 12006 verifyFormat("#import \"a/b/string\""); 12007 verifyFormat("#import \"string.h\""); 12008 verifyFormat("#import \"string.h\""); 12009 verifyFormat("#if __has_include(<strstream>)\n" 12010 "#include <strstream>\n" 12011 "#endif"); 12012 12013 verifyFormat("#define MY_IMPORT <a/b>"); 12014 12015 verifyFormat("#if __has_include(<a/b>)"); 12016 verifyFormat("#if __has_include_next(<a/b>)"); 12017 verifyFormat("#define F __has_include(<a/b>)"); 12018 verifyFormat("#define F __has_include_next(<a/b>)"); 12019 12020 // Protocol buffer definition or missing "#". 12021 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 12022 getLLVMStyleWithColumns(30)); 12023 12024 FormatStyle Style = getLLVMStyle(); 12025 Style.AlwaysBreakBeforeMultilineStrings = true; 12026 Style.ColumnLimit = 0; 12027 verifyFormat("#import \"abc.h\"", Style); 12028 12029 // But 'import' might also be a regular C++ namespace. 12030 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12031 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12032 } 12033 12034 //===----------------------------------------------------------------------===// 12035 // Error recovery tests. 12036 //===----------------------------------------------------------------------===// 12037 12038 TEST_F(FormatTest, IncompleteParameterLists) { 12039 FormatStyle NoBinPacking = getLLVMStyle(); 12040 NoBinPacking.BinPackParameters = false; 12041 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12042 " double *min_x,\n" 12043 " double *max_x,\n" 12044 " double *min_y,\n" 12045 " double *max_y,\n" 12046 " double *min_z,\n" 12047 " double *max_z, ) {}", 12048 NoBinPacking); 12049 } 12050 12051 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12052 verifyFormat("void f() { return; }\n42"); 12053 verifyFormat("void f() {\n" 12054 " if (0)\n" 12055 " return;\n" 12056 "}\n" 12057 "42"); 12058 verifyFormat("void f() { return }\n42"); 12059 verifyFormat("void f() {\n" 12060 " if (0)\n" 12061 " return\n" 12062 "}\n" 12063 "42"); 12064 } 12065 12066 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12067 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12068 EXPECT_EQ("void f() {\n" 12069 " if (a)\n" 12070 " return\n" 12071 "}", 12072 format("void f ( ) { if ( a ) return }")); 12073 EXPECT_EQ("namespace N {\n" 12074 "void f()\n" 12075 "}", 12076 format("namespace N { void f() }")); 12077 EXPECT_EQ("namespace N {\n" 12078 "void f() {}\n" 12079 "void g()\n" 12080 "} // namespace N", 12081 format("namespace N { void f( ) { } void g( ) }")); 12082 } 12083 12084 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12085 verifyFormat("int aaaaaaaa =\n" 12086 " // Overlylongcomment\n" 12087 " b;", 12088 getLLVMStyleWithColumns(20)); 12089 verifyFormat("function(\n" 12090 " ShortArgument,\n" 12091 " LoooooooooooongArgument);\n", 12092 getLLVMStyleWithColumns(20)); 12093 } 12094 12095 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12096 verifyFormat("public:"); 12097 verifyFormat("class A {\n" 12098 "public\n" 12099 " void f() {}\n" 12100 "};"); 12101 verifyFormat("public\n" 12102 "int qwerty;"); 12103 verifyFormat("public\n" 12104 "B {}"); 12105 verifyFormat("public\n" 12106 "{}"); 12107 verifyFormat("public\n" 12108 "B { int x; }"); 12109 } 12110 12111 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12112 verifyFormat("{"); 12113 verifyFormat("#})"); 12114 verifyNoCrash("(/**/[:!] ?[)."); 12115 } 12116 12117 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12118 // Found by oss-fuzz: 12119 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12120 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12121 Style.ColumnLimit = 60; 12122 verifyNoCrash( 12123 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12124 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12125 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12126 Style); 12127 } 12128 12129 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12130 verifyFormat("do {\n}"); 12131 verifyFormat("do {\n}\n" 12132 "f();"); 12133 verifyFormat("do {\n}\n" 12134 "wheeee(fun);"); 12135 verifyFormat("do {\n" 12136 " f();\n" 12137 "}"); 12138 } 12139 12140 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12141 verifyFormat("if {\n foo;\n foo();\n}"); 12142 verifyFormat("switch {\n foo;\n foo();\n}"); 12143 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12144 verifyIncompleteFormat("ERROR: for target;"); 12145 verifyFormat("while {\n foo;\n foo();\n}"); 12146 verifyFormat("do {\n foo;\n foo();\n} while;"); 12147 } 12148 12149 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12150 verifyIncompleteFormat("namespace {\n" 12151 "class Foo { Foo (\n" 12152 "};\n" 12153 "} // namespace"); 12154 } 12155 12156 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12157 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12158 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12159 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12160 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12161 12162 EXPECT_EQ("{\n" 12163 " {\n" 12164 " breakme(\n" 12165 " qwe);\n" 12166 " }\n", 12167 format("{\n" 12168 " {\n" 12169 " breakme(qwe);\n" 12170 "}\n", 12171 getLLVMStyleWithColumns(10))); 12172 } 12173 12174 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12175 verifyFormat("int x = {\n" 12176 " avariable,\n" 12177 " b(alongervariable)};", 12178 getLLVMStyleWithColumns(25)); 12179 } 12180 12181 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12182 verifyFormat("return (a)(b){1, 2, 3};"); 12183 } 12184 12185 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12186 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12187 verifyFormat("vector<int> x{\n" 12188 " 1,\n" 12189 " 2,\n" 12190 " 3,\n" 12191 " 4,\n" 12192 "};"); 12193 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12194 verifyFormat("f({1, 2});"); 12195 verifyFormat("auto v = Foo{-1};"); 12196 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12197 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12198 verifyFormat("new vector<int>{1, 2, 3};"); 12199 verifyFormat("new int[3]{1, 2, 3};"); 12200 verifyFormat("new int{1};"); 12201 verifyFormat("return {arg1, arg2};"); 12202 verifyFormat("return {arg1, SomeType{parameter}};"); 12203 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12204 verifyFormat("new T{arg1, arg2};"); 12205 verifyFormat("f(MyMap[{composite, key}]);"); 12206 verifyFormat("class Class {\n" 12207 " T member = {arg1, arg2};\n" 12208 "};"); 12209 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12210 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12211 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12212 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12213 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12214 12215 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12216 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12217 verifyFormat("auto i = decltype(x){};"); 12218 verifyFormat("auto i = typeof(x){};"); 12219 verifyFormat("auto i = _Atomic(x){};"); 12220 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12221 verifyFormat("Node n{1, Node{1000}, //\n" 12222 " 2};"); 12223 verifyFormat("Aaaa aaaaaaa{\n" 12224 " {\n" 12225 " aaaa,\n" 12226 " },\n" 12227 "};"); 12228 verifyFormat("class C : public D {\n" 12229 " SomeClass SC{2};\n" 12230 "};"); 12231 verifyFormat("class C : public A {\n" 12232 " class D : public B {\n" 12233 " void f() { int i{2}; }\n" 12234 " };\n" 12235 "};"); 12236 verifyFormat("#define A {a, a},"); 12237 // Don't confuse braced list initializers with compound statements. 12238 verifyFormat( 12239 "class A {\n" 12240 " A() : a{} {}\n" 12241 " A(int b) : b(b) {}\n" 12242 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12243 " int a, b;\n" 12244 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12245 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12246 "{}\n" 12247 "};"); 12248 12249 // Avoid breaking between equal sign and opening brace 12250 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12251 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12252 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12253 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12254 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12255 " {\"ccccccccccccccccccccc\", 2}};", 12256 AvoidBreakingFirstArgument); 12257 12258 // Binpacking only if there is no trailing comma 12259 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12260 " cccccccccc, dddddddddd};", 12261 getLLVMStyleWithColumns(50)); 12262 verifyFormat("const Aaaaaa aaaaa = {\n" 12263 " aaaaaaaaaaa,\n" 12264 " bbbbbbbbbbb,\n" 12265 " ccccccccccc,\n" 12266 " ddddddddddd,\n" 12267 "};", 12268 getLLVMStyleWithColumns(50)); 12269 12270 // Cases where distinguising braced lists and blocks is hard. 12271 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12272 verifyFormat("void f() {\n" 12273 " return; // comment\n" 12274 "}\n" 12275 "SomeType t;"); 12276 verifyFormat("void f() {\n" 12277 " if (a) {\n" 12278 " f();\n" 12279 " }\n" 12280 "}\n" 12281 "SomeType t;"); 12282 12283 // In combination with BinPackArguments = false. 12284 FormatStyle NoBinPacking = getLLVMStyle(); 12285 NoBinPacking.BinPackArguments = false; 12286 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12287 " bbbbb,\n" 12288 " ccccc,\n" 12289 " ddddd,\n" 12290 " eeeee,\n" 12291 " ffffff,\n" 12292 " ggggg,\n" 12293 " hhhhhh,\n" 12294 " iiiiii,\n" 12295 " jjjjjj,\n" 12296 " kkkkkk};", 12297 NoBinPacking); 12298 verifyFormat("const Aaaaaa aaaaa = {\n" 12299 " aaaaa,\n" 12300 " bbbbb,\n" 12301 " ccccc,\n" 12302 " ddddd,\n" 12303 " eeeee,\n" 12304 " ffffff,\n" 12305 " ggggg,\n" 12306 " hhhhhh,\n" 12307 " iiiiii,\n" 12308 " jjjjjj,\n" 12309 " kkkkkk,\n" 12310 "};", 12311 NoBinPacking); 12312 verifyFormat( 12313 "const Aaaaaa aaaaa = {\n" 12314 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12315 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12316 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12317 "};", 12318 NoBinPacking); 12319 12320 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12321 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12322 " CDDDP83848_BMCR_REGISTER,\n" 12323 " CDDDP83848_BMSR_REGISTER,\n" 12324 " CDDDP83848_RBR_REGISTER};", 12325 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12326 " CDDDP83848_BMSR_REGISTER,\n" 12327 " CDDDP83848_RBR_REGISTER};", 12328 NoBinPacking)); 12329 12330 // FIXME: The alignment of these trailing comments might be bad. Then again, 12331 // this might be utterly useless in real code. 12332 verifyFormat("Constructor::Constructor()\n" 12333 " : some_value{ //\n" 12334 " aaaaaaa, //\n" 12335 " bbbbbbb} {}"); 12336 12337 // In braced lists, the first comment is always assumed to belong to the 12338 // first element. Thus, it can be moved to the next or previous line as 12339 // appropriate. 12340 EXPECT_EQ("function({// First element:\n" 12341 " 1,\n" 12342 " // Second element:\n" 12343 " 2});", 12344 format("function({\n" 12345 " // First element:\n" 12346 " 1,\n" 12347 " // Second element:\n" 12348 " 2});")); 12349 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12350 " // First element:\n" 12351 " 1,\n" 12352 " // Second element:\n" 12353 " 2};", 12354 format("std::vector<int> MyNumbers{// First element:\n" 12355 " 1,\n" 12356 " // Second element:\n" 12357 " 2};", 12358 getLLVMStyleWithColumns(30))); 12359 // A trailing comma should still lead to an enforced line break and no 12360 // binpacking. 12361 EXPECT_EQ("vector<int> SomeVector = {\n" 12362 " // aaa\n" 12363 " 1,\n" 12364 " 2,\n" 12365 "};", 12366 format("vector<int> SomeVector = { // aaa\n" 12367 " 1, 2, };")); 12368 12369 // C++11 brace initializer list l-braces should not be treated any differently 12370 // when breaking before lambda bodies is enabled 12371 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12372 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12373 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12374 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12375 verifyFormat( 12376 "std::runtime_error{\n" 12377 " \"Long string which will force a break onto the next line...\"};", 12378 BreakBeforeLambdaBody); 12379 12380 FormatStyle ExtraSpaces = getLLVMStyle(); 12381 ExtraSpaces.Cpp11BracedListStyle = false; 12382 ExtraSpaces.ColumnLimit = 75; 12383 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12384 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12385 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12386 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12387 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12388 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12389 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12390 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12391 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12392 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12393 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12394 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12395 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12396 verifyFormat("class Class {\n" 12397 " T member = { arg1, arg2 };\n" 12398 "};", 12399 ExtraSpaces); 12400 verifyFormat( 12401 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12402 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12403 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12404 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12405 ExtraSpaces); 12406 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12407 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12408 ExtraSpaces); 12409 verifyFormat( 12410 "someFunction(OtherParam,\n" 12411 " BracedList{ // comment 1 (Forcing interesting break)\n" 12412 " param1, param2,\n" 12413 " // comment 2\n" 12414 " param3, param4 });", 12415 ExtraSpaces); 12416 verifyFormat( 12417 "std::this_thread::sleep_for(\n" 12418 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12419 ExtraSpaces); 12420 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12421 " aaaaaaa,\n" 12422 " aaaaaaaaaa,\n" 12423 " aaaaa,\n" 12424 " aaaaaaaaaaaaaaa,\n" 12425 " aaa,\n" 12426 " aaaaaaaaaa,\n" 12427 " a,\n" 12428 " aaaaaaaaaaaaaaaaaaaaa,\n" 12429 " aaaaaaaaaaaa,\n" 12430 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12431 " aaaaaaa,\n" 12432 " a};"); 12433 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12434 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12435 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12436 12437 // Avoid breaking between initializer/equal sign and opening brace 12438 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12439 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12440 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12441 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12442 " { \"ccccccccccccccccccccc\", 2 }\n" 12443 "};", 12444 ExtraSpaces); 12445 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12446 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12447 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12448 " { \"ccccccccccccccccccccc\", 2 }\n" 12449 "};", 12450 ExtraSpaces); 12451 12452 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12453 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12454 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12455 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12456 12457 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12458 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12459 SpaceBetweenBraces.SpacesInParentheses = true; 12460 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12461 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12462 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12463 verifyFormat("vector< int > x{ // comment 1\n" 12464 " 1, 2, 3, 4 };", 12465 SpaceBetweenBraces); 12466 SpaceBetweenBraces.ColumnLimit = 20; 12467 EXPECT_EQ("vector< int > x{\n" 12468 " 1, 2, 3, 4 };", 12469 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12470 SpaceBetweenBraces.ColumnLimit = 24; 12471 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12472 " 3, 4 };", 12473 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12474 EXPECT_EQ("vector< int > x{\n" 12475 " 1,\n" 12476 " 2,\n" 12477 " 3,\n" 12478 " 4,\n" 12479 "};", 12480 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12481 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12482 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12483 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12484 } 12485 12486 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12487 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12488 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12489 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12490 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12491 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12492 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12493 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12494 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12495 " 1, 22, 333, 4444, 55555, //\n" 12496 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12497 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12498 verifyFormat( 12499 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12500 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12501 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12502 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12503 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12504 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12505 " 7777777};"); 12506 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12507 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12508 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12509 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12510 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12511 " // Separating comment.\n" 12512 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12513 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12514 " // Leading comment\n" 12515 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12516 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12517 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12518 " 1, 1, 1, 1};", 12519 getLLVMStyleWithColumns(39)); 12520 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12521 " 1, 1, 1, 1};", 12522 getLLVMStyleWithColumns(38)); 12523 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12524 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12525 getLLVMStyleWithColumns(43)); 12526 verifyFormat( 12527 "static unsigned SomeValues[10][3] = {\n" 12528 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12529 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12530 verifyFormat("static auto fields = new vector<string>{\n" 12531 " \"aaaaaaaaaaaaa\",\n" 12532 " \"aaaaaaaaaaaaa\",\n" 12533 " \"aaaaaaaaaaaa\",\n" 12534 " \"aaaaaaaaaaaaaa\",\n" 12535 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12536 " \"aaaaaaaaaaaa\",\n" 12537 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12538 "};"); 12539 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12540 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12541 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12542 " 3, cccccccccccccccccccccc};", 12543 getLLVMStyleWithColumns(60)); 12544 12545 // Trailing commas. 12546 verifyFormat("vector<int> x = {\n" 12547 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12548 "};", 12549 getLLVMStyleWithColumns(39)); 12550 verifyFormat("vector<int> x = {\n" 12551 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12552 "};", 12553 getLLVMStyleWithColumns(39)); 12554 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12555 " 1, 1, 1, 1,\n" 12556 " /**/ /**/};", 12557 getLLVMStyleWithColumns(39)); 12558 12559 // Trailing comment in the first line. 12560 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12561 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12562 " 111111111, 222222222, 3333333333, 444444444, //\n" 12563 " 11111111, 22222222, 333333333, 44444444};"); 12564 // Trailing comment in the last line. 12565 verifyFormat("int aaaaa[] = {\n" 12566 " 1, 2, 3, // comment\n" 12567 " 4, 5, 6 // comment\n" 12568 "};"); 12569 12570 // With nested lists, we should either format one item per line or all nested 12571 // lists one on line. 12572 // FIXME: For some nested lists, we can do better. 12573 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12574 " {aaaaaaaaaaaaaaaaaaa},\n" 12575 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12576 " {aaaaaaaaaaaaaaaaa}};", 12577 getLLVMStyleWithColumns(60)); 12578 verifyFormat( 12579 "SomeStruct my_struct_array = {\n" 12580 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12581 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12582 " {aaa, aaa},\n" 12583 " {aaa, aaa},\n" 12584 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12585 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12586 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12587 12588 // No column layout should be used here. 12589 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12590 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12591 12592 verifyNoCrash("a<,"); 12593 12594 // No braced initializer here. 12595 verifyFormat("void f() {\n" 12596 " struct Dummy {};\n" 12597 " f(v);\n" 12598 "}"); 12599 12600 // Long lists should be formatted in columns even if they are nested. 12601 verifyFormat( 12602 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12603 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12604 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12605 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12606 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12607 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12608 12609 // Allow "single-column" layout even if that violates the column limit. There 12610 // isn't going to be a better way. 12611 verifyFormat("std::vector<int> a = {\n" 12612 " aaaaaaaa,\n" 12613 " aaaaaaaa,\n" 12614 " aaaaaaaa,\n" 12615 " aaaaaaaa,\n" 12616 " aaaaaaaaaa,\n" 12617 " aaaaaaaa,\n" 12618 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12619 getLLVMStyleWithColumns(30)); 12620 verifyFormat("vector<int> aaaa = {\n" 12621 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12622 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12623 " aaaaaa.aaaaaaa,\n" 12624 " aaaaaa.aaaaaaa,\n" 12625 " aaaaaa.aaaaaaa,\n" 12626 " aaaaaa.aaaaaaa,\n" 12627 "};"); 12628 12629 // Don't create hanging lists. 12630 verifyFormat("someFunction(Param, {List1, List2,\n" 12631 " List3});", 12632 getLLVMStyleWithColumns(35)); 12633 verifyFormat("someFunction(Param, Param,\n" 12634 " {List1, List2,\n" 12635 " List3});", 12636 getLLVMStyleWithColumns(35)); 12637 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12638 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12639 } 12640 12641 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12642 FormatStyle DoNotMerge = getLLVMStyle(); 12643 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12644 12645 verifyFormat("void f() { return 42; }"); 12646 verifyFormat("void f() {\n" 12647 " return 42;\n" 12648 "}", 12649 DoNotMerge); 12650 verifyFormat("void f() {\n" 12651 " // Comment\n" 12652 "}"); 12653 verifyFormat("{\n" 12654 "#error {\n" 12655 " int a;\n" 12656 "}"); 12657 verifyFormat("{\n" 12658 " int a;\n" 12659 "#error {\n" 12660 "}"); 12661 verifyFormat("void f() {} // comment"); 12662 verifyFormat("void f() { int a; } // comment"); 12663 verifyFormat("void f() {\n" 12664 "} // comment", 12665 DoNotMerge); 12666 verifyFormat("void f() {\n" 12667 " int a;\n" 12668 "} // comment", 12669 DoNotMerge); 12670 verifyFormat("void f() {\n" 12671 "} // comment", 12672 getLLVMStyleWithColumns(15)); 12673 12674 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12675 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12676 12677 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12678 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12679 verifyFormat("class C {\n" 12680 " C()\n" 12681 " : iiiiiiii(nullptr),\n" 12682 " kkkkkkk(nullptr),\n" 12683 " mmmmmmm(nullptr),\n" 12684 " nnnnnnn(nullptr) {}\n" 12685 "};", 12686 getGoogleStyle()); 12687 12688 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12689 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12690 EXPECT_EQ("class C {\n" 12691 " A() : b(0) {}\n" 12692 "};", 12693 format("class C{A():b(0){}};", NoColumnLimit)); 12694 EXPECT_EQ("A()\n" 12695 " : b(0) {\n" 12696 "}", 12697 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12698 12699 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12700 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12701 FormatStyle::SFS_None; 12702 EXPECT_EQ("A()\n" 12703 " : b(0) {\n" 12704 "}", 12705 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12706 EXPECT_EQ("A()\n" 12707 " : b(0) {\n" 12708 "}", 12709 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12710 12711 verifyFormat("#define A \\\n" 12712 " void f() { \\\n" 12713 " int i; \\\n" 12714 " }", 12715 getLLVMStyleWithColumns(20)); 12716 verifyFormat("#define A \\\n" 12717 " void f() { int i; }", 12718 getLLVMStyleWithColumns(21)); 12719 verifyFormat("#define A \\\n" 12720 " void f() { \\\n" 12721 " int i; \\\n" 12722 " } \\\n" 12723 " int j;", 12724 getLLVMStyleWithColumns(22)); 12725 verifyFormat("#define A \\\n" 12726 " void f() { int i; } \\\n" 12727 " int j;", 12728 getLLVMStyleWithColumns(23)); 12729 } 12730 12731 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12732 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12733 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12734 verifyFormat("class C {\n" 12735 " int f() {}\n" 12736 "};", 12737 MergeEmptyOnly); 12738 verifyFormat("class C {\n" 12739 " int f() {\n" 12740 " return 42;\n" 12741 " }\n" 12742 "};", 12743 MergeEmptyOnly); 12744 verifyFormat("int f() {}", MergeEmptyOnly); 12745 verifyFormat("int f() {\n" 12746 " return 42;\n" 12747 "}", 12748 MergeEmptyOnly); 12749 12750 // Also verify behavior when BraceWrapping.AfterFunction = true 12751 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12752 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12753 verifyFormat("int f() {}", MergeEmptyOnly); 12754 verifyFormat("class C {\n" 12755 " int f() {}\n" 12756 "};", 12757 MergeEmptyOnly); 12758 } 12759 12760 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12761 FormatStyle MergeInlineOnly = getLLVMStyle(); 12762 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12763 verifyFormat("class C {\n" 12764 " int f() { return 42; }\n" 12765 "};", 12766 MergeInlineOnly); 12767 verifyFormat("int f() {\n" 12768 " return 42;\n" 12769 "}", 12770 MergeInlineOnly); 12771 12772 // SFS_Inline implies SFS_Empty 12773 verifyFormat("class C {\n" 12774 " int f() {}\n" 12775 "};", 12776 MergeInlineOnly); 12777 verifyFormat("int f() {}", MergeInlineOnly); 12778 // https://llvm.org/PR54147 12779 verifyFormat("auto lambda = []() {\n" 12780 " // comment\n" 12781 " f();\n" 12782 " g();\n" 12783 "};", 12784 MergeInlineOnly); 12785 12786 verifyFormat("class C {\n" 12787 "#ifdef A\n" 12788 " int f() { return 42; }\n" 12789 "#endif\n" 12790 "};", 12791 MergeInlineOnly); 12792 12793 verifyFormat("struct S {\n" 12794 "// comment\n" 12795 "#ifdef FOO\n" 12796 " int foo() { bar(); }\n" 12797 "#endif\n" 12798 "};", 12799 MergeInlineOnly); 12800 12801 // Also verify behavior when BraceWrapping.AfterFunction = true 12802 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12803 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12804 verifyFormat("class C {\n" 12805 " int f() { return 42; }\n" 12806 "};", 12807 MergeInlineOnly); 12808 verifyFormat("int f()\n" 12809 "{\n" 12810 " return 42;\n" 12811 "}", 12812 MergeInlineOnly); 12813 12814 // SFS_Inline implies SFS_Empty 12815 verifyFormat("int f() {}", MergeInlineOnly); 12816 verifyFormat("class C {\n" 12817 " int f() {}\n" 12818 "};", 12819 MergeInlineOnly); 12820 12821 MergeInlineOnly.BraceWrapping.AfterClass = true; 12822 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12823 verifyFormat("class C\n" 12824 "{\n" 12825 " int f() { return 42; }\n" 12826 "};", 12827 MergeInlineOnly); 12828 verifyFormat("struct C\n" 12829 "{\n" 12830 " int f() { return 42; }\n" 12831 "};", 12832 MergeInlineOnly); 12833 verifyFormat("int f()\n" 12834 "{\n" 12835 " return 42;\n" 12836 "}", 12837 MergeInlineOnly); 12838 verifyFormat("int f() {}", MergeInlineOnly); 12839 verifyFormat("class C\n" 12840 "{\n" 12841 " int f() { return 42; }\n" 12842 "};", 12843 MergeInlineOnly); 12844 verifyFormat("struct C\n" 12845 "{\n" 12846 " int f() { return 42; }\n" 12847 "};", 12848 MergeInlineOnly); 12849 verifyFormat("struct C\n" 12850 "// comment\n" 12851 "/* comment */\n" 12852 "// comment\n" 12853 "{\n" 12854 " int f() { return 42; }\n" 12855 "};", 12856 MergeInlineOnly); 12857 verifyFormat("/* comment */ struct C\n" 12858 "{\n" 12859 " int f() { return 42; }\n" 12860 "};", 12861 MergeInlineOnly); 12862 } 12863 12864 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12865 FormatStyle MergeInlineOnly = getLLVMStyle(); 12866 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12867 FormatStyle::SFS_InlineOnly; 12868 verifyFormat("class C {\n" 12869 " int f() { return 42; }\n" 12870 "};", 12871 MergeInlineOnly); 12872 verifyFormat("int f() {\n" 12873 " return 42;\n" 12874 "}", 12875 MergeInlineOnly); 12876 12877 // SFS_InlineOnly does not imply SFS_Empty 12878 verifyFormat("class C {\n" 12879 " int f() {}\n" 12880 "};", 12881 MergeInlineOnly); 12882 verifyFormat("int f() {\n" 12883 "}", 12884 MergeInlineOnly); 12885 12886 // Also verify behavior when BraceWrapping.AfterFunction = true 12887 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12888 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12889 verifyFormat("class C {\n" 12890 " int f() { return 42; }\n" 12891 "};", 12892 MergeInlineOnly); 12893 verifyFormat("int f()\n" 12894 "{\n" 12895 " return 42;\n" 12896 "}", 12897 MergeInlineOnly); 12898 12899 // SFS_InlineOnly does not imply SFS_Empty 12900 verifyFormat("int f()\n" 12901 "{\n" 12902 "}", 12903 MergeInlineOnly); 12904 verifyFormat("class C {\n" 12905 " int f() {}\n" 12906 "};", 12907 MergeInlineOnly); 12908 } 12909 12910 TEST_F(FormatTest, SplitEmptyFunction) { 12911 FormatStyle Style = getLLVMStyleWithColumns(40); 12912 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12913 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12914 Style.BraceWrapping.AfterFunction = true; 12915 Style.BraceWrapping.SplitEmptyFunction = false; 12916 12917 verifyFormat("int f()\n" 12918 "{}", 12919 Style); 12920 verifyFormat("int f()\n" 12921 "{\n" 12922 " return 42;\n" 12923 "}", 12924 Style); 12925 verifyFormat("int f()\n" 12926 "{\n" 12927 " // some comment\n" 12928 "}", 12929 Style); 12930 12931 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12932 verifyFormat("int f() {}", Style); 12933 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12934 "{}", 12935 Style); 12936 verifyFormat("int f()\n" 12937 "{\n" 12938 " return 0;\n" 12939 "}", 12940 Style); 12941 12942 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12943 verifyFormat("class Foo {\n" 12944 " int f() {}\n" 12945 "};\n", 12946 Style); 12947 verifyFormat("class Foo {\n" 12948 " int f() { return 0; }\n" 12949 "};\n", 12950 Style); 12951 verifyFormat("class Foo {\n" 12952 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12953 " {}\n" 12954 "};\n", 12955 Style); 12956 verifyFormat("class Foo {\n" 12957 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12958 " {\n" 12959 " return 0;\n" 12960 " }\n" 12961 "};\n", 12962 Style); 12963 12964 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12965 verifyFormat("int f() {}", Style); 12966 verifyFormat("int f() { return 0; }", Style); 12967 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12968 "{}", 12969 Style); 12970 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12971 "{\n" 12972 " return 0;\n" 12973 "}", 12974 Style); 12975 } 12976 12977 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12978 FormatStyle Style = getLLVMStyleWithColumns(40); 12979 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12980 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12981 Style.BraceWrapping.AfterFunction = true; 12982 Style.BraceWrapping.SplitEmptyFunction = true; 12983 Style.BraceWrapping.SplitEmptyRecord = false; 12984 12985 verifyFormat("class C {};", Style); 12986 verifyFormat("struct C {};", Style); 12987 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12988 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12989 "{\n" 12990 "}", 12991 Style); 12992 verifyFormat("class C {\n" 12993 " C()\n" 12994 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12995 " bbbbbbbbbbbbbbbbbbb()\n" 12996 " {\n" 12997 " }\n" 12998 " void\n" 12999 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13000 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13001 " {\n" 13002 " }\n" 13003 "};", 13004 Style); 13005 } 13006 13007 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 13008 FormatStyle Style = getLLVMStyle(); 13009 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13010 verifyFormat("#ifdef A\n" 13011 "int f() {}\n" 13012 "#else\n" 13013 "int g() {}\n" 13014 "#endif", 13015 Style); 13016 } 13017 13018 TEST_F(FormatTest, SplitEmptyClass) { 13019 FormatStyle Style = getLLVMStyle(); 13020 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13021 Style.BraceWrapping.AfterClass = true; 13022 Style.BraceWrapping.SplitEmptyRecord = false; 13023 13024 verifyFormat("class Foo\n" 13025 "{};", 13026 Style); 13027 verifyFormat("/* something */ class Foo\n" 13028 "{};", 13029 Style); 13030 verifyFormat("template <typename X> class Foo\n" 13031 "{};", 13032 Style); 13033 verifyFormat("class Foo\n" 13034 "{\n" 13035 " Foo();\n" 13036 "};", 13037 Style); 13038 verifyFormat("typedef class Foo\n" 13039 "{\n" 13040 "} Foo_t;", 13041 Style); 13042 13043 Style.BraceWrapping.SplitEmptyRecord = true; 13044 Style.BraceWrapping.AfterStruct = true; 13045 verifyFormat("class rep\n" 13046 "{\n" 13047 "};", 13048 Style); 13049 verifyFormat("struct rep\n" 13050 "{\n" 13051 "};", 13052 Style); 13053 verifyFormat("template <typename T> class rep\n" 13054 "{\n" 13055 "};", 13056 Style); 13057 verifyFormat("template <typename T> struct rep\n" 13058 "{\n" 13059 "};", 13060 Style); 13061 verifyFormat("class rep\n" 13062 "{\n" 13063 " int x;\n" 13064 "};", 13065 Style); 13066 verifyFormat("struct rep\n" 13067 "{\n" 13068 " int x;\n" 13069 "};", 13070 Style); 13071 verifyFormat("template <typename T> class rep\n" 13072 "{\n" 13073 " int x;\n" 13074 "};", 13075 Style); 13076 verifyFormat("template <typename T> struct rep\n" 13077 "{\n" 13078 " int x;\n" 13079 "};", 13080 Style); 13081 verifyFormat("template <typename T> class rep // Foo\n" 13082 "{\n" 13083 " int x;\n" 13084 "};", 13085 Style); 13086 verifyFormat("template <typename T> struct rep // Bar\n" 13087 "{\n" 13088 " int x;\n" 13089 "};", 13090 Style); 13091 13092 verifyFormat("template <typename T> class rep<T>\n" 13093 "{\n" 13094 " int x;\n" 13095 "};", 13096 Style); 13097 13098 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13099 "{\n" 13100 " int x;\n" 13101 "};", 13102 Style); 13103 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13104 "{\n" 13105 "};", 13106 Style); 13107 13108 verifyFormat("#include \"stdint.h\"\n" 13109 "namespace rep {}", 13110 Style); 13111 verifyFormat("#include <stdint.h>\n" 13112 "namespace rep {}", 13113 Style); 13114 verifyFormat("#include <stdint.h>\n" 13115 "namespace rep {}", 13116 "#include <stdint.h>\n" 13117 "namespace rep {\n" 13118 "\n" 13119 "\n" 13120 "}", 13121 Style); 13122 } 13123 13124 TEST_F(FormatTest, SplitEmptyStruct) { 13125 FormatStyle Style = getLLVMStyle(); 13126 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13127 Style.BraceWrapping.AfterStruct = true; 13128 Style.BraceWrapping.SplitEmptyRecord = false; 13129 13130 verifyFormat("struct Foo\n" 13131 "{};", 13132 Style); 13133 verifyFormat("/* something */ struct Foo\n" 13134 "{};", 13135 Style); 13136 verifyFormat("template <typename X> struct Foo\n" 13137 "{};", 13138 Style); 13139 verifyFormat("struct Foo\n" 13140 "{\n" 13141 " Foo();\n" 13142 "};", 13143 Style); 13144 verifyFormat("typedef struct Foo\n" 13145 "{\n" 13146 "} Foo_t;", 13147 Style); 13148 // typedef struct Bar {} Bar_t; 13149 } 13150 13151 TEST_F(FormatTest, SplitEmptyUnion) { 13152 FormatStyle Style = getLLVMStyle(); 13153 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13154 Style.BraceWrapping.AfterUnion = true; 13155 Style.BraceWrapping.SplitEmptyRecord = false; 13156 13157 verifyFormat("union Foo\n" 13158 "{};", 13159 Style); 13160 verifyFormat("/* something */ union Foo\n" 13161 "{};", 13162 Style); 13163 verifyFormat("union Foo\n" 13164 "{\n" 13165 " A,\n" 13166 "};", 13167 Style); 13168 verifyFormat("typedef union Foo\n" 13169 "{\n" 13170 "} Foo_t;", 13171 Style); 13172 } 13173 13174 TEST_F(FormatTest, SplitEmptyNamespace) { 13175 FormatStyle Style = getLLVMStyle(); 13176 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13177 Style.BraceWrapping.AfterNamespace = true; 13178 Style.BraceWrapping.SplitEmptyNamespace = false; 13179 13180 verifyFormat("namespace Foo\n" 13181 "{};", 13182 Style); 13183 verifyFormat("/* something */ namespace Foo\n" 13184 "{};", 13185 Style); 13186 verifyFormat("inline namespace Foo\n" 13187 "{};", 13188 Style); 13189 verifyFormat("/* something */ inline namespace Foo\n" 13190 "{};", 13191 Style); 13192 verifyFormat("export namespace Foo\n" 13193 "{};", 13194 Style); 13195 verifyFormat("namespace Foo\n" 13196 "{\n" 13197 "void Bar();\n" 13198 "};", 13199 Style); 13200 } 13201 13202 TEST_F(FormatTest, NeverMergeShortRecords) { 13203 FormatStyle Style = getLLVMStyle(); 13204 13205 verifyFormat("class Foo {\n" 13206 " Foo();\n" 13207 "};", 13208 Style); 13209 verifyFormat("typedef class Foo {\n" 13210 " Foo();\n" 13211 "} Foo_t;", 13212 Style); 13213 verifyFormat("struct Foo {\n" 13214 " Foo();\n" 13215 "};", 13216 Style); 13217 verifyFormat("typedef struct Foo {\n" 13218 " Foo();\n" 13219 "} Foo_t;", 13220 Style); 13221 verifyFormat("union Foo {\n" 13222 " A,\n" 13223 "};", 13224 Style); 13225 verifyFormat("typedef union Foo {\n" 13226 " A,\n" 13227 "} Foo_t;", 13228 Style); 13229 verifyFormat("namespace Foo {\n" 13230 "void Bar();\n" 13231 "};", 13232 Style); 13233 13234 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13235 Style.BraceWrapping.AfterClass = true; 13236 Style.BraceWrapping.AfterStruct = true; 13237 Style.BraceWrapping.AfterUnion = true; 13238 Style.BraceWrapping.AfterNamespace = true; 13239 verifyFormat("class Foo\n" 13240 "{\n" 13241 " Foo();\n" 13242 "};", 13243 Style); 13244 verifyFormat("typedef class Foo\n" 13245 "{\n" 13246 " Foo();\n" 13247 "} Foo_t;", 13248 Style); 13249 verifyFormat("struct Foo\n" 13250 "{\n" 13251 " Foo();\n" 13252 "};", 13253 Style); 13254 verifyFormat("typedef struct Foo\n" 13255 "{\n" 13256 " Foo();\n" 13257 "} Foo_t;", 13258 Style); 13259 verifyFormat("union Foo\n" 13260 "{\n" 13261 " A,\n" 13262 "};", 13263 Style); 13264 verifyFormat("typedef union Foo\n" 13265 "{\n" 13266 " A,\n" 13267 "} Foo_t;", 13268 Style); 13269 verifyFormat("namespace Foo\n" 13270 "{\n" 13271 "void Bar();\n" 13272 "};", 13273 Style); 13274 } 13275 13276 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13277 // Elaborate type variable declarations. 13278 verifyFormat("struct foo a = {bar};\nint n;"); 13279 verifyFormat("class foo a = {bar};\nint n;"); 13280 verifyFormat("union foo a = {bar};\nint n;"); 13281 13282 // Elaborate types inside function definitions. 13283 verifyFormat("struct foo f() {}\nint n;"); 13284 verifyFormat("class foo f() {}\nint n;"); 13285 verifyFormat("union foo f() {}\nint n;"); 13286 13287 // Templates. 13288 verifyFormat("template <class X> void f() {}\nint n;"); 13289 verifyFormat("template <struct X> void f() {}\nint n;"); 13290 verifyFormat("template <union X> void f() {}\nint n;"); 13291 13292 // Actual definitions... 13293 verifyFormat("struct {\n} n;"); 13294 verifyFormat( 13295 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13296 verifyFormat("union Z {\n int n;\n} x;"); 13297 verifyFormat("class MACRO Z {\n} n;"); 13298 verifyFormat("class MACRO(X) Z {\n} n;"); 13299 verifyFormat("class __attribute__(X) Z {\n} n;"); 13300 verifyFormat("class __declspec(X) Z {\n} n;"); 13301 verifyFormat("class A##B##C {\n} n;"); 13302 verifyFormat("class alignas(16) Z {\n} n;"); 13303 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13304 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13305 13306 // Redefinition from nested context: 13307 verifyFormat("class A::B::C {\n} n;"); 13308 13309 // Template definitions. 13310 verifyFormat( 13311 "template <typename F>\n" 13312 "Matcher(const Matcher<F> &Other,\n" 13313 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13314 " !is_same<F, T>::value>::type * = 0)\n" 13315 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13316 13317 // FIXME: This is still incorrectly handled at the formatter side. 13318 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13319 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13320 13321 // FIXME: 13322 // This now gets parsed incorrectly as class definition. 13323 // verifyFormat("class A<int> f() {\n}\nint n;"); 13324 13325 // Elaborate types where incorrectly parsing the structural element would 13326 // break the indent. 13327 verifyFormat("if (true)\n" 13328 " class X x;\n" 13329 "else\n" 13330 " f();\n"); 13331 13332 // This is simply incomplete. Formatting is not important, but must not crash. 13333 verifyFormat("class A:"); 13334 } 13335 13336 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13337 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13338 format("#error Leave all white!!!!! space* alone!\n")); 13339 EXPECT_EQ( 13340 "#warning Leave all white!!!!! space* alone!\n", 13341 format("#warning Leave all white!!!!! space* alone!\n")); 13342 EXPECT_EQ("#error 1", format(" # error 1")); 13343 EXPECT_EQ("#warning 1", format(" # warning 1")); 13344 } 13345 13346 TEST_F(FormatTest, FormatHashIfExpressions) { 13347 verifyFormat("#if AAAA && BBBB"); 13348 verifyFormat("#if (AAAA && BBBB)"); 13349 verifyFormat("#elif (AAAA && BBBB)"); 13350 // FIXME: Come up with a better indentation for #elif. 13351 verifyFormat( 13352 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13353 " defined(BBBBBBBB)\n" 13354 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13355 " defined(BBBBBBBB)\n" 13356 "#endif", 13357 getLLVMStyleWithColumns(65)); 13358 } 13359 13360 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13361 FormatStyle AllowsMergedIf = getGoogleStyle(); 13362 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13363 FormatStyle::SIS_WithoutElse; 13364 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13365 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13366 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13367 EXPECT_EQ("if (true) return 42;", 13368 format("if (true)\nreturn 42;", AllowsMergedIf)); 13369 FormatStyle ShortMergedIf = AllowsMergedIf; 13370 ShortMergedIf.ColumnLimit = 25; 13371 verifyFormat("#define A \\\n" 13372 " if (true) return 42;", 13373 ShortMergedIf); 13374 verifyFormat("#define A \\\n" 13375 " f(); \\\n" 13376 " if (true)\n" 13377 "#define B", 13378 ShortMergedIf); 13379 verifyFormat("#define A \\\n" 13380 " f(); \\\n" 13381 " if (true)\n" 13382 "g();", 13383 ShortMergedIf); 13384 verifyFormat("{\n" 13385 "#ifdef A\n" 13386 " // Comment\n" 13387 " if (true) continue;\n" 13388 "#endif\n" 13389 " // Comment\n" 13390 " if (true) continue;\n" 13391 "}", 13392 ShortMergedIf); 13393 ShortMergedIf.ColumnLimit = 33; 13394 verifyFormat("#define A \\\n" 13395 " if constexpr (true) return 42;", 13396 ShortMergedIf); 13397 verifyFormat("#define A \\\n" 13398 " if CONSTEXPR (true) return 42;", 13399 ShortMergedIf); 13400 ShortMergedIf.ColumnLimit = 29; 13401 verifyFormat("#define A \\\n" 13402 " if (aaaaaaaaaa) return 1; \\\n" 13403 " return 2;", 13404 ShortMergedIf); 13405 ShortMergedIf.ColumnLimit = 28; 13406 verifyFormat("#define A \\\n" 13407 " if (aaaaaaaaaa) \\\n" 13408 " return 1; \\\n" 13409 " return 2;", 13410 ShortMergedIf); 13411 verifyFormat("#define A \\\n" 13412 " if constexpr (aaaaaaa) \\\n" 13413 " return 1; \\\n" 13414 " return 2;", 13415 ShortMergedIf); 13416 verifyFormat("#define A \\\n" 13417 " if CONSTEXPR (aaaaaaa) \\\n" 13418 " return 1; \\\n" 13419 " return 2;", 13420 ShortMergedIf); 13421 13422 verifyFormat("//\n" 13423 "#define a \\\n" 13424 " if \\\n" 13425 " 0", 13426 getChromiumStyle(FormatStyle::LK_Cpp)); 13427 } 13428 13429 TEST_F(FormatTest, FormatStarDependingOnContext) { 13430 verifyFormat("void f(int *a);"); 13431 verifyFormat("void f() { f(fint * b); }"); 13432 verifyFormat("class A {\n void f(int *a);\n};"); 13433 verifyFormat("class A {\n int *a;\n};"); 13434 verifyFormat("namespace a {\n" 13435 "namespace b {\n" 13436 "class A {\n" 13437 " void f() {}\n" 13438 " int *a;\n" 13439 "};\n" 13440 "} // namespace b\n" 13441 "} // namespace a"); 13442 } 13443 13444 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13445 verifyFormat("while"); 13446 verifyFormat("operator"); 13447 } 13448 13449 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13450 // This code would be painfully slow to format if we didn't skip it. 13451 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 13452 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13453 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13454 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13455 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13456 "A(1, 1)\n" 13457 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13458 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13459 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13460 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13461 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13462 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13463 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13464 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13465 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13466 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13467 // Deeply nested part is untouched, rest is formatted. 13468 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13469 format(std::string("int i;\n") + Code + "int j;\n", 13470 getLLVMStyle(), SC_ExpectIncomplete)); 13471 } 13472 13473 //===----------------------------------------------------------------------===// 13474 // Objective-C tests. 13475 //===----------------------------------------------------------------------===// 13476 13477 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13478 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13479 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13480 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13481 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13482 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13483 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13484 format("-(NSInteger)Method3:(id)anObject;")); 13485 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13486 format("-(NSInteger)Method4:(id)anObject;")); 13487 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13488 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13489 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13490 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13491 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13492 "forAllCells:(BOOL)flag;", 13493 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13494 "forAllCells:(BOOL)flag;")); 13495 13496 // Very long objectiveC method declaration. 13497 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13498 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13499 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13500 " inRange:(NSRange)range\n" 13501 " outRange:(NSRange)out_range\n" 13502 " outRange1:(NSRange)out_range1\n" 13503 " outRange2:(NSRange)out_range2\n" 13504 " outRange3:(NSRange)out_range3\n" 13505 " outRange4:(NSRange)out_range4\n" 13506 " outRange5:(NSRange)out_range5\n" 13507 " outRange6:(NSRange)out_range6\n" 13508 " outRange7:(NSRange)out_range7\n" 13509 " outRange8:(NSRange)out_range8\n" 13510 " outRange9:(NSRange)out_range9;"); 13511 13512 // When the function name has to be wrapped. 13513 FormatStyle Style = getLLVMStyle(); 13514 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13515 // and always indents instead. 13516 Style.IndentWrappedFunctionNames = false; 13517 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13518 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13519 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13520 "}", 13521 Style); 13522 Style.IndentWrappedFunctionNames = true; 13523 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13524 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13525 " anotherName:(NSString)dddddddddddddd {\n" 13526 "}", 13527 Style); 13528 13529 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13530 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13531 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13532 // protocol lists (but not for template classes): 13533 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13534 13535 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13536 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13537 13538 // If there's no return type (very rare in practice!), LLVM and Google style 13539 // agree. 13540 verifyFormat("- foo;"); 13541 verifyFormat("- foo:(int)f;"); 13542 verifyGoogleFormat("- foo:(int)foo;"); 13543 } 13544 13545 TEST_F(FormatTest, BreaksStringLiterals) { 13546 EXPECT_EQ("\"some text \"\n" 13547 "\"other\";", 13548 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13549 EXPECT_EQ("\"some text \"\n" 13550 "\"other\";", 13551 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13552 EXPECT_EQ( 13553 "#define A \\\n" 13554 " \"some \" \\\n" 13555 " \"text \" \\\n" 13556 " \"other\";", 13557 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13558 EXPECT_EQ( 13559 "#define A \\\n" 13560 " \"so \" \\\n" 13561 " \"text \" \\\n" 13562 " \"other\";", 13563 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13564 13565 EXPECT_EQ("\"some text\"", 13566 format("\"some text\"", getLLVMStyleWithColumns(1))); 13567 EXPECT_EQ("\"some text\"", 13568 format("\"some text\"", getLLVMStyleWithColumns(11))); 13569 EXPECT_EQ("\"some \"\n" 13570 "\"text\"", 13571 format("\"some text\"", getLLVMStyleWithColumns(10))); 13572 EXPECT_EQ("\"some \"\n" 13573 "\"text\"", 13574 format("\"some text\"", getLLVMStyleWithColumns(7))); 13575 EXPECT_EQ("\"some\"\n" 13576 "\" tex\"\n" 13577 "\"t\"", 13578 format("\"some text\"", getLLVMStyleWithColumns(6))); 13579 EXPECT_EQ("\"some\"\n" 13580 "\" tex\"\n" 13581 "\" and\"", 13582 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13583 EXPECT_EQ("\"some\"\n" 13584 "\"/tex\"\n" 13585 "\"/and\"", 13586 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13587 13588 EXPECT_EQ("variable =\n" 13589 " \"long string \"\n" 13590 " \"literal\";", 13591 format("variable = \"long string literal\";", 13592 getLLVMStyleWithColumns(20))); 13593 13594 EXPECT_EQ("variable = f(\n" 13595 " \"long string \"\n" 13596 " \"literal\",\n" 13597 " short,\n" 13598 " loooooooooooooooooooong);", 13599 format("variable = f(\"long string literal\", short, " 13600 "loooooooooooooooooooong);", 13601 getLLVMStyleWithColumns(20))); 13602 13603 EXPECT_EQ( 13604 "f(g(\"long string \"\n" 13605 " \"literal\"),\n" 13606 " b);", 13607 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13608 EXPECT_EQ("f(g(\"long string \"\n" 13609 " \"literal\",\n" 13610 " a),\n" 13611 " b);", 13612 format("f(g(\"long string literal\", a), b);", 13613 getLLVMStyleWithColumns(20))); 13614 EXPECT_EQ( 13615 "f(\"one two\".split(\n" 13616 " variable));", 13617 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13618 EXPECT_EQ("f(\"one two three four five six \"\n" 13619 " \"seven\".split(\n" 13620 " really_looooong_variable));", 13621 format("f(\"one two three four five six seven\"." 13622 "split(really_looooong_variable));", 13623 getLLVMStyleWithColumns(33))); 13624 13625 EXPECT_EQ("f(\"some \"\n" 13626 " \"text\",\n" 13627 " other);", 13628 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13629 13630 // Only break as a last resort. 13631 verifyFormat( 13632 "aaaaaaaaaaaaaaaaaaaa(\n" 13633 " aaaaaaaaaaaaaaaaaaaa,\n" 13634 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13635 13636 EXPECT_EQ("\"splitmea\"\n" 13637 "\"trandomp\"\n" 13638 "\"oint\"", 13639 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13640 13641 EXPECT_EQ("\"split/\"\n" 13642 "\"pathat/\"\n" 13643 "\"slashes\"", 13644 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13645 13646 EXPECT_EQ("\"split/\"\n" 13647 "\"pathat/\"\n" 13648 "\"slashes\"", 13649 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13650 EXPECT_EQ("\"split at \"\n" 13651 "\"spaces/at/\"\n" 13652 "\"slashes.at.any$\"\n" 13653 "\"non-alphanumeric%\"\n" 13654 "\"1111111111characte\"\n" 13655 "\"rs\"", 13656 format("\"split at " 13657 "spaces/at/" 13658 "slashes.at." 13659 "any$non-" 13660 "alphanumeric%" 13661 "1111111111characte" 13662 "rs\"", 13663 getLLVMStyleWithColumns(20))); 13664 13665 // Verify that splitting the strings understands 13666 // Style::AlwaysBreakBeforeMultilineStrings. 13667 EXPECT_EQ("aaaaaaaaaaaa(\n" 13668 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13669 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13670 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13671 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13672 "aaaaaaaaaaaaaaaaaaaaaa\");", 13673 getGoogleStyle())); 13674 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13675 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13676 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13677 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13678 "aaaaaaaaaaaaaaaaaaaaaa\";", 13679 getGoogleStyle())); 13680 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13681 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13682 format("llvm::outs() << " 13683 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13684 "aaaaaaaaaaaaaaaaaaa\";")); 13685 EXPECT_EQ("ffff(\n" 13686 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13687 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13688 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13689 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13690 getGoogleStyle())); 13691 13692 FormatStyle Style = getLLVMStyleWithColumns(12); 13693 Style.BreakStringLiterals = false; 13694 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13695 13696 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13697 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13698 EXPECT_EQ("#define A \\\n" 13699 " \"some \" \\\n" 13700 " \"text \" \\\n" 13701 " \"other\";", 13702 format("#define A \"some text other\";", AlignLeft)); 13703 } 13704 13705 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13706 EXPECT_EQ("C a = \"some more \"\n" 13707 " \"text\";", 13708 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13709 } 13710 13711 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13712 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13713 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13714 EXPECT_EQ("int i = a(b());", 13715 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13716 } 13717 13718 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13719 EXPECT_EQ( 13720 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13721 "(\n" 13722 " \"x\t\");", 13723 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13724 "aaaaaaa(" 13725 "\"x\t\");")); 13726 } 13727 13728 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13729 EXPECT_EQ( 13730 "u8\"utf8 string \"\n" 13731 "u8\"literal\";", 13732 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13733 EXPECT_EQ( 13734 "u\"utf16 string \"\n" 13735 "u\"literal\";", 13736 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13737 EXPECT_EQ( 13738 "U\"utf32 string \"\n" 13739 "U\"literal\";", 13740 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13741 EXPECT_EQ("L\"wide string \"\n" 13742 "L\"literal\";", 13743 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13744 EXPECT_EQ("@\"NSString \"\n" 13745 "@\"literal\";", 13746 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13747 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13748 13749 // This input makes clang-format try to split the incomplete unicode escape 13750 // sequence, which used to lead to a crasher. 13751 verifyNoCrash( 13752 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13753 getLLVMStyleWithColumns(60)); 13754 } 13755 13756 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13757 FormatStyle Style = getGoogleStyleWithColumns(15); 13758 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13759 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13760 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13761 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13762 EXPECT_EQ("u8R\"x(raw literal)x\";", 13763 format("u8R\"x(raw literal)x\";", Style)); 13764 } 13765 13766 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13767 FormatStyle Style = getLLVMStyleWithColumns(20); 13768 EXPECT_EQ( 13769 "_T(\"aaaaaaaaaaaaaa\")\n" 13770 "_T(\"aaaaaaaaaaaaaa\")\n" 13771 "_T(\"aaaaaaaaaaaa\")", 13772 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13773 EXPECT_EQ("f(x,\n" 13774 " _T(\"aaaaaaaaaaaa\")\n" 13775 " _T(\"aaa\"),\n" 13776 " z);", 13777 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13778 13779 // FIXME: Handle embedded spaces in one iteration. 13780 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13781 // "_T(\"aaaaaaaaaaaaa\")\n" 13782 // "_T(\"aaaaaaaaaaaaa\")\n" 13783 // "_T(\"a\")", 13784 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13785 // getLLVMStyleWithColumns(20))); 13786 EXPECT_EQ( 13787 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13788 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13789 EXPECT_EQ("f(\n" 13790 "#if !TEST\n" 13791 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13792 "#endif\n" 13793 ");", 13794 format("f(\n" 13795 "#if !TEST\n" 13796 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13797 "#endif\n" 13798 ");")); 13799 EXPECT_EQ("f(\n" 13800 "\n" 13801 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13802 format("f(\n" 13803 "\n" 13804 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13805 // Regression test for accessing tokens past the end of a vector in the 13806 // TokenLexer. 13807 verifyNoCrash(R"(_T( 13808 " 13809 ) 13810 )"); 13811 } 13812 13813 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13814 // In a function call with two operands, the second can be broken with no line 13815 // break before it. 13816 EXPECT_EQ( 13817 "func(a, \"long long \"\n" 13818 " \"long long\");", 13819 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13820 // In a function call with three operands, the second must be broken with a 13821 // line break before it. 13822 EXPECT_EQ("func(a,\n" 13823 " \"long long long \"\n" 13824 " \"long\",\n" 13825 " c);", 13826 format("func(a, \"long long long long\", c);", 13827 getLLVMStyleWithColumns(24))); 13828 // In a function call with three operands, the third must be broken with a 13829 // line break before it. 13830 EXPECT_EQ("func(a, b,\n" 13831 " \"long long long \"\n" 13832 " \"long\");", 13833 format("func(a, b, \"long long long long\");", 13834 getLLVMStyleWithColumns(24))); 13835 // In a function call with three operands, both the second and the third must 13836 // be broken with a line break before them. 13837 EXPECT_EQ("func(a,\n" 13838 " \"long long long \"\n" 13839 " \"long\",\n" 13840 " \"long long long \"\n" 13841 " \"long\");", 13842 format("func(a, \"long long long long\", \"long long long long\");", 13843 getLLVMStyleWithColumns(24))); 13844 // In a chain of << with two operands, the second can be broken with no line 13845 // break before it. 13846 EXPECT_EQ("a << \"line line \"\n" 13847 " \"line\";", 13848 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13849 // In a chain of << with three operands, the second can be broken with no line 13850 // break before it. 13851 EXPECT_EQ( 13852 "abcde << \"line \"\n" 13853 " \"line line\"\n" 13854 " << c;", 13855 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13856 // In a chain of << with three operands, the third must be broken with a line 13857 // break before it. 13858 EXPECT_EQ( 13859 "a << b\n" 13860 " << \"line line \"\n" 13861 " \"line\";", 13862 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13863 // In a chain of << with three operands, the second can be broken with no line 13864 // break before it and the third must be broken with a line break before it. 13865 EXPECT_EQ("abcd << \"line line \"\n" 13866 " \"line\"\n" 13867 " << \"line line \"\n" 13868 " \"line\";", 13869 format("abcd << \"line line line\" << \"line line line\";", 13870 getLLVMStyleWithColumns(20))); 13871 // In a chain of binary operators with two operands, the second can be broken 13872 // with no line break before it. 13873 EXPECT_EQ( 13874 "abcd + \"line line \"\n" 13875 " \"line line\";", 13876 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13877 // In a chain of binary operators with three operands, the second must be 13878 // broken with a line break before it. 13879 EXPECT_EQ("abcd +\n" 13880 " \"line line \"\n" 13881 " \"line line\" +\n" 13882 " e;", 13883 format("abcd + \"line line line line\" + e;", 13884 getLLVMStyleWithColumns(20))); 13885 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13886 // the first must be broken with a line break before it. 13887 FormatStyle Style = getLLVMStyleWithColumns(25); 13888 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13889 EXPECT_EQ("someFunction(\n" 13890 " \"long long long \"\n" 13891 " \"long\",\n" 13892 " a);", 13893 format("someFunction(\"long long long long\", a);", Style)); 13894 } 13895 13896 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13897 EXPECT_EQ( 13898 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13900 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13901 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13902 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13903 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13904 } 13905 13906 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13907 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13908 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13909 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13910 "multiline raw string literal xxxxxxxxxxxxxx\n" 13911 ")x\",\n" 13912 " a),\n" 13913 " b);", 13914 format("fffffffffff(g(R\"x(\n" 13915 "multiline raw string literal xxxxxxxxxxxxxx\n" 13916 ")x\", a), b);", 13917 getGoogleStyleWithColumns(20))); 13918 EXPECT_EQ("fffffffffff(\n" 13919 " g(R\"x(qqq\n" 13920 "multiline raw string literal xxxxxxxxxxxxxx\n" 13921 ")x\",\n" 13922 " a),\n" 13923 " b);", 13924 format("fffffffffff(g(R\"x(qqq\n" 13925 "multiline raw string literal xxxxxxxxxxxxxx\n" 13926 ")x\", a), b);", 13927 getGoogleStyleWithColumns(20))); 13928 13929 EXPECT_EQ("fffffffffff(R\"x(\n" 13930 "multiline raw string literal xxxxxxxxxxxxxx\n" 13931 ")x\");", 13932 format("fffffffffff(R\"x(\n" 13933 "multiline raw string literal xxxxxxxxxxxxxx\n" 13934 ")x\");", 13935 getGoogleStyleWithColumns(20))); 13936 EXPECT_EQ("fffffffffff(R\"x(\n" 13937 "multiline raw string literal xxxxxxxxxxxxxx\n" 13938 ")x\" + bbbbbb);", 13939 format("fffffffffff(R\"x(\n" 13940 "multiline raw string literal xxxxxxxxxxxxxx\n" 13941 ")x\" + bbbbbb);", 13942 getGoogleStyleWithColumns(20))); 13943 EXPECT_EQ("fffffffffff(\n" 13944 " R\"x(\n" 13945 "multiline raw string literal xxxxxxxxxxxxxx\n" 13946 ")x\" +\n" 13947 " bbbbbb);", 13948 format("fffffffffff(\n" 13949 " R\"x(\n" 13950 "multiline raw string literal xxxxxxxxxxxxxx\n" 13951 ")x\" + bbbbbb);", 13952 getGoogleStyleWithColumns(20))); 13953 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13954 format("fffffffffff(\n" 13955 " R\"(single line raw string)\" + bbbbbb);")); 13956 } 13957 13958 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13959 verifyFormat("string a = \"unterminated;"); 13960 EXPECT_EQ("function(\"unterminated,\n" 13961 " OtherParameter);", 13962 format("function( \"unterminated,\n" 13963 " OtherParameter);")); 13964 } 13965 13966 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13967 FormatStyle Style = getLLVMStyle(); 13968 Style.Standard = FormatStyle::LS_Cpp03; 13969 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13970 format("#define x(_a) printf(\"foo\"_a);", Style)); 13971 } 13972 13973 TEST_F(FormatTest, CppLexVersion) { 13974 FormatStyle Style = getLLVMStyle(); 13975 // Formatting of x * y differs if x is a type. 13976 verifyFormat("void foo() { MACRO(a * b); }", Style); 13977 verifyFormat("void foo() { MACRO(int *b); }", Style); 13978 13979 // LLVM style uses latest lexer. 13980 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13981 Style.Standard = FormatStyle::LS_Cpp17; 13982 // But in c++17, char8_t isn't a keyword. 13983 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13984 } 13985 13986 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13987 13988 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13989 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13990 " \"ddeeefff\");", 13991 format("someFunction(\"aaabbbcccdddeeefff\");", 13992 getLLVMStyleWithColumns(25))); 13993 EXPECT_EQ("someFunction1234567890(\n" 13994 " \"aaabbbcccdddeeefff\");", 13995 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13996 getLLVMStyleWithColumns(26))); 13997 EXPECT_EQ("someFunction1234567890(\n" 13998 " \"aaabbbcccdddeeeff\"\n" 13999 " \"f\");", 14000 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14001 getLLVMStyleWithColumns(25))); 14002 EXPECT_EQ("someFunction1234567890(\n" 14003 " \"aaabbbcccdddeeeff\"\n" 14004 " \"f\");", 14005 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14006 getLLVMStyleWithColumns(24))); 14007 EXPECT_EQ("someFunction(\n" 14008 " \"aaabbbcc ddde \"\n" 14009 " \"efff\");", 14010 format("someFunction(\"aaabbbcc ddde efff\");", 14011 getLLVMStyleWithColumns(25))); 14012 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 14013 " \"ddeeefff\");", 14014 format("someFunction(\"aaabbbccc ddeeefff\");", 14015 getLLVMStyleWithColumns(25))); 14016 EXPECT_EQ("someFunction1234567890(\n" 14017 " \"aaabb \"\n" 14018 " \"cccdddeeefff\");", 14019 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 14020 getLLVMStyleWithColumns(25))); 14021 EXPECT_EQ("#define A \\\n" 14022 " string s = \\\n" 14023 " \"123456789\" \\\n" 14024 " \"0\"; \\\n" 14025 " int i;", 14026 format("#define A string s = \"1234567890\"; int i;", 14027 getLLVMStyleWithColumns(20))); 14028 EXPECT_EQ("someFunction(\n" 14029 " \"aaabbbcc \"\n" 14030 " \"dddeeefff\");", 14031 format("someFunction(\"aaabbbcc dddeeefff\");", 14032 getLLVMStyleWithColumns(25))); 14033 } 14034 14035 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 14036 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 14037 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 14038 EXPECT_EQ("\"test\"\n" 14039 "\"\\n\"", 14040 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 14041 EXPECT_EQ("\"tes\\\\\"\n" 14042 "\"n\"", 14043 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 14044 EXPECT_EQ("\"\\\\\\\\\"\n" 14045 "\"\\n\"", 14046 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 14047 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 14048 EXPECT_EQ("\"\\uff01\"\n" 14049 "\"test\"", 14050 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14051 EXPECT_EQ("\"\\Uff01ff02\"", 14052 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14053 EXPECT_EQ("\"\\x000000000001\"\n" 14054 "\"next\"", 14055 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14056 EXPECT_EQ("\"\\x000000000001next\"", 14057 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14058 EXPECT_EQ("\"\\x000000000001\"", 14059 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14060 EXPECT_EQ("\"test\"\n" 14061 "\"\\000000\"\n" 14062 "\"000001\"", 14063 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14064 EXPECT_EQ("\"test\\000\"\n" 14065 "\"00000000\"\n" 14066 "\"1\"", 14067 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14068 } 14069 14070 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14071 verifyFormat("void f() {\n" 14072 " return g() {}\n" 14073 " void h() {}"); 14074 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14075 "g();\n" 14076 "}"); 14077 } 14078 14079 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14080 verifyFormat( 14081 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14082 } 14083 14084 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14085 verifyFormat("class X {\n" 14086 " void f() {\n" 14087 " }\n" 14088 "};", 14089 getLLVMStyleWithColumns(12)); 14090 } 14091 14092 TEST_F(FormatTest, ConfigurableIndentWidth) { 14093 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14094 EightIndent.IndentWidth = 8; 14095 EightIndent.ContinuationIndentWidth = 8; 14096 verifyFormat("void f() {\n" 14097 " someFunction();\n" 14098 " if (true) {\n" 14099 " f();\n" 14100 " }\n" 14101 "}", 14102 EightIndent); 14103 verifyFormat("class X {\n" 14104 " void f() {\n" 14105 " }\n" 14106 "};", 14107 EightIndent); 14108 verifyFormat("int x[] = {\n" 14109 " call(),\n" 14110 " call()};", 14111 EightIndent); 14112 } 14113 14114 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14115 verifyFormat("double\n" 14116 "f();", 14117 getLLVMStyleWithColumns(8)); 14118 } 14119 14120 TEST_F(FormatTest, ConfigurableUseOfTab) { 14121 FormatStyle Tab = getLLVMStyleWithColumns(42); 14122 Tab.IndentWidth = 8; 14123 Tab.UseTab = FormatStyle::UT_Always; 14124 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14125 14126 EXPECT_EQ("if (aaaaaaaa && // q\n" 14127 " bb)\t\t// w\n" 14128 "\t;", 14129 format("if (aaaaaaaa &&// q\n" 14130 "bb)// w\n" 14131 ";", 14132 Tab)); 14133 EXPECT_EQ("if (aaa && bbb) // w\n" 14134 "\t;", 14135 format("if(aaa&&bbb)// w\n" 14136 ";", 14137 Tab)); 14138 14139 verifyFormat("class X {\n" 14140 "\tvoid f() {\n" 14141 "\t\tsomeFunction(parameter1,\n" 14142 "\t\t\t parameter2);\n" 14143 "\t}\n" 14144 "};", 14145 Tab); 14146 verifyFormat("#define A \\\n" 14147 "\tvoid f() { \\\n" 14148 "\t\tsomeFunction( \\\n" 14149 "\t\t parameter1, \\\n" 14150 "\t\t parameter2); \\\n" 14151 "\t}", 14152 Tab); 14153 verifyFormat("int a;\t // x\n" 14154 "int bbbbbbbb; // x\n", 14155 Tab); 14156 14157 Tab.TabWidth = 4; 14158 Tab.IndentWidth = 8; 14159 verifyFormat("class TabWidth4Indent8 {\n" 14160 "\t\tvoid f() {\n" 14161 "\t\t\t\tsomeFunction(parameter1,\n" 14162 "\t\t\t\t\t\t\t parameter2);\n" 14163 "\t\t}\n" 14164 "};", 14165 Tab); 14166 14167 Tab.TabWidth = 4; 14168 Tab.IndentWidth = 4; 14169 verifyFormat("class TabWidth4Indent4 {\n" 14170 "\tvoid f() {\n" 14171 "\t\tsomeFunction(parameter1,\n" 14172 "\t\t\t\t\t parameter2);\n" 14173 "\t}\n" 14174 "};", 14175 Tab); 14176 14177 Tab.TabWidth = 8; 14178 Tab.IndentWidth = 4; 14179 verifyFormat("class TabWidth8Indent4 {\n" 14180 " void f() {\n" 14181 "\tsomeFunction(parameter1,\n" 14182 "\t\t parameter2);\n" 14183 " }\n" 14184 "};", 14185 Tab); 14186 14187 Tab.TabWidth = 8; 14188 Tab.IndentWidth = 8; 14189 EXPECT_EQ("/*\n" 14190 "\t a\t\tcomment\n" 14191 "\t in multiple lines\n" 14192 " */", 14193 format(" /*\t \t \n" 14194 " \t \t a\t\tcomment\t \t\n" 14195 " \t \t in multiple lines\t\n" 14196 " \t */", 14197 Tab)); 14198 14199 Tab.UseTab = FormatStyle::UT_ForIndentation; 14200 verifyFormat("{\n" 14201 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14202 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14203 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14204 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14205 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14206 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14207 "};", 14208 Tab); 14209 verifyFormat("enum AA {\n" 14210 "\ta1, // Force multiple lines\n" 14211 "\ta2,\n" 14212 "\ta3\n" 14213 "};", 14214 Tab); 14215 EXPECT_EQ("if (aaaaaaaa && // q\n" 14216 " bb) // w\n" 14217 "\t;", 14218 format("if (aaaaaaaa &&// q\n" 14219 "bb)// w\n" 14220 ";", 14221 Tab)); 14222 verifyFormat("class X {\n" 14223 "\tvoid f() {\n" 14224 "\t\tsomeFunction(parameter1,\n" 14225 "\t\t parameter2);\n" 14226 "\t}\n" 14227 "};", 14228 Tab); 14229 verifyFormat("{\n" 14230 "\tQ(\n" 14231 "\t {\n" 14232 "\t\t int a;\n" 14233 "\t\t someFunction(aaaaaaaa,\n" 14234 "\t\t bbbbbbb);\n" 14235 "\t },\n" 14236 "\t p);\n" 14237 "}", 14238 Tab); 14239 EXPECT_EQ("{\n" 14240 "\t/* aaaa\n" 14241 "\t bbbb */\n" 14242 "}", 14243 format("{\n" 14244 "/* aaaa\n" 14245 " bbbb */\n" 14246 "}", 14247 Tab)); 14248 EXPECT_EQ("{\n" 14249 "\t/*\n" 14250 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14251 "\t bbbbbbbbbbbbb\n" 14252 "\t*/\n" 14253 "}", 14254 format("{\n" 14255 "/*\n" 14256 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14257 "*/\n" 14258 "}", 14259 Tab)); 14260 EXPECT_EQ("{\n" 14261 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14262 "\t// bbbbbbbbbbbbb\n" 14263 "}", 14264 format("{\n" 14265 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14266 "}", 14267 Tab)); 14268 EXPECT_EQ("{\n" 14269 "\t/*\n" 14270 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14271 "\t bbbbbbbbbbbbb\n" 14272 "\t*/\n" 14273 "}", 14274 format("{\n" 14275 "\t/*\n" 14276 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14277 "\t*/\n" 14278 "}", 14279 Tab)); 14280 EXPECT_EQ("{\n" 14281 "\t/*\n" 14282 "\n" 14283 "\t*/\n" 14284 "}", 14285 format("{\n" 14286 "\t/*\n" 14287 "\n" 14288 "\t*/\n" 14289 "}", 14290 Tab)); 14291 EXPECT_EQ("{\n" 14292 "\t/*\n" 14293 " asdf\n" 14294 "\t*/\n" 14295 "}", 14296 format("{\n" 14297 "\t/*\n" 14298 " asdf\n" 14299 "\t*/\n" 14300 "}", 14301 Tab)); 14302 14303 verifyFormat("void f() {\n" 14304 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14305 "\t : bbbbbbbbbbbbbbbbbb\n" 14306 "}", 14307 Tab); 14308 FormatStyle TabNoBreak = Tab; 14309 TabNoBreak.BreakBeforeTernaryOperators = false; 14310 verifyFormat("void f() {\n" 14311 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14312 "\t bbbbbbbbbbbbbbbbbb\n" 14313 "}", 14314 TabNoBreak); 14315 verifyFormat("void f() {\n" 14316 "\treturn true ?\n" 14317 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14318 "\t bbbbbbbbbbbbbbbbbbbb\n" 14319 "}", 14320 TabNoBreak); 14321 14322 Tab.UseTab = FormatStyle::UT_Never; 14323 EXPECT_EQ("/*\n" 14324 " a\t\tcomment\n" 14325 " in multiple lines\n" 14326 " */", 14327 format(" /*\t \t \n" 14328 " \t \t a\t\tcomment\t \t\n" 14329 " \t \t in multiple lines\t\n" 14330 " \t */", 14331 Tab)); 14332 EXPECT_EQ("/* some\n" 14333 " comment */", 14334 format(" \t \t /* some\n" 14335 " \t \t comment */", 14336 Tab)); 14337 EXPECT_EQ("int a; /* some\n" 14338 " comment */", 14339 format(" \t \t int a; /* some\n" 14340 " \t \t comment */", 14341 Tab)); 14342 14343 EXPECT_EQ("int a; /* some\n" 14344 "comment */", 14345 format(" \t \t int\ta; /* some\n" 14346 " \t \t comment */", 14347 Tab)); 14348 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14349 " comment */", 14350 format(" \t \t f(\"\t\t\"); /* some\n" 14351 " \t \t comment */", 14352 Tab)); 14353 EXPECT_EQ("{\n" 14354 " /*\n" 14355 " * Comment\n" 14356 " */\n" 14357 " int i;\n" 14358 "}", 14359 format("{\n" 14360 "\t/*\n" 14361 "\t * Comment\n" 14362 "\t */\n" 14363 "\t int i;\n" 14364 "}", 14365 Tab)); 14366 14367 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14368 Tab.TabWidth = 8; 14369 Tab.IndentWidth = 8; 14370 EXPECT_EQ("if (aaaaaaaa && // q\n" 14371 " bb) // w\n" 14372 "\t;", 14373 format("if (aaaaaaaa &&// q\n" 14374 "bb)// w\n" 14375 ";", 14376 Tab)); 14377 EXPECT_EQ("if (aaa && bbb) // w\n" 14378 "\t;", 14379 format("if(aaa&&bbb)// w\n" 14380 ";", 14381 Tab)); 14382 verifyFormat("class X {\n" 14383 "\tvoid f() {\n" 14384 "\t\tsomeFunction(parameter1,\n" 14385 "\t\t\t parameter2);\n" 14386 "\t}\n" 14387 "};", 14388 Tab); 14389 verifyFormat("#define A \\\n" 14390 "\tvoid f() { \\\n" 14391 "\t\tsomeFunction( \\\n" 14392 "\t\t parameter1, \\\n" 14393 "\t\t parameter2); \\\n" 14394 "\t}", 14395 Tab); 14396 Tab.TabWidth = 4; 14397 Tab.IndentWidth = 8; 14398 verifyFormat("class TabWidth4Indent8 {\n" 14399 "\t\tvoid f() {\n" 14400 "\t\t\t\tsomeFunction(parameter1,\n" 14401 "\t\t\t\t\t\t\t parameter2);\n" 14402 "\t\t}\n" 14403 "};", 14404 Tab); 14405 Tab.TabWidth = 4; 14406 Tab.IndentWidth = 4; 14407 verifyFormat("class TabWidth4Indent4 {\n" 14408 "\tvoid f() {\n" 14409 "\t\tsomeFunction(parameter1,\n" 14410 "\t\t\t\t\t parameter2);\n" 14411 "\t}\n" 14412 "};", 14413 Tab); 14414 Tab.TabWidth = 8; 14415 Tab.IndentWidth = 4; 14416 verifyFormat("class TabWidth8Indent4 {\n" 14417 " void f() {\n" 14418 "\tsomeFunction(parameter1,\n" 14419 "\t\t parameter2);\n" 14420 " }\n" 14421 "};", 14422 Tab); 14423 Tab.TabWidth = 8; 14424 Tab.IndentWidth = 8; 14425 EXPECT_EQ("/*\n" 14426 "\t a\t\tcomment\n" 14427 "\t in multiple lines\n" 14428 " */", 14429 format(" /*\t \t \n" 14430 " \t \t a\t\tcomment\t \t\n" 14431 " \t \t in multiple lines\t\n" 14432 " \t */", 14433 Tab)); 14434 verifyFormat("{\n" 14435 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14436 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14437 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14438 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14439 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14440 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14441 "};", 14442 Tab); 14443 verifyFormat("enum AA {\n" 14444 "\ta1, // Force multiple lines\n" 14445 "\ta2,\n" 14446 "\ta3\n" 14447 "};", 14448 Tab); 14449 EXPECT_EQ("if (aaaaaaaa && // q\n" 14450 " bb) // w\n" 14451 "\t;", 14452 format("if (aaaaaaaa &&// q\n" 14453 "bb)// w\n" 14454 ";", 14455 Tab)); 14456 verifyFormat("class X {\n" 14457 "\tvoid f() {\n" 14458 "\t\tsomeFunction(parameter1,\n" 14459 "\t\t\t parameter2);\n" 14460 "\t}\n" 14461 "};", 14462 Tab); 14463 verifyFormat("{\n" 14464 "\tQ(\n" 14465 "\t {\n" 14466 "\t\t int a;\n" 14467 "\t\t someFunction(aaaaaaaa,\n" 14468 "\t\t\t\t bbbbbbb);\n" 14469 "\t },\n" 14470 "\t p);\n" 14471 "}", 14472 Tab); 14473 EXPECT_EQ("{\n" 14474 "\t/* aaaa\n" 14475 "\t bbbb */\n" 14476 "}", 14477 format("{\n" 14478 "/* aaaa\n" 14479 " bbbb */\n" 14480 "}", 14481 Tab)); 14482 EXPECT_EQ("{\n" 14483 "\t/*\n" 14484 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14485 "\t bbbbbbbbbbbbb\n" 14486 "\t*/\n" 14487 "}", 14488 format("{\n" 14489 "/*\n" 14490 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14491 "*/\n" 14492 "}", 14493 Tab)); 14494 EXPECT_EQ("{\n" 14495 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14496 "\t// bbbbbbbbbbbbb\n" 14497 "}", 14498 format("{\n" 14499 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14500 "}", 14501 Tab)); 14502 EXPECT_EQ("{\n" 14503 "\t/*\n" 14504 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14505 "\t bbbbbbbbbbbbb\n" 14506 "\t*/\n" 14507 "}", 14508 format("{\n" 14509 "\t/*\n" 14510 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14511 "\t*/\n" 14512 "}", 14513 Tab)); 14514 EXPECT_EQ("{\n" 14515 "\t/*\n" 14516 "\n" 14517 "\t*/\n" 14518 "}", 14519 format("{\n" 14520 "\t/*\n" 14521 "\n" 14522 "\t*/\n" 14523 "}", 14524 Tab)); 14525 EXPECT_EQ("{\n" 14526 "\t/*\n" 14527 " asdf\n" 14528 "\t*/\n" 14529 "}", 14530 format("{\n" 14531 "\t/*\n" 14532 " asdf\n" 14533 "\t*/\n" 14534 "}", 14535 Tab)); 14536 EXPECT_EQ("/* some\n" 14537 " comment */", 14538 format(" \t \t /* some\n" 14539 " \t \t comment */", 14540 Tab)); 14541 EXPECT_EQ("int a; /* some\n" 14542 " comment */", 14543 format(" \t \t int a; /* some\n" 14544 " \t \t comment */", 14545 Tab)); 14546 EXPECT_EQ("int a; /* some\n" 14547 "comment */", 14548 format(" \t \t int\ta; /* some\n" 14549 " \t \t comment */", 14550 Tab)); 14551 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14552 " comment */", 14553 format(" \t \t f(\"\t\t\"); /* some\n" 14554 " \t \t comment */", 14555 Tab)); 14556 EXPECT_EQ("{\n" 14557 "\t/*\n" 14558 "\t * Comment\n" 14559 "\t */\n" 14560 "\tint i;\n" 14561 "}", 14562 format("{\n" 14563 "\t/*\n" 14564 "\t * Comment\n" 14565 "\t */\n" 14566 "\t int i;\n" 14567 "}", 14568 Tab)); 14569 Tab.TabWidth = 2; 14570 Tab.IndentWidth = 2; 14571 EXPECT_EQ("{\n" 14572 "\t/* aaaa\n" 14573 "\t\t bbbb */\n" 14574 "}", 14575 format("{\n" 14576 "/* aaaa\n" 14577 "\t bbbb */\n" 14578 "}", 14579 Tab)); 14580 EXPECT_EQ("{\n" 14581 "\t/*\n" 14582 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14583 "\t\tbbbbbbbbbbbbb\n" 14584 "\t*/\n" 14585 "}", 14586 format("{\n" 14587 "/*\n" 14588 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14589 "*/\n" 14590 "}", 14591 Tab)); 14592 Tab.AlignConsecutiveAssignments.Enabled = true; 14593 Tab.AlignConsecutiveDeclarations.Enabled = true; 14594 Tab.TabWidth = 4; 14595 Tab.IndentWidth = 4; 14596 verifyFormat("class Assign {\n" 14597 "\tvoid f() {\n" 14598 "\t\tint x = 123;\n" 14599 "\t\tint random = 4;\n" 14600 "\t\tstd::string alphabet =\n" 14601 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14602 "\t}\n" 14603 "};", 14604 Tab); 14605 14606 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14607 Tab.TabWidth = 8; 14608 Tab.IndentWidth = 8; 14609 EXPECT_EQ("if (aaaaaaaa && // q\n" 14610 " bb) // w\n" 14611 "\t;", 14612 format("if (aaaaaaaa &&// q\n" 14613 "bb)// w\n" 14614 ";", 14615 Tab)); 14616 EXPECT_EQ("if (aaa && bbb) // w\n" 14617 "\t;", 14618 format("if(aaa&&bbb)// w\n" 14619 ";", 14620 Tab)); 14621 verifyFormat("class X {\n" 14622 "\tvoid f() {\n" 14623 "\t\tsomeFunction(parameter1,\n" 14624 "\t\t parameter2);\n" 14625 "\t}\n" 14626 "};", 14627 Tab); 14628 verifyFormat("#define A \\\n" 14629 "\tvoid f() { \\\n" 14630 "\t\tsomeFunction( \\\n" 14631 "\t\t parameter1, \\\n" 14632 "\t\t parameter2); \\\n" 14633 "\t}", 14634 Tab); 14635 Tab.TabWidth = 4; 14636 Tab.IndentWidth = 8; 14637 verifyFormat("class TabWidth4Indent8 {\n" 14638 "\t\tvoid f() {\n" 14639 "\t\t\t\tsomeFunction(parameter1,\n" 14640 "\t\t\t\t parameter2);\n" 14641 "\t\t}\n" 14642 "};", 14643 Tab); 14644 Tab.TabWidth = 4; 14645 Tab.IndentWidth = 4; 14646 verifyFormat("class TabWidth4Indent4 {\n" 14647 "\tvoid f() {\n" 14648 "\t\tsomeFunction(parameter1,\n" 14649 "\t\t parameter2);\n" 14650 "\t}\n" 14651 "};", 14652 Tab); 14653 Tab.TabWidth = 8; 14654 Tab.IndentWidth = 4; 14655 verifyFormat("class TabWidth8Indent4 {\n" 14656 " void f() {\n" 14657 "\tsomeFunction(parameter1,\n" 14658 "\t parameter2);\n" 14659 " }\n" 14660 "};", 14661 Tab); 14662 Tab.TabWidth = 8; 14663 Tab.IndentWidth = 8; 14664 EXPECT_EQ("/*\n" 14665 " a\t\tcomment\n" 14666 " in multiple lines\n" 14667 " */", 14668 format(" /*\t \t \n" 14669 " \t \t a\t\tcomment\t \t\n" 14670 " \t \t in multiple lines\t\n" 14671 " \t */", 14672 Tab)); 14673 verifyFormat("{\n" 14674 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14675 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14676 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14677 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14678 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14679 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14680 "};", 14681 Tab); 14682 verifyFormat("enum AA {\n" 14683 "\ta1, // Force multiple lines\n" 14684 "\ta2,\n" 14685 "\ta3\n" 14686 "};", 14687 Tab); 14688 EXPECT_EQ("if (aaaaaaaa && // q\n" 14689 " bb) // w\n" 14690 "\t;", 14691 format("if (aaaaaaaa &&// q\n" 14692 "bb)// w\n" 14693 ";", 14694 Tab)); 14695 verifyFormat("class X {\n" 14696 "\tvoid f() {\n" 14697 "\t\tsomeFunction(parameter1,\n" 14698 "\t\t parameter2);\n" 14699 "\t}\n" 14700 "};", 14701 Tab); 14702 verifyFormat("{\n" 14703 "\tQ(\n" 14704 "\t {\n" 14705 "\t\t int a;\n" 14706 "\t\t someFunction(aaaaaaaa,\n" 14707 "\t\t bbbbbbb);\n" 14708 "\t },\n" 14709 "\t p);\n" 14710 "}", 14711 Tab); 14712 EXPECT_EQ("{\n" 14713 "\t/* aaaa\n" 14714 "\t bbbb */\n" 14715 "}", 14716 format("{\n" 14717 "/* aaaa\n" 14718 " bbbb */\n" 14719 "}", 14720 Tab)); 14721 EXPECT_EQ("{\n" 14722 "\t/*\n" 14723 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14724 "\t bbbbbbbbbbbbb\n" 14725 "\t*/\n" 14726 "}", 14727 format("{\n" 14728 "/*\n" 14729 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14730 "*/\n" 14731 "}", 14732 Tab)); 14733 EXPECT_EQ("{\n" 14734 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14735 "\t// bbbbbbbbbbbbb\n" 14736 "}", 14737 format("{\n" 14738 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14739 "}", 14740 Tab)); 14741 EXPECT_EQ("{\n" 14742 "\t/*\n" 14743 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14744 "\t bbbbbbbbbbbbb\n" 14745 "\t*/\n" 14746 "}", 14747 format("{\n" 14748 "\t/*\n" 14749 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14750 "\t*/\n" 14751 "}", 14752 Tab)); 14753 EXPECT_EQ("{\n" 14754 "\t/*\n" 14755 "\n" 14756 "\t*/\n" 14757 "}", 14758 format("{\n" 14759 "\t/*\n" 14760 "\n" 14761 "\t*/\n" 14762 "}", 14763 Tab)); 14764 EXPECT_EQ("{\n" 14765 "\t/*\n" 14766 " asdf\n" 14767 "\t*/\n" 14768 "}", 14769 format("{\n" 14770 "\t/*\n" 14771 " asdf\n" 14772 "\t*/\n" 14773 "}", 14774 Tab)); 14775 EXPECT_EQ("/* some\n" 14776 " comment */", 14777 format(" \t \t /* some\n" 14778 " \t \t comment */", 14779 Tab)); 14780 EXPECT_EQ("int a; /* some\n" 14781 " comment */", 14782 format(" \t \t int a; /* some\n" 14783 " \t \t comment */", 14784 Tab)); 14785 EXPECT_EQ("int a; /* some\n" 14786 "comment */", 14787 format(" \t \t int\ta; /* some\n" 14788 " \t \t comment */", 14789 Tab)); 14790 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14791 " comment */", 14792 format(" \t \t f(\"\t\t\"); /* some\n" 14793 " \t \t comment */", 14794 Tab)); 14795 EXPECT_EQ("{\n" 14796 "\t/*\n" 14797 "\t * Comment\n" 14798 "\t */\n" 14799 "\tint i;\n" 14800 "}", 14801 format("{\n" 14802 "\t/*\n" 14803 "\t * Comment\n" 14804 "\t */\n" 14805 "\t int i;\n" 14806 "}", 14807 Tab)); 14808 Tab.TabWidth = 2; 14809 Tab.IndentWidth = 2; 14810 EXPECT_EQ("{\n" 14811 "\t/* aaaa\n" 14812 "\t bbbb */\n" 14813 "}", 14814 format("{\n" 14815 "/* aaaa\n" 14816 " bbbb */\n" 14817 "}", 14818 Tab)); 14819 EXPECT_EQ("{\n" 14820 "\t/*\n" 14821 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14822 "\t bbbbbbbbbbbbb\n" 14823 "\t*/\n" 14824 "}", 14825 format("{\n" 14826 "/*\n" 14827 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14828 "*/\n" 14829 "}", 14830 Tab)); 14831 Tab.AlignConsecutiveAssignments.Enabled = true; 14832 Tab.AlignConsecutiveDeclarations.Enabled = true; 14833 Tab.TabWidth = 4; 14834 Tab.IndentWidth = 4; 14835 verifyFormat("class Assign {\n" 14836 "\tvoid f() {\n" 14837 "\t\tint x = 123;\n" 14838 "\t\tint random = 4;\n" 14839 "\t\tstd::string alphabet =\n" 14840 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14841 "\t}\n" 14842 "};", 14843 Tab); 14844 Tab.AlignOperands = FormatStyle::OAS_Align; 14845 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14846 " cccccccccccccccccccc;", 14847 Tab); 14848 // no alignment 14849 verifyFormat("int aaaaaaaaaa =\n" 14850 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14851 Tab); 14852 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14853 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14854 " : 333333333333333;", 14855 Tab); 14856 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14857 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14858 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14859 " + cccccccccccccccccccc;", 14860 Tab); 14861 } 14862 14863 TEST_F(FormatTest, ZeroTabWidth) { 14864 FormatStyle Tab = getLLVMStyleWithColumns(42); 14865 Tab.IndentWidth = 8; 14866 Tab.UseTab = FormatStyle::UT_Never; 14867 Tab.TabWidth = 0; 14868 EXPECT_EQ("void a(){\n" 14869 " // line starts with '\t'\n" 14870 "};", 14871 format("void a(){\n" 14872 "\t// line starts with '\t'\n" 14873 "};", 14874 Tab)); 14875 14876 EXPECT_EQ("void a(){\n" 14877 " // line starts with '\t'\n" 14878 "};", 14879 format("void a(){\n" 14880 "\t\t// line starts with '\t'\n" 14881 "};", 14882 Tab)); 14883 14884 Tab.UseTab = FormatStyle::UT_ForIndentation; 14885 EXPECT_EQ("void a(){\n" 14886 " // line starts with '\t'\n" 14887 "};", 14888 format("void a(){\n" 14889 "\t// line starts with '\t'\n" 14890 "};", 14891 Tab)); 14892 14893 EXPECT_EQ("void a(){\n" 14894 " // line starts with '\t'\n" 14895 "};", 14896 format("void a(){\n" 14897 "\t\t// line starts with '\t'\n" 14898 "};", 14899 Tab)); 14900 14901 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14902 EXPECT_EQ("void a(){\n" 14903 " // line starts with '\t'\n" 14904 "};", 14905 format("void a(){\n" 14906 "\t// line starts with '\t'\n" 14907 "};", 14908 Tab)); 14909 14910 EXPECT_EQ("void a(){\n" 14911 " // line starts with '\t'\n" 14912 "};", 14913 format("void a(){\n" 14914 "\t\t// line starts with '\t'\n" 14915 "};", 14916 Tab)); 14917 14918 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14919 EXPECT_EQ("void a(){\n" 14920 " // line starts with '\t'\n" 14921 "};", 14922 format("void a(){\n" 14923 "\t// line starts with '\t'\n" 14924 "};", 14925 Tab)); 14926 14927 EXPECT_EQ("void a(){\n" 14928 " // line starts with '\t'\n" 14929 "};", 14930 format("void a(){\n" 14931 "\t\t// line starts with '\t'\n" 14932 "};", 14933 Tab)); 14934 14935 Tab.UseTab = FormatStyle::UT_Always; 14936 EXPECT_EQ("void a(){\n" 14937 "// line starts with '\t'\n" 14938 "};", 14939 format("void a(){\n" 14940 "\t// line starts with '\t'\n" 14941 "};", 14942 Tab)); 14943 14944 EXPECT_EQ("void a(){\n" 14945 "// line starts with '\t'\n" 14946 "};", 14947 format("void a(){\n" 14948 "\t\t// line starts with '\t'\n" 14949 "};", 14950 Tab)); 14951 } 14952 14953 TEST_F(FormatTest, CalculatesOriginalColumn) { 14954 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14955 "q\"; /* some\n" 14956 " comment */", 14957 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14958 "q\"; /* some\n" 14959 " comment */", 14960 getLLVMStyle())); 14961 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14962 "/* some\n" 14963 " comment */", 14964 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14965 " /* some\n" 14966 " comment */", 14967 getLLVMStyle())); 14968 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14969 "qqq\n" 14970 "/* some\n" 14971 " comment */", 14972 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14973 "qqq\n" 14974 " /* some\n" 14975 " comment */", 14976 getLLVMStyle())); 14977 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14978 "wwww; /* some\n" 14979 " comment */", 14980 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14981 "wwww; /* some\n" 14982 " comment */", 14983 getLLVMStyle())); 14984 } 14985 14986 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14987 FormatStyle NoSpace = getLLVMStyle(); 14988 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14989 14990 verifyFormat("while(true)\n" 14991 " continue;", 14992 NoSpace); 14993 verifyFormat("for(;;)\n" 14994 " continue;", 14995 NoSpace); 14996 verifyFormat("if(true)\n" 14997 " f();\n" 14998 "else if(true)\n" 14999 " f();", 15000 NoSpace); 15001 verifyFormat("do {\n" 15002 " do_something();\n" 15003 "} while(something());", 15004 NoSpace); 15005 verifyFormat("switch(x) {\n" 15006 "default:\n" 15007 " break;\n" 15008 "}", 15009 NoSpace); 15010 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 15011 verifyFormat("size_t x = sizeof(x);", NoSpace); 15012 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 15013 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 15014 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 15015 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 15016 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 15017 verifyFormat("alignas(128) char a[128];", NoSpace); 15018 verifyFormat("size_t x = alignof(MyType);", NoSpace); 15019 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 15020 verifyFormat("int f() throw(Deprecated);", NoSpace); 15021 verifyFormat("typedef void (*cb)(int);", NoSpace); 15022 verifyFormat("T A::operator()();", NoSpace); 15023 verifyFormat("X A::operator++(T);", NoSpace); 15024 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 15025 15026 FormatStyle Space = getLLVMStyle(); 15027 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 15028 15029 verifyFormat("int f ();", Space); 15030 verifyFormat("void f (int a, T b) {\n" 15031 " while (true)\n" 15032 " continue;\n" 15033 "}", 15034 Space); 15035 verifyFormat("if (true)\n" 15036 " f ();\n" 15037 "else if (true)\n" 15038 " f ();", 15039 Space); 15040 verifyFormat("do {\n" 15041 " do_something ();\n" 15042 "} while (something ());", 15043 Space); 15044 verifyFormat("switch (x) {\n" 15045 "default:\n" 15046 " break;\n" 15047 "}", 15048 Space); 15049 verifyFormat("A::A () : a (1) {}", Space); 15050 verifyFormat("void f () __attribute__ ((asdf));", Space); 15051 verifyFormat("*(&a + 1);\n" 15052 "&((&a)[1]);\n" 15053 "a[(b + c) * d];\n" 15054 "(((a + 1) * 2) + 3) * 4;", 15055 Space); 15056 verifyFormat("#define A(x) x", Space); 15057 verifyFormat("#define A (x) x", Space); 15058 verifyFormat("#if defined(x)\n" 15059 "#endif", 15060 Space); 15061 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15062 verifyFormat("size_t x = sizeof (x);", Space); 15063 verifyFormat("auto f (int x) -> decltype (x);", Space); 15064 verifyFormat("auto f (int x) -> typeof (x);", Space); 15065 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15066 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15067 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15068 verifyFormat("alignas (128) char a[128];", Space); 15069 verifyFormat("size_t x = alignof (MyType);", Space); 15070 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15071 verifyFormat("int f () throw (Deprecated);", Space); 15072 verifyFormat("typedef void (*cb) (int);", Space); 15073 // FIXME these tests regressed behaviour. 15074 // verifyFormat("T A::operator() ();", Space); 15075 // verifyFormat("X A::operator++ (T);", Space); 15076 verifyFormat("auto lambda = [] () { return 0; };", Space); 15077 verifyFormat("int x = int (y);", Space); 15078 15079 FormatStyle SomeSpace = getLLVMStyle(); 15080 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15081 15082 verifyFormat("[]() -> float {}", SomeSpace); 15083 verifyFormat("[] (auto foo) {}", SomeSpace); 15084 verifyFormat("[foo]() -> int {}", SomeSpace); 15085 verifyFormat("int f();", SomeSpace); 15086 verifyFormat("void f (int a, T b) {\n" 15087 " while (true)\n" 15088 " continue;\n" 15089 "}", 15090 SomeSpace); 15091 verifyFormat("if (true)\n" 15092 " f();\n" 15093 "else if (true)\n" 15094 " f();", 15095 SomeSpace); 15096 verifyFormat("do {\n" 15097 " do_something();\n" 15098 "} while (something());", 15099 SomeSpace); 15100 verifyFormat("switch (x) {\n" 15101 "default:\n" 15102 " break;\n" 15103 "}", 15104 SomeSpace); 15105 verifyFormat("A::A() : a (1) {}", SomeSpace); 15106 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15107 verifyFormat("*(&a + 1);\n" 15108 "&((&a)[1]);\n" 15109 "a[(b + c) * d];\n" 15110 "(((a + 1) * 2) + 3) * 4;", 15111 SomeSpace); 15112 verifyFormat("#define A(x) x", SomeSpace); 15113 verifyFormat("#define A (x) x", SomeSpace); 15114 verifyFormat("#if defined(x)\n" 15115 "#endif", 15116 SomeSpace); 15117 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15118 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15119 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15120 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15121 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15122 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15123 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15124 verifyFormat("alignas (128) char a[128];", SomeSpace); 15125 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15126 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15127 SomeSpace); 15128 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15129 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15130 verifyFormat("T A::operator()();", SomeSpace); 15131 // FIXME these tests regressed behaviour. 15132 // verifyFormat("X A::operator++ (T);", SomeSpace); 15133 verifyFormat("int x = int (y);", SomeSpace); 15134 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15135 15136 FormatStyle SpaceControlStatements = getLLVMStyle(); 15137 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15138 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15139 15140 verifyFormat("while (true)\n" 15141 " continue;", 15142 SpaceControlStatements); 15143 verifyFormat("if (true)\n" 15144 " f();\n" 15145 "else if (true)\n" 15146 " f();", 15147 SpaceControlStatements); 15148 verifyFormat("for (;;) {\n" 15149 " do_something();\n" 15150 "}", 15151 SpaceControlStatements); 15152 verifyFormat("do {\n" 15153 " do_something();\n" 15154 "} while (something());", 15155 SpaceControlStatements); 15156 verifyFormat("switch (x) {\n" 15157 "default:\n" 15158 " break;\n" 15159 "}", 15160 SpaceControlStatements); 15161 15162 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15163 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15164 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15165 15166 verifyFormat("int f ();", SpaceFuncDecl); 15167 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15168 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15169 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15170 verifyFormat("#define A(x) x", SpaceFuncDecl); 15171 verifyFormat("#define A (x) x", SpaceFuncDecl); 15172 verifyFormat("#if defined(x)\n" 15173 "#endif", 15174 SpaceFuncDecl); 15175 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15176 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15177 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15178 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15179 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15180 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15181 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15182 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15183 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15184 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15185 SpaceFuncDecl); 15186 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15187 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15188 // FIXME these tests regressed behaviour. 15189 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15190 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15191 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15192 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15193 verifyFormat("int x = int(y);", SpaceFuncDecl); 15194 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15195 SpaceFuncDecl); 15196 15197 FormatStyle SpaceFuncDef = getLLVMStyle(); 15198 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15199 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15200 15201 verifyFormat("int f();", SpaceFuncDef); 15202 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15203 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15204 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15205 verifyFormat("#define A(x) x", SpaceFuncDef); 15206 verifyFormat("#define A (x) x", SpaceFuncDef); 15207 verifyFormat("#if defined(x)\n" 15208 "#endif", 15209 SpaceFuncDef); 15210 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15211 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15212 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15213 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15214 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15215 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15216 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15217 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15218 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15219 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15220 SpaceFuncDef); 15221 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15222 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15223 verifyFormat("T A::operator()();", SpaceFuncDef); 15224 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15225 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15226 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15227 verifyFormat("int x = int(y);", SpaceFuncDef); 15228 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15229 SpaceFuncDef); 15230 15231 FormatStyle SpaceIfMacros = getLLVMStyle(); 15232 SpaceIfMacros.IfMacros.clear(); 15233 SpaceIfMacros.IfMacros.push_back("MYIF"); 15234 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15235 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15236 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15237 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15238 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15239 15240 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15241 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15242 FormatStyle::SBS_Never); 15243 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15244 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15245 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15246 verifyFormat("for (;;) {\n" 15247 "}", 15248 SpaceForeachMacros); 15249 verifyFormat("foreach (Item *item, itemlist) {\n" 15250 "}", 15251 SpaceForeachMacros); 15252 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15253 "}", 15254 SpaceForeachMacros); 15255 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15256 "}", 15257 SpaceForeachMacros); 15258 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15259 15260 FormatStyle SomeSpace2 = getLLVMStyle(); 15261 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15262 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15263 verifyFormat("[]() -> float {}", SomeSpace2); 15264 verifyFormat("[] (auto foo) {}", SomeSpace2); 15265 verifyFormat("[foo]() -> int {}", SomeSpace2); 15266 verifyFormat("int f();", SomeSpace2); 15267 verifyFormat("void f (int a, T b) {\n" 15268 " while (true)\n" 15269 " continue;\n" 15270 "}", 15271 SomeSpace2); 15272 verifyFormat("if (true)\n" 15273 " f();\n" 15274 "else if (true)\n" 15275 " f();", 15276 SomeSpace2); 15277 verifyFormat("do {\n" 15278 " do_something();\n" 15279 "} while (something());", 15280 SomeSpace2); 15281 verifyFormat("switch (x) {\n" 15282 "default:\n" 15283 " break;\n" 15284 "}", 15285 SomeSpace2); 15286 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15287 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15288 verifyFormat("*(&a + 1);\n" 15289 "&((&a)[1]);\n" 15290 "a[(b + c) * d];\n" 15291 "(((a + 1) * 2) + 3) * 4;", 15292 SomeSpace2); 15293 verifyFormat("#define A(x) x", SomeSpace2); 15294 verifyFormat("#define A (x) x", SomeSpace2); 15295 verifyFormat("#if defined(x)\n" 15296 "#endif", 15297 SomeSpace2); 15298 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15299 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15300 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15301 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15302 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15303 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15304 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15305 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15306 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15307 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15308 SomeSpace2); 15309 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15310 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15311 verifyFormat("T A::operator()();", SomeSpace2); 15312 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15313 verifyFormat("int x = int (y);", SomeSpace2); 15314 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15315 15316 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15317 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15318 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15319 .AfterOverloadedOperator = true; 15320 15321 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15322 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15323 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15324 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15325 15326 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15327 .AfterOverloadedOperator = false; 15328 15329 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15330 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15331 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15332 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15333 15334 auto SpaceAfterRequires = getLLVMStyle(); 15335 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15336 EXPECT_FALSE( 15337 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15338 EXPECT_FALSE( 15339 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15340 verifyFormat("void f(auto x)\n" 15341 " requires requires(int i) { x + i; }\n" 15342 "{}", 15343 SpaceAfterRequires); 15344 verifyFormat("void f(auto x)\n" 15345 " requires(requires(int i) { x + i; })\n" 15346 "{}", 15347 SpaceAfterRequires); 15348 verifyFormat("if (requires(int i) { x + i; })\n" 15349 " return;", 15350 SpaceAfterRequires); 15351 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15352 verifyFormat("template <typename T>\n" 15353 " requires(Foo<T>)\n" 15354 "class Bar;", 15355 SpaceAfterRequires); 15356 15357 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15358 verifyFormat("void f(auto x)\n" 15359 " requires requires(int i) { x + i; }\n" 15360 "{}", 15361 SpaceAfterRequires); 15362 verifyFormat("void f(auto x)\n" 15363 " requires (requires(int i) { x + i; })\n" 15364 "{}", 15365 SpaceAfterRequires); 15366 verifyFormat("if (requires(int i) { x + i; })\n" 15367 " return;", 15368 SpaceAfterRequires); 15369 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15370 verifyFormat("template <typename T>\n" 15371 " requires (Foo<T>)\n" 15372 "class Bar;", 15373 SpaceAfterRequires); 15374 15375 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15376 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15377 verifyFormat("void f(auto x)\n" 15378 " requires requires (int i) { x + i; }\n" 15379 "{}", 15380 SpaceAfterRequires); 15381 verifyFormat("void f(auto x)\n" 15382 " requires(requires (int i) { x + i; })\n" 15383 "{}", 15384 SpaceAfterRequires); 15385 verifyFormat("if (requires (int i) { x + i; })\n" 15386 " return;", 15387 SpaceAfterRequires); 15388 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15389 verifyFormat("template <typename T>\n" 15390 " requires(Foo<T>)\n" 15391 "class Bar;", 15392 SpaceAfterRequires); 15393 15394 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15395 verifyFormat("void f(auto x)\n" 15396 " requires requires (int i) { x + i; }\n" 15397 "{}", 15398 SpaceAfterRequires); 15399 verifyFormat("void f(auto x)\n" 15400 " requires (requires (int i) { x + i; })\n" 15401 "{}", 15402 SpaceAfterRequires); 15403 verifyFormat("if (requires (int i) { x + i; })\n" 15404 " return;", 15405 SpaceAfterRequires); 15406 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15407 verifyFormat("template <typename T>\n" 15408 " requires (Foo<T>)\n" 15409 "class Bar;", 15410 SpaceAfterRequires); 15411 } 15412 15413 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15414 FormatStyle Spaces = getLLVMStyle(); 15415 Spaces.SpaceAfterLogicalNot = true; 15416 15417 verifyFormat("bool x = ! y", Spaces); 15418 verifyFormat("if (! isFailure())", Spaces); 15419 verifyFormat("if (! (a && b))", Spaces); 15420 verifyFormat("\"Error!\"", Spaces); 15421 verifyFormat("! ! x", Spaces); 15422 } 15423 15424 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15425 FormatStyle Spaces = getLLVMStyle(); 15426 15427 Spaces.SpacesInParentheses = true; 15428 verifyFormat("do_something( ::globalVar );", Spaces); 15429 verifyFormat("call( x, y, z );", Spaces); 15430 verifyFormat("call();", Spaces); 15431 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15432 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15433 Spaces); 15434 verifyFormat("while ( (bool)1 )\n" 15435 " continue;", 15436 Spaces); 15437 verifyFormat("for ( ;; )\n" 15438 " continue;", 15439 Spaces); 15440 verifyFormat("if ( true )\n" 15441 " f();\n" 15442 "else if ( true )\n" 15443 " f();", 15444 Spaces); 15445 verifyFormat("do {\n" 15446 " do_something( (int)i );\n" 15447 "} while ( something() );", 15448 Spaces); 15449 verifyFormat("switch ( x ) {\n" 15450 "default:\n" 15451 " break;\n" 15452 "}", 15453 Spaces); 15454 15455 Spaces.SpacesInParentheses = false; 15456 Spaces.SpacesInCStyleCastParentheses = true; 15457 verifyFormat("Type *A = ( Type * )P;", Spaces); 15458 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15459 verifyFormat("x = ( int32 )y;", Spaces); 15460 verifyFormat("int a = ( int )(2.0f);", Spaces); 15461 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15462 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15463 verifyFormat("#define x (( int )-1)", Spaces); 15464 15465 // Run the first set of tests again with: 15466 Spaces.SpacesInParentheses = false; 15467 Spaces.SpaceInEmptyParentheses = true; 15468 Spaces.SpacesInCStyleCastParentheses = true; 15469 verifyFormat("call(x, y, z);", Spaces); 15470 verifyFormat("call( );", Spaces); 15471 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15472 verifyFormat("while (( bool )1)\n" 15473 " continue;", 15474 Spaces); 15475 verifyFormat("for (;;)\n" 15476 " continue;", 15477 Spaces); 15478 verifyFormat("if (true)\n" 15479 " f( );\n" 15480 "else if (true)\n" 15481 " f( );", 15482 Spaces); 15483 verifyFormat("do {\n" 15484 " do_something(( int )i);\n" 15485 "} while (something( ));", 15486 Spaces); 15487 verifyFormat("switch (x) {\n" 15488 "default:\n" 15489 " break;\n" 15490 "}", 15491 Spaces); 15492 15493 // Run the first set of tests again with: 15494 Spaces.SpaceAfterCStyleCast = true; 15495 verifyFormat("call(x, y, z);", Spaces); 15496 verifyFormat("call( );", Spaces); 15497 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15498 verifyFormat("while (( bool ) 1)\n" 15499 " continue;", 15500 Spaces); 15501 verifyFormat("for (;;)\n" 15502 " continue;", 15503 Spaces); 15504 verifyFormat("if (true)\n" 15505 " f( );\n" 15506 "else if (true)\n" 15507 " f( );", 15508 Spaces); 15509 verifyFormat("do {\n" 15510 " do_something(( int ) i);\n" 15511 "} while (something( ));", 15512 Spaces); 15513 verifyFormat("switch (x) {\n" 15514 "default:\n" 15515 " break;\n" 15516 "}", 15517 Spaces); 15518 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15519 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15520 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15521 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15522 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15523 15524 // Run subset of tests again with: 15525 Spaces.SpacesInCStyleCastParentheses = false; 15526 Spaces.SpaceAfterCStyleCast = true; 15527 verifyFormat("while ((bool) 1)\n" 15528 " continue;", 15529 Spaces); 15530 verifyFormat("do {\n" 15531 " do_something((int) i);\n" 15532 "} while (something( ));", 15533 Spaces); 15534 15535 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15536 verifyFormat("size_t idx = (size_t) a;", Spaces); 15537 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15538 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15539 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15540 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15541 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15542 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15543 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15544 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15545 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15546 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15547 Spaces.ColumnLimit = 80; 15548 Spaces.IndentWidth = 4; 15549 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15550 verifyFormat("void foo( ) {\n" 15551 " size_t foo = (*(function))(\n" 15552 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15553 "BarrrrrrrrrrrrLong,\n" 15554 " FoooooooooLooooong);\n" 15555 "}", 15556 Spaces); 15557 Spaces.SpaceAfterCStyleCast = false; 15558 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15559 verifyFormat("size_t idx = (size_t)a;", Spaces); 15560 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15561 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15562 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15563 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15564 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15565 15566 verifyFormat("void foo( ) {\n" 15567 " size_t foo = (*(function))(\n" 15568 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15569 "BarrrrrrrrrrrrLong,\n" 15570 " FoooooooooLooooong);\n" 15571 "}", 15572 Spaces); 15573 } 15574 15575 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15576 verifyFormat("int a[5];"); 15577 verifyFormat("a[3] += 42;"); 15578 15579 FormatStyle Spaces = getLLVMStyle(); 15580 Spaces.SpacesInSquareBrackets = true; 15581 // Not lambdas. 15582 verifyFormat("int a[ 5 ];", Spaces); 15583 verifyFormat("a[ 3 ] += 42;", Spaces); 15584 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15585 verifyFormat("double &operator[](int i) { return 0; }\n" 15586 "int i;", 15587 Spaces); 15588 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15589 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15590 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15591 // Lambdas. 15592 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15593 verifyFormat("return [ i, args... ] {};", Spaces); 15594 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15595 verifyFormat("int foo = [ = ]() {};", Spaces); 15596 verifyFormat("int foo = [ & ]() {};", Spaces); 15597 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15598 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15599 } 15600 15601 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15602 FormatStyle NoSpaceStyle = getLLVMStyle(); 15603 verifyFormat("int a[5];", NoSpaceStyle); 15604 verifyFormat("a[3] += 42;", NoSpaceStyle); 15605 15606 verifyFormat("int a[1];", NoSpaceStyle); 15607 verifyFormat("int 1 [a];", NoSpaceStyle); 15608 verifyFormat("int a[1][2];", NoSpaceStyle); 15609 verifyFormat("a[7] = 5;", NoSpaceStyle); 15610 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15611 verifyFormat("f([] {})", NoSpaceStyle); 15612 15613 FormatStyle Space = getLLVMStyle(); 15614 Space.SpaceBeforeSquareBrackets = true; 15615 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15616 verifyFormat("return [i, args...] {};", Space); 15617 15618 verifyFormat("int a [5];", Space); 15619 verifyFormat("a [3] += 42;", Space); 15620 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15621 verifyFormat("double &operator[](int i) { return 0; }\n" 15622 "int i;", 15623 Space); 15624 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15625 verifyFormat("int i = a [a][a]->f();", Space); 15626 verifyFormat("int i = (*b) [a]->f();", Space); 15627 15628 verifyFormat("int a [1];", Space); 15629 verifyFormat("int 1 [a];", Space); 15630 verifyFormat("int a [1][2];", Space); 15631 verifyFormat("a [7] = 5;", Space); 15632 verifyFormat("int a = (f()) [23];", Space); 15633 verifyFormat("f([] {})", Space); 15634 } 15635 15636 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15637 verifyFormat("int a = 5;"); 15638 verifyFormat("a += 42;"); 15639 verifyFormat("a or_eq 8;"); 15640 15641 FormatStyle Spaces = getLLVMStyle(); 15642 Spaces.SpaceBeforeAssignmentOperators = false; 15643 verifyFormat("int a= 5;", Spaces); 15644 verifyFormat("a+= 42;", Spaces); 15645 verifyFormat("a or_eq 8;", Spaces); 15646 } 15647 15648 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15649 verifyFormat("class Foo : public Bar {};"); 15650 verifyFormat("Foo::Foo() : foo(1) {}"); 15651 verifyFormat("for (auto a : b) {\n}"); 15652 verifyFormat("int x = a ? b : c;"); 15653 verifyFormat("{\n" 15654 "label0:\n" 15655 " int x = 0;\n" 15656 "}"); 15657 verifyFormat("switch (x) {\n" 15658 "case 1:\n" 15659 "default:\n" 15660 "}"); 15661 verifyFormat("switch (allBraces) {\n" 15662 "case 1: {\n" 15663 " break;\n" 15664 "}\n" 15665 "case 2: {\n" 15666 " [[fallthrough]];\n" 15667 "}\n" 15668 "default: {\n" 15669 " break;\n" 15670 "}\n" 15671 "}"); 15672 15673 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15674 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15675 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15676 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15677 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15678 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15679 verifyFormat("{\n" 15680 "label1:\n" 15681 " int x = 0;\n" 15682 "}", 15683 CtorInitializerStyle); 15684 verifyFormat("switch (x) {\n" 15685 "case 1:\n" 15686 "default:\n" 15687 "}", 15688 CtorInitializerStyle); 15689 verifyFormat("switch (allBraces) {\n" 15690 "case 1: {\n" 15691 " break;\n" 15692 "}\n" 15693 "case 2: {\n" 15694 " [[fallthrough]];\n" 15695 "}\n" 15696 "default: {\n" 15697 " break;\n" 15698 "}\n" 15699 "}", 15700 CtorInitializerStyle); 15701 CtorInitializerStyle.BreakConstructorInitializers = 15702 FormatStyle::BCIS_AfterColon; 15703 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15704 " aaaaaaaaaaaaaaaa(1),\n" 15705 " bbbbbbbbbbbbbbbb(2) {}", 15706 CtorInitializerStyle); 15707 CtorInitializerStyle.BreakConstructorInitializers = 15708 FormatStyle::BCIS_BeforeComma; 15709 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15710 " : aaaaaaaaaaaaaaaa(1)\n" 15711 " , bbbbbbbbbbbbbbbb(2) {}", 15712 CtorInitializerStyle); 15713 CtorInitializerStyle.BreakConstructorInitializers = 15714 FormatStyle::BCIS_BeforeColon; 15715 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15716 " : aaaaaaaaaaaaaaaa(1),\n" 15717 " bbbbbbbbbbbbbbbb(2) {}", 15718 CtorInitializerStyle); 15719 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15720 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15721 ": aaaaaaaaaaaaaaaa(1),\n" 15722 " bbbbbbbbbbbbbbbb(2) {}", 15723 CtorInitializerStyle); 15724 15725 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15726 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15727 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15728 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15729 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15730 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15731 verifyFormat("{\n" 15732 "label2:\n" 15733 " int x = 0;\n" 15734 "}", 15735 InheritanceStyle); 15736 verifyFormat("switch (x) {\n" 15737 "case 1:\n" 15738 "default:\n" 15739 "}", 15740 InheritanceStyle); 15741 verifyFormat("switch (allBraces) {\n" 15742 "case 1: {\n" 15743 " break;\n" 15744 "}\n" 15745 "case 2: {\n" 15746 " [[fallthrough]];\n" 15747 "}\n" 15748 "default: {\n" 15749 " break;\n" 15750 "}\n" 15751 "}", 15752 InheritanceStyle); 15753 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15754 verifyFormat("class Foooooooooooooooooooooo\n" 15755 " : public aaaaaaaaaaaaaaaaaa,\n" 15756 " public bbbbbbbbbbbbbbbbbb {\n" 15757 "}", 15758 InheritanceStyle); 15759 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15760 verifyFormat("class Foooooooooooooooooooooo:\n" 15761 " public aaaaaaaaaaaaaaaaaa,\n" 15762 " public bbbbbbbbbbbbbbbbbb {\n" 15763 "}", 15764 InheritanceStyle); 15765 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15766 verifyFormat("class Foooooooooooooooooooooo\n" 15767 " : public aaaaaaaaaaaaaaaaaa\n" 15768 " , public bbbbbbbbbbbbbbbbbb {\n" 15769 "}", 15770 InheritanceStyle); 15771 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15772 verifyFormat("class Foooooooooooooooooooooo\n" 15773 " : public aaaaaaaaaaaaaaaaaa,\n" 15774 " public bbbbbbbbbbbbbbbbbb {\n" 15775 "}", 15776 InheritanceStyle); 15777 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15778 verifyFormat("class Foooooooooooooooooooooo\n" 15779 ": public aaaaaaaaaaaaaaaaaa,\n" 15780 " public bbbbbbbbbbbbbbbbbb {}", 15781 InheritanceStyle); 15782 15783 FormatStyle ForLoopStyle = getLLVMStyle(); 15784 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15785 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15786 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15787 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15788 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15789 verifyFormat("{\n" 15790 "label2:\n" 15791 " int x = 0;\n" 15792 "}", 15793 ForLoopStyle); 15794 verifyFormat("switch (x) {\n" 15795 "case 1:\n" 15796 "default:\n" 15797 "}", 15798 ForLoopStyle); 15799 verifyFormat("switch (allBraces) {\n" 15800 "case 1: {\n" 15801 " break;\n" 15802 "}\n" 15803 "case 2: {\n" 15804 " [[fallthrough]];\n" 15805 "}\n" 15806 "default: {\n" 15807 " break;\n" 15808 "}\n" 15809 "}", 15810 ForLoopStyle); 15811 15812 FormatStyle CaseStyle = getLLVMStyle(); 15813 CaseStyle.SpaceBeforeCaseColon = true; 15814 verifyFormat("class Foo : public Bar {};", CaseStyle); 15815 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15816 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15817 verifyFormat("int x = a ? b : c;", CaseStyle); 15818 verifyFormat("switch (x) {\n" 15819 "case 1 :\n" 15820 "default :\n" 15821 "}", 15822 CaseStyle); 15823 verifyFormat("switch (allBraces) {\n" 15824 "case 1 : {\n" 15825 " break;\n" 15826 "}\n" 15827 "case 2 : {\n" 15828 " [[fallthrough]];\n" 15829 "}\n" 15830 "default : {\n" 15831 " break;\n" 15832 "}\n" 15833 "}", 15834 CaseStyle); 15835 15836 FormatStyle NoSpaceStyle = getLLVMStyle(); 15837 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15838 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15839 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15840 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15841 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15842 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15843 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15844 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15845 verifyFormat("{\n" 15846 "label3:\n" 15847 " int x = 0;\n" 15848 "}", 15849 NoSpaceStyle); 15850 verifyFormat("switch (x) {\n" 15851 "case 1:\n" 15852 "default:\n" 15853 "}", 15854 NoSpaceStyle); 15855 verifyFormat("switch (allBraces) {\n" 15856 "case 1: {\n" 15857 " break;\n" 15858 "}\n" 15859 "case 2: {\n" 15860 " [[fallthrough]];\n" 15861 "}\n" 15862 "default: {\n" 15863 " break;\n" 15864 "}\n" 15865 "}", 15866 NoSpaceStyle); 15867 15868 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15869 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15870 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15871 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15872 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15873 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15874 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15875 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15876 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15877 verifyFormat("{\n" 15878 "label3:\n" 15879 " int x = 0;\n" 15880 "}", 15881 InvertedSpaceStyle); 15882 verifyFormat("switch (x) {\n" 15883 "case 1 :\n" 15884 "case 2 : {\n" 15885 " break;\n" 15886 "}\n" 15887 "default :\n" 15888 " break;\n" 15889 "}", 15890 InvertedSpaceStyle); 15891 verifyFormat("switch (allBraces) {\n" 15892 "case 1 : {\n" 15893 " break;\n" 15894 "}\n" 15895 "case 2 : {\n" 15896 " [[fallthrough]];\n" 15897 "}\n" 15898 "default : {\n" 15899 " break;\n" 15900 "}\n" 15901 "}", 15902 InvertedSpaceStyle); 15903 } 15904 15905 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15906 FormatStyle Style = getLLVMStyle(); 15907 15908 Style.PointerAlignment = FormatStyle::PAS_Left; 15909 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15910 verifyFormat("void* const* x = NULL;", Style); 15911 15912 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15913 do { \ 15914 Style.PointerAlignment = FormatStyle::Pointers; \ 15915 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15916 verifyFormat(Code, Style); \ 15917 } while (false) 15918 15919 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15920 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15921 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15922 15923 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15924 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15925 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15926 15927 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15928 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15929 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15930 15931 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15932 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15933 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15934 15935 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15936 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15937 SAPQ_Default); 15938 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15939 SAPQ_Default); 15940 15941 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15942 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15943 SAPQ_Before); 15944 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15945 SAPQ_Before); 15946 15947 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15948 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15949 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15950 SAPQ_After); 15951 15952 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15953 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15954 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15955 15956 #undef verifyQualifierSpaces 15957 15958 FormatStyle Spaces = getLLVMStyle(); 15959 Spaces.AttributeMacros.push_back("qualified"); 15960 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15961 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15962 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15963 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15964 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15965 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15966 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15967 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15968 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15969 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15970 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15971 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15972 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15973 15974 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15975 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15976 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15977 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15978 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15979 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15980 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15981 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15982 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15983 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15984 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15985 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15986 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15987 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15988 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15989 15990 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15991 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15992 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15993 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15994 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15995 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15996 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15997 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15998 } 15999 16000 TEST_F(FormatTest, AlignConsecutiveMacros) { 16001 FormatStyle Style = getLLVMStyle(); 16002 Style.AlignConsecutiveAssignments.Enabled = true; 16003 Style.AlignConsecutiveDeclarations.Enabled = true; 16004 16005 verifyFormat("#define a 3\n" 16006 "#define bbbb 4\n" 16007 "#define ccc (5)", 16008 Style); 16009 16010 verifyFormat("#define f(x) (x * x)\n" 16011 "#define fff(x, y, z) (x * y + z)\n" 16012 "#define ffff(x, y) (x - y)", 16013 Style); 16014 16015 verifyFormat("#define foo(x, y) (x + y)\n" 16016 "#define bar (5, 6)(2 + 2)", 16017 Style); 16018 16019 verifyFormat("#define a 3\n" 16020 "#define bbbb 4\n" 16021 "#define ccc (5)\n" 16022 "#define f(x) (x * x)\n" 16023 "#define fff(x, y, z) (x * y + z)\n" 16024 "#define ffff(x, y) (x - y)", 16025 Style); 16026 16027 Style.AlignConsecutiveMacros.Enabled = true; 16028 verifyFormat("#define a 3\n" 16029 "#define bbbb 4\n" 16030 "#define ccc (5)", 16031 Style); 16032 16033 verifyFormat("#define true 1\n" 16034 "#define false 0", 16035 Style); 16036 16037 verifyFormat("#define f(x) (x * x)\n" 16038 "#define fff(x, y, z) (x * y + z)\n" 16039 "#define ffff(x, y) (x - y)", 16040 Style); 16041 16042 verifyFormat("#define foo(x, y) (x + y)\n" 16043 "#define bar (5, 6)(2 + 2)", 16044 Style); 16045 16046 verifyFormat("#define a 3\n" 16047 "#define bbbb 4\n" 16048 "#define ccc (5)\n" 16049 "#define f(x) (x * x)\n" 16050 "#define fff(x, y, z) (x * y + z)\n" 16051 "#define ffff(x, y) (x - y)", 16052 Style); 16053 16054 verifyFormat("#define a 5\n" 16055 "#define foo(x, y) (x + y)\n" 16056 "#define CCC (6)\n" 16057 "auto lambda = []() {\n" 16058 " auto ii = 0;\n" 16059 " float j = 0;\n" 16060 " return 0;\n" 16061 "};\n" 16062 "int i = 0;\n" 16063 "float i2 = 0;\n" 16064 "auto v = type{\n" 16065 " i = 1, //\n" 16066 " (i = 2), //\n" 16067 " i = 3 //\n" 16068 "};", 16069 Style); 16070 16071 Style.AlignConsecutiveMacros.Enabled = false; 16072 Style.ColumnLimit = 20; 16073 16074 verifyFormat("#define a \\\n" 16075 " \"aabbbbbbbbbbbb\"\n" 16076 "#define D \\\n" 16077 " \"aabbbbbbbbbbbb\" \\\n" 16078 " \"ccddeeeeeeeee\"\n" 16079 "#define B \\\n" 16080 " \"QQQQQQQQQQQQQ\" \\\n" 16081 " \"FFFFFFFFFFFFF\" \\\n" 16082 " \"LLLLLLLL\"\n", 16083 Style); 16084 16085 Style.AlignConsecutiveMacros.Enabled = true; 16086 verifyFormat("#define a \\\n" 16087 " \"aabbbbbbbbbbbb\"\n" 16088 "#define D \\\n" 16089 " \"aabbbbbbbbbbbb\" \\\n" 16090 " \"ccddeeeeeeeee\"\n" 16091 "#define B \\\n" 16092 " \"QQQQQQQQQQQQQ\" \\\n" 16093 " \"FFFFFFFFFFFFF\" \\\n" 16094 " \"LLLLLLLL\"\n", 16095 Style); 16096 16097 // Test across comments 16098 Style.MaxEmptyLinesToKeep = 10; 16099 Style.ReflowComments = false; 16100 Style.AlignConsecutiveMacros.AcrossComments = true; 16101 EXPECT_EQ("#define a 3\n" 16102 "// line comment\n" 16103 "#define bbbb 4\n" 16104 "#define ccc (5)", 16105 format("#define a 3\n" 16106 "// line comment\n" 16107 "#define bbbb 4\n" 16108 "#define ccc (5)", 16109 Style)); 16110 16111 EXPECT_EQ("#define a 3\n" 16112 "/* block comment */\n" 16113 "#define bbbb 4\n" 16114 "#define ccc (5)", 16115 format("#define a 3\n" 16116 "/* block comment */\n" 16117 "#define bbbb 4\n" 16118 "#define ccc (5)", 16119 Style)); 16120 16121 EXPECT_EQ("#define a 3\n" 16122 "/* multi-line *\n" 16123 " * block comment */\n" 16124 "#define bbbb 4\n" 16125 "#define ccc (5)", 16126 format("#define a 3\n" 16127 "/* multi-line *\n" 16128 " * block comment */\n" 16129 "#define bbbb 4\n" 16130 "#define ccc (5)", 16131 Style)); 16132 16133 EXPECT_EQ("#define a 3\n" 16134 "// multi-line line comment\n" 16135 "//\n" 16136 "#define bbbb 4\n" 16137 "#define ccc (5)", 16138 format("#define a 3\n" 16139 "// multi-line line comment\n" 16140 "//\n" 16141 "#define bbbb 4\n" 16142 "#define ccc (5)", 16143 Style)); 16144 16145 EXPECT_EQ("#define a 3\n" 16146 "// empty lines still break.\n" 16147 "\n" 16148 "#define bbbb 4\n" 16149 "#define ccc (5)", 16150 format("#define a 3\n" 16151 "// empty lines still break.\n" 16152 "\n" 16153 "#define bbbb 4\n" 16154 "#define ccc (5)", 16155 Style)); 16156 16157 // Test across empty lines 16158 Style.AlignConsecutiveMacros.AcrossComments = false; 16159 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16160 EXPECT_EQ("#define a 3\n" 16161 "\n" 16162 "#define bbbb 4\n" 16163 "#define ccc (5)", 16164 format("#define a 3\n" 16165 "\n" 16166 "#define bbbb 4\n" 16167 "#define ccc (5)", 16168 Style)); 16169 16170 EXPECT_EQ("#define a 3\n" 16171 "\n" 16172 "\n" 16173 "\n" 16174 "#define bbbb 4\n" 16175 "#define ccc (5)", 16176 format("#define a 3\n" 16177 "\n" 16178 "\n" 16179 "\n" 16180 "#define bbbb 4\n" 16181 "#define ccc (5)", 16182 Style)); 16183 16184 EXPECT_EQ("#define a 3\n" 16185 "// comments should break alignment\n" 16186 "//\n" 16187 "#define bbbb 4\n" 16188 "#define ccc (5)", 16189 format("#define a 3\n" 16190 "// comments should break alignment\n" 16191 "//\n" 16192 "#define bbbb 4\n" 16193 "#define ccc (5)", 16194 Style)); 16195 16196 // Test across empty lines and comments 16197 Style.AlignConsecutiveMacros.AcrossComments = true; 16198 verifyFormat("#define a 3\n" 16199 "\n" 16200 "// line comment\n" 16201 "#define bbbb 4\n" 16202 "#define ccc (5)", 16203 Style); 16204 16205 EXPECT_EQ("#define a 3\n" 16206 "\n" 16207 "\n" 16208 "/* multi-line *\n" 16209 " * block comment */\n" 16210 "\n" 16211 "\n" 16212 "#define bbbb 4\n" 16213 "#define ccc (5)", 16214 format("#define a 3\n" 16215 "\n" 16216 "\n" 16217 "/* multi-line *\n" 16218 " * block comment */\n" 16219 "\n" 16220 "\n" 16221 "#define bbbb 4\n" 16222 "#define ccc (5)", 16223 Style)); 16224 16225 EXPECT_EQ("#define a 3\n" 16226 "\n" 16227 "\n" 16228 "/* multi-line *\n" 16229 " * block comment */\n" 16230 "\n" 16231 "\n" 16232 "#define bbbb 4\n" 16233 "#define ccc (5)", 16234 format("#define a 3\n" 16235 "\n" 16236 "\n" 16237 "/* multi-line *\n" 16238 " * block comment */\n" 16239 "\n" 16240 "\n" 16241 "#define bbbb 4\n" 16242 "#define ccc (5)", 16243 Style)); 16244 } 16245 16246 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16247 FormatStyle Alignment = getLLVMStyle(); 16248 Alignment.AlignConsecutiveMacros.Enabled = true; 16249 Alignment.AlignConsecutiveAssignments.Enabled = true; 16250 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16251 16252 Alignment.MaxEmptyLinesToKeep = 10; 16253 /* Test alignment across empty lines */ 16254 EXPECT_EQ("int a = 5;\n" 16255 "\n" 16256 "int oneTwoThree = 123;", 16257 format("int a = 5;\n" 16258 "\n" 16259 "int oneTwoThree= 123;", 16260 Alignment)); 16261 EXPECT_EQ("int a = 5;\n" 16262 "int one = 1;\n" 16263 "\n" 16264 "int oneTwoThree = 123;", 16265 format("int a = 5;\n" 16266 "int one = 1;\n" 16267 "\n" 16268 "int oneTwoThree = 123;", 16269 Alignment)); 16270 EXPECT_EQ("int a = 5;\n" 16271 "int one = 1;\n" 16272 "\n" 16273 "int oneTwoThree = 123;\n" 16274 "int oneTwo = 12;", 16275 format("int a = 5;\n" 16276 "int one = 1;\n" 16277 "\n" 16278 "int oneTwoThree = 123;\n" 16279 "int oneTwo = 12;", 16280 Alignment)); 16281 16282 /* Test across comments */ 16283 EXPECT_EQ("int a = 5;\n" 16284 "/* block comment */\n" 16285 "int oneTwoThree = 123;", 16286 format("int a = 5;\n" 16287 "/* block comment */\n" 16288 "int oneTwoThree=123;", 16289 Alignment)); 16290 16291 EXPECT_EQ("int a = 5;\n" 16292 "// line comment\n" 16293 "int oneTwoThree = 123;", 16294 format("int a = 5;\n" 16295 "// line comment\n" 16296 "int oneTwoThree=123;", 16297 Alignment)); 16298 16299 /* Test across comments and newlines */ 16300 EXPECT_EQ("int a = 5;\n" 16301 "\n" 16302 "/* block comment */\n" 16303 "int oneTwoThree = 123;", 16304 format("int a = 5;\n" 16305 "\n" 16306 "/* block comment */\n" 16307 "int oneTwoThree=123;", 16308 Alignment)); 16309 16310 EXPECT_EQ("int a = 5;\n" 16311 "\n" 16312 "// line comment\n" 16313 "int oneTwoThree = 123;", 16314 format("int a = 5;\n" 16315 "\n" 16316 "// line comment\n" 16317 "int oneTwoThree=123;", 16318 Alignment)); 16319 } 16320 16321 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16322 FormatStyle Alignment = getLLVMStyle(); 16323 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16324 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16325 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16326 16327 Alignment.MaxEmptyLinesToKeep = 10; 16328 /* Test alignment across empty lines */ 16329 EXPECT_EQ("int a = 5;\n" 16330 "\n" 16331 "float const oneTwoThree = 123;", 16332 format("int a = 5;\n" 16333 "\n" 16334 "float const oneTwoThree = 123;", 16335 Alignment)); 16336 EXPECT_EQ("int a = 5;\n" 16337 "float const one = 1;\n" 16338 "\n" 16339 "int oneTwoThree = 123;", 16340 format("int a = 5;\n" 16341 "float const one = 1;\n" 16342 "\n" 16343 "int oneTwoThree = 123;", 16344 Alignment)); 16345 16346 /* Test across comments */ 16347 EXPECT_EQ("float const a = 5;\n" 16348 "/* block comment */\n" 16349 "int oneTwoThree = 123;", 16350 format("float const a = 5;\n" 16351 "/* block comment */\n" 16352 "int oneTwoThree=123;", 16353 Alignment)); 16354 16355 EXPECT_EQ("float const a = 5;\n" 16356 "// line comment\n" 16357 "int oneTwoThree = 123;", 16358 format("float const a = 5;\n" 16359 "// line comment\n" 16360 "int oneTwoThree=123;", 16361 Alignment)); 16362 16363 /* Test across comments and newlines */ 16364 EXPECT_EQ("float const a = 5;\n" 16365 "\n" 16366 "/* block comment */\n" 16367 "int oneTwoThree = 123;", 16368 format("float const a = 5;\n" 16369 "\n" 16370 "/* block comment */\n" 16371 "int oneTwoThree=123;", 16372 Alignment)); 16373 16374 EXPECT_EQ("float const a = 5;\n" 16375 "\n" 16376 "// line comment\n" 16377 "int oneTwoThree = 123;", 16378 format("float const a = 5;\n" 16379 "\n" 16380 "// line comment\n" 16381 "int oneTwoThree=123;", 16382 Alignment)); 16383 } 16384 16385 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16386 FormatStyle Alignment = getLLVMStyle(); 16387 Alignment.AlignConsecutiveBitFields.Enabled = true; 16388 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16389 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16390 16391 Alignment.MaxEmptyLinesToKeep = 10; 16392 /* Test alignment across empty lines */ 16393 EXPECT_EQ("int a : 5;\n" 16394 "\n" 16395 "int longbitfield : 6;", 16396 format("int a : 5;\n" 16397 "\n" 16398 "int longbitfield : 6;", 16399 Alignment)); 16400 EXPECT_EQ("int a : 5;\n" 16401 "int one : 1;\n" 16402 "\n" 16403 "int longbitfield : 6;", 16404 format("int a : 5;\n" 16405 "int one : 1;\n" 16406 "\n" 16407 "int longbitfield : 6;", 16408 Alignment)); 16409 16410 /* Test across comments */ 16411 EXPECT_EQ("int a : 5;\n" 16412 "/* block comment */\n" 16413 "int longbitfield : 6;", 16414 format("int a : 5;\n" 16415 "/* block comment */\n" 16416 "int longbitfield : 6;", 16417 Alignment)); 16418 EXPECT_EQ("int a : 5;\n" 16419 "int one : 1;\n" 16420 "// line comment\n" 16421 "int longbitfield : 6;", 16422 format("int a : 5;\n" 16423 "int one : 1;\n" 16424 "// line comment\n" 16425 "int longbitfield : 6;", 16426 Alignment)); 16427 16428 /* Test across comments and newlines */ 16429 EXPECT_EQ("int a : 5;\n" 16430 "/* block comment */\n" 16431 "\n" 16432 "int longbitfield : 6;", 16433 format("int a : 5;\n" 16434 "/* block comment */\n" 16435 "\n" 16436 "int longbitfield : 6;", 16437 Alignment)); 16438 EXPECT_EQ("int a : 5;\n" 16439 "int one : 1;\n" 16440 "\n" 16441 "// line comment\n" 16442 "\n" 16443 "int longbitfield : 6;", 16444 format("int a : 5;\n" 16445 "int one : 1;\n" 16446 "\n" 16447 "// line comment \n" 16448 "\n" 16449 "int longbitfield : 6;", 16450 Alignment)); 16451 } 16452 16453 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16454 FormatStyle Alignment = getLLVMStyle(); 16455 Alignment.AlignConsecutiveMacros.Enabled = true; 16456 Alignment.AlignConsecutiveAssignments.Enabled = true; 16457 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16458 16459 Alignment.MaxEmptyLinesToKeep = 10; 16460 /* Test alignment across empty lines */ 16461 EXPECT_EQ("int a = 5;\n" 16462 "\n" 16463 "int oneTwoThree = 123;", 16464 format("int a = 5;\n" 16465 "\n" 16466 "int oneTwoThree= 123;", 16467 Alignment)); 16468 EXPECT_EQ("int a = 5;\n" 16469 "int one = 1;\n" 16470 "\n" 16471 "int oneTwoThree = 123;", 16472 format("int a = 5;\n" 16473 "int one = 1;\n" 16474 "\n" 16475 "int oneTwoThree = 123;", 16476 Alignment)); 16477 16478 /* Test across comments */ 16479 EXPECT_EQ("int a = 5;\n" 16480 "/* block comment */\n" 16481 "int oneTwoThree = 123;", 16482 format("int a = 5;\n" 16483 "/* block comment */\n" 16484 "int oneTwoThree=123;", 16485 Alignment)); 16486 16487 EXPECT_EQ("int a = 5;\n" 16488 "// line comment\n" 16489 "int oneTwoThree = 123;", 16490 format("int a = 5;\n" 16491 "// line comment\n" 16492 "int oneTwoThree=123;", 16493 Alignment)); 16494 16495 EXPECT_EQ("int a = 5;\n" 16496 "/*\n" 16497 " * multi-line block comment\n" 16498 " */\n" 16499 "int oneTwoThree = 123;", 16500 format("int a = 5;\n" 16501 "/*\n" 16502 " * multi-line block comment\n" 16503 " */\n" 16504 "int oneTwoThree=123;", 16505 Alignment)); 16506 16507 EXPECT_EQ("int a = 5;\n" 16508 "//\n" 16509 "// multi-line line comment\n" 16510 "//\n" 16511 "int oneTwoThree = 123;", 16512 format("int a = 5;\n" 16513 "//\n" 16514 "// multi-line line comment\n" 16515 "//\n" 16516 "int oneTwoThree=123;", 16517 Alignment)); 16518 16519 /* Test across comments and newlines */ 16520 EXPECT_EQ("int a = 5;\n" 16521 "\n" 16522 "/* block comment */\n" 16523 "int oneTwoThree = 123;", 16524 format("int a = 5;\n" 16525 "\n" 16526 "/* block comment */\n" 16527 "int oneTwoThree=123;", 16528 Alignment)); 16529 16530 EXPECT_EQ("int a = 5;\n" 16531 "\n" 16532 "// line comment\n" 16533 "int oneTwoThree = 123;", 16534 format("int a = 5;\n" 16535 "\n" 16536 "// line comment\n" 16537 "int oneTwoThree=123;", 16538 Alignment)); 16539 } 16540 16541 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16542 FormatStyle Alignment = getLLVMStyle(); 16543 Alignment.AlignConsecutiveMacros.Enabled = true; 16544 Alignment.AlignConsecutiveAssignments.Enabled = true; 16545 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16546 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16547 verifyFormat("int a = 5;\n" 16548 "int oneTwoThree = 123;", 16549 Alignment); 16550 verifyFormat("int a = method();\n" 16551 "int oneTwoThree = 133;", 16552 Alignment); 16553 verifyFormat("a &= 5;\n" 16554 "bcd *= 5;\n" 16555 "ghtyf += 5;\n" 16556 "dvfvdb -= 5;\n" 16557 "a /= 5;\n" 16558 "vdsvsv %= 5;\n" 16559 "sfdbddfbdfbb ^= 5;\n" 16560 "dvsdsv |= 5;\n" 16561 "int dsvvdvsdvvv = 123;", 16562 Alignment); 16563 verifyFormat("int i = 1, j = 10;\n" 16564 "something = 2000;", 16565 Alignment); 16566 verifyFormat("something = 2000;\n" 16567 "int i = 1, j = 10;\n", 16568 Alignment); 16569 verifyFormat("something = 2000;\n" 16570 "another = 911;\n" 16571 "int i = 1, j = 10;\n" 16572 "oneMore = 1;\n" 16573 "i = 2;", 16574 Alignment); 16575 verifyFormat("int a = 5;\n" 16576 "int one = 1;\n" 16577 "method();\n" 16578 "int oneTwoThree = 123;\n" 16579 "int oneTwo = 12;", 16580 Alignment); 16581 verifyFormat("int oneTwoThree = 123;\n" 16582 "int oneTwo = 12;\n" 16583 "method();\n", 16584 Alignment); 16585 verifyFormat("int oneTwoThree = 123; // comment\n" 16586 "int oneTwo = 12; // comment", 16587 Alignment); 16588 16589 // Bug 25167 16590 /* Uncomment when fixed 16591 verifyFormat("#if A\n" 16592 "#else\n" 16593 "int aaaaaaaa = 12;\n" 16594 "#endif\n" 16595 "#if B\n" 16596 "#else\n" 16597 "int a = 12;\n" 16598 "#endif\n", 16599 Alignment); 16600 verifyFormat("enum foo {\n" 16601 "#if A\n" 16602 "#else\n" 16603 " aaaaaaaa = 12;\n" 16604 "#endif\n" 16605 "#if B\n" 16606 "#else\n" 16607 " a = 12;\n" 16608 "#endif\n" 16609 "};\n", 16610 Alignment); 16611 */ 16612 16613 Alignment.MaxEmptyLinesToKeep = 10; 16614 /* Test alignment across empty lines */ 16615 EXPECT_EQ("int a = 5;\n" 16616 "\n" 16617 "int oneTwoThree = 123;", 16618 format("int a = 5;\n" 16619 "\n" 16620 "int oneTwoThree= 123;", 16621 Alignment)); 16622 EXPECT_EQ("int a = 5;\n" 16623 "int one = 1;\n" 16624 "\n" 16625 "int oneTwoThree = 123;", 16626 format("int a = 5;\n" 16627 "int one = 1;\n" 16628 "\n" 16629 "int oneTwoThree = 123;", 16630 Alignment)); 16631 EXPECT_EQ("int a = 5;\n" 16632 "int one = 1;\n" 16633 "\n" 16634 "int oneTwoThree = 123;\n" 16635 "int oneTwo = 12;", 16636 format("int a = 5;\n" 16637 "int one = 1;\n" 16638 "\n" 16639 "int oneTwoThree = 123;\n" 16640 "int oneTwo = 12;", 16641 Alignment)); 16642 16643 /* Test across comments */ 16644 EXPECT_EQ("int a = 5;\n" 16645 "/* block comment */\n" 16646 "int oneTwoThree = 123;", 16647 format("int a = 5;\n" 16648 "/* block comment */\n" 16649 "int oneTwoThree=123;", 16650 Alignment)); 16651 16652 EXPECT_EQ("int a = 5;\n" 16653 "// line comment\n" 16654 "int oneTwoThree = 123;", 16655 format("int a = 5;\n" 16656 "// line comment\n" 16657 "int oneTwoThree=123;", 16658 Alignment)); 16659 16660 /* Test across comments and newlines */ 16661 EXPECT_EQ("int a = 5;\n" 16662 "\n" 16663 "/* block comment */\n" 16664 "int oneTwoThree = 123;", 16665 format("int a = 5;\n" 16666 "\n" 16667 "/* block comment */\n" 16668 "int oneTwoThree=123;", 16669 Alignment)); 16670 16671 EXPECT_EQ("int a = 5;\n" 16672 "\n" 16673 "// line comment\n" 16674 "int oneTwoThree = 123;", 16675 format("int a = 5;\n" 16676 "\n" 16677 "// line comment\n" 16678 "int oneTwoThree=123;", 16679 Alignment)); 16680 16681 EXPECT_EQ("int a = 5;\n" 16682 "//\n" 16683 "// multi-line line comment\n" 16684 "//\n" 16685 "int oneTwoThree = 123;", 16686 format("int a = 5;\n" 16687 "//\n" 16688 "// multi-line line comment\n" 16689 "//\n" 16690 "int oneTwoThree=123;", 16691 Alignment)); 16692 16693 EXPECT_EQ("int a = 5;\n" 16694 "/*\n" 16695 " * multi-line block comment\n" 16696 " */\n" 16697 "int oneTwoThree = 123;", 16698 format("int a = 5;\n" 16699 "/*\n" 16700 " * multi-line block comment\n" 16701 " */\n" 16702 "int oneTwoThree=123;", 16703 Alignment)); 16704 16705 EXPECT_EQ("int a = 5;\n" 16706 "\n" 16707 "/* block comment */\n" 16708 "\n" 16709 "\n" 16710 "\n" 16711 "int oneTwoThree = 123;", 16712 format("int a = 5;\n" 16713 "\n" 16714 "/* block comment */\n" 16715 "\n" 16716 "\n" 16717 "\n" 16718 "int oneTwoThree=123;", 16719 Alignment)); 16720 16721 EXPECT_EQ("int a = 5;\n" 16722 "\n" 16723 "// line comment\n" 16724 "\n" 16725 "\n" 16726 "\n" 16727 "int oneTwoThree = 123;", 16728 format("int a = 5;\n" 16729 "\n" 16730 "// line comment\n" 16731 "\n" 16732 "\n" 16733 "\n" 16734 "int oneTwoThree=123;", 16735 Alignment)); 16736 16737 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16738 verifyFormat("#define A \\\n" 16739 " int aaaa = 12; \\\n" 16740 " int b = 23; \\\n" 16741 " int ccc = 234; \\\n" 16742 " int dddddddddd = 2345;", 16743 Alignment); 16744 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16745 verifyFormat("#define A \\\n" 16746 " int aaaa = 12; \\\n" 16747 " int b = 23; \\\n" 16748 " int ccc = 234; \\\n" 16749 " int dddddddddd = 2345;", 16750 Alignment); 16751 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16752 verifyFormat("#define A " 16753 " \\\n" 16754 " int aaaa = 12; " 16755 " \\\n" 16756 " int b = 23; " 16757 " \\\n" 16758 " int ccc = 234; " 16759 " \\\n" 16760 " int dddddddddd = 2345;", 16761 Alignment); 16762 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16763 "k = 4, int l = 5,\n" 16764 " int m = 6) {\n" 16765 " int j = 10;\n" 16766 " otherThing = 1;\n" 16767 "}", 16768 Alignment); 16769 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16770 " int i = 1;\n" 16771 " int j = 2;\n" 16772 " int big = 10000;\n" 16773 "}", 16774 Alignment); 16775 verifyFormat("class C {\n" 16776 "public:\n" 16777 " int i = 1;\n" 16778 " virtual void f() = 0;\n" 16779 "};", 16780 Alignment); 16781 verifyFormat("int i = 1;\n" 16782 "if (SomeType t = getSomething()) {\n" 16783 "}\n" 16784 "int j = 2;\n" 16785 "int big = 10000;", 16786 Alignment); 16787 verifyFormat("int j = 7;\n" 16788 "for (int k = 0; k < N; ++k) {\n" 16789 "}\n" 16790 "int j = 2;\n" 16791 "int big = 10000;\n" 16792 "}", 16793 Alignment); 16794 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16795 verifyFormat("int i = 1;\n" 16796 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16797 " = someLooooooooooooooooongFunction();\n" 16798 "int j = 2;", 16799 Alignment); 16800 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16801 verifyFormat("int i = 1;\n" 16802 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16803 " someLooooooooooooooooongFunction();\n" 16804 "int j = 2;", 16805 Alignment); 16806 16807 verifyFormat("auto lambda = []() {\n" 16808 " auto i = 0;\n" 16809 " return 0;\n" 16810 "};\n" 16811 "int i = 0;\n" 16812 "auto v = type{\n" 16813 " i = 1, //\n" 16814 " (i = 2), //\n" 16815 " i = 3 //\n" 16816 "};", 16817 Alignment); 16818 16819 verifyFormat( 16820 "int i = 1;\n" 16821 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16822 " loooooooooooooooooooooongParameterB);\n" 16823 "int j = 2;", 16824 Alignment); 16825 16826 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16827 " typename B = very_long_type_name_1,\n" 16828 " typename T_2 = very_long_type_name_2>\n" 16829 "auto foo() {}\n", 16830 Alignment); 16831 verifyFormat("int a, b = 1;\n" 16832 "int c = 2;\n" 16833 "int dd = 3;\n", 16834 Alignment); 16835 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16836 "float b[1][] = {{3.f}};\n", 16837 Alignment); 16838 verifyFormat("for (int i = 0; i < 1; i++)\n" 16839 " int x = 1;\n", 16840 Alignment); 16841 verifyFormat("for (i = 0; i < 1; i++)\n" 16842 " x = 1;\n" 16843 "y = 1;\n", 16844 Alignment); 16845 16846 Alignment.ReflowComments = true; 16847 Alignment.ColumnLimit = 50; 16848 EXPECT_EQ("int x = 0;\n" 16849 "int yy = 1; /// specificlennospace\n" 16850 "int zzz = 2;\n", 16851 format("int x = 0;\n" 16852 "int yy = 1; ///specificlennospace\n" 16853 "int zzz = 2;\n", 16854 Alignment)); 16855 } 16856 16857 TEST_F(FormatTest, AlignCompoundAssignments) { 16858 FormatStyle Alignment = getLLVMStyle(); 16859 Alignment.AlignConsecutiveAssignments.Enabled = true; 16860 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 16861 Alignment.AlignConsecutiveAssignments.PadOperators = false; 16862 verifyFormat("sfdbddfbdfbb = 5;\n" 16863 "dvsdsv = 5;\n" 16864 "int dsvvdvsdvvv = 123;", 16865 Alignment); 16866 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16867 "dvsdsv |= 5;\n" 16868 "int dsvvdvsdvvv = 123;", 16869 Alignment); 16870 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16871 "dvsdsv <<= 5;\n" 16872 "int dsvvdvsdvvv = 123;", 16873 Alignment); 16874 // Test that `<=` is not treated as a compound assignment. 16875 verifyFormat("aa &= 5;\n" 16876 "b <= 10;\n" 16877 "c = 15;", 16878 Alignment); 16879 Alignment.AlignConsecutiveAssignments.PadOperators = true; 16880 verifyFormat("sfdbddfbdfbb = 5;\n" 16881 "dvsdsv = 5;\n" 16882 "int dsvvdvsdvvv = 123;", 16883 Alignment); 16884 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16885 "dvsdsv |= 5;\n" 16886 "int dsvvdvsdvvv = 123;", 16887 Alignment); 16888 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16889 "dvsdsv <<= 5;\n" 16890 "int dsvvdvsdvvv = 123;", 16891 Alignment); 16892 EXPECT_EQ("a += 5;\n" 16893 "one = 1;\n" 16894 "\n" 16895 "oneTwoThree = 123;\n", 16896 format("a += 5;\n" 16897 "one = 1;\n" 16898 "\n" 16899 "oneTwoThree = 123;\n", 16900 Alignment)); 16901 EXPECT_EQ("a += 5;\n" 16902 "one = 1;\n" 16903 "//\n" 16904 "oneTwoThree = 123;\n", 16905 format("a += 5;\n" 16906 "one = 1;\n" 16907 "//\n" 16908 "oneTwoThree = 123;\n", 16909 Alignment)); 16910 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16911 EXPECT_EQ("a += 5;\n" 16912 "one = 1;\n" 16913 "\n" 16914 "oneTwoThree = 123;\n", 16915 format("a += 5;\n" 16916 "one = 1;\n" 16917 "\n" 16918 "oneTwoThree = 123;\n", 16919 Alignment)); 16920 EXPECT_EQ("a += 5;\n" 16921 "one = 1;\n" 16922 "//\n" 16923 "oneTwoThree = 123;\n", 16924 format("a += 5;\n" 16925 "one = 1;\n" 16926 "//\n" 16927 "oneTwoThree = 123;\n", 16928 Alignment)); 16929 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 16930 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16931 EXPECT_EQ("a += 5;\n" 16932 "one = 1;\n" 16933 "\n" 16934 "oneTwoThree = 123;\n", 16935 format("a += 5;\n" 16936 "one = 1;\n" 16937 "\n" 16938 "oneTwoThree = 123;\n", 16939 Alignment)); 16940 EXPECT_EQ("a += 5;\n" 16941 "one = 1;\n" 16942 "//\n" 16943 "oneTwoThree = 123;\n", 16944 format("a += 5;\n" 16945 "one = 1;\n" 16946 "//\n" 16947 "oneTwoThree = 123;\n", 16948 Alignment)); 16949 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16950 EXPECT_EQ("a += 5;\n" 16951 "one >>= 1;\n" 16952 "\n" 16953 "oneTwoThree = 123;\n", 16954 format("a += 5;\n" 16955 "one >>= 1;\n" 16956 "\n" 16957 "oneTwoThree = 123;\n", 16958 Alignment)); 16959 EXPECT_EQ("a += 5;\n" 16960 "one = 1;\n" 16961 "//\n" 16962 "oneTwoThree <<= 123;\n", 16963 format("a += 5;\n" 16964 "one = 1;\n" 16965 "//\n" 16966 "oneTwoThree <<= 123;\n", 16967 Alignment)); 16968 } 16969 16970 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16971 FormatStyle Alignment = getLLVMStyle(); 16972 Alignment.AlignConsecutiveMacros.Enabled = true; 16973 verifyFormat("int a = 5;\n" 16974 "int oneTwoThree = 123;", 16975 Alignment); 16976 verifyFormat("int a = 5;\n" 16977 "int oneTwoThree = 123;", 16978 Alignment); 16979 16980 Alignment.AlignConsecutiveAssignments.Enabled = true; 16981 verifyFormat("int a = 5;\n" 16982 "int oneTwoThree = 123;", 16983 Alignment); 16984 verifyFormat("int a = method();\n" 16985 "int oneTwoThree = 133;", 16986 Alignment); 16987 verifyFormat("aa <= 5;\n" 16988 "a &= 5;\n" 16989 "bcd *= 5;\n" 16990 "ghtyf += 5;\n" 16991 "dvfvdb -= 5;\n" 16992 "a /= 5;\n" 16993 "vdsvsv %= 5;\n" 16994 "sfdbddfbdfbb ^= 5;\n" 16995 "dvsdsv |= 5;\n" 16996 "int dsvvdvsdvvv = 123;", 16997 Alignment); 16998 verifyFormat("int i = 1, j = 10;\n" 16999 "something = 2000;", 17000 Alignment); 17001 verifyFormat("something = 2000;\n" 17002 "int i = 1, j = 10;\n", 17003 Alignment); 17004 verifyFormat("something = 2000;\n" 17005 "another = 911;\n" 17006 "int i = 1, j = 10;\n" 17007 "oneMore = 1;\n" 17008 "i = 2;", 17009 Alignment); 17010 verifyFormat("int a = 5;\n" 17011 "int one = 1;\n" 17012 "method();\n" 17013 "int oneTwoThree = 123;\n" 17014 "int oneTwo = 12;", 17015 Alignment); 17016 verifyFormat("int oneTwoThree = 123;\n" 17017 "int oneTwo = 12;\n" 17018 "method();\n", 17019 Alignment); 17020 verifyFormat("int oneTwoThree = 123; // comment\n" 17021 "int oneTwo = 12; // comment", 17022 Alignment); 17023 verifyFormat("int f() = default;\n" 17024 "int &operator() = default;\n" 17025 "int &operator=() {", 17026 Alignment); 17027 verifyFormat("int f() = delete;\n" 17028 "int &operator() = delete;\n" 17029 "int &operator=() {", 17030 Alignment); 17031 verifyFormat("int f() = default; // comment\n" 17032 "int &operator() = default; // comment\n" 17033 "int &operator=() {", 17034 Alignment); 17035 verifyFormat("int f() = default;\n" 17036 "int &operator() = default;\n" 17037 "int &operator==() {", 17038 Alignment); 17039 verifyFormat("int f() = default;\n" 17040 "int &operator() = default;\n" 17041 "int &operator<=() {", 17042 Alignment); 17043 verifyFormat("int f() = default;\n" 17044 "int &operator() = default;\n" 17045 "int &operator!=() {", 17046 Alignment); 17047 verifyFormat("int f() = default;\n" 17048 "int &operator() = default;\n" 17049 "int &operator=();", 17050 Alignment); 17051 verifyFormat("int f() = delete;\n" 17052 "int &operator() = delete;\n" 17053 "int &operator=();", 17054 Alignment); 17055 verifyFormat("/* long long padding */ int f() = default;\n" 17056 "int &operator() = default;\n" 17057 "int &operator/**/ =();", 17058 Alignment); 17059 // https://llvm.org/PR33697 17060 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17061 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17062 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17063 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17064 " void f() = delete;\n" 17065 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17066 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17067 "};\n", 17068 AlignmentWithPenalty); 17069 17070 // Bug 25167 17071 /* Uncomment when fixed 17072 verifyFormat("#if A\n" 17073 "#else\n" 17074 "int aaaaaaaa = 12;\n" 17075 "#endif\n" 17076 "#if B\n" 17077 "#else\n" 17078 "int a = 12;\n" 17079 "#endif\n", 17080 Alignment); 17081 verifyFormat("enum foo {\n" 17082 "#if A\n" 17083 "#else\n" 17084 " aaaaaaaa = 12;\n" 17085 "#endif\n" 17086 "#if B\n" 17087 "#else\n" 17088 " a = 12;\n" 17089 "#endif\n" 17090 "};\n", 17091 Alignment); 17092 */ 17093 17094 EXPECT_EQ("int a = 5;\n" 17095 "\n" 17096 "int oneTwoThree = 123;", 17097 format("int a = 5;\n" 17098 "\n" 17099 "int oneTwoThree= 123;", 17100 Alignment)); 17101 EXPECT_EQ("int a = 5;\n" 17102 "int one = 1;\n" 17103 "\n" 17104 "int oneTwoThree = 123;", 17105 format("int a = 5;\n" 17106 "int one = 1;\n" 17107 "\n" 17108 "int oneTwoThree = 123;", 17109 Alignment)); 17110 EXPECT_EQ("int a = 5;\n" 17111 "int one = 1;\n" 17112 "\n" 17113 "int oneTwoThree = 123;\n" 17114 "int oneTwo = 12;", 17115 format("int a = 5;\n" 17116 "int one = 1;\n" 17117 "\n" 17118 "int oneTwoThree = 123;\n" 17119 "int oneTwo = 12;", 17120 Alignment)); 17121 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17122 verifyFormat("#define A \\\n" 17123 " int aaaa = 12; \\\n" 17124 " int b = 23; \\\n" 17125 " int ccc = 234; \\\n" 17126 " int dddddddddd = 2345;", 17127 Alignment); 17128 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17129 verifyFormat("#define A \\\n" 17130 " int aaaa = 12; \\\n" 17131 " int b = 23; \\\n" 17132 " int ccc = 234; \\\n" 17133 " int dddddddddd = 2345;", 17134 Alignment); 17135 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17136 verifyFormat("#define A " 17137 " \\\n" 17138 " int aaaa = 12; " 17139 " \\\n" 17140 " int b = 23; " 17141 " \\\n" 17142 " int ccc = 234; " 17143 " \\\n" 17144 " int dddddddddd = 2345;", 17145 Alignment); 17146 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17147 "k = 4, int l = 5,\n" 17148 " int m = 6) {\n" 17149 " int j = 10;\n" 17150 " otherThing = 1;\n" 17151 "}", 17152 Alignment); 17153 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17154 " int i = 1;\n" 17155 " int j = 2;\n" 17156 " int big = 10000;\n" 17157 "}", 17158 Alignment); 17159 verifyFormat("class C {\n" 17160 "public:\n" 17161 " int i = 1;\n" 17162 " virtual void f() = 0;\n" 17163 "};", 17164 Alignment); 17165 verifyFormat("int i = 1;\n" 17166 "if (SomeType t = getSomething()) {\n" 17167 "}\n" 17168 "int j = 2;\n" 17169 "int big = 10000;", 17170 Alignment); 17171 verifyFormat("int j = 7;\n" 17172 "for (int k = 0; k < N; ++k) {\n" 17173 "}\n" 17174 "int j = 2;\n" 17175 "int big = 10000;\n" 17176 "}", 17177 Alignment); 17178 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17179 verifyFormat("int i = 1;\n" 17180 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17181 " = someLooooooooooooooooongFunction();\n" 17182 "int j = 2;", 17183 Alignment); 17184 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17185 verifyFormat("int i = 1;\n" 17186 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17187 " someLooooooooooooooooongFunction();\n" 17188 "int j = 2;", 17189 Alignment); 17190 17191 verifyFormat("auto lambda = []() {\n" 17192 " auto i = 0;\n" 17193 " return 0;\n" 17194 "};\n" 17195 "int i = 0;\n" 17196 "auto v = type{\n" 17197 " i = 1, //\n" 17198 " (i = 2), //\n" 17199 " i = 3 //\n" 17200 "};", 17201 Alignment); 17202 17203 verifyFormat( 17204 "int i = 1;\n" 17205 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17206 " loooooooooooooooooooooongParameterB);\n" 17207 "int j = 2;", 17208 Alignment); 17209 17210 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17211 " typename B = very_long_type_name_1,\n" 17212 " typename T_2 = very_long_type_name_2>\n" 17213 "auto foo() {}\n", 17214 Alignment); 17215 verifyFormat("int a, b = 1;\n" 17216 "int c = 2;\n" 17217 "int dd = 3;\n", 17218 Alignment); 17219 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17220 "float b[1][] = {{3.f}};\n", 17221 Alignment); 17222 verifyFormat("for (int i = 0; i < 1; i++)\n" 17223 " int x = 1;\n", 17224 Alignment); 17225 verifyFormat("for (i = 0; i < 1; i++)\n" 17226 " x = 1;\n" 17227 "y = 1;\n", 17228 Alignment); 17229 17230 EXPECT_EQ(Alignment.ReflowComments, true); 17231 Alignment.ColumnLimit = 50; 17232 EXPECT_EQ("int x = 0;\n" 17233 "int yy = 1; /// specificlennospace\n" 17234 "int zzz = 2;\n", 17235 format("int x = 0;\n" 17236 "int yy = 1; ///specificlennospace\n" 17237 "int zzz = 2;\n", 17238 Alignment)); 17239 17240 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17241 "auto b = [] {\n" 17242 " f();\n" 17243 " return;\n" 17244 "};", 17245 Alignment); 17246 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17247 "auto b = g([] {\n" 17248 " f();\n" 17249 " return;\n" 17250 "});", 17251 Alignment); 17252 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17253 "auto b = g(param, [] {\n" 17254 " f();\n" 17255 " return;\n" 17256 "});", 17257 Alignment); 17258 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17259 "auto b = [] {\n" 17260 " if (condition) {\n" 17261 " return;\n" 17262 " }\n" 17263 "};", 17264 Alignment); 17265 17266 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17267 " ccc ? aaaaa : bbbbb,\n" 17268 " dddddddddddddddddddddddddd);", 17269 Alignment); 17270 // FIXME: https://llvm.org/PR53497 17271 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17272 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17273 // " ccc ? aaaaa : bbbbb,\n" 17274 // " dddddddddddddddddddddddddd);", 17275 // Alignment); 17276 } 17277 17278 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17279 FormatStyle Alignment = getLLVMStyle(); 17280 Alignment.AlignConsecutiveBitFields.Enabled = true; 17281 verifyFormat("int const a : 5;\n" 17282 "int oneTwoThree : 23;", 17283 Alignment); 17284 17285 // Initializers are allowed starting with c++2a 17286 verifyFormat("int const a : 5 = 1;\n" 17287 "int oneTwoThree : 23 = 0;", 17288 Alignment); 17289 17290 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17291 verifyFormat("int const a : 5;\n" 17292 "int oneTwoThree : 23;", 17293 Alignment); 17294 17295 verifyFormat("int const a : 5; // comment\n" 17296 "int oneTwoThree : 23; // comment", 17297 Alignment); 17298 17299 verifyFormat("int const a : 5 = 1;\n" 17300 "int oneTwoThree : 23 = 0;", 17301 Alignment); 17302 17303 Alignment.AlignConsecutiveAssignments.Enabled = true; 17304 verifyFormat("int const a : 5 = 1;\n" 17305 "int oneTwoThree : 23 = 0;", 17306 Alignment); 17307 verifyFormat("int const a : 5 = {1};\n" 17308 "int oneTwoThree : 23 = 0;", 17309 Alignment); 17310 17311 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17312 verifyFormat("int const a :5;\n" 17313 "int oneTwoThree:23;", 17314 Alignment); 17315 17316 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17317 verifyFormat("int const a :5;\n" 17318 "int oneTwoThree :23;", 17319 Alignment); 17320 17321 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17322 verifyFormat("int const a : 5;\n" 17323 "int oneTwoThree: 23;", 17324 Alignment); 17325 17326 // Known limitations: ':' is only recognized as a bitfield colon when 17327 // followed by a number. 17328 /* 17329 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17330 "int a : 5;", 17331 Alignment); 17332 */ 17333 } 17334 17335 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17336 FormatStyle Alignment = getLLVMStyle(); 17337 Alignment.AlignConsecutiveMacros.Enabled = true; 17338 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17339 verifyFormat("float const a = 5;\n" 17340 "int oneTwoThree = 123;", 17341 Alignment); 17342 verifyFormat("int a = 5;\n" 17343 "float const oneTwoThree = 123;", 17344 Alignment); 17345 17346 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17347 verifyFormat("float const a = 5;\n" 17348 "int oneTwoThree = 123;", 17349 Alignment); 17350 verifyFormat("int a = method();\n" 17351 "float const oneTwoThree = 133;", 17352 Alignment); 17353 verifyFormat("int i = 1, j = 10;\n" 17354 "something = 2000;", 17355 Alignment); 17356 verifyFormat("something = 2000;\n" 17357 "int i = 1, j = 10;\n", 17358 Alignment); 17359 verifyFormat("float something = 2000;\n" 17360 "double another = 911;\n" 17361 "int i = 1, j = 10;\n" 17362 "const int *oneMore = 1;\n" 17363 "unsigned i = 2;", 17364 Alignment); 17365 verifyFormat("float a = 5;\n" 17366 "int one = 1;\n" 17367 "method();\n" 17368 "const double oneTwoThree = 123;\n" 17369 "const unsigned int oneTwo = 12;", 17370 Alignment); 17371 verifyFormat("int oneTwoThree{0}; // comment\n" 17372 "unsigned oneTwo; // comment", 17373 Alignment); 17374 verifyFormat("unsigned int *a;\n" 17375 "int *b;\n" 17376 "unsigned int Const *c;\n" 17377 "unsigned int const *d;\n" 17378 "unsigned int Const &e;\n" 17379 "unsigned int const &f;", 17380 Alignment); 17381 verifyFormat("Const unsigned int *c;\n" 17382 "const unsigned int *d;\n" 17383 "Const unsigned int &e;\n" 17384 "const unsigned int &f;\n" 17385 "const unsigned g;\n" 17386 "Const unsigned h;", 17387 Alignment); 17388 EXPECT_EQ("float const a = 5;\n" 17389 "\n" 17390 "int oneTwoThree = 123;", 17391 format("float const a = 5;\n" 17392 "\n" 17393 "int oneTwoThree= 123;", 17394 Alignment)); 17395 EXPECT_EQ("float a = 5;\n" 17396 "int one = 1;\n" 17397 "\n" 17398 "unsigned oneTwoThree = 123;", 17399 format("float a = 5;\n" 17400 "int one = 1;\n" 17401 "\n" 17402 "unsigned oneTwoThree = 123;", 17403 Alignment)); 17404 EXPECT_EQ("float a = 5;\n" 17405 "int one = 1;\n" 17406 "\n" 17407 "unsigned oneTwoThree = 123;\n" 17408 "int oneTwo = 12;", 17409 format("float a = 5;\n" 17410 "int one = 1;\n" 17411 "\n" 17412 "unsigned oneTwoThree = 123;\n" 17413 "int oneTwo = 12;", 17414 Alignment)); 17415 // Function prototype alignment 17416 verifyFormat("int a();\n" 17417 "double b();", 17418 Alignment); 17419 verifyFormat("int a(int x);\n" 17420 "double b();", 17421 Alignment); 17422 unsigned OldColumnLimit = Alignment.ColumnLimit; 17423 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17424 // otherwise the function parameters will be re-flowed onto a single line. 17425 Alignment.ColumnLimit = 0; 17426 EXPECT_EQ("int a(int x,\n" 17427 " float y);\n" 17428 "double b(int x,\n" 17429 " double y);", 17430 format("int a(int x,\n" 17431 " float y);\n" 17432 "double b(int x,\n" 17433 " double y);", 17434 Alignment)); 17435 // This ensures that function parameters of function declarations are 17436 // correctly indented when their owning functions are indented. 17437 // The failure case here is for 'double y' to not be indented enough. 17438 EXPECT_EQ("double a(int x);\n" 17439 "int b(int y,\n" 17440 " double z);", 17441 format("double a(int x);\n" 17442 "int b(int y,\n" 17443 " double z);", 17444 Alignment)); 17445 // Set ColumnLimit low so that we induce wrapping immediately after 17446 // the function name and opening paren. 17447 Alignment.ColumnLimit = 13; 17448 verifyFormat("int function(\n" 17449 " int x,\n" 17450 " bool y);", 17451 Alignment); 17452 Alignment.ColumnLimit = OldColumnLimit; 17453 // Ensure function pointers don't screw up recursive alignment 17454 verifyFormat("int a(int x, void (*fp)(int y));\n" 17455 "double b();", 17456 Alignment); 17457 Alignment.AlignConsecutiveAssignments.Enabled = true; 17458 // Ensure recursive alignment is broken by function braces, so that the 17459 // "a = 1" does not align with subsequent assignments inside the function 17460 // body. 17461 verifyFormat("int func(int a = 1) {\n" 17462 " int b = 2;\n" 17463 " int cc = 3;\n" 17464 "}", 17465 Alignment); 17466 verifyFormat("float something = 2000;\n" 17467 "double another = 911;\n" 17468 "int i = 1, j = 10;\n" 17469 "const int *oneMore = 1;\n" 17470 "unsigned i = 2;", 17471 Alignment); 17472 verifyFormat("int oneTwoThree = {0}; // comment\n" 17473 "unsigned oneTwo = 0; // comment", 17474 Alignment); 17475 // Make sure that scope is correctly tracked, in the absence of braces 17476 verifyFormat("for (int i = 0; i < n; i++)\n" 17477 " j = i;\n" 17478 "double x = 1;\n", 17479 Alignment); 17480 verifyFormat("if (int i = 0)\n" 17481 " j = i;\n" 17482 "double x = 1;\n", 17483 Alignment); 17484 // Ensure operator[] and operator() are comprehended 17485 verifyFormat("struct test {\n" 17486 " long long int foo();\n" 17487 " int operator[](int a);\n" 17488 " double bar();\n" 17489 "};\n", 17490 Alignment); 17491 verifyFormat("struct test {\n" 17492 " long long int foo();\n" 17493 " int operator()(int a);\n" 17494 " double bar();\n" 17495 "};\n", 17496 Alignment); 17497 // http://llvm.org/PR52914 17498 verifyFormat("char *a[] = {\"a\", // comment\n" 17499 " \"bb\"};\n" 17500 "int bbbbbbb = 0;", 17501 Alignment); 17502 17503 // PAS_Right 17504 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17505 " int const i = 1;\n" 17506 " int *j = 2;\n" 17507 " int big = 10000;\n" 17508 "\n" 17509 " unsigned oneTwoThree = 123;\n" 17510 " int oneTwo = 12;\n" 17511 " method();\n" 17512 " float k = 2;\n" 17513 " int ll = 10000;\n" 17514 "}", 17515 format("void SomeFunction(int parameter= 0) {\n" 17516 " int const i= 1;\n" 17517 " int *j=2;\n" 17518 " int big = 10000;\n" 17519 "\n" 17520 "unsigned oneTwoThree =123;\n" 17521 "int oneTwo = 12;\n" 17522 " method();\n" 17523 "float k= 2;\n" 17524 "int ll=10000;\n" 17525 "}", 17526 Alignment)); 17527 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17528 " int const i = 1;\n" 17529 " int **j = 2, ***k;\n" 17530 " int &k = i;\n" 17531 " int &&l = i + j;\n" 17532 " int big = 10000;\n" 17533 "\n" 17534 " unsigned oneTwoThree = 123;\n" 17535 " int oneTwo = 12;\n" 17536 " method();\n" 17537 " float k = 2;\n" 17538 " int ll = 10000;\n" 17539 "}", 17540 format("void SomeFunction(int parameter= 0) {\n" 17541 " int const i= 1;\n" 17542 " int **j=2,***k;\n" 17543 "int &k=i;\n" 17544 "int &&l=i+j;\n" 17545 " int big = 10000;\n" 17546 "\n" 17547 "unsigned oneTwoThree =123;\n" 17548 "int oneTwo = 12;\n" 17549 " method();\n" 17550 "float k= 2;\n" 17551 "int ll=10000;\n" 17552 "}", 17553 Alignment)); 17554 // variables are aligned at their name, pointers are at the right most 17555 // position 17556 verifyFormat("int *a;\n" 17557 "int **b;\n" 17558 "int ***c;\n" 17559 "int foobar;\n", 17560 Alignment); 17561 17562 // PAS_Left 17563 FormatStyle AlignmentLeft = Alignment; 17564 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17565 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17566 " int const i = 1;\n" 17567 " int* j = 2;\n" 17568 " int big = 10000;\n" 17569 "\n" 17570 " unsigned oneTwoThree = 123;\n" 17571 " int oneTwo = 12;\n" 17572 " method();\n" 17573 " float k = 2;\n" 17574 " int ll = 10000;\n" 17575 "}", 17576 format("void SomeFunction(int parameter= 0) {\n" 17577 " int const i= 1;\n" 17578 " int *j=2;\n" 17579 " int big = 10000;\n" 17580 "\n" 17581 "unsigned oneTwoThree =123;\n" 17582 "int oneTwo = 12;\n" 17583 " method();\n" 17584 "float k= 2;\n" 17585 "int ll=10000;\n" 17586 "}", 17587 AlignmentLeft)); 17588 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17589 " int const i = 1;\n" 17590 " int** j = 2;\n" 17591 " int& k = i;\n" 17592 " int&& l = i + j;\n" 17593 " int big = 10000;\n" 17594 "\n" 17595 " unsigned oneTwoThree = 123;\n" 17596 " int oneTwo = 12;\n" 17597 " method();\n" 17598 " float k = 2;\n" 17599 " int ll = 10000;\n" 17600 "}", 17601 format("void SomeFunction(int parameter= 0) {\n" 17602 " int const i= 1;\n" 17603 " int **j=2;\n" 17604 "int &k=i;\n" 17605 "int &&l=i+j;\n" 17606 " int big = 10000;\n" 17607 "\n" 17608 "unsigned oneTwoThree =123;\n" 17609 "int oneTwo = 12;\n" 17610 " method();\n" 17611 "float k= 2;\n" 17612 "int ll=10000;\n" 17613 "}", 17614 AlignmentLeft)); 17615 // variables are aligned at their name, pointers are at the left most position 17616 verifyFormat("int* a;\n" 17617 "int** b;\n" 17618 "int*** c;\n" 17619 "int foobar;\n", 17620 AlignmentLeft); 17621 17622 // PAS_Middle 17623 FormatStyle AlignmentMiddle = Alignment; 17624 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17625 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17626 " int const i = 1;\n" 17627 " int * j = 2;\n" 17628 " int big = 10000;\n" 17629 "\n" 17630 " unsigned oneTwoThree = 123;\n" 17631 " int oneTwo = 12;\n" 17632 " method();\n" 17633 " float k = 2;\n" 17634 " int ll = 10000;\n" 17635 "}", 17636 format("void SomeFunction(int parameter= 0) {\n" 17637 " int const i= 1;\n" 17638 " int *j=2;\n" 17639 " int big = 10000;\n" 17640 "\n" 17641 "unsigned oneTwoThree =123;\n" 17642 "int oneTwo = 12;\n" 17643 " method();\n" 17644 "float k= 2;\n" 17645 "int ll=10000;\n" 17646 "}", 17647 AlignmentMiddle)); 17648 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17649 " int const i = 1;\n" 17650 " int ** j = 2, ***k;\n" 17651 " int & k = i;\n" 17652 " int && l = i + j;\n" 17653 " int big = 10000;\n" 17654 "\n" 17655 " unsigned oneTwoThree = 123;\n" 17656 " int oneTwo = 12;\n" 17657 " method();\n" 17658 " float k = 2;\n" 17659 " int ll = 10000;\n" 17660 "}", 17661 format("void SomeFunction(int parameter= 0) {\n" 17662 " int const i= 1;\n" 17663 " int **j=2,***k;\n" 17664 "int &k=i;\n" 17665 "int &&l=i+j;\n" 17666 " int big = 10000;\n" 17667 "\n" 17668 "unsigned oneTwoThree =123;\n" 17669 "int oneTwo = 12;\n" 17670 " method();\n" 17671 "float k= 2;\n" 17672 "int ll=10000;\n" 17673 "}", 17674 AlignmentMiddle)); 17675 // variables are aligned at their name, pointers are in the middle 17676 verifyFormat("int * a;\n" 17677 "int * b;\n" 17678 "int *** c;\n" 17679 "int foobar;\n", 17680 AlignmentMiddle); 17681 17682 Alignment.AlignConsecutiveAssignments.Enabled = false; 17683 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17684 verifyFormat("#define A \\\n" 17685 " int aaaa = 12; \\\n" 17686 " float b = 23; \\\n" 17687 " const int ccc = 234; \\\n" 17688 " unsigned dddddddddd = 2345;", 17689 Alignment); 17690 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17691 verifyFormat("#define A \\\n" 17692 " int aaaa = 12; \\\n" 17693 " float b = 23; \\\n" 17694 " const int ccc = 234; \\\n" 17695 " unsigned dddddddddd = 2345;", 17696 Alignment); 17697 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17698 Alignment.ColumnLimit = 30; 17699 verifyFormat("#define A \\\n" 17700 " int aaaa = 12; \\\n" 17701 " float b = 23; \\\n" 17702 " const int ccc = 234; \\\n" 17703 " int dddddddddd = 2345;", 17704 Alignment); 17705 Alignment.ColumnLimit = 80; 17706 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17707 "k = 4, int l = 5,\n" 17708 " int m = 6) {\n" 17709 " const int j = 10;\n" 17710 " otherThing = 1;\n" 17711 "}", 17712 Alignment); 17713 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17714 " int const i = 1;\n" 17715 " int *j = 2;\n" 17716 " int big = 10000;\n" 17717 "}", 17718 Alignment); 17719 verifyFormat("class C {\n" 17720 "public:\n" 17721 " int i = 1;\n" 17722 " virtual void f() = 0;\n" 17723 "};", 17724 Alignment); 17725 verifyFormat("float i = 1;\n" 17726 "if (SomeType t = getSomething()) {\n" 17727 "}\n" 17728 "const unsigned j = 2;\n" 17729 "int big = 10000;", 17730 Alignment); 17731 verifyFormat("float j = 7;\n" 17732 "for (int k = 0; k < N; ++k) {\n" 17733 "}\n" 17734 "unsigned j = 2;\n" 17735 "int big = 10000;\n" 17736 "}", 17737 Alignment); 17738 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17739 verifyFormat("float i = 1;\n" 17740 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17741 " = someLooooooooooooooooongFunction();\n" 17742 "int j = 2;", 17743 Alignment); 17744 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17745 verifyFormat("int i = 1;\n" 17746 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17747 " someLooooooooooooooooongFunction();\n" 17748 "int j = 2;", 17749 Alignment); 17750 17751 Alignment.AlignConsecutiveAssignments.Enabled = true; 17752 verifyFormat("auto lambda = []() {\n" 17753 " auto ii = 0;\n" 17754 " float j = 0;\n" 17755 " return 0;\n" 17756 "};\n" 17757 "int i = 0;\n" 17758 "float i2 = 0;\n" 17759 "auto v = type{\n" 17760 " i = 1, //\n" 17761 " (i = 2), //\n" 17762 " i = 3 //\n" 17763 "};", 17764 Alignment); 17765 Alignment.AlignConsecutiveAssignments.Enabled = false; 17766 17767 verifyFormat( 17768 "int i = 1;\n" 17769 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17770 " loooooooooooooooooooooongParameterB);\n" 17771 "int j = 2;", 17772 Alignment); 17773 17774 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17775 // We expect declarations and assignments to align, as long as it doesn't 17776 // exceed the column limit, starting a new alignment sequence whenever it 17777 // happens. 17778 Alignment.AlignConsecutiveAssignments.Enabled = true; 17779 Alignment.ColumnLimit = 30; 17780 verifyFormat("float ii = 1;\n" 17781 "unsigned j = 2;\n" 17782 "int someVerylongVariable = 1;\n" 17783 "AnotherLongType ll = 123456;\n" 17784 "VeryVeryLongType k = 2;\n" 17785 "int myvar = 1;", 17786 Alignment); 17787 Alignment.ColumnLimit = 80; 17788 Alignment.AlignConsecutiveAssignments.Enabled = false; 17789 17790 verifyFormat( 17791 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17792 " typename LongType, typename B>\n" 17793 "auto foo() {}\n", 17794 Alignment); 17795 verifyFormat("float a, b = 1;\n" 17796 "int c = 2;\n" 17797 "int dd = 3;\n", 17798 Alignment); 17799 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17800 "float b[1][] = {{3.f}};\n", 17801 Alignment); 17802 Alignment.AlignConsecutiveAssignments.Enabled = true; 17803 verifyFormat("float a, b = 1;\n" 17804 "int c = 2;\n" 17805 "int dd = 3;\n", 17806 Alignment); 17807 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17808 "float b[1][] = {{3.f}};\n", 17809 Alignment); 17810 Alignment.AlignConsecutiveAssignments.Enabled = false; 17811 17812 Alignment.ColumnLimit = 30; 17813 Alignment.BinPackParameters = false; 17814 verifyFormat("void foo(float a,\n" 17815 " float b,\n" 17816 " int c,\n" 17817 " uint32_t *d) {\n" 17818 " int *e = 0;\n" 17819 " float f = 0;\n" 17820 " double g = 0;\n" 17821 "}\n" 17822 "void bar(ino_t a,\n" 17823 " int b,\n" 17824 " uint32_t *c,\n" 17825 " bool d) {}\n", 17826 Alignment); 17827 Alignment.BinPackParameters = true; 17828 Alignment.ColumnLimit = 80; 17829 17830 // Bug 33507 17831 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17832 verifyFormat( 17833 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17834 " static const Version verVs2017;\n" 17835 " return true;\n" 17836 "});\n", 17837 Alignment); 17838 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17839 17840 // See llvm.org/PR35641 17841 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17842 verifyFormat("int func() { //\n" 17843 " int b;\n" 17844 " unsigned c;\n" 17845 "}", 17846 Alignment); 17847 17848 // See PR37175 17849 FormatStyle Style = getMozillaStyle(); 17850 Style.AlignConsecutiveDeclarations.Enabled = true; 17851 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17852 "foo(int a);", 17853 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17854 17855 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17856 verifyFormat("unsigned int* a;\n" 17857 "int* b;\n" 17858 "unsigned int Const* c;\n" 17859 "unsigned int const* d;\n" 17860 "unsigned int Const& e;\n" 17861 "unsigned int const& f;", 17862 Alignment); 17863 verifyFormat("Const unsigned int* c;\n" 17864 "const unsigned int* d;\n" 17865 "Const unsigned int& e;\n" 17866 "const unsigned int& f;\n" 17867 "const unsigned g;\n" 17868 "Const unsigned h;", 17869 Alignment); 17870 17871 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17872 verifyFormat("unsigned int * a;\n" 17873 "int * b;\n" 17874 "unsigned int Const * c;\n" 17875 "unsigned int const * d;\n" 17876 "unsigned int Const & e;\n" 17877 "unsigned int const & f;", 17878 Alignment); 17879 verifyFormat("Const unsigned int * c;\n" 17880 "const unsigned int * d;\n" 17881 "Const unsigned int & e;\n" 17882 "const unsigned int & f;\n" 17883 "const unsigned g;\n" 17884 "Const unsigned h;", 17885 Alignment); 17886 17887 // See PR46529 17888 FormatStyle BracedAlign = getLLVMStyle(); 17889 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 17890 verifyFormat("const auto result{[]() {\n" 17891 " const auto something = 1;\n" 17892 " return 2;\n" 17893 "}};", 17894 BracedAlign); 17895 verifyFormat("int foo{[]() {\n" 17896 " int bar{0};\n" 17897 " return 0;\n" 17898 "}()};", 17899 BracedAlign); 17900 BracedAlign.Cpp11BracedListStyle = false; 17901 verifyFormat("const auto result{ []() {\n" 17902 " const auto something = 1;\n" 17903 " return 2;\n" 17904 "} };", 17905 BracedAlign); 17906 verifyFormat("int foo{ []() {\n" 17907 " int bar{ 0 };\n" 17908 " return 0;\n" 17909 "}() };", 17910 BracedAlign); 17911 } 17912 17913 TEST_F(FormatTest, AlignWithLineBreaks) { 17914 auto Style = getLLVMStyleWithColumns(120); 17915 17916 EXPECT_EQ(Style.AlignConsecutiveAssignments, 17917 FormatStyle::AlignConsecutiveStyle( 17918 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 17919 /*AcrossComments=*/false, /*AlignCompound=*/false, 17920 /*PadOperators=*/true})); 17921 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 17922 FormatStyle::AlignConsecutiveStyle({})); 17923 verifyFormat("void foo() {\n" 17924 " int myVar = 5;\n" 17925 " double x = 3.14;\n" 17926 " auto str = \"Hello \"\n" 17927 " \"World\";\n" 17928 " auto s = \"Hello \"\n" 17929 " \"Again\";\n" 17930 "}", 17931 Style); 17932 17933 // clang-format off 17934 verifyFormat("void foo() {\n" 17935 " const int capacityBefore = Entries.capacity();\n" 17936 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17937 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17938 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17939 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17940 "}", 17941 Style); 17942 // clang-format on 17943 17944 Style.AlignConsecutiveAssignments.Enabled = true; 17945 verifyFormat("void foo() {\n" 17946 " int myVar = 5;\n" 17947 " double x = 3.14;\n" 17948 " auto str = \"Hello \"\n" 17949 " \"World\";\n" 17950 " auto s = \"Hello \"\n" 17951 " \"Again\";\n" 17952 "}", 17953 Style); 17954 17955 // clang-format off 17956 verifyFormat("void foo() {\n" 17957 " const int capacityBefore = Entries.capacity();\n" 17958 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17959 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17960 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17961 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17962 "}", 17963 Style); 17964 // clang-format on 17965 17966 Style.AlignConsecutiveAssignments.Enabled = false; 17967 Style.AlignConsecutiveDeclarations.Enabled = true; 17968 verifyFormat("void foo() {\n" 17969 " int myVar = 5;\n" 17970 " double x = 3.14;\n" 17971 " auto str = \"Hello \"\n" 17972 " \"World\";\n" 17973 " auto s = \"Hello \"\n" 17974 " \"Again\";\n" 17975 "}", 17976 Style); 17977 17978 // clang-format off 17979 verifyFormat("void foo() {\n" 17980 " const int capacityBefore = Entries.capacity();\n" 17981 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17982 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17983 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17984 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17985 "}", 17986 Style); 17987 // clang-format on 17988 17989 Style.AlignConsecutiveAssignments.Enabled = true; 17990 Style.AlignConsecutiveDeclarations.Enabled = true; 17991 17992 verifyFormat("void foo() {\n" 17993 " int myVar = 5;\n" 17994 " double x = 3.14;\n" 17995 " auto str = \"Hello \"\n" 17996 " \"World\";\n" 17997 " auto s = \"Hello \"\n" 17998 " \"Again\";\n" 17999 "}", 18000 Style); 18001 18002 // clang-format off 18003 verifyFormat("void foo() {\n" 18004 " const int capacityBefore = Entries.capacity();\n" 18005 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18006 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18007 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18008 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18009 "}", 18010 Style); 18011 // clang-format on 18012 18013 Style = getLLVMStyleWithColumns(120); 18014 Style.AlignConsecutiveAssignments.Enabled = true; 18015 Style.ContinuationIndentWidth = 4; 18016 Style.IndentWidth = 4; 18017 18018 // clang-format off 18019 verifyFormat("void SomeFunc() {\n" 18020 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18021 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18022 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18023 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18024 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18025 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18026 "}", 18027 Style); 18028 // clang-format on 18029 18030 Style.BinPackArguments = false; 18031 18032 // clang-format off 18033 verifyFormat("void SomeFunc() {\n" 18034 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 18035 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18036 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 18037 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18038 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 18039 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18040 "}", 18041 Style); 18042 // clang-format on 18043 } 18044 18045 TEST_F(FormatTest, AlignWithInitializerPeriods) { 18046 auto Style = getLLVMStyleWithColumns(60); 18047 18048 verifyFormat("void foo1(void) {\n" 18049 " BYTE p[1] = 1;\n" 18050 " A B = {.one_foooooooooooooooo = 2,\n" 18051 " .two_fooooooooooooo = 3,\n" 18052 " .three_fooooooooooooo = 4};\n" 18053 " BYTE payload = 2;\n" 18054 "}", 18055 Style); 18056 18057 Style.AlignConsecutiveAssignments.Enabled = true; 18058 Style.AlignConsecutiveDeclarations.Enabled = false; 18059 verifyFormat("void foo2(void) {\n" 18060 " BYTE p[1] = 1;\n" 18061 " A B = {.one_foooooooooooooooo = 2,\n" 18062 " .two_fooooooooooooo = 3,\n" 18063 " .three_fooooooooooooo = 4};\n" 18064 " BYTE payload = 2;\n" 18065 "}", 18066 Style); 18067 18068 Style.AlignConsecutiveAssignments.Enabled = false; 18069 Style.AlignConsecutiveDeclarations.Enabled = true; 18070 verifyFormat("void foo3(void) {\n" 18071 " BYTE p[1] = 1;\n" 18072 " A B = {.one_foooooooooooooooo = 2,\n" 18073 " .two_fooooooooooooo = 3,\n" 18074 " .three_fooooooooooooo = 4};\n" 18075 " BYTE payload = 2;\n" 18076 "}", 18077 Style); 18078 18079 Style.AlignConsecutiveAssignments.Enabled = true; 18080 Style.AlignConsecutiveDeclarations.Enabled = true; 18081 verifyFormat("void foo4(void) {\n" 18082 " BYTE p[1] = 1;\n" 18083 " A B = {.one_foooooooooooooooo = 2,\n" 18084 " .two_fooooooooooooo = 3,\n" 18085 " .three_fooooooooooooo = 4};\n" 18086 " BYTE payload = 2;\n" 18087 "}", 18088 Style); 18089 } 18090 18091 TEST_F(FormatTest, LinuxBraceBreaking) { 18092 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18093 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18094 verifyFormat("namespace a\n" 18095 "{\n" 18096 "class A\n" 18097 "{\n" 18098 " void f()\n" 18099 " {\n" 18100 " if (true) {\n" 18101 " a();\n" 18102 " b();\n" 18103 " } else {\n" 18104 " a();\n" 18105 " }\n" 18106 " }\n" 18107 " void g() { return; }\n" 18108 "};\n" 18109 "struct B {\n" 18110 " int x;\n" 18111 "};\n" 18112 "} // namespace a\n", 18113 LinuxBraceStyle); 18114 verifyFormat("enum X {\n" 18115 " Y = 0,\n" 18116 "}\n", 18117 LinuxBraceStyle); 18118 verifyFormat("struct S {\n" 18119 " int Type;\n" 18120 " union {\n" 18121 " int x;\n" 18122 " double y;\n" 18123 " } Value;\n" 18124 " class C\n" 18125 " {\n" 18126 " MyFavoriteType Value;\n" 18127 " } Class;\n" 18128 "}\n", 18129 LinuxBraceStyle); 18130 } 18131 18132 TEST_F(FormatTest, MozillaBraceBreaking) { 18133 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18134 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18135 MozillaBraceStyle.FixNamespaceComments = false; 18136 verifyFormat("namespace a {\n" 18137 "class A\n" 18138 "{\n" 18139 " void f()\n" 18140 " {\n" 18141 " if (true) {\n" 18142 " a();\n" 18143 " b();\n" 18144 " }\n" 18145 " }\n" 18146 " void g() { return; }\n" 18147 "};\n" 18148 "enum E\n" 18149 "{\n" 18150 " A,\n" 18151 " // foo\n" 18152 " B,\n" 18153 " C\n" 18154 "};\n" 18155 "struct B\n" 18156 "{\n" 18157 " int x;\n" 18158 "};\n" 18159 "}\n", 18160 MozillaBraceStyle); 18161 verifyFormat("struct S\n" 18162 "{\n" 18163 " int Type;\n" 18164 " union\n" 18165 " {\n" 18166 " int x;\n" 18167 " double y;\n" 18168 " } Value;\n" 18169 " class C\n" 18170 " {\n" 18171 " MyFavoriteType Value;\n" 18172 " } Class;\n" 18173 "}\n", 18174 MozillaBraceStyle); 18175 } 18176 18177 TEST_F(FormatTest, StroustrupBraceBreaking) { 18178 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18179 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18180 verifyFormat("namespace a {\n" 18181 "class A {\n" 18182 " void f()\n" 18183 " {\n" 18184 " if (true) {\n" 18185 " a();\n" 18186 " b();\n" 18187 " }\n" 18188 " }\n" 18189 " void g() { return; }\n" 18190 "};\n" 18191 "struct B {\n" 18192 " int x;\n" 18193 "};\n" 18194 "} // namespace a\n", 18195 StroustrupBraceStyle); 18196 18197 verifyFormat("void foo()\n" 18198 "{\n" 18199 " if (a) {\n" 18200 " a();\n" 18201 " }\n" 18202 " else {\n" 18203 " b();\n" 18204 " }\n" 18205 "}\n", 18206 StroustrupBraceStyle); 18207 18208 verifyFormat("#ifdef _DEBUG\n" 18209 "int foo(int i = 0)\n" 18210 "#else\n" 18211 "int foo(int i = 5)\n" 18212 "#endif\n" 18213 "{\n" 18214 " return i;\n" 18215 "}", 18216 StroustrupBraceStyle); 18217 18218 verifyFormat("void foo() {}\n" 18219 "void bar()\n" 18220 "#ifdef _DEBUG\n" 18221 "{\n" 18222 " foo();\n" 18223 "}\n" 18224 "#else\n" 18225 "{\n" 18226 "}\n" 18227 "#endif", 18228 StroustrupBraceStyle); 18229 18230 verifyFormat("void foobar() { int i = 5; }\n" 18231 "#ifdef _DEBUG\n" 18232 "void bar() {}\n" 18233 "#else\n" 18234 "void bar() { foobar(); }\n" 18235 "#endif", 18236 StroustrupBraceStyle); 18237 } 18238 18239 TEST_F(FormatTest, AllmanBraceBreaking) { 18240 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18241 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18242 18243 EXPECT_EQ("namespace a\n" 18244 "{\n" 18245 "void f();\n" 18246 "void g();\n" 18247 "} // namespace a\n", 18248 format("namespace a\n" 18249 "{\n" 18250 "void f();\n" 18251 "void g();\n" 18252 "}\n", 18253 AllmanBraceStyle)); 18254 18255 verifyFormat("namespace a\n" 18256 "{\n" 18257 "class A\n" 18258 "{\n" 18259 " void f()\n" 18260 " {\n" 18261 " if (true)\n" 18262 " {\n" 18263 " a();\n" 18264 " b();\n" 18265 " }\n" 18266 " }\n" 18267 " void g() { return; }\n" 18268 "};\n" 18269 "struct B\n" 18270 "{\n" 18271 " int x;\n" 18272 "};\n" 18273 "union C\n" 18274 "{\n" 18275 "};\n" 18276 "} // namespace a", 18277 AllmanBraceStyle); 18278 18279 verifyFormat("void f()\n" 18280 "{\n" 18281 " if (true)\n" 18282 " {\n" 18283 " a();\n" 18284 " }\n" 18285 " else if (false)\n" 18286 " {\n" 18287 " b();\n" 18288 " }\n" 18289 " else\n" 18290 " {\n" 18291 " c();\n" 18292 " }\n" 18293 "}\n", 18294 AllmanBraceStyle); 18295 18296 verifyFormat("void f()\n" 18297 "{\n" 18298 " for (int i = 0; i < 10; ++i)\n" 18299 " {\n" 18300 " a();\n" 18301 " }\n" 18302 " while (false)\n" 18303 " {\n" 18304 " b();\n" 18305 " }\n" 18306 " do\n" 18307 " {\n" 18308 " c();\n" 18309 " } while (false)\n" 18310 "}\n", 18311 AllmanBraceStyle); 18312 18313 verifyFormat("void f(int a)\n" 18314 "{\n" 18315 " switch (a)\n" 18316 " {\n" 18317 " case 0:\n" 18318 " break;\n" 18319 " case 1:\n" 18320 " {\n" 18321 " break;\n" 18322 " }\n" 18323 " case 2:\n" 18324 " {\n" 18325 " }\n" 18326 " break;\n" 18327 " default:\n" 18328 " break;\n" 18329 " }\n" 18330 "}\n", 18331 AllmanBraceStyle); 18332 18333 verifyFormat("enum X\n" 18334 "{\n" 18335 " Y = 0,\n" 18336 "}\n", 18337 AllmanBraceStyle); 18338 verifyFormat("enum X\n" 18339 "{\n" 18340 " Y = 0\n" 18341 "}\n", 18342 AllmanBraceStyle); 18343 18344 verifyFormat("@interface BSApplicationController ()\n" 18345 "{\n" 18346 "@private\n" 18347 " id _extraIvar;\n" 18348 "}\n" 18349 "@end\n", 18350 AllmanBraceStyle); 18351 18352 verifyFormat("#ifdef _DEBUG\n" 18353 "int foo(int i = 0)\n" 18354 "#else\n" 18355 "int foo(int i = 5)\n" 18356 "#endif\n" 18357 "{\n" 18358 " return i;\n" 18359 "}", 18360 AllmanBraceStyle); 18361 18362 verifyFormat("void foo() {}\n" 18363 "void bar()\n" 18364 "#ifdef _DEBUG\n" 18365 "{\n" 18366 " foo();\n" 18367 "}\n" 18368 "#else\n" 18369 "{\n" 18370 "}\n" 18371 "#endif", 18372 AllmanBraceStyle); 18373 18374 verifyFormat("void foobar() { int i = 5; }\n" 18375 "#ifdef _DEBUG\n" 18376 "void bar() {}\n" 18377 "#else\n" 18378 "void bar() { foobar(); }\n" 18379 "#endif", 18380 AllmanBraceStyle); 18381 18382 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18383 FormatStyle::SLS_All); 18384 18385 verifyFormat("[](int i) { return i + 2; };\n" 18386 "[](int i, int j)\n" 18387 "{\n" 18388 " auto x = i + j;\n" 18389 " auto y = i * j;\n" 18390 " return x ^ y;\n" 18391 "};\n" 18392 "void foo()\n" 18393 "{\n" 18394 " auto shortLambda = [](int i) { return i + 2; };\n" 18395 " auto longLambda = [](int i, int j)\n" 18396 " {\n" 18397 " auto x = i + j;\n" 18398 " auto y = i * j;\n" 18399 " return x ^ y;\n" 18400 " };\n" 18401 "}", 18402 AllmanBraceStyle); 18403 18404 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18405 18406 verifyFormat("[](int i)\n" 18407 "{\n" 18408 " return i + 2;\n" 18409 "};\n" 18410 "[](int i, int j)\n" 18411 "{\n" 18412 " auto x = i + j;\n" 18413 " auto y = i * j;\n" 18414 " return x ^ y;\n" 18415 "};\n" 18416 "void foo()\n" 18417 "{\n" 18418 " auto shortLambda = [](int i)\n" 18419 " {\n" 18420 " return i + 2;\n" 18421 " };\n" 18422 " auto longLambda = [](int i, int j)\n" 18423 " {\n" 18424 " auto x = i + j;\n" 18425 " auto y = i * j;\n" 18426 " return x ^ y;\n" 18427 " };\n" 18428 "}", 18429 AllmanBraceStyle); 18430 18431 // Reset 18432 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18433 18434 // This shouldn't affect ObjC blocks.. 18435 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18436 " // ...\n" 18437 " int i;\n" 18438 "}];", 18439 AllmanBraceStyle); 18440 verifyFormat("void (^block)(void) = ^{\n" 18441 " // ...\n" 18442 " int i;\n" 18443 "};", 18444 AllmanBraceStyle); 18445 // .. or dict literals. 18446 verifyFormat("void f()\n" 18447 "{\n" 18448 " // ...\n" 18449 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18450 "}", 18451 AllmanBraceStyle); 18452 verifyFormat("void f()\n" 18453 "{\n" 18454 " // ...\n" 18455 " [object someMethod:@{a : @\"b\"}];\n" 18456 "}", 18457 AllmanBraceStyle); 18458 verifyFormat("int f()\n" 18459 "{ // comment\n" 18460 " return 42;\n" 18461 "}", 18462 AllmanBraceStyle); 18463 18464 AllmanBraceStyle.ColumnLimit = 19; 18465 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18466 AllmanBraceStyle.ColumnLimit = 18; 18467 verifyFormat("void f()\n" 18468 "{\n" 18469 " int i;\n" 18470 "}", 18471 AllmanBraceStyle); 18472 AllmanBraceStyle.ColumnLimit = 80; 18473 18474 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18475 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18476 FormatStyle::SIS_WithoutElse; 18477 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18478 verifyFormat("void f(bool b)\n" 18479 "{\n" 18480 " if (b)\n" 18481 " {\n" 18482 " return;\n" 18483 " }\n" 18484 "}\n", 18485 BreakBeforeBraceShortIfs); 18486 verifyFormat("void f(bool b)\n" 18487 "{\n" 18488 " if constexpr (b)\n" 18489 " {\n" 18490 " return;\n" 18491 " }\n" 18492 "}\n", 18493 BreakBeforeBraceShortIfs); 18494 verifyFormat("void f(bool b)\n" 18495 "{\n" 18496 " if CONSTEXPR (b)\n" 18497 " {\n" 18498 " return;\n" 18499 " }\n" 18500 "}\n", 18501 BreakBeforeBraceShortIfs); 18502 verifyFormat("void f(bool b)\n" 18503 "{\n" 18504 " if (b) return;\n" 18505 "}\n", 18506 BreakBeforeBraceShortIfs); 18507 verifyFormat("void f(bool b)\n" 18508 "{\n" 18509 " if constexpr (b) return;\n" 18510 "}\n", 18511 BreakBeforeBraceShortIfs); 18512 verifyFormat("void f(bool b)\n" 18513 "{\n" 18514 " if CONSTEXPR (b) return;\n" 18515 "}\n", 18516 BreakBeforeBraceShortIfs); 18517 verifyFormat("void f(bool b)\n" 18518 "{\n" 18519 " while (b)\n" 18520 " {\n" 18521 " return;\n" 18522 " }\n" 18523 "}\n", 18524 BreakBeforeBraceShortIfs); 18525 } 18526 18527 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18528 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18529 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18530 18531 // Make a few changes to the style for testing purposes 18532 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18533 FormatStyle::SFS_Empty; 18534 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18535 18536 // FIXME: this test case can't decide whether there should be a blank line 18537 // after the ~D() line or not. It adds one if one doesn't exist in the test 18538 // and it removes the line if one exists. 18539 /* 18540 verifyFormat("class A;\n" 18541 "namespace B\n" 18542 " {\n" 18543 "class C;\n" 18544 "// Comment\n" 18545 "class D\n" 18546 " {\n" 18547 "public:\n" 18548 " D();\n" 18549 " ~D() {}\n" 18550 "private:\n" 18551 " enum E\n" 18552 " {\n" 18553 " F\n" 18554 " }\n" 18555 " };\n" 18556 " } // namespace B\n", 18557 WhitesmithsBraceStyle); 18558 */ 18559 18560 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18561 verifyFormat("namespace a\n" 18562 " {\n" 18563 "class A\n" 18564 " {\n" 18565 " void f()\n" 18566 " {\n" 18567 " if (true)\n" 18568 " {\n" 18569 " a();\n" 18570 " b();\n" 18571 " }\n" 18572 " }\n" 18573 " void g()\n" 18574 " {\n" 18575 " return;\n" 18576 " }\n" 18577 " };\n" 18578 "struct B\n" 18579 " {\n" 18580 " int x;\n" 18581 " };\n" 18582 " } // namespace a", 18583 WhitesmithsBraceStyle); 18584 18585 verifyFormat("namespace a\n" 18586 " {\n" 18587 "namespace b\n" 18588 " {\n" 18589 "class A\n" 18590 " {\n" 18591 " void f()\n" 18592 " {\n" 18593 " if (true)\n" 18594 " {\n" 18595 " a();\n" 18596 " b();\n" 18597 " }\n" 18598 " }\n" 18599 " void g()\n" 18600 " {\n" 18601 " return;\n" 18602 " }\n" 18603 " };\n" 18604 "struct B\n" 18605 " {\n" 18606 " int x;\n" 18607 " };\n" 18608 " } // namespace b\n" 18609 " } // namespace a", 18610 WhitesmithsBraceStyle); 18611 18612 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18613 verifyFormat("namespace a\n" 18614 " {\n" 18615 "namespace b\n" 18616 " {\n" 18617 " class A\n" 18618 " {\n" 18619 " void f()\n" 18620 " {\n" 18621 " if (true)\n" 18622 " {\n" 18623 " a();\n" 18624 " b();\n" 18625 " }\n" 18626 " }\n" 18627 " void g()\n" 18628 " {\n" 18629 " return;\n" 18630 " }\n" 18631 " };\n" 18632 " struct B\n" 18633 " {\n" 18634 " int x;\n" 18635 " };\n" 18636 " } // namespace b\n" 18637 " } // namespace a", 18638 WhitesmithsBraceStyle); 18639 18640 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18641 verifyFormat("namespace a\n" 18642 " {\n" 18643 " namespace b\n" 18644 " {\n" 18645 " class A\n" 18646 " {\n" 18647 " void f()\n" 18648 " {\n" 18649 " if (true)\n" 18650 " {\n" 18651 " a();\n" 18652 " b();\n" 18653 " }\n" 18654 " }\n" 18655 " void g()\n" 18656 " {\n" 18657 " return;\n" 18658 " }\n" 18659 " };\n" 18660 " struct B\n" 18661 " {\n" 18662 " int x;\n" 18663 " };\n" 18664 " } // namespace b\n" 18665 " } // namespace a", 18666 WhitesmithsBraceStyle); 18667 18668 verifyFormat("void f()\n" 18669 " {\n" 18670 " if (true)\n" 18671 " {\n" 18672 " a();\n" 18673 " }\n" 18674 " else if (false)\n" 18675 " {\n" 18676 " b();\n" 18677 " }\n" 18678 " else\n" 18679 " {\n" 18680 " c();\n" 18681 " }\n" 18682 " }\n", 18683 WhitesmithsBraceStyle); 18684 18685 verifyFormat("void f()\n" 18686 " {\n" 18687 " for (int i = 0; i < 10; ++i)\n" 18688 " {\n" 18689 " a();\n" 18690 " }\n" 18691 " while (false)\n" 18692 " {\n" 18693 " b();\n" 18694 " }\n" 18695 " do\n" 18696 " {\n" 18697 " c();\n" 18698 " } while (false)\n" 18699 " }\n", 18700 WhitesmithsBraceStyle); 18701 18702 WhitesmithsBraceStyle.IndentCaseLabels = true; 18703 verifyFormat("void switchTest1(int a)\n" 18704 " {\n" 18705 " switch (a)\n" 18706 " {\n" 18707 " case 2:\n" 18708 " {\n" 18709 " }\n" 18710 " break;\n" 18711 " }\n" 18712 " }\n", 18713 WhitesmithsBraceStyle); 18714 18715 verifyFormat("void switchTest2(int a)\n" 18716 " {\n" 18717 " switch (a)\n" 18718 " {\n" 18719 " case 0:\n" 18720 " break;\n" 18721 " case 1:\n" 18722 " {\n" 18723 " break;\n" 18724 " }\n" 18725 " case 2:\n" 18726 " {\n" 18727 " }\n" 18728 " break;\n" 18729 " default:\n" 18730 " break;\n" 18731 " }\n" 18732 " }\n", 18733 WhitesmithsBraceStyle); 18734 18735 verifyFormat("void switchTest3(int a)\n" 18736 " {\n" 18737 " switch (a)\n" 18738 " {\n" 18739 " case 0:\n" 18740 " {\n" 18741 " foo(x);\n" 18742 " }\n" 18743 " break;\n" 18744 " default:\n" 18745 " {\n" 18746 " foo(1);\n" 18747 " }\n" 18748 " break;\n" 18749 " }\n" 18750 " }\n", 18751 WhitesmithsBraceStyle); 18752 18753 WhitesmithsBraceStyle.IndentCaseLabels = false; 18754 18755 verifyFormat("void switchTest4(int a)\n" 18756 " {\n" 18757 " switch (a)\n" 18758 " {\n" 18759 " case 2:\n" 18760 " {\n" 18761 " }\n" 18762 " break;\n" 18763 " }\n" 18764 " }\n", 18765 WhitesmithsBraceStyle); 18766 18767 verifyFormat("void switchTest5(int a)\n" 18768 " {\n" 18769 " switch (a)\n" 18770 " {\n" 18771 " case 0:\n" 18772 " break;\n" 18773 " case 1:\n" 18774 " {\n" 18775 " foo();\n" 18776 " break;\n" 18777 " }\n" 18778 " case 2:\n" 18779 " {\n" 18780 " }\n" 18781 " break;\n" 18782 " default:\n" 18783 " break;\n" 18784 " }\n" 18785 " }\n", 18786 WhitesmithsBraceStyle); 18787 18788 verifyFormat("void switchTest6(int a)\n" 18789 " {\n" 18790 " switch (a)\n" 18791 " {\n" 18792 " case 0:\n" 18793 " {\n" 18794 " foo(x);\n" 18795 " }\n" 18796 " break;\n" 18797 " default:\n" 18798 " {\n" 18799 " foo(1);\n" 18800 " }\n" 18801 " break;\n" 18802 " }\n" 18803 " }\n", 18804 WhitesmithsBraceStyle); 18805 18806 verifyFormat("enum X\n" 18807 " {\n" 18808 " Y = 0, // testing\n" 18809 " }\n", 18810 WhitesmithsBraceStyle); 18811 18812 verifyFormat("enum X\n" 18813 " {\n" 18814 " Y = 0\n" 18815 " }\n", 18816 WhitesmithsBraceStyle); 18817 verifyFormat("enum X\n" 18818 " {\n" 18819 " Y = 0,\n" 18820 " Z = 1\n" 18821 " };\n", 18822 WhitesmithsBraceStyle); 18823 18824 verifyFormat("@interface BSApplicationController ()\n" 18825 " {\n" 18826 "@private\n" 18827 " id _extraIvar;\n" 18828 " }\n" 18829 "@end\n", 18830 WhitesmithsBraceStyle); 18831 18832 verifyFormat("#ifdef _DEBUG\n" 18833 "int foo(int i = 0)\n" 18834 "#else\n" 18835 "int foo(int i = 5)\n" 18836 "#endif\n" 18837 " {\n" 18838 " return i;\n" 18839 " }", 18840 WhitesmithsBraceStyle); 18841 18842 verifyFormat("void foo() {}\n" 18843 "void bar()\n" 18844 "#ifdef _DEBUG\n" 18845 " {\n" 18846 " foo();\n" 18847 " }\n" 18848 "#else\n" 18849 " {\n" 18850 " }\n" 18851 "#endif", 18852 WhitesmithsBraceStyle); 18853 18854 verifyFormat("void foobar()\n" 18855 " {\n" 18856 " int i = 5;\n" 18857 " }\n" 18858 "#ifdef _DEBUG\n" 18859 "void bar()\n" 18860 " {\n" 18861 " }\n" 18862 "#else\n" 18863 "void bar()\n" 18864 " {\n" 18865 " foobar();\n" 18866 " }\n" 18867 "#endif", 18868 WhitesmithsBraceStyle); 18869 18870 // This shouldn't affect ObjC blocks.. 18871 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18872 " // ...\n" 18873 " int i;\n" 18874 "}];", 18875 WhitesmithsBraceStyle); 18876 verifyFormat("void (^block)(void) = ^{\n" 18877 " // ...\n" 18878 " int i;\n" 18879 "};", 18880 WhitesmithsBraceStyle); 18881 // .. or dict literals. 18882 verifyFormat("void f()\n" 18883 " {\n" 18884 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18885 " }", 18886 WhitesmithsBraceStyle); 18887 18888 verifyFormat("int f()\n" 18889 " { // comment\n" 18890 " return 42;\n" 18891 " }", 18892 WhitesmithsBraceStyle); 18893 18894 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18895 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18896 FormatStyle::SIS_OnlyFirstIf; 18897 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18898 verifyFormat("void f(bool b)\n" 18899 " {\n" 18900 " if (b)\n" 18901 " {\n" 18902 " return;\n" 18903 " }\n" 18904 " }\n", 18905 BreakBeforeBraceShortIfs); 18906 verifyFormat("void f(bool b)\n" 18907 " {\n" 18908 " if (b) return;\n" 18909 " }\n", 18910 BreakBeforeBraceShortIfs); 18911 verifyFormat("void f(bool b)\n" 18912 " {\n" 18913 " while (b)\n" 18914 " {\n" 18915 " return;\n" 18916 " }\n" 18917 " }\n", 18918 BreakBeforeBraceShortIfs); 18919 } 18920 18921 TEST_F(FormatTest, GNUBraceBreaking) { 18922 FormatStyle GNUBraceStyle = getLLVMStyle(); 18923 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18924 verifyFormat("namespace a\n" 18925 "{\n" 18926 "class A\n" 18927 "{\n" 18928 " void f()\n" 18929 " {\n" 18930 " int a;\n" 18931 " {\n" 18932 " int b;\n" 18933 " }\n" 18934 " if (true)\n" 18935 " {\n" 18936 " a();\n" 18937 " b();\n" 18938 " }\n" 18939 " }\n" 18940 " void g() { return; }\n" 18941 "}\n" 18942 "} // namespace a", 18943 GNUBraceStyle); 18944 18945 verifyFormat("void f()\n" 18946 "{\n" 18947 " if (true)\n" 18948 " {\n" 18949 " a();\n" 18950 " }\n" 18951 " else if (false)\n" 18952 " {\n" 18953 " b();\n" 18954 " }\n" 18955 " else\n" 18956 " {\n" 18957 " c();\n" 18958 " }\n" 18959 "}\n", 18960 GNUBraceStyle); 18961 18962 verifyFormat("void f()\n" 18963 "{\n" 18964 " for (int i = 0; i < 10; ++i)\n" 18965 " {\n" 18966 " a();\n" 18967 " }\n" 18968 " while (false)\n" 18969 " {\n" 18970 " b();\n" 18971 " }\n" 18972 " do\n" 18973 " {\n" 18974 " c();\n" 18975 " }\n" 18976 " while (false);\n" 18977 "}\n", 18978 GNUBraceStyle); 18979 18980 verifyFormat("void f(int a)\n" 18981 "{\n" 18982 " switch (a)\n" 18983 " {\n" 18984 " case 0:\n" 18985 " break;\n" 18986 " case 1:\n" 18987 " {\n" 18988 " break;\n" 18989 " }\n" 18990 " case 2:\n" 18991 " {\n" 18992 " }\n" 18993 " break;\n" 18994 " default:\n" 18995 " break;\n" 18996 " }\n" 18997 "}\n", 18998 GNUBraceStyle); 18999 19000 verifyFormat("enum X\n" 19001 "{\n" 19002 " Y = 0,\n" 19003 "}\n", 19004 GNUBraceStyle); 19005 19006 verifyFormat("@interface BSApplicationController ()\n" 19007 "{\n" 19008 "@private\n" 19009 " id _extraIvar;\n" 19010 "}\n" 19011 "@end\n", 19012 GNUBraceStyle); 19013 19014 verifyFormat("#ifdef _DEBUG\n" 19015 "int foo(int i = 0)\n" 19016 "#else\n" 19017 "int foo(int i = 5)\n" 19018 "#endif\n" 19019 "{\n" 19020 " return i;\n" 19021 "}", 19022 GNUBraceStyle); 19023 19024 verifyFormat("void foo() {}\n" 19025 "void bar()\n" 19026 "#ifdef _DEBUG\n" 19027 "{\n" 19028 " foo();\n" 19029 "}\n" 19030 "#else\n" 19031 "{\n" 19032 "}\n" 19033 "#endif", 19034 GNUBraceStyle); 19035 19036 verifyFormat("void foobar() { int i = 5; }\n" 19037 "#ifdef _DEBUG\n" 19038 "void bar() {}\n" 19039 "#else\n" 19040 "void bar() { foobar(); }\n" 19041 "#endif", 19042 GNUBraceStyle); 19043 } 19044 19045 TEST_F(FormatTest, WebKitBraceBreaking) { 19046 FormatStyle WebKitBraceStyle = getLLVMStyle(); 19047 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 19048 WebKitBraceStyle.FixNamespaceComments = false; 19049 verifyFormat("namespace a {\n" 19050 "class A {\n" 19051 " void f()\n" 19052 " {\n" 19053 " if (true) {\n" 19054 " a();\n" 19055 " b();\n" 19056 " }\n" 19057 " }\n" 19058 " void g() { return; }\n" 19059 "};\n" 19060 "enum E {\n" 19061 " A,\n" 19062 " // foo\n" 19063 " B,\n" 19064 " C\n" 19065 "};\n" 19066 "struct B {\n" 19067 " int x;\n" 19068 "};\n" 19069 "}\n", 19070 WebKitBraceStyle); 19071 verifyFormat("struct S {\n" 19072 " int Type;\n" 19073 " union {\n" 19074 " int x;\n" 19075 " double y;\n" 19076 " } Value;\n" 19077 " class C {\n" 19078 " MyFavoriteType Value;\n" 19079 " } Class;\n" 19080 "};\n", 19081 WebKitBraceStyle); 19082 } 19083 19084 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19085 verifyFormat("void f() {\n" 19086 " try {\n" 19087 " } catch (const Exception &e) {\n" 19088 " }\n" 19089 "}\n", 19090 getLLVMStyle()); 19091 } 19092 19093 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19094 auto Style = getLLVMStyle(); 19095 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19096 Style.AlignConsecutiveAssignments.Enabled = true; 19097 Style.AlignConsecutiveDeclarations.Enabled = true; 19098 verifyFormat("struct test demo[] = {\n" 19099 " {56, 23, \"hello\"},\n" 19100 " {-1, 93463, \"world\"},\n" 19101 " { 7, 5, \"!!\"}\n" 19102 "};\n", 19103 Style); 19104 19105 verifyFormat("struct test demo[] = {\n" 19106 " {56, 23, \"hello\"}, // first line\n" 19107 " {-1, 93463, \"world\"}, // second line\n" 19108 " { 7, 5, \"!!\"} // third line\n" 19109 "};\n", 19110 Style); 19111 19112 verifyFormat("struct test demo[4] = {\n" 19113 " { 56, 23, 21, \"oh\"}, // first line\n" 19114 " { -1, 93463, 22, \"my\"}, // second line\n" 19115 " { 7, 5, 1, \"goodness\"} // third line\n" 19116 " {234, 5, 1, \"gracious\"} // fourth line\n" 19117 "};\n", 19118 Style); 19119 19120 verifyFormat("struct test demo[3] = {\n" 19121 " {56, 23, \"hello\"},\n" 19122 " {-1, 93463, \"world\"},\n" 19123 " { 7, 5, \"!!\"}\n" 19124 "};\n", 19125 Style); 19126 19127 verifyFormat("struct test demo[3] = {\n" 19128 " {int{56}, 23, \"hello\"},\n" 19129 " {int{-1}, 93463, \"world\"},\n" 19130 " { int{7}, 5, \"!!\"}\n" 19131 "};\n", 19132 Style); 19133 19134 verifyFormat("struct test demo[] = {\n" 19135 " {56, 23, \"hello\"},\n" 19136 " {-1, 93463, \"world\"},\n" 19137 " { 7, 5, \"!!\"},\n" 19138 "};\n", 19139 Style); 19140 19141 verifyFormat("test demo[] = {\n" 19142 " {56, 23, \"hello\"},\n" 19143 " {-1, 93463, \"world\"},\n" 19144 " { 7, 5, \"!!\"},\n" 19145 "};\n", 19146 Style); 19147 19148 verifyFormat("demo = std::array<struct test, 3>{\n" 19149 " test{56, 23, \"hello\"},\n" 19150 " test{-1, 93463, \"world\"},\n" 19151 " test{ 7, 5, \"!!\"},\n" 19152 "};\n", 19153 Style); 19154 19155 verifyFormat("test demo[] = {\n" 19156 " {56, 23, \"hello\"},\n" 19157 "#if X\n" 19158 " {-1, 93463, \"world\"},\n" 19159 "#endif\n" 19160 " { 7, 5, \"!!\"}\n" 19161 "};\n", 19162 Style); 19163 19164 verifyFormat( 19165 "test demo[] = {\n" 19166 " { 7, 23,\n" 19167 " \"hello world i am a very long line that really, in any\"\n" 19168 " \"just world, ought to be split over multiple lines\"},\n" 19169 " {-1, 93463, \"world\"},\n" 19170 " {56, 5, \"!!\"}\n" 19171 "};\n", 19172 Style); 19173 19174 verifyFormat("return GradForUnaryCwise(g, {\n" 19175 " {{\"sign\"}, \"Sign\", " 19176 " {\"x\", \"dy\"}},\n" 19177 " { {\"dx\"}, \"Mul\", {\"dy\"" 19178 ", \"sign\"}},\n" 19179 "});\n", 19180 Style); 19181 19182 Style.ColumnLimit = 0; 19183 EXPECT_EQ( 19184 "test demo[] = {\n" 19185 " {56, 23, \"hello world i am a very long line that really, " 19186 "in any just world, ought to be split over multiple lines\"},\n" 19187 " {-1, 93463, " 19188 " \"world\"},\n" 19189 " { 7, 5, " 19190 " \"!!\"},\n" 19191 "};", 19192 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19193 "that really, in any just world, ought to be split over multiple " 19194 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19195 Style)); 19196 19197 Style.ColumnLimit = 80; 19198 verifyFormat("test demo[] = {\n" 19199 " {56, 23, /* a comment */ \"hello\"},\n" 19200 " {-1, 93463, \"world\"},\n" 19201 " { 7, 5, \"!!\"}\n" 19202 "};\n", 19203 Style); 19204 19205 verifyFormat("test demo[] = {\n" 19206 " {56, 23, \"hello\"},\n" 19207 " {-1, 93463, \"world\" /* comment here */},\n" 19208 " { 7, 5, \"!!\"}\n" 19209 "};\n", 19210 Style); 19211 19212 verifyFormat("test demo[] = {\n" 19213 " {56, /* a comment */ 23, \"hello\"},\n" 19214 " {-1, 93463, \"world\"},\n" 19215 " { 7, 5, \"!!\"}\n" 19216 "};\n", 19217 Style); 19218 19219 Style.ColumnLimit = 20; 19220 EXPECT_EQ( 19221 "demo = std::array<\n" 19222 " struct test, 3>{\n" 19223 " test{\n" 19224 " 56, 23,\n" 19225 " \"hello \"\n" 19226 " \"world i \"\n" 19227 " \"am a very \"\n" 19228 " \"long line \"\n" 19229 " \"that \"\n" 19230 " \"really, \"\n" 19231 " \"in any \"\n" 19232 " \"just \"\n" 19233 " \"world, \"\n" 19234 " \"ought to \"\n" 19235 " \"be split \"\n" 19236 " \"over \"\n" 19237 " \"multiple \"\n" 19238 " \"lines\"},\n" 19239 " test{-1, 93463,\n" 19240 " \"world\"},\n" 19241 " test{ 7, 5,\n" 19242 " \"!!\" },\n" 19243 "};", 19244 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19245 "i am a very long line that really, in any just world, ought " 19246 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19247 "test{7, 5, \"!!\"},};", 19248 Style)); 19249 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19250 Style = getLLVMStyleWithColumns(50); 19251 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19252 verifyFormat("static A x = {\n" 19253 " {{init1, init2, init3, init4},\n" 19254 " {init1, init2, init3, init4}}\n" 19255 "};", 19256 Style); 19257 // TODO: Fix the indentations below when this option is fully functional. 19258 verifyFormat("int a[][] = {\n" 19259 " {\n" 19260 " {0, 2}, //\n" 19261 " {1, 2} //\n" 19262 " }\n" 19263 "};", 19264 Style); 19265 Style.ColumnLimit = 100; 19266 EXPECT_EQ( 19267 "test demo[] = {\n" 19268 " {56, 23,\n" 19269 " \"hello world i am a very long line that really, in any just world" 19270 ", ought to be split over \"\n" 19271 " \"multiple lines\" },\n" 19272 " {-1, 93463, \"world\"},\n" 19273 " { 7, 5, \"!!\"},\n" 19274 "};", 19275 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19276 "that really, in any just world, ought to be split over multiple " 19277 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19278 Style)); 19279 19280 Style = getLLVMStyleWithColumns(50); 19281 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19282 verifyFormat("struct test demo[] = {\n" 19283 " {56, 23, \"hello\"},\n" 19284 " {-1, 93463, \"world\"},\n" 19285 " { 7, 5, \"!!\"}\n" 19286 "};\n" 19287 "static A x = {\n" 19288 " {{init1, init2, init3, init4},\n" 19289 " {init1, init2, init3, init4}}\n" 19290 "};", 19291 Style); 19292 Style.ColumnLimit = 100; 19293 Style.AlignConsecutiveAssignments.AcrossComments = true; 19294 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19295 verifyFormat("struct test demo[] = {\n" 19296 " {56, 23, \"hello\"},\n" 19297 " {-1, 93463, \"world\"},\n" 19298 " { 7, 5, \"!!\"}\n" 19299 "};\n" 19300 "struct test demo[4] = {\n" 19301 " { 56, 23, 21, \"oh\"}, // first line\n" 19302 " { -1, 93463, 22, \"my\"}, // second line\n" 19303 " { 7, 5, 1, \"goodness\"} // third line\n" 19304 " {234, 5, 1, \"gracious\"} // fourth line\n" 19305 "};\n", 19306 Style); 19307 EXPECT_EQ( 19308 "test demo[] = {\n" 19309 " {56,\n" 19310 " \"hello world i am a very long line that really, in any just world" 19311 ", ought to be split over \"\n" 19312 " \"multiple lines\", 23},\n" 19313 " {-1, \"world\", 93463},\n" 19314 " { 7, \"!!\", 5},\n" 19315 "};", 19316 format("test demo[] = {{56, \"hello world i am a very long line " 19317 "that really, in any just world, ought to be split over multiple " 19318 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19319 Style)); 19320 } 19321 19322 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19323 auto Style = getLLVMStyle(); 19324 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19325 /* FIXME: This case gets misformatted. 19326 verifyFormat("auto foo = Items{\n" 19327 " Section{0, bar(), },\n" 19328 " Section{1, boo() }\n" 19329 "};\n", 19330 Style); 19331 */ 19332 verifyFormat("auto foo = Items{\n" 19333 " Section{\n" 19334 " 0, bar(),\n" 19335 " }\n" 19336 "};\n", 19337 Style); 19338 verifyFormat("struct test demo[] = {\n" 19339 " {56, 23, \"hello\"},\n" 19340 " {-1, 93463, \"world\"},\n" 19341 " {7, 5, \"!!\" }\n" 19342 "};\n", 19343 Style); 19344 verifyFormat("struct test demo[] = {\n" 19345 " {56, 23, \"hello\"}, // first line\n" 19346 " {-1, 93463, \"world\"}, // second line\n" 19347 " {7, 5, \"!!\" } // third line\n" 19348 "};\n", 19349 Style); 19350 verifyFormat("struct test demo[4] = {\n" 19351 " {56, 23, 21, \"oh\" }, // first line\n" 19352 " {-1, 93463, 22, \"my\" }, // second line\n" 19353 " {7, 5, 1, \"goodness\"} // third line\n" 19354 " {234, 5, 1, \"gracious\"} // fourth line\n" 19355 "};\n", 19356 Style); 19357 verifyFormat("struct test demo[3] = {\n" 19358 " {56, 23, \"hello\"},\n" 19359 " {-1, 93463, \"world\"},\n" 19360 " {7, 5, \"!!\" }\n" 19361 "};\n", 19362 Style); 19363 19364 verifyFormat("struct test demo[3] = {\n" 19365 " {int{56}, 23, \"hello\"},\n" 19366 " {int{-1}, 93463, \"world\"},\n" 19367 " {int{7}, 5, \"!!\" }\n" 19368 "};\n", 19369 Style); 19370 verifyFormat("struct test demo[] = {\n" 19371 " {56, 23, \"hello\"},\n" 19372 " {-1, 93463, \"world\"},\n" 19373 " {7, 5, \"!!\" },\n" 19374 "};\n", 19375 Style); 19376 verifyFormat("test demo[] = {\n" 19377 " {56, 23, \"hello\"},\n" 19378 " {-1, 93463, \"world\"},\n" 19379 " {7, 5, \"!!\" },\n" 19380 "};\n", 19381 Style); 19382 verifyFormat("demo = std::array<struct test, 3>{\n" 19383 " test{56, 23, \"hello\"},\n" 19384 " test{-1, 93463, \"world\"},\n" 19385 " test{7, 5, \"!!\" },\n" 19386 "};\n", 19387 Style); 19388 verifyFormat("test demo[] = {\n" 19389 " {56, 23, \"hello\"},\n" 19390 "#if X\n" 19391 " {-1, 93463, \"world\"},\n" 19392 "#endif\n" 19393 " {7, 5, \"!!\" }\n" 19394 "};\n", 19395 Style); 19396 verifyFormat( 19397 "test demo[] = {\n" 19398 " {7, 23,\n" 19399 " \"hello world i am a very long line that really, in any\"\n" 19400 " \"just world, ought to be split over multiple lines\"},\n" 19401 " {-1, 93463, \"world\" },\n" 19402 " {56, 5, \"!!\" }\n" 19403 "};\n", 19404 Style); 19405 19406 verifyFormat("return GradForUnaryCwise(g, {\n" 19407 " {{\"sign\"}, \"Sign\", {\"x\", " 19408 "\"dy\"} },\n" 19409 " {{\"dx\"}, \"Mul\", " 19410 "{\"dy\", \"sign\"}},\n" 19411 "});\n", 19412 Style); 19413 19414 Style.ColumnLimit = 0; 19415 EXPECT_EQ( 19416 "test demo[] = {\n" 19417 " {56, 23, \"hello world i am a very long line that really, in any " 19418 "just world, ought to be split over multiple lines\"},\n" 19419 " {-1, 93463, \"world\" " 19420 " },\n" 19421 " {7, 5, \"!!\" " 19422 " },\n" 19423 "};", 19424 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19425 "that really, in any just world, ought to be split over multiple " 19426 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19427 Style)); 19428 19429 Style.ColumnLimit = 80; 19430 verifyFormat("test demo[] = {\n" 19431 " {56, 23, /* a comment */ \"hello\"},\n" 19432 " {-1, 93463, \"world\" },\n" 19433 " {7, 5, \"!!\" }\n" 19434 "};\n", 19435 Style); 19436 19437 verifyFormat("test demo[] = {\n" 19438 " {56, 23, \"hello\" },\n" 19439 " {-1, 93463, \"world\" /* comment here */},\n" 19440 " {7, 5, \"!!\" }\n" 19441 "};\n", 19442 Style); 19443 19444 verifyFormat("test demo[] = {\n" 19445 " {56, /* a comment */ 23, \"hello\"},\n" 19446 " {-1, 93463, \"world\"},\n" 19447 " {7, 5, \"!!\" }\n" 19448 "};\n", 19449 Style); 19450 19451 Style.ColumnLimit = 20; 19452 EXPECT_EQ( 19453 "demo = std::array<\n" 19454 " struct test, 3>{\n" 19455 " test{\n" 19456 " 56, 23,\n" 19457 " \"hello \"\n" 19458 " \"world i \"\n" 19459 " \"am a very \"\n" 19460 " \"long line \"\n" 19461 " \"that \"\n" 19462 " \"really, \"\n" 19463 " \"in any \"\n" 19464 " \"just \"\n" 19465 " \"world, \"\n" 19466 " \"ought to \"\n" 19467 " \"be split \"\n" 19468 " \"over \"\n" 19469 " \"multiple \"\n" 19470 " \"lines\"},\n" 19471 " test{-1, 93463,\n" 19472 " \"world\"},\n" 19473 " test{7, 5,\n" 19474 " \"!!\" },\n" 19475 "};", 19476 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19477 "i am a very long line that really, in any just world, ought " 19478 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19479 "test{7, 5, \"!!\"},};", 19480 Style)); 19481 19482 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19483 Style = getLLVMStyleWithColumns(50); 19484 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19485 verifyFormat("static A x = {\n" 19486 " {{init1, init2, init3, init4},\n" 19487 " {init1, init2, init3, init4}}\n" 19488 "};", 19489 Style); 19490 Style.ColumnLimit = 100; 19491 EXPECT_EQ( 19492 "test demo[] = {\n" 19493 " {56, 23,\n" 19494 " \"hello world i am a very long line that really, in any just world" 19495 ", ought to be split over \"\n" 19496 " \"multiple lines\" },\n" 19497 " {-1, 93463, \"world\"},\n" 19498 " {7, 5, \"!!\" },\n" 19499 "};", 19500 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19501 "that really, in any just world, ought to be split over multiple " 19502 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19503 Style)); 19504 } 19505 19506 TEST_F(FormatTest, UnderstandsPragmas) { 19507 verifyFormat("#pragma omp reduction(| : var)"); 19508 verifyFormat("#pragma omp reduction(+ : var)"); 19509 19510 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19511 "(including parentheses).", 19512 format("#pragma mark Any non-hyphenated or hyphenated string " 19513 "(including parentheses).")); 19514 } 19515 19516 TEST_F(FormatTest, UnderstandPragmaOption) { 19517 verifyFormat("#pragma option -C -A"); 19518 19519 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19520 } 19521 19522 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19523 FormatStyle Style = getLLVMStyleWithColumns(20); 19524 19525 // See PR41213 19526 EXPECT_EQ("/*\n" 19527 " *\t9012345\n" 19528 " * /8901\n" 19529 " */", 19530 format("/*\n" 19531 " *\t9012345 /8901\n" 19532 " */", 19533 Style)); 19534 EXPECT_EQ("/*\n" 19535 " *345678\n" 19536 " *\t/8901\n" 19537 " */", 19538 format("/*\n" 19539 " *345678\t/8901\n" 19540 " */", 19541 Style)); 19542 19543 verifyFormat("int a; // the\n" 19544 " // comment", 19545 Style); 19546 EXPECT_EQ("int a; /* first line\n" 19547 " * second\n" 19548 " * line third\n" 19549 " * line\n" 19550 " */", 19551 format("int a; /* first line\n" 19552 " * second\n" 19553 " * line third\n" 19554 " * line\n" 19555 " */", 19556 Style)); 19557 EXPECT_EQ("int a; // first line\n" 19558 " // second\n" 19559 " // line third\n" 19560 " // line", 19561 format("int a; // first line\n" 19562 " // second line\n" 19563 " // third line", 19564 Style)); 19565 19566 Style.PenaltyExcessCharacter = 90; 19567 verifyFormat("int a; // the comment", Style); 19568 EXPECT_EQ("int a; // the comment\n" 19569 " // aaa", 19570 format("int a; // the comment aaa", Style)); 19571 EXPECT_EQ("int a; /* first line\n" 19572 " * second line\n" 19573 " * third line\n" 19574 " */", 19575 format("int a; /* first line\n" 19576 " * second line\n" 19577 " * third line\n" 19578 " */", 19579 Style)); 19580 EXPECT_EQ("int a; // first line\n" 19581 " // second line\n" 19582 " // third line", 19583 format("int a; // first line\n" 19584 " // second line\n" 19585 " // third line", 19586 Style)); 19587 // FIXME: Investigate why this is not getting the same layout as the test 19588 // above. 19589 EXPECT_EQ("int a; /* first line\n" 19590 " * second line\n" 19591 " * third line\n" 19592 " */", 19593 format("int a; /* first line second line third line" 19594 "\n*/", 19595 Style)); 19596 19597 EXPECT_EQ("// foo bar baz bazfoo\n" 19598 "// foo bar foo bar\n", 19599 format("// foo bar baz bazfoo\n" 19600 "// foo bar foo bar\n", 19601 Style)); 19602 EXPECT_EQ("// foo bar baz bazfoo\n" 19603 "// foo bar foo bar\n", 19604 format("// foo bar baz bazfoo\n" 19605 "// foo bar foo bar\n", 19606 Style)); 19607 19608 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19609 // next one. 19610 EXPECT_EQ("// foo bar baz bazfoo\n" 19611 "// bar foo bar\n", 19612 format("// foo bar baz bazfoo bar\n" 19613 "// foo bar\n", 19614 Style)); 19615 19616 EXPECT_EQ("// foo bar baz bazfoo\n" 19617 "// foo bar baz bazfoo\n" 19618 "// bar foo bar\n", 19619 format("// foo bar baz bazfoo\n" 19620 "// foo bar baz bazfoo bar\n" 19621 "// foo bar\n", 19622 Style)); 19623 19624 EXPECT_EQ("// foo bar baz bazfoo\n" 19625 "// foo bar baz bazfoo\n" 19626 "// bar foo bar\n", 19627 format("// foo bar baz bazfoo\n" 19628 "// foo bar baz bazfoo bar\n" 19629 "// foo bar\n", 19630 Style)); 19631 19632 // Make sure we do not keep protruding characters if strict mode reflow is 19633 // cheaper than keeping protruding characters. 19634 Style.ColumnLimit = 21; 19635 EXPECT_EQ( 19636 "// foo foo foo foo\n" 19637 "// foo foo foo foo\n" 19638 "// foo foo foo foo\n", 19639 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19640 19641 EXPECT_EQ("int a = /* long block\n" 19642 " comment */\n" 19643 " 42;", 19644 format("int a = /* long block comment */ 42;", Style)); 19645 } 19646 19647 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19648 FormatStyle Style = getLLVMStyle(); 19649 Style.ColumnLimit = 8; 19650 Style.PenaltyExcessCharacter = 15; 19651 verifyFormat("int foo(\n" 19652 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19653 Style); 19654 Style.PenaltyBreakOpenParenthesis = 200; 19655 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19656 format("int foo(\n" 19657 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19658 Style)); 19659 } 19660 19661 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19662 FormatStyle Style = getLLVMStyle(); 19663 Style.ColumnLimit = 5; 19664 Style.PenaltyExcessCharacter = 150; 19665 verifyFormat("foo((\n" 19666 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19667 19668 Style); 19669 Style.PenaltyBreakOpenParenthesis = 100000; 19670 EXPECT_EQ("foo((int)\n" 19671 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19672 format("foo((\n" 19673 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19674 Style)); 19675 } 19676 19677 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19678 FormatStyle Style = getLLVMStyle(); 19679 Style.ColumnLimit = 4; 19680 Style.PenaltyExcessCharacter = 100; 19681 verifyFormat("for (\n" 19682 " int iiiiiiiiiiiiiiiii =\n" 19683 " 0;\n" 19684 " iiiiiiiiiiiiiiiii <\n" 19685 " 2;\n" 19686 " iiiiiiiiiiiiiiiii++) {\n" 19687 "}", 19688 19689 Style); 19690 Style.PenaltyBreakOpenParenthesis = 1250; 19691 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19692 " 0;\n" 19693 " iiiiiiiiiiiiiiiii <\n" 19694 " 2;\n" 19695 " iiiiiiiiiiiiiiiii++) {\n" 19696 "}", 19697 format("for (\n" 19698 " int iiiiiiiiiiiiiiiii =\n" 19699 " 0;\n" 19700 " iiiiiiiiiiiiiiiii <\n" 19701 " 2;\n" 19702 " iiiiiiiiiiiiiiiii++) {\n" 19703 "}", 19704 Style)); 19705 } 19706 19707 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19708 for (size_t i = 1; i < Styles.size(); ++i) \ 19709 EXPECT_EQ(Styles[0], Styles[i]) \ 19710 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19711 19712 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19713 SmallVector<FormatStyle, 3> Styles; 19714 Styles.resize(3); 19715 19716 Styles[0] = getLLVMStyle(); 19717 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19718 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19719 EXPECT_ALL_STYLES_EQUAL(Styles); 19720 19721 Styles[0] = getGoogleStyle(); 19722 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19723 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19724 EXPECT_ALL_STYLES_EQUAL(Styles); 19725 19726 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19727 EXPECT_TRUE( 19728 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19729 EXPECT_TRUE( 19730 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19731 EXPECT_ALL_STYLES_EQUAL(Styles); 19732 19733 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19734 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19735 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19736 EXPECT_ALL_STYLES_EQUAL(Styles); 19737 19738 Styles[0] = getMozillaStyle(); 19739 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19740 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19741 EXPECT_ALL_STYLES_EQUAL(Styles); 19742 19743 Styles[0] = getWebKitStyle(); 19744 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19745 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19746 EXPECT_ALL_STYLES_EQUAL(Styles); 19747 19748 Styles[0] = getGNUStyle(); 19749 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19750 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19751 EXPECT_ALL_STYLES_EQUAL(Styles); 19752 19753 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19754 } 19755 19756 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19757 SmallVector<FormatStyle, 8> Styles; 19758 Styles.resize(2); 19759 19760 Styles[0] = getGoogleStyle(); 19761 Styles[1] = getLLVMStyle(); 19762 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19763 EXPECT_ALL_STYLES_EQUAL(Styles); 19764 19765 Styles.resize(5); 19766 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19767 Styles[1] = getLLVMStyle(); 19768 Styles[1].Language = FormatStyle::LK_JavaScript; 19769 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19770 19771 Styles[2] = getLLVMStyle(); 19772 Styles[2].Language = FormatStyle::LK_JavaScript; 19773 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19774 "BasedOnStyle: Google", 19775 &Styles[2]) 19776 .value()); 19777 19778 Styles[3] = getLLVMStyle(); 19779 Styles[3].Language = FormatStyle::LK_JavaScript; 19780 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19781 "Language: JavaScript", 19782 &Styles[3]) 19783 .value()); 19784 19785 Styles[4] = getLLVMStyle(); 19786 Styles[4].Language = FormatStyle::LK_JavaScript; 19787 EXPECT_EQ(0, parseConfiguration("---\n" 19788 "BasedOnStyle: LLVM\n" 19789 "IndentWidth: 123\n" 19790 "---\n" 19791 "BasedOnStyle: Google\n" 19792 "Language: JavaScript", 19793 &Styles[4]) 19794 .value()); 19795 EXPECT_ALL_STYLES_EQUAL(Styles); 19796 } 19797 19798 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19799 Style.FIELD = false; \ 19800 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19801 EXPECT_TRUE(Style.FIELD); \ 19802 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19803 EXPECT_FALSE(Style.FIELD); 19804 19805 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19806 19807 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19808 Style.STRUCT.FIELD = false; \ 19809 EXPECT_EQ(0, \ 19810 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19811 .value()); \ 19812 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19813 EXPECT_EQ(0, \ 19814 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19815 .value()); \ 19816 EXPECT_FALSE(Style.STRUCT.FIELD); 19817 19818 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19819 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19820 19821 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19822 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19823 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19824 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19825 19826 TEST_F(FormatTest, ParsesConfigurationBools) { 19827 FormatStyle Style = {}; 19828 Style.Language = FormatStyle::LK_Cpp; 19829 CHECK_PARSE_BOOL(AlignTrailingComments); 19830 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19831 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19832 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19833 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19834 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19835 CHECK_PARSE_BOOL(BinPackArguments); 19836 CHECK_PARSE_BOOL(BinPackParameters); 19837 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19838 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19839 CHECK_PARSE_BOOL(BreakStringLiterals); 19840 CHECK_PARSE_BOOL(CompactNamespaces); 19841 CHECK_PARSE_BOOL(DeriveLineEnding); 19842 CHECK_PARSE_BOOL(DerivePointerAlignment); 19843 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19844 CHECK_PARSE_BOOL(DisableFormat); 19845 CHECK_PARSE_BOOL(IndentAccessModifiers); 19846 CHECK_PARSE_BOOL(IndentCaseLabels); 19847 CHECK_PARSE_BOOL(IndentCaseBlocks); 19848 CHECK_PARSE_BOOL(IndentGotoLabels); 19849 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19850 CHECK_PARSE_BOOL(IndentRequiresClause); 19851 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19852 CHECK_PARSE_BOOL(InsertBraces); 19853 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19854 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19855 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19856 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19857 CHECK_PARSE_BOOL(ReflowComments); 19858 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19859 CHECK_PARSE_BOOL(SortUsingDeclarations); 19860 CHECK_PARSE_BOOL(SpacesInParentheses); 19861 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19862 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19863 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19864 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19865 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19866 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19867 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19868 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19869 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19870 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19871 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19872 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19873 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19874 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19875 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19876 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19877 CHECK_PARSE_BOOL(UseCRLF); 19878 19879 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19880 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19881 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19882 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19883 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19884 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19885 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19886 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19887 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19888 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19889 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19890 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19891 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19892 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19893 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19894 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19895 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19896 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19897 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19898 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19899 AfterFunctionDeclarationName); 19900 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19901 AfterFunctionDefinitionName); 19902 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19903 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19904 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19905 } 19906 19907 #undef CHECK_PARSE_BOOL 19908 19909 TEST_F(FormatTest, ParsesConfiguration) { 19910 FormatStyle Style = {}; 19911 Style.Language = FormatStyle::LK_Cpp; 19912 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19913 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19914 ConstructorInitializerIndentWidth, 1234u); 19915 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19916 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19917 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19918 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19919 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19920 PenaltyBreakBeforeFirstCallParameter, 1234u); 19921 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19922 PenaltyBreakTemplateDeclaration, 1234u); 19923 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19924 1234u); 19925 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19926 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19927 PenaltyReturnTypeOnItsOwnLine, 1234u); 19928 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19929 SpacesBeforeTrailingComments, 1234u); 19930 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19931 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19932 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19933 19934 Style.QualifierAlignment = FormatStyle::QAS_Right; 19935 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19936 FormatStyle::QAS_Leave); 19937 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19938 FormatStyle::QAS_Right); 19939 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19940 FormatStyle::QAS_Left); 19941 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19942 FormatStyle::QAS_Custom); 19943 19944 Style.QualifierOrder.clear(); 19945 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19946 std::vector<std::string>({"const", "volatile", "type"})); 19947 Style.QualifierOrder.clear(); 19948 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19949 std::vector<std::string>({"const", "type"})); 19950 Style.QualifierOrder.clear(); 19951 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19952 std::vector<std::string>({"volatile", "type"})); 19953 19954 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 19955 do { \ 19956 Style.FIELD.Enabled = true; \ 19957 CHECK_PARSE(#FIELD ": None", FIELD, \ 19958 FormatStyle::AlignConsecutiveStyle( \ 19959 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19960 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19961 /*PadOperators=*/true})); \ 19962 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 19963 FormatStyle::AlignConsecutiveStyle( \ 19964 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19965 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19966 /*PadOperators=*/true})); \ 19967 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 19968 FormatStyle::AlignConsecutiveStyle( \ 19969 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19970 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19971 /*PadOperators=*/true})); \ 19972 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 19973 FormatStyle::AlignConsecutiveStyle( \ 19974 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19975 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 19976 /*PadOperators=*/true})); \ 19977 /* For backwards compability, false / true should still parse */ \ 19978 CHECK_PARSE(#FIELD ": false", FIELD, \ 19979 FormatStyle::AlignConsecutiveStyle( \ 19980 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19981 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19982 /*PadOperators=*/true})); \ 19983 CHECK_PARSE(#FIELD ": true", FIELD, \ 19984 FormatStyle::AlignConsecutiveStyle( \ 19985 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19986 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19987 /*PadOperators=*/true})); \ 19988 \ 19989 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 19990 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 19991 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 19992 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 19993 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 19994 } while (false) 19995 19996 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 19997 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 19998 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 19999 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 20000 20001 #undef CHECK_ALIGN_CONSECUTIVE 20002 20003 Style.PointerAlignment = FormatStyle::PAS_Middle; 20004 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 20005 FormatStyle::PAS_Left); 20006 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 20007 FormatStyle::PAS_Right); 20008 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 20009 FormatStyle::PAS_Middle); 20010 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 20011 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 20012 FormatStyle::RAS_Pointer); 20013 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 20014 FormatStyle::RAS_Left); 20015 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 20016 FormatStyle::RAS_Right); 20017 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 20018 FormatStyle::RAS_Middle); 20019 // For backward compatibility: 20020 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 20021 FormatStyle::PAS_Left); 20022 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 20023 FormatStyle::PAS_Right); 20024 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 20025 FormatStyle::PAS_Middle); 20026 20027 Style.Standard = FormatStyle::LS_Auto; 20028 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 20029 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 20030 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 20031 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 20032 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 20033 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 20034 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 20035 // Legacy aliases: 20036 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 20037 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 20038 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 20039 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 20040 20041 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 20042 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 20043 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 20044 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 20045 FormatStyle::BOS_None); 20046 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 20047 FormatStyle::BOS_All); 20048 // For backward compatibility: 20049 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 20050 FormatStyle::BOS_None); 20051 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 20052 FormatStyle::BOS_All); 20053 20054 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20055 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20056 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20057 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20058 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20059 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20060 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20061 // For backward compatibility: 20062 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20063 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20064 20065 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20066 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20067 FormatStyle::BILS_AfterComma); 20068 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20069 FormatStyle::BILS_BeforeComma); 20070 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20071 FormatStyle::BILS_AfterColon); 20072 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20073 FormatStyle::BILS_BeforeColon); 20074 // For backward compatibility: 20075 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20076 FormatStyle::BILS_BeforeComma); 20077 20078 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20079 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20080 FormatStyle::PCIS_Never); 20081 CHECK_PARSE("PackConstructorInitializers: BinPack", 20082 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20083 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20084 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20085 CHECK_PARSE("PackConstructorInitializers: NextLine", 20086 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20087 // For backward compatibility: 20088 CHECK_PARSE("BasedOnStyle: Google\n" 20089 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20090 "AllowAllConstructorInitializersOnNextLine: false", 20091 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20092 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20093 CHECK_PARSE("BasedOnStyle: Google\n" 20094 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20095 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20096 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20097 "AllowAllConstructorInitializersOnNextLine: true", 20098 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20099 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20100 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20101 "AllowAllConstructorInitializersOnNextLine: false", 20102 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20103 20104 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20105 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20106 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20107 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20108 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20109 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20110 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20111 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20112 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20113 20114 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20115 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20116 FormatStyle::BAS_Align); 20117 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20118 FormatStyle::BAS_DontAlign); 20119 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20120 FormatStyle::BAS_AlwaysBreak); 20121 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20122 FormatStyle::BAS_BlockIndent); 20123 // For backward compatibility: 20124 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20125 FormatStyle::BAS_DontAlign); 20126 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20127 FormatStyle::BAS_Align); 20128 20129 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20130 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20131 FormatStyle::ENAS_DontAlign); 20132 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20133 FormatStyle::ENAS_Left); 20134 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20135 FormatStyle::ENAS_Right); 20136 // For backward compatibility: 20137 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20138 FormatStyle::ENAS_Left); 20139 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20140 FormatStyle::ENAS_Right); 20141 20142 Style.AlignOperands = FormatStyle::OAS_Align; 20143 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20144 FormatStyle::OAS_DontAlign); 20145 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20146 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20147 FormatStyle::OAS_AlignAfterOperator); 20148 // For backward compatibility: 20149 CHECK_PARSE("AlignOperands: false", AlignOperands, 20150 FormatStyle::OAS_DontAlign); 20151 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20152 20153 Style.UseTab = FormatStyle::UT_ForIndentation; 20154 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20155 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20156 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20157 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20158 FormatStyle::UT_ForContinuationAndIndentation); 20159 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20160 FormatStyle::UT_AlignWithSpaces); 20161 // For backward compatibility: 20162 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20163 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20164 20165 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20166 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20167 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20168 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20169 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20170 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20171 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20172 // For backward compatibility: 20173 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20174 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20175 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20176 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20177 20178 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20179 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20180 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20181 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20182 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20183 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20184 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20185 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20186 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20187 // For backward compatibility: 20188 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20189 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20190 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20191 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20192 20193 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20194 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20195 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20196 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20197 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20198 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20199 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20200 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20201 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20202 20203 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20204 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20205 FormatStyle::SBPO_Never); 20206 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20207 FormatStyle::SBPO_Always); 20208 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20209 FormatStyle::SBPO_ControlStatements); 20210 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20211 SpaceBeforeParens, 20212 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20213 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20214 FormatStyle::SBPO_NonEmptyParentheses); 20215 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20216 FormatStyle::SBPO_Custom); 20217 // For backward compatibility: 20218 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20219 FormatStyle::SBPO_Never); 20220 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20221 FormatStyle::SBPO_ControlStatements); 20222 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20223 SpaceBeforeParens, 20224 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20225 20226 Style.ColumnLimit = 123; 20227 FormatStyle BaseStyle = getLLVMStyle(); 20228 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20229 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20230 20231 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20232 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20233 FormatStyle::BS_Attach); 20234 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20235 FormatStyle::BS_Linux); 20236 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20237 FormatStyle::BS_Mozilla); 20238 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20239 FormatStyle::BS_Stroustrup); 20240 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20241 FormatStyle::BS_Allman); 20242 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20243 FormatStyle::BS_Whitesmiths); 20244 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20245 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20246 FormatStyle::BS_WebKit); 20247 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20248 FormatStyle::BS_Custom); 20249 20250 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20251 CHECK_PARSE("BraceWrapping:\n" 20252 " AfterControlStatement: MultiLine", 20253 BraceWrapping.AfterControlStatement, 20254 FormatStyle::BWACS_MultiLine); 20255 CHECK_PARSE("BraceWrapping:\n" 20256 " AfterControlStatement: Always", 20257 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20258 CHECK_PARSE("BraceWrapping:\n" 20259 " AfterControlStatement: Never", 20260 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20261 // For backward compatibility: 20262 CHECK_PARSE("BraceWrapping:\n" 20263 " AfterControlStatement: true", 20264 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20265 CHECK_PARSE("BraceWrapping:\n" 20266 " AfterControlStatement: false", 20267 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20268 20269 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20270 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20271 FormatStyle::RTBS_None); 20272 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20273 FormatStyle::RTBS_All); 20274 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20275 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20276 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20277 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20278 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20279 AlwaysBreakAfterReturnType, 20280 FormatStyle::RTBS_TopLevelDefinitions); 20281 20282 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20283 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20284 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20285 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20286 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20287 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20288 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20289 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20290 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20291 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20292 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20293 20294 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20295 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20296 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20297 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20298 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20299 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20300 AlwaysBreakAfterDefinitionReturnType, 20301 FormatStyle::DRTBS_TopLevel); 20302 20303 Style.NamespaceIndentation = FormatStyle::NI_All; 20304 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20305 FormatStyle::NI_None); 20306 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20307 FormatStyle::NI_Inner); 20308 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20309 FormatStyle::NI_All); 20310 20311 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20312 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20313 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20314 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20315 AllowShortIfStatementsOnASingleLine, 20316 FormatStyle::SIS_WithoutElse); 20317 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20318 AllowShortIfStatementsOnASingleLine, 20319 FormatStyle::SIS_OnlyFirstIf); 20320 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20321 AllowShortIfStatementsOnASingleLine, 20322 FormatStyle::SIS_AllIfsAndElse); 20323 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20324 AllowShortIfStatementsOnASingleLine, 20325 FormatStyle::SIS_OnlyFirstIf); 20326 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20327 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20328 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20329 AllowShortIfStatementsOnASingleLine, 20330 FormatStyle::SIS_WithoutElse); 20331 20332 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20333 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20334 FormatStyle::IEBS_AfterExternBlock); 20335 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20336 FormatStyle::IEBS_Indent); 20337 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20338 FormatStyle::IEBS_NoIndent); 20339 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20340 FormatStyle::IEBS_Indent); 20341 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20342 FormatStyle::IEBS_NoIndent); 20343 20344 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20345 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20346 FormatStyle::BFCS_Both); 20347 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20348 FormatStyle::BFCS_None); 20349 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20350 FormatStyle::BFCS_Before); 20351 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20352 FormatStyle::BFCS_After); 20353 20354 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20355 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20356 FormatStyle::SJSIO_After); 20357 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20358 FormatStyle::SJSIO_Before); 20359 20360 // FIXME: This is required because parsing a configuration simply overwrites 20361 // the first N elements of the list instead of resetting it. 20362 Style.ForEachMacros.clear(); 20363 std::vector<std::string> BoostForeach; 20364 BoostForeach.push_back("BOOST_FOREACH"); 20365 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20366 std::vector<std::string> BoostAndQForeach; 20367 BoostAndQForeach.push_back("BOOST_FOREACH"); 20368 BoostAndQForeach.push_back("Q_FOREACH"); 20369 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20370 BoostAndQForeach); 20371 20372 Style.IfMacros.clear(); 20373 std::vector<std::string> CustomIfs; 20374 CustomIfs.push_back("MYIF"); 20375 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20376 20377 Style.AttributeMacros.clear(); 20378 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20379 std::vector<std::string>{"__capability"}); 20380 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20381 std::vector<std::string>({"attr1", "attr2"})); 20382 20383 Style.StatementAttributeLikeMacros.clear(); 20384 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20385 StatementAttributeLikeMacros, 20386 std::vector<std::string>({"emit", "Q_EMIT"})); 20387 20388 Style.StatementMacros.clear(); 20389 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20390 std::vector<std::string>{"QUNUSED"}); 20391 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20392 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20393 20394 Style.NamespaceMacros.clear(); 20395 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20396 std::vector<std::string>{"TESTSUITE"}); 20397 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20398 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20399 20400 Style.WhitespaceSensitiveMacros.clear(); 20401 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20402 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20403 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20404 WhitespaceSensitiveMacros, 20405 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20406 Style.WhitespaceSensitiveMacros.clear(); 20407 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20408 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20409 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20410 WhitespaceSensitiveMacros, 20411 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20412 20413 Style.IncludeStyle.IncludeCategories.clear(); 20414 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20415 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20416 CHECK_PARSE("IncludeCategories:\n" 20417 " - Regex: abc/.*\n" 20418 " Priority: 2\n" 20419 " - Regex: .*\n" 20420 " Priority: 1\n" 20421 " CaseSensitive: true\n", 20422 IncludeStyle.IncludeCategories, ExpectedCategories); 20423 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20424 "abc$"); 20425 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20426 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20427 20428 Style.SortIncludes = FormatStyle::SI_Never; 20429 CHECK_PARSE("SortIncludes: true", SortIncludes, 20430 FormatStyle::SI_CaseSensitive); 20431 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20432 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20433 FormatStyle::SI_CaseInsensitive); 20434 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20435 FormatStyle::SI_CaseSensitive); 20436 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20437 20438 Style.RawStringFormats.clear(); 20439 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20440 { 20441 FormatStyle::LK_TextProto, 20442 {"pb", "proto"}, 20443 {"PARSE_TEXT_PROTO"}, 20444 /*CanonicalDelimiter=*/"", 20445 "llvm", 20446 }, 20447 { 20448 FormatStyle::LK_Cpp, 20449 {"cc", "cpp"}, 20450 {"C_CODEBLOCK", "CPPEVAL"}, 20451 /*CanonicalDelimiter=*/"cc", 20452 /*BasedOnStyle=*/"", 20453 }, 20454 }; 20455 20456 CHECK_PARSE("RawStringFormats:\n" 20457 " - Language: TextProto\n" 20458 " Delimiters:\n" 20459 " - 'pb'\n" 20460 " - 'proto'\n" 20461 " EnclosingFunctions:\n" 20462 " - 'PARSE_TEXT_PROTO'\n" 20463 " BasedOnStyle: llvm\n" 20464 " - Language: Cpp\n" 20465 " Delimiters:\n" 20466 " - 'cc'\n" 20467 " - 'cpp'\n" 20468 " EnclosingFunctions:\n" 20469 " - 'C_CODEBLOCK'\n" 20470 " - 'CPPEVAL'\n" 20471 " CanonicalDelimiter: 'cc'", 20472 RawStringFormats, ExpectedRawStringFormats); 20473 20474 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20475 " Minimum: 0\n" 20476 " Maximum: 0", 20477 SpacesInLineCommentPrefix.Minimum, 0u); 20478 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20479 Style.SpacesInLineCommentPrefix.Minimum = 1; 20480 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20481 " Minimum: 2", 20482 SpacesInLineCommentPrefix.Minimum, 0u); 20483 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20484 " Maximum: -1", 20485 SpacesInLineCommentPrefix.Maximum, -1u); 20486 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20487 " Minimum: 2", 20488 SpacesInLineCommentPrefix.Minimum, 2u); 20489 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20490 " Maximum: 1", 20491 SpacesInLineCommentPrefix.Maximum, 1u); 20492 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20493 20494 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20495 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20496 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20497 FormatStyle::SIAS_Always); 20498 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20499 // For backward compatibility: 20500 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20501 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20502 20503 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20504 FormatStyle::RCPS_WithPreceding); 20505 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20506 FormatStyle::RCPS_WithFollowing); 20507 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20508 FormatStyle::RCPS_SingleLine); 20509 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20510 FormatStyle::RCPS_OwnLine); 20511 20512 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20513 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20514 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20515 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20516 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20517 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20518 // For backward compatibility: 20519 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20520 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20521 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20522 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20523 } 20524 20525 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20526 FormatStyle Style = {}; 20527 Style.Language = FormatStyle::LK_Cpp; 20528 CHECK_PARSE("Language: Cpp\n" 20529 "IndentWidth: 12", 20530 IndentWidth, 12u); 20531 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20532 "IndentWidth: 34", 20533 &Style), 20534 ParseError::Unsuitable); 20535 FormatStyle BinPackedTCS = {}; 20536 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20537 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20538 "InsertTrailingCommas: Wrapped", 20539 &BinPackedTCS), 20540 ParseError::BinPackTrailingCommaConflict); 20541 EXPECT_EQ(12u, Style.IndentWidth); 20542 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20543 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20544 20545 Style.Language = FormatStyle::LK_JavaScript; 20546 CHECK_PARSE("Language: JavaScript\n" 20547 "IndentWidth: 12", 20548 IndentWidth, 12u); 20549 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20550 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20551 "IndentWidth: 34", 20552 &Style), 20553 ParseError::Unsuitable); 20554 EXPECT_EQ(23u, Style.IndentWidth); 20555 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20556 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20557 20558 CHECK_PARSE("BasedOnStyle: LLVM\n" 20559 "IndentWidth: 67", 20560 IndentWidth, 67u); 20561 20562 CHECK_PARSE("---\n" 20563 "Language: JavaScript\n" 20564 "IndentWidth: 12\n" 20565 "---\n" 20566 "Language: Cpp\n" 20567 "IndentWidth: 34\n" 20568 "...\n", 20569 IndentWidth, 12u); 20570 20571 Style.Language = FormatStyle::LK_Cpp; 20572 CHECK_PARSE("---\n" 20573 "Language: JavaScript\n" 20574 "IndentWidth: 12\n" 20575 "---\n" 20576 "Language: Cpp\n" 20577 "IndentWidth: 34\n" 20578 "...\n", 20579 IndentWidth, 34u); 20580 CHECK_PARSE("---\n" 20581 "IndentWidth: 78\n" 20582 "---\n" 20583 "Language: JavaScript\n" 20584 "IndentWidth: 56\n" 20585 "...\n", 20586 IndentWidth, 78u); 20587 20588 Style.ColumnLimit = 123; 20589 Style.IndentWidth = 234; 20590 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20591 Style.TabWidth = 345; 20592 EXPECT_FALSE(parseConfiguration("---\n" 20593 "IndentWidth: 456\n" 20594 "BreakBeforeBraces: Allman\n" 20595 "---\n" 20596 "Language: JavaScript\n" 20597 "IndentWidth: 111\n" 20598 "TabWidth: 111\n" 20599 "---\n" 20600 "Language: Cpp\n" 20601 "BreakBeforeBraces: Stroustrup\n" 20602 "TabWidth: 789\n" 20603 "...\n", 20604 &Style)); 20605 EXPECT_EQ(123u, Style.ColumnLimit); 20606 EXPECT_EQ(456u, Style.IndentWidth); 20607 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20608 EXPECT_EQ(789u, Style.TabWidth); 20609 20610 EXPECT_EQ(parseConfiguration("---\n" 20611 "Language: JavaScript\n" 20612 "IndentWidth: 56\n" 20613 "---\n" 20614 "IndentWidth: 78\n" 20615 "...\n", 20616 &Style), 20617 ParseError::Error); 20618 EXPECT_EQ(parseConfiguration("---\n" 20619 "Language: JavaScript\n" 20620 "IndentWidth: 56\n" 20621 "---\n" 20622 "Language: JavaScript\n" 20623 "IndentWidth: 78\n" 20624 "...\n", 20625 &Style), 20626 ParseError::Error); 20627 20628 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20629 } 20630 20631 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20632 FormatStyle Style = {}; 20633 Style.Language = FormatStyle::LK_JavaScript; 20634 Style.BreakBeforeTernaryOperators = true; 20635 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20636 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20637 20638 Style.BreakBeforeTernaryOperators = true; 20639 EXPECT_EQ(0, parseConfiguration("---\n" 20640 "BasedOnStyle: Google\n" 20641 "---\n" 20642 "Language: JavaScript\n" 20643 "IndentWidth: 76\n" 20644 "...\n", 20645 &Style) 20646 .value()); 20647 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20648 EXPECT_EQ(76u, Style.IndentWidth); 20649 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20650 } 20651 20652 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20653 FormatStyle Style = getLLVMStyle(); 20654 std::string YAML = configurationAsText(Style); 20655 FormatStyle ParsedStyle = {}; 20656 ParsedStyle.Language = FormatStyle::LK_Cpp; 20657 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20658 EXPECT_EQ(Style, ParsedStyle); 20659 } 20660 20661 TEST_F(FormatTest, WorksFor8bitEncodings) { 20662 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20663 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20664 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20665 "\"\xef\xee\xf0\xf3...\"", 20666 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20667 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20668 "\xef\xee\xf0\xf3...\"", 20669 getLLVMStyleWithColumns(12))); 20670 } 20671 20672 TEST_F(FormatTest, HandlesUTF8BOM) { 20673 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20674 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20675 format("\xef\xbb\xbf#include <iostream>")); 20676 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20677 format("\xef\xbb\xbf\n#include <iostream>")); 20678 } 20679 20680 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20681 #if !defined(_MSC_VER) 20682 20683 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20684 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20685 getLLVMStyleWithColumns(35)); 20686 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20687 getLLVMStyleWithColumns(31)); 20688 verifyFormat("// Однажды в студёную зимнюю пору...", 20689 getLLVMStyleWithColumns(36)); 20690 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20691 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20692 getLLVMStyleWithColumns(39)); 20693 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20694 getLLVMStyleWithColumns(35)); 20695 } 20696 20697 TEST_F(FormatTest, SplitsUTF8Strings) { 20698 // Non-printable characters' width is currently considered to be the length in 20699 // bytes in UTF8. The characters can be displayed in very different manner 20700 // (zero-width, single width with a substitution glyph, expanded to their code 20701 // (e.g. "<8d>"), so there's no single correct way to handle them. 20702 EXPECT_EQ("\"aaaaÄ\"\n" 20703 "\"\xc2\x8d\";", 20704 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20705 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20706 "\"\xc2\x8d\";", 20707 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20708 EXPECT_EQ("\"Однажды, в \"\n" 20709 "\"студёную \"\n" 20710 "\"зимнюю \"\n" 20711 "\"пору,\"", 20712 format("\"Однажды, в студёную зимнюю пору,\"", 20713 getLLVMStyleWithColumns(13))); 20714 EXPECT_EQ( 20715 "\"一 二 三 \"\n" 20716 "\"四 五六 \"\n" 20717 "\"七 八 九 \"\n" 20718 "\"十\"", 20719 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20720 EXPECT_EQ("\"一\t\"\n" 20721 "\"二 \t\"\n" 20722 "\"三 四 \"\n" 20723 "\"五\t\"\n" 20724 "\"六 \t\"\n" 20725 "\"七 \"\n" 20726 "\"八九十\tqq\"", 20727 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20728 getLLVMStyleWithColumns(11))); 20729 20730 // UTF8 character in an escape sequence. 20731 EXPECT_EQ("\"aaaaaa\"\n" 20732 "\"\\\xC2\x8D\"", 20733 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20734 } 20735 20736 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20737 EXPECT_EQ("const char *sssss =\n" 20738 " \"一二三四五六七八\\\n" 20739 " 九 十\";", 20740 format("const char *sssss = \"一二三四五六七八\\\n" 20741 " 九 十\";", 20742 getLLVMStyleWithColumns(30))); 20743 } 20744 20745 TEST_F(FormatTest, SplitsUTF8LineComments) { 20746 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20747 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20748 EXPECT_EQ("// Я из лесу\n" 20749 "// вышел; был\n" 20750 "// сильный\n" 20751 "// мороз.", 20752 format("// Я из лесу вышел; был сильный мороз.", 20753 getLLVMStyleWithColumns(13))); 20754 EXPECT_EQ("// 一二三\n" 20755 "// 四五六七\n" 20756 "// 八 九\n" 20757 "// 十", 20758 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20759 } 20760 20761 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20762 EXPECT_EQ("/* Гляжу,\n" 20763 " * поднимается\n" 20764 " * медленно в\n" 20765 " * гору\n" 20766 " * Лошадка,\n" 20767 " * везущая\n" 20768 " * хворосту\n" 20769 " * воз. */", 20770 format("/* Гляжу, поднимается медленно в гору\n" 20771 " * Лошадка, везущая хворосту воз. */", 20772 getLLVMStyleWithColumns(13))); 20773 EXPECT_EQ( 20774 "/* 一二三\n" 20775 " * 四五六七\n" 20776 " * 八 九\n" 20777 " * 十 */", 20778 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20779 EXPECT_EQ("/* \n" 20780 " * \n" 20781 " * - */", 20782 format("/* - */", getLLVMStyleWithColumns(12))); 20783 } 20784 20785 #endif // _MSC_VER 20786 20787 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20788 FormatStyle Style = getLLVMStyle(); 20789 20790 Style.ConstructorInitializerIndentWidth = 4; 20791 verifyFormat( 20792 "SomeClass::Constructor()\n" 20793 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20794 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20795 Style); 20796 20797 Style.ConstructorInitializerIndentWidth = 2; 20798 verifyFormat( 20799 "SomeClass::Constructor()\n" 20800 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20801 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20802 Style); 20803 20804 Style.ConstructorInitializerIndentWidth = 0; 20805 verifyFormat( 20806 "SomeClass::Constructor()\n" 20807 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20808 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20809 Style); 20810 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20811 verifyFormat( 20812 "SomeLongTemplateVariableName<\n" 20813 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20814 Style); 20815 verifyFormat("bool smaller = 1 < " 20816 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20817 " " 20818 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20819 Style); 20820 20821 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20822 verifyFormat("SomeClass::Constructor() :\n" 20823 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20824 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20825 Style); 20826 } 20827 20828 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20829 FormatStyle Style = getLLVMStyle(); 20830 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20831 Style.ConstructorInitializerIndentWidth = 4; 20832 verifyFormat("SomeClass::Constructor()\n" 20833 " : a(a)\n" 20834 " , b(b)\n" 20835 " , c(c) {}", 20836 Style); 20837 verifyFormat("SomeClass::Constructor()\n" 20838 " : a(a) {}", 20839 Style); 20840 20841 Style.ColumnLimit = 0; 20842 verifyFormat("SomeClass::Constructor()\n" 20843 " : a(a) {}", 20844 Style); 20845 verifyFormat("SomeClass::Constructor() noexcept\n" 20846 " : a(a) {}", 20847 Style); 20848 verifyFormat("SomeClass::Constructor()\n" 20849 " : a(a)\n" 20850 " , b(b)\n" 20851 " , c(c) {}", 20852 Style); 20853 verifyFormat("SomeClass::Constructor()\n" 20854 " : a(a) {\n" 20855 " foo();\n" 20856 " bar();\n" 20857 "}", 20858 Style); 20859 20860 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20861 verifyFormat("SomeClass::Constructor()\n" 20862 " : a(a)\n" 20863 " , b(b)\n" 20864 " , c(c) {\n}", 20865 Style); 20866 verifyFormat("SomeClass::Constructor()\n" 20867 " : a(a) {\n}", 20868 Style); 20869 20870 Style.ColumnLimit = 80; 20871 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20872 Style.ConstructorInitializerIndentWidth = 2; 20873 verifyFormat("SomeClass::Constructor()\n" 20874 " : a(a)\n" 20875 " , b(b)\n" 20876 " , c(c) {}", 20877 Style); 20878 20879 Style.ConstructorInitializerIndentWidth = 0; 20880 verifyFormat("SomeClass::Constructor()\n" 20881 ": a(a)\n" 20882 ", b(b)\n" 20883 ", c(c) {}", 20884 Style); 20885 20886 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20887 Style.ConstructorInitializerIndentWidth = 4; 20888 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20889 verifyFormat( 20890 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20891 Style); 20892 verifyFormat( 20893 "SomeClass::Constructor()\n" 20894 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20895 Style); 20896 Style.ConstructorInitializerIndentWidth = 4; 20897 Style.ColumnLimit = 60; 20898 verifyFormat("SomeClass::Constructor()\n" 20899 " : aaaaaaaa(aaaaaaaa)\n" 20900 " , aaaaaaaa(aaaaaaaa)\n" 20901 " , aaaaaaaa(aaaaaaaa) {}", 20902 Style); 20903 } 20904 20905 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20906 FormatStyle Style = getLLVMStyle(); 20907 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20908 Style.ConstructorInitializerIndentWidth = 4; 20909 verifyFormat("SomeClass::Constructor()\n" 20910 " : a{a}\n" 20911 " , b{b} {}", 20912 Style); 20913 verifyFormat("SomeClass::Constructor()\n" 20914 " : a{a}\n" 20915 "#if CONDITION\n" 20916 " , b{b}\n" 20917 "#endif\n" 20918 "{\n}", 20919 Style); 20920 Style.ConstructorInitializerIndentWidth = 2; 20921 verifyFormat("SomeClass::Constructor()\n" 20922 "#if CONDITION\n" 20923 " : a{a}\n" 20924 "#endif\n" 20925 " , b{b}\n" 20926 " , c{c} {\n}", 20927 Style); 20928 Style.ConstructorInitializerIndentWidth = 0; 20929 verifyFormat("SomeClass::Constructor()\n" 20930 ": a{a}\n" 20931 "#ifdef CONDITION\n" 20932 ", b{b}\n" 20933 "#else\n" 20934 ", c{c}\n" 20935 "#endif\n" 20936 ", d{d} {\n}", 20937 Style); 20938 Style.ConstructorInitializerIndentWidth = 4; 20939 verifyFormat("SomeClass::Constructor()\n" 20940 " : a{a}\n" 20941 "#if WINDOWS\n" 20942 "#if DEBUG\n" 20943 " , b{0}\n" 20944 "#else\n" 20945 " , b{1}\n" 20946 "#endif\n" 20947 "#else\n" 20948 "#if DEBUG\n" 20949 " , b{2}\n" 20950 "#else\n" 20951 " , b{3}\n" 20952 "#endif\n" 20953 "#endif\n" 20954 "{\n}", 20955 Style); 20956 verifyFormat("SomeClass::Constructor()\n" 20957 " : a{a}\n" 20958 "#if WINDOWS\n" 20959 " , b{0}\n" 20960 "#if DEBUG\n" 20961 " , c{0}\n" 20962 "#else\n" 20963 " , c{1}\n" 20964 "#endif\n" 20965 "#else\n" 20966 "#if DEBUG\n" 20967 " , c{2}\n" 20968 "#else\n" 20969 " , c{3}\n" 20970 "#endif\n" 20971 " , b{1}\n" 20972 "#endif\n" 20973 "{\n}", 20974 Style); 20975 } 20976 20977 TEST_F(FormatTest, Destructors) { 20978 verifyFormat("void F(int &i) { i.~int(); }"); 20979 verifyFormat("void F(int &i) { i->~int(); }"); 20980 } 20981 20982 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20983 FormatStyle Style = getWebKitStyle(); 20984 20985 // Don't indent in outer namespaces. 20986 verifyFormat("namespace outer {\n" 20987 "int i;\n" 20988 "namespace inner {\n" 20989 " int i;\n" 20990 "} // namespace inner\n" 20991 "} // namespace outer\n" 20992 "namespace other_outer {\n" 20993 "int i;\n" 20994 "}", 20995 Style); 20996 20997 // Don't indent case labels. 20998 verifyFormat("switch (variable) {\n" 20999 "case 1:\n" 21000 "case 2:\n" 21001 " doSomething();\n" 21002 " break;\n" 21003 "default:\n" 21004 " ++variable;\n" 21005 "}", 21006 Style); 21007 21008 // Wrap before binary operators. 21009 EXPECT_EQ("void f()\n" 21010 "{\n" 21011 " if (aaaaaaaaaaaaaaaa\n" 21012 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 21013 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21014 " return;\n" 21015 "}", 21016 format("void f() {\n" 21017 "if (aaaaaaaaaaaaaaaa\n" 21018 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 21019 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21020 "return;\n" 21021 "}", 21022 Style)); 21023 21024 // Allow functions on a single line. 21025 verifyFormat("void f() { return; }", Style); 21026 21027 // Allow empty blocks on a single line and insert a space in empty blocks. 21028 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 21029 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 21030 // However, don't merge non-empty short loops. 21031 EXPECT_EQ("while (true) {\n" 21032 " continue;\n" 21033 "}", 21034 format("while (true) { continue; }", Style)); 21035 21036 // Constructor initializers are formatted one per line with the "," on the 21037 // new line. 21038 verifyFormat("Constructor()\n" 21039 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 21040 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 21041 " aaaaaaaaaaaaaa)\n" 21042 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 21043 "{\n" 21044 "}", 21045 Style); 21046 verifyFormat("SomeClass::Constructor()\n" 21047 " : a(a)\n" 21048 "{\n" 21049 "}", 21050 Style); 21051 EXPECT_EQ("SomeClass::Constructor()\n" 21052 " : a(a)\n" 21053 "{\n" 21054 "}", 21055 format("SomeClass::Constructor():a(a){}", Style)); 21056 verifyFormat("SomeClass::Constructor()\n" 21057 " : a(a)\n" 21058 " , b(b)\n" 21059 " , c(c)\n" 21060 "{\n" 21061 "}", 21062 Style); 21063 verifyFormat("SomeClass::Constructor()\n" 21064 " : a(a)\n" 21065 "{\n" 21066 " foo();\n" 21067 " bar();\n" 21068 "}", 21069 Style); 21070 21071 // Access specifiers should be aligned left. 21072 verifyFormat("class C {\n" 21073 "public:\n" 21074 " int i;\n" 21075 "};", 21076 Style); 21077 21078 // Do not align comments. 21079 verifyFormat("int a; // Do not\n" 21080 "double b; // align comments.", 21081 Style); 21082 21083 // Do not align operands. 21084 EXPECT_EQ("ASSERT(aaaa\n" 21085 " || bbbb);", 21086 format("ASSERT ( aaaa\n||bbbb);", Style)); 21087 21088 // Accept input's line breaks. 21089 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21090 " || bbbbbbbbbbbbbbb) {\n" 21091 " i++;\n" 21092 "}", 21093 format("if (aaaaaaaaaaaaaaa\n" 21094 "|| bbbbbbbbbbbbbbb) { i++; }", 21095 Style)); 21096 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21097 " i++;\n" 21098 "}", 21099 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21100 21101 // Don't automatically break all macro definitions (llvm.org/PR17842). 21102 verifyFormat("#define aNumber 10", Style); 21103 // However, generally keep the line breaks that the user authored. 21104 EXPECT_EQ("#define aNumber \\\n" 21105 " 10", 21106 format("#define aNumber \\\n" 21107 " 10", 21108 Style)); 21109 21110 // Keep empty and one-element array literals on a single line. 21111 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21112 " copyItems:YES];", 21113 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21114 "copyItems:YES];", 21115 Style)); 21116 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21117 " copyItems:YES];", 21118 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21119 " copyItems:YES];", 21120 Style)); 21121 // FIXME: This does not seem right, there should be more indentation before 21122 // the array literal's entries. Nested blocks have the same problem. 21123 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21124 " @\"a\",\n" 21125 " @\"a\"\n" 21126 "]\n" 21127 " copyItems:YES];", 21128 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21129 " @\"a\",\n" 21130 " @\"a\"\n" 21131 " ]\n" 21132 " copyItems:YES];", 21133 Style)); 21134 EXPECT_EQ( 21135 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21136 " copyItems:YES];", 21137 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21138 " copyItems:YES];", 21139 Style)); 21140 21141 verifyFormat("[self.a b:c c:d];", Style); 21142 EXPECT_EQ("[self.a b:c\n" 21143 " c:d];", 21144 format("[self.a b:c\n" 21145 "c:d];", 21146 Style)); 21147 } 21148 21149 TEST_F(FormatTest, FormatsLambdas) { 21150 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21151 verifyFormat( 21152 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21153 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21154 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21155 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21156 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21157 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21158 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21159 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21160 verifyFormat("int x = f(*+[] {});"); 21161 verifyFormat("void f() {\n" 21162 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21163 "}\n"); 21164 verifyFormat("void f() {\n" 21165 " other(x.begin(), //\n" 21166 " x.end(), //\n" 21167 " [&](int, int) { return 1; });\n" 21168 "}\n"); 21169 verifyFormat("void f() {\n" 21170 " other.other.other.other.other(\n" 21171 " x.begin(), x.end(),\n" 21172 " [something, rather](int, int, int, int, int, int, int) { " 21173 "return 1; });\n" 21174 "}\n"); 21175 verifyFormat( 21176 "void f() {\n" 21177 " other.other.other.other.other(\n" 21178 " x.begin(), x.end(),\n" 21179 " [something, rather](int, int, int, int, int, int, int) {\n" 21180 " //\n" 21181 " });\n" 21182 "}\n"); 21183 verifyFormat("SomeFunction([]() { // A cool function...\n" 21184 " return 43;\n" 21185 "});"); 21186 EXPECT_EQ("SomeFunction([]() {\n" 21187 "#define A a\n" 21188 " return 43;\n" 21189 "});", 21190 format("SomeFunction([](){\n" 21191 "#define A a\n" 21192 "return 43;\n" 21193 "});")); 21194 verifyFormat("void f() {\n" 21195 " SomeFunction([](decltype(x), A *a) {});\n" 21196 " SomeFunction([](typeof(x), A *a) {});\n" 21197 " SomeFunction([](_Atomic(x), A *a) {});\n" 21198 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21199 "}"); 21200 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21201 " [](const aaaaaaaaaa &a) { return a; });"); 21202 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21203 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21204 "});"); 21205 verifyFormat("Constructor()\n" 21206 " : Field([] { // comment\n" 21207 " int i;\n" 21208 " }) {}"); 21209 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21210 " return some_parameter.size();\n" 21211 "};"); 21212 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21213 " [](const string &s) { return s; };"); 21214 verifyFormat("int i = aaaaaa ? 1 //\n" 21215 " : [] {\n" 21216 " return 2; //\n" 21217 " }();"); 21218 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21219 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21220 " return x == 2; // force break\n" 21221 " });"); 21222 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21223 " [=](int iiiiiiiiiiii) {\n" 21224 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21225 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21226 " });", 21227 getLLVMStyleWithColumns(60)); 21228 21229 verifyFormat("SomeFunction({[&] {\n" 21230 " // comment\n" 21231 " },\n" 21232 " [&] {\n" 21233 " // comment\n" 21234 " }});"); 21235 verifyFormat("SomeFunction({[&] {\n" 21236 " // comment\n" 21237 "}});"); 21238 verifyFormat( 21239 "virtual aaaaaaaaaaaaaaaa(\n" 21240 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21241 " aaaaa aaaaaaaaa);"); 21242 21243 // Lambdas with return types. 21244 verifyFormat("int c = []() -> int { return 2; }();\n"); 21245 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21246 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21247 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21248 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21249 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21250 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21251 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21252 verifyFormat("[a, a]() -> a<1> {};"); 21253 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21254 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21255 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21256 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21257 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21258 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21259 verifyFormat("[]() -> foo<!5> { return {}; };"); 21260 verifyFormat("[]() -> foo<~5> { return {}; };"); 21261 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21262 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21263 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21264 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21265 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21266 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21267 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21268 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21269 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21270 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21271 verifyFormat("namespace bar {\n" 21272 "// broken:\n" 21273 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21274 "} // namespace bar"); 21275 verifyFormat("namespace bar {\n" 21276 "// broken:\n" 21277 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21278 "} // namespace bar"); 21279 verifyFormat("namespace bar {\n" 21280 "// broken:\n" 21281 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21282 "} // namespace bar"); 21283 verifyFormat("namespace bar {\n" 21284 "// broken:\n" 21285 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21286 "} // namespace bar"); 21287 verifyFormat("namespace bar {\n" 21288 "// broken:\n" 21289 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21290 "} // namespace bar"); 21291 verifyFormat("namespace bar {\n" 21292 "// broken:\n" 21293 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21294 "} // namespace bar"); 21295 verifyFormat("namespace bar {\n" 21296 "// broken:\n" 21297 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21298 "} // namespace bar"); 21299 verifyFormat("namespace bar {\n" 21300 "// broken:\n" 21301 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21302 "} // namespace bar"); 21303 verifyFormat("namespace bar {\n" 21304 "// broken:\n" 21305 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21306 "} // namespace bar"); 21307 verifyFormat("namespace bar {\n" 21308 "// broken:\n" 21309 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21310 "} // namespace bar"); 21311 verifyFormat("namespace bar {\n" 21312 "// broken:\n" 21313 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21314 "} // namespace bar"); 21315 verifyFormat("namespace bar {\n" 21316 "// broken:\n" 21317 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21318 "} // namespace bar"); 21319 verifyFormat("namespace bar {\n" 21320 "// broken:\n" 21321 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21322 "} // namespace bar"); 21323 verifyFormat("namespace bar {\n" 21324 "// broken:\n" 21325 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21326 "} // namespace bar"); 21327 verifyFormat("namespace bar {\n" 21328 "// broken:\n" 21329 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21330 "} // namespace bar"); 21331 verifyFormat("namespace bar {\n" 21332 "// broken:\n" 21333 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21334 "} // namespace bar"); 21335 verifyFormat("namespace bar {\n" 21336 "// broken:\n" 21337 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21338 "} // namespace bar"); 21339 verifyFormat("namespace bar {\n" 21340 "// broken:\n" 21341 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21342 "} // namespace bar"); 21343 verifyFormat("[]() -> a<1> {};"); 21344 verifyFormat("[]() -> a<1> { ; };"); 21345 verifyFormat("[]() -> a<1> { ; }();"); 21346 verifyFormat("[a, a]() -> a<true> {};"); 21347 verifyFormat("[]() -> a<true> {};"); 21348 verifyFormat("[]() -> a<true> { ; };"); 21349 verifyFormat("[]() -> a<true> { ; }();"); 21350 verifyFormat("[a, a]() -> a<false> {};"); 21351 verifyFormat("[]() -> a<false> {};"); 21352 verifyFormat("[]() -> a<false> { ; };"); 21353 verifyFormat("[]() -> a<false> { ; }();"); 21354 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21355 verifyFormat("namespace bar {\n" 21356 "auto foo{[]() -> foo<false> { ; }};\n" 21357 "} // namespace bar"); 21358 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21359 " int j) -> int {\n" 21360 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21361 "};"); 21362 verifyFormat( 21363 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21364 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21365 " return aaaaaaaaaaaaaaaaa;\n" 21366 " });", 21367 getLLVMStyleWithColumns(70)); 21368 verifyFormat("[]() //\n" 21369 " -> int {\n" 21370 " return 1; //\n" 21371 "};"); 21372 verifyFormat("[]() -> Void<T...> {};"); 21373 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21374 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21375 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21376 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21377 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21378 verifyFormat("return int{[x = x]() { return x; }()};"); 21379 21380 // Lambdas with explicit template argument lists. 21381 verifyFormat( 21382 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21383 verifyFormat("auto L = []<class T>(T) {\n" 21384 " {\n" 21385 " f();\n" 21386 " g();\n" 21387 " }\n" 21388 "};\n"); 21389 verifyFormat("auto L = []<class... T>(T...) {\n" 21390 " {\n" 21391 " f();\n" 21392 " g();\n" 21393 " }\n" 21394 "};\n"); 21395 verifyFormat("auto L = []<typename... T>(T...) {\n" 21396 " {\n" 21397 " f();\n" 21398 " g();\n" 21399 " }\n" 21400 "};\n"); 21401 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21402 " {\n" 21403 " f();\n" 21404 " g();\n" 21405 " }\n" 21406 "};\n"); 21407 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21408 " {\n" 21409 " f();\n" 21410 " g();\n" 21411 " }\n" 21412 "};\n"); 21413 21414 // Multiple lambdas in the same parentheses change indentation rules. These 21415 // lambdas are forced to start on new lines. 21416 verifyFormat("SomeFunction(\n" 21417 " []() {\n" 21418 " //\n" 21419 " },\n" 21420 " []() {\n" 21421 " //\n" 21422 " });"); 21423 21424 // A lambda passed as arg0 is always pushed to the next line. 21425 verifyFormat("SomeFunction(\n" 21426 " [this] {\n" 21427 " //\n" 21428 " },\n" 21429 " 1);\n"); 21430 21431 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21432 // the arg0 case above. 21433 auto Style = getGoogleStyle(); 21434 Style.BinPackArguments = false; 21435 verifyFormat("SomeFunction(\n" 21436 " a,\n" 21437 " [this] {\n" 21438 " //\n" 21439 " },\n" 21440 " b);\n", 21441 Style); 21442 verifyFormat("SomeFunction(\n" 21443 " a,\n" 21444 " [this] {\n" 21445 " //\n" 21446 " },\n" 21447 " b);\n"); 21448 21449 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21450 // the BinPackArguments value (as long as the code is wide enough). 21451 verifyFormat( 21452 "something->SomeFunction(\n" 21453 " a,\n" 21454 " [this] {\n" 21455 " " 21456 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21457 " },\n" 21458 " b);\n"); 21459 21460 // A multi-line lambda is pulled up as long as the introducer fits on the 21461 // previous line and there are no further args. 21462 verifyFormat("function(1, [this, that] {\n" 21463 " //\n" 21464 "});\n"); 21465 verifyFormat("function([this, that] {\n" 21466 " //\n" 21467 "});\n"); 21468 // FIXME: this format is not ideal and we should consider forcing the first 21469 // arg onto its own line. 21470 verifyFormat("function(a, b, c, //\n" 21471 " d, [this, that] {\n" 21472 " //\n" 21473 " });\n"); 21474 21475 // Multiple lambdas are treated correctly even when there is a short arg0. 21476 verifyFormat("SomeFunction(\n" 21477 " 1,\n" 21478 " [this] {\n" 21479 " //\n" 21480 " },\n" 21481 " [this] {\n" 21482 " //\n" 21483 " },\n" 21484 " 1);\n"); 21485 21486 // More complex introducers. 21487 verifyFormat("return [i, args...] {};"); 21488 21489 // Not lambdas. 21490 verifyFormat("constexpr char hello[]{\"hello\"};"); 21491 verifyFormat("double &operator[](int i) { return 0; }\n" 21492 "int i;"); 21493 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21494 verifyFormat("int i = a[a][a]->f();"); 21495 verifyFormat("int i = (*b)[a]->f();"); 21496 21497 // Other corner cases. 21498 verifyFormat("void f() {\n" 21499 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21500 " );\n" 21501 "}"); 21502 verifyFormat("auto k = *[](int *j) { return j; }(&i);"); 21503 21504 // Lambdas created through weird macros. 21505 verifyFormat("void f() {\n" 21506 " MACRO((const AA &a) { return 1; });\n" 21507 " MACRO((AA &a) { return 1; });\n" 21508 "}"); 21509 21510 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21511 " doo_dah();\n" 21512 " doo_dah();\n" 21513 " })) {\n" 21514 "}"); 21515 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21516 " doo_dah();\n" 21517 " doo_dah();\n" 21518 " })) {\n" 21519 "}"); 21520 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21521 " doo_dah();\n" 21522 " doo_dah();\n" 21523 " })) {\n" 21524 "}"); 21525 verifyFormat("auto lambda = []() {\n" 21526 " int a = 2\n" 21527 "#if A\n" 21528 " + 2\n" 21529 "#endif\n" 21530 " ;\n" 21531 "};"); 21532 21533 // Lambdas with complex multiline introducers. 21534 verifyFormat( 21535 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21536 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21537 " -> ::std::unordered_set<\n" 21538 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21539 " //\n" 21540 " });"); 21541 21542 FormatStyle DoNotMerge = getLLVMStyle(); 21543 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21544 verifyFormat("auto c = []() {\n" 21545 " return b;\n" 21546 "};", 21547 "auto c = []() { return b; };", DoNotMerge); 21548 verifyFormat("auto c = []() {\n" 21549 "};", 21550 " auto c = []() {};", DoNotMerge); 21551 21552 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21553 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21554 verifyFormat("auto c = []() {\n" 21555 " return b;\n" 21556 "};", 21557 "auto c = []() {\n" 21558 " return b;\n" 21559 " };", 21560 MergeEmptyOnly); 21561 verifyFormat("auto c = []() {};", 21562 "auto c = []() {\n" 21563 "};", 21564 MergeEmptyOnly); 21565 21566 FormatStyle MergeInline = getLLVMStyle(); 21567 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21568 verifyFormat("auto c = []() {\n" 21569 " return b;\n" 21570 "};", 21571 "auto c = []() { return b; };", MergeInline); 21572 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21573 MergeInline); 21574 verifyFormat("function([]() { return b; }, a)", 21575 "function([]() { return b; }, a)", MergeInline); 21576 verifyFormat("function(a, []() { return b; })", 21577 "function(a, []() { return b; })", MergeInline); 21578 21579 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21580 // AllowShortLambdasOnASingleLine 21581 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21582 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21583 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21584 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21585 FormatStyle::ShortLambdaStyle::SLS_None; 21586 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21587 " []()\n" 21588 " {\n" 21589 " return 17;\n" 21590 " });", 21591 LLVMWithBeforeLambdaBody); 21592 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21593 " []()\n" 21594 " {\n" 21595 " });", 21596 LLVMWithBeforeLambdaBody); 21597 verifyFormat("auto fct_SLS_None = []()\n" 21598 "{\n" 21599 " return 17;\n" 21600 "};", 21601 LLVMWithBeforeLambdaBody); 21602 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21603 " []()\n" 21604 " {\n" 21605 " return Call(\n" 21606 " []()\n" 21607 " {\n" 21608 " return 17;\n" 21609 " });\n" 21610 " });", 21611 LLVMWithBeforeLambdaBody); 21612 verifyFormat("void Fct() {\n" 21613 " return {[]()\n" 21614 " {\n" 21615 " return 17;\n" 21616 " }};\n" 21617 "}", 21618 LLVMWithBeforeLambdaBody); 21619 21620 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21621 FormatStyle::ShortLambdaStyle::SLS_Empty; 21622 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21623 " []()\n" 21624 " {\n" 21625 " return 17;\n" 21626 " });", 21627 LLVMWithBeforeLambdaBody); 21628 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21629 LLVMWithBeforeLambdaBody); 21630 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21631 "ongFunctionName_SLS_Empty(\n" 21632 " []() {});", 21633 LLVMWithBeforeLambdaBody); 21634 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21635 " []()\n" 21636 " {\n" 21637 " return 17;\n" 21638 " });", 21639 LLVMWithBeforeLambdaBody); 21640 verifyFormat("auto fct_SLS_Empty = []()\n" 21641 "{\n" 21642 " return 17;\n" 21643 "};", 21644 LLVMWithBeforeLambdaBody); 21645 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21646 " []()\n" 21647 " {\n" 21648 " return Call([]() {});\n" 21649 " });", 21650 LLVMWithBeforeLambdaBody); 21651 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21652 " []()\n" 21653 " {\n" 21654 " return Call([]() {});\n" 21655 " });", 21656 LLVMWithBeforeLambdaBody); 21657 verifyFormat( 21658 "FctWithLongLineInLambda_SLS_Empty(\n" 21659 " []()\n" 21660 " {\n" 21661 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21662 " AndShouldNotBeConsiderAsInline,\n" 21663 " LambdaBodyMustBeBreak);\n" 21664 " });", 21665 LLVMWithBeforeLambdaBody); 21666 21667 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21668 FormatStyle::ShortLambdaStyle::SLS_Inline; 21669 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21670 LLVMWithBeforeLambdaBody); 21671 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21672 LLVMWithBeforeLambdaBody); 21673 verifyFormat("auto fct_SLS_Inline = []()\n" 21674 "{\n" 21675 " return 17;\n" 21676 "};", 21677 LLVMWithBeforeLambdaBody); 21678 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21679 "17; }); });", 21680 LLVMWithBeforeLambdaBody); 21681 verifyFormat( 21682 "FctWithLongLineInLambda_SLS_Inline(\n" 21683 " []()\n" 21684 " {\n" 21685 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21686 " AndShouldNotBeConsiderAsInline,\n" 21687 " LambdaBodyMustBeBreak);\n" 21688 " });", 21689 LLVMWithBeforeLambdaBody); 21690 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21691 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21692 " []() { return 17; });", 21693 LLVMWithBeforeLambdaBody); 21694 verifyFormat( 21695 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21696 LLVMWithBeforeLambdaBody); 21697 21698 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21699 FormatStyle::ShortLambdaStyle::SLS_All; 21700 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21701 LLVMWithBeforeLambdaBody); 21702 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21703 LLVMWithBeforeLambdaBody); 21704 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21705 LLVMWithBeforeLambdaBody); 21706 verifyFormat("FctWithOneParam_SLS_All(\n" 21707 " []()\n" 21708 " {\n" 21709 " // A cool function...\n" 21710 " return 43;\n" 21711 " });", 21712 LLVMWithBeforeLambdaBody); 21713 verifyFormat("FctWithMultipleParams_SLS_All(" 21714 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21715 " []() { return 17; });", 21716 LLVMWithBeforeLambdaBody); 21717 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21718 LLVMWithBeforeLambdaBody); 21719 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21720 LLVMWithBeforeLambdaBody); 21721 verifyFormat( 21722 "FctWithLongLineInLambda_SLS_All(\n" 21723 " []()\n" 21724 " {\n" 21725 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21726 " AndShouldNotBeConsiderAsInline,\n" 21727 " LambdaBodyMustBeBreak);\n" 21728 " });", 21729 LLVMWithBeforeLambdaBody); 21730 verifyFormat( 21731 "auto fct_SLS_All = []()\n" 21732 "{\n" 21733 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21734 " AndShouldNotBeConsiderAsInline,\n" 21735 " LambdaBodyMustBeBreak);\n" 21736 "};", 21737 LLVMWithBeforeLambdaBody); 21738 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21739 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21740 LLVMWithBeforeLambdaBody); 21741 verifyFormat( 21742 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21743 " FirstParam,\n" 21744 " SecondParam,\n" 21745 " ThirdParam,\n" 21746 " FourthParam);", 21747 LLVMWithBeforeLambdaBody); 21748 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21749 " []() { return " 21750 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21751 " FirstParam,\n" 21752 " SecondParam,\n" 21753 " ThirdParam,\n" 21754 " FourthParam);", 21755 LLVMWithBeforeLambdaBody); 21756 verifyFormat( 21757 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21758 " SecondParam,\n" 21759 " ThirdParam,\n" 21760 " FourthParam,\n" 21761 " []() { return SomeValueNotSoLong; });", 21762 LLVMWithBeforeLambdaBody); 21763 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21764 " []()\n" 21765 " {\n" 21766 " return " 21767 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21768 "eConsiderAsInline;\n" 21769 " });", 21770 LLVMWithBeforeLambdaBody); 21771 verifyFormat( 21772 "FctWithLongLineInLambda_SLS_All(\n" 21773 " []()\n" 21774 " {\n" 21775 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21776 " AndShouldNotBeConsiderAsInline,\n" 21777 " LambdaBodyMustBeBreak);\n" 21778 " });", 21779 LLVMWithBeforeLambdaBody); 21780 verifyFormat("FctWithTwoParams_SLS_All(\n" 21781 " []()\n" 21782 " {\n" 21783 " // A cool function...\n" 21784 " return 43;\n" 21785 " },\n" 21786 " 87);", 21787 LLVMWithBeforeLambdaBody); 21788 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21789 LLVMWithBeforeLambdaBody); 21790 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21791 LLVMWithBeforeLambdaBody); 21792 verifyFormat( 21793 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21794 LLVMWithBeforeLambdaBody); 21795 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21796 "}); }, x);", 21797 LLVMWithBeforeLambdaBody); 21798 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21799 " []()\n" 21800 " {\n" 21801 " // A cool function...\n" 21802 " return Call([]() { return 17; });\n" 21803 " });", 21804 LLVMWithBeforeLambdaBody); 21805 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21806 " []()\n" 21807 " {\n" 21808 " return Call(\n" 21809 " []()\n" 21810 " {\n" 21811 " // A cool function...\n" 21812 " return 17;\n" 21813 " });\n" 21814 " });", 21815 LLVMWithBeforeLambdaBody); 21816 21817 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21818 FormatStyle::ShortLambdaStyle::SLS_None; 21819 21820 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21821 "{\n" 21822 " return MyAssignment::SelectFromList(this);\n" 21823 "};\n", 21824 LLVMWithBeforeLambdaBody); 21825 21826 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21827 "{\n" 21828 " return MyAssignment::SelectFromList(this);\n" 21829 "};\n", 21830 LLVMWithBeforeLambdaBody); 21831 21832 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21833 "{\n" 21834 " return MyAssignment::SelectFromList(this);\n" 21835 "};\n", 21836 LLVMWithBeforeLambdaBody); 21837 21838 verifyFormat("namespace test {\n" 21839 "class Test {\n" 21840 "public:\n" 21841 " Test() = default;\n" 21842 "};\n" 21843 "} // namespace test", 21844 LLVMWithBeforeLambdaBody); 21845 21846 // Lambdas with different indentation styles. 21847 Style = getLLVMStyleWithColumns(100); 21848 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21849 " return promise.then(\n" 21850 " [this, &someVariable, someObject = " 21851 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21852 " return someObject.startAsyncAction().then(\n" 21853 " [this, &someVariable](AsyncActionResult result) " 21854 "mutable { result.processMore(); });\n" 21855 " });\n" 21856 "}\n", 21857 format("SomeResult doSomething(SomeObject promise) {\n" 21858 " return promise.then([this, &someVariable, someObject = " 21859 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21860 " return someObject.startAsyncAction().then([this, " 21861 "&someVariable](AsyncActionResult result) mutable {\n" 21862 " result.processMore();\n" 21863 " });\n" 21864 " });\n" 21865 "}\n", 21866 Style)); 21867 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21868 verifyFormat("test() {\n" 21869 " ([]() -> {\n" 21870 " int b = 32;\n" 21871 " return 3;\n" 21872 " }).foo();\n" 21873 "}", 21874 Style); 21875 verifyFormat("test() {\n" 21876 " []() -> {\n" 21877 " int b = 32;\n" 21878 " return 3;\n" 21879 " }\n" 21880 "}", 21881 Style); 21882 verifyFormat("std::sort(v.begin(), v.end(),\n" 21883 " [](const auto &someLongArgumentName, const auto " 21884 "&someOtherLongArgumentName) {\n" 21885 " return someLongArgumentName.someMemberVariable < " 21886 "someOtherLongArgumentName.someMemberVariable;\n" 21887 "});", 21888 Style); 21889 verifyFormat("test() {\n" 21890 " (\n" 21891 " []() -> {\n" 21892 " int b = 32;\n" 21893 " return 3;\n" 21894 " },\n" 21895 " foo, bar)\n" 21896 " .foo();\n" 21897 "}", 21898 Style); 21899 verifyFormat("test() {\n" 21900 " ([]() -> {\n" 21901 " int b = 32;\n" 21902 " return 3;\n" 21903 " })\n" 21904 " .foo()\n" 21905 " .bar();\n" 21906 "}", 21907 Style); 21908 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21909 " return promise.then(\n" 21910 " [this, &someVariable, someObject = " 21911 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21912 " return someObject.startAsyncAction().then(\n" 21913 " [this, &someVariable](AsyncActionResult result) mutable { " 21914 "result.processMore(); });\n" 21915 " });\n" 21916 "}\n", 21917 format("SomeResult doSomething(SomeObject promise) {\n" 21918 " return promise.then([this, &someVariable, someObject = " 21919 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21920 " return someObject.startAsyncAction().then([this, " 21921 "&someVariable](AsyncActionResult result) mutable {\n" 21922 " result.processMore();\n" 21923 " });\n" 21924 " });\n" 21925 "}\n", 21926 Style)); 21927 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21928 " return promise.then([this, &someVariable] {\n" 21929 " return someObject.startAsyncAction().then(\n" 21930 " [this, &someVariable](AsyncActionResult result) mutable { " 21931 "result.processMore(); });\n" 21932 " });\n" 21933 "}\n", 21934 format("SomeResult doSomething(SomeObject promise) {\n" 21935 " return promise.then([this, &someVariable] {\n" 21936 " return someObject.startAsyncAction().then([this, " 21937 "&someVariable](AsyncActionResult result) mutable {\n" 21938 " result.processMore();\n" 21939 " });\n" 21940 " });\n" 21941 "}\n", 21942 Style)); 21943 Style = getGoogleStyle(); 21944 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21945 EXPECT_EQ("#define A \\\n" 21946 " [] { \\\n" 21947 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21948 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21949 " }", 21950 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21951 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21952 Style)); 21953 // TODO: The current formatting has a minor issue that's not worth fixing 21954 // right now whereby the closing brace is indented relative to the signature 21955 // instead of being aligned. This only happens with macros. 21956 } 21957 21958 TEST_F(FormatTest, LambdaWithLineComments) { 21959 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21960 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21961 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21962 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21963 FormatStyle::ShortLambdaStyle::SLS_All; 21964 21965 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21966 verifyFormat("auto k = []() // comment\n" 21967 "{ return; }", 21968 LLVMWithBeforeLambdaBody); 21969 verifyFormat("auto k = []() /* comment */ { return; }", 21970 LLVMWithBeforeLambdaBody); 21971 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21972 LLVMWithBeforeLambdaBody); 21973 verifyFormat("auto k = []() // X\n" 21974 "{ return; }", 21975 LLVMWithBeforeLambdaBody); 21976 verifyFormat( 21977 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21978 "{ return; }", 21979 LLVMWithBeforeLambdaBody); 21980 21981 LLVMWithBeforeLambdaBody.ColumnLimit = 0; 21982 21983 verifyFormat("foo([]()\n" 21984 " {\n" 21985 " bar(); //\n" 21986 " return 1; // comment\n" 21987 " }());", 21988 "foo([]() {\n" 21989 " bar(); //\n" 21990 " return 1; // comment\n" 21991 "}());", 21992 LLVMWithBeforeLambdaBody); 21993 verifyFormat("foo(\n" 21994 " 1, MACRO {\n" 21995 " baz();\n" 21996 " bar(); // comment\n" 21997 " },\n" 21998 " []() {});", 21999 "foo(\n" 22000 " 1, MACRO { baz(); bar(); // comment\n" 22001 " }, []() {}\n" 22002 ");", 22003 LLVMWithBeforeLambdaBody); 22004 } 22005 22006 TEST_F(FormatTest, EmptyLinesInLambdas) { 22007 verifyFormat("auto lambda = []() {\n" 22008 " x(); //\n" 22009 "};", 22010 "auto lambda = []() {\n" 22011 "\n" 22012 " x(); //\n" 22013 "\n" 22014 "};"); 22015 } 22016 22017 TEST_F(FormatTest, FormatsBlocks) { 22018 FormatStyle ShortBlocks = getLLVMStyle(); 22019 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22020 verifyFormat("int (^Block)(int, int);", ShortBlocks); 22021 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 22022 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 22023 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 22024 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 22025 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 22026 22027 verifyFormat("foo(^{ bar(); });", ShortBlocks); 22028 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 22029 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 22030 22031 verifyFormat("[operation setCompletionBlock:^{\n" 22032 " [self onOperationDone];\n" 22033 "}];"); 22034 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 22035 " [self onOperationDone];\n" 22036 "}]};"); 22037 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 22038 " f();\n" 22039 "}];"); 22040 verifyFormat("int a = [operation block:^int(int *i) {\n" 22041 " return 1;\n" 22042 "}];"); 22043 verifyFormat("[myObject doSomethingWith:arg1\n" 22044 " aaa:^int(int *a) {\n" 22045 " return 1;\n" 22046 " }\n" 22047 " bbb:f(a * bbbbbbbb)];"); 22048 22049 verifyFormat("[operation setCompletionBlock:^{\n" 22050 " [self.delegate newDataAvailable];\n" 22051 "}];", 22052 getLLVMStyleWithColumns(60)); 22053 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 22054 " NSString *path = [self sessionFilePath];\n" 22055 " if (path) {\n" 22056 " // ...\n" 22057 " }\n" 22058 "});"); 22059 verifyFormat("[[SessionService sharedService]\n" 22060 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22061 " if (window) {\n" 22062 " [self windowDidLoad:window];\n" 22063 " } else {\n" 22064 " [self errorLoadingWindow];\n" 22065 " }\n" 22066 " }];"); 22067 verifyFormat("void (^largeBlock)(void) = ^{\n" 22068 " // ...\n" 22069 "};\n", 22070 getLLVMStyleWithColumns(40)); 22071 verifyFormat("[[SessionService sharedService]\n" 22072 " loadWindowWithCompletionBlock: //\n" 22073 " ^(SessionWindow *window) {\n" 22074 " if (window) {\n" 22075 " [self windowDidLoad:window];\n" 22076 " } else {\n" 22077 " [self errorLoadingWindow];\n" 22078 " }\n" 22079 " }];", 22080 getLLVMStyleWithColumns(60)); 22081 verifyFormat("[myObject doSomethingWith:arg1\n" 22082 " firstBlock:^(Foo *a) {\n" 22083 " // ...\n" 22084 " int i;\n" 22085 " }\n" 22086 " secondBlock:^(Bar *b) {\n" 22087 " // ...\n" 22088 " int i;\n" 22089 " }\n" 22090 " thirdBlock:^Foo(Bar *b) {\n" 22091 " // ...\n" 22092 " int i;\n" 22093 " }];"); 22094 verifyFormat("[myObject doSomethingWith:arg1\n" 22095 " firstBlock:-1\n" 22096 " secondBlock:^(Bar *b) {\n" 22097 " // ...\n" 22098 " int i;\n" 22099 " }];"); 22100 22101 verifyFormat("f(^{\n" 22102 " @autoreleasepool {\n" 22103 " if (a) {\n" 22104 " g();\n" 22105 " }\n" 22106 " }\n" 22107 "});"); 22108 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22109 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22110 "};"); 22111 22112 FormatStyle FourIndent = getLLVMStyle(); 22113 FourIndent.ObjCBlockIndentWidth = 4; 22114 verifyFormat("[operation setCompletionBlock:^{\n" 22115 " [self onOperationDone];\n" 22116 "}];", 22117 FourIndent); 22118 } 22119 22120 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22121 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22122 22123 verifyFormat("[[SessionService sharedService] " 22124 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22125 " if (window) {\n" 22126 " [self windowDidLoad:window];\n" 22127 " } else {\n" 22128 " [self errorLoadingWindow];\n" 22129 " }\n" 22130 "}];", 22131 ZeroColumn); 22132 EXPECT_EQ("[[SessionService sharedService]\n" 22133 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22134 " if (window) {\n" 22135 " [self windowDidLoad:window];\n" 22136 " } else {\n" 22137 " [self errorLoadingWindow];\n" 22138 " }\n" 22139 " }];", 22140 format("[[SessionService sharedService]\n" 22141 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22142 " if (window) {\n" 22143 " [self windowDidLoad:window];\n" 22144 " } else {\n" 22145 " [self errorLoadingWindow];\n" 22146 " }\n" 22147 "}];", 22148 ZeroColumn)); 22149 verifyFormat("[myObject doSomethingWith:arg1\n" 22150 " firstBlock:^(Foo *a) {\n" 22151 " // ...\n" 22152 " int i;\n" 22153 " }\n" 22154 " secondBlock:^(Bar *b) {\n" 22155 " // ...\n" 22156 " int i;\n" 22157 " }\n" 22158 " thirdBlock:^Foo(Bar *b) {\n" 22159 " // ...\n" 22160 " int i;\n" 22161 " }];", 22162 ZeroColumn); 22163 verifyFormat("f(^{\n" 22164 " @autoreleasepool {\n" 22165 " if (a) {\n" 22166 " g();\n" 22167 " }\n" 22168 " }\n" 22169 "});", 22170 ZeroColumn); 22171 verifyFormat("void (^largeBlock)(void) = ^{\n" 22172 " // ...\n" 22173 "};", 22174 ZeroColumn); 22175 22176 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22177 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22178 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22179 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22180 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22181 " int i;\n" 22182 "};", 22183 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22184 } 22185 22186 TEST_F(FormatTest, SupportsCRLF) { 22187 EXPECT_EQ("int a;\r\n" 22188 "int b;\r\n" 22189 "int c;\r\n", 22190 format("int a;\r\n" 22191 " int b;\r\n" 22192 " int c;\r\n", 22193 getLLVMStyle())); 22194 EXPECT_EQ("int a;\r\n" 22195 "int b;\r\n" 22196 "int c;\r\n", 22197 format("int a;\r\n" 22198 " int b;\n" 22199 " int c;\r\n", 22200 getLLVMStyle())); 22201 EXPECT_EQ("int a;\n" 22202 "int b;\n" 22203 "int c;\n", 22204 format("int a;\r\n" 22205 " int b;\n" 22206 " int c;\n", 22207 getLLVMStyle())); 22208 EXPECT_EQ("\"aaaaaaa \"\r\n" 22209 "\"bbbbbbb\";\r\n", 22210 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22211 EXPECT_EQ("#define A \\\r\n" 22212 " b; \\\r\n" 22213 " c; \\\r\n" 22214 " d;\r\n", 22215 format("#define A \\\r\n" 22216 " b; \\\r\n" 22217 " c; d; \r\n", 22218 getGoogleStyle())); 22219 22220 EXPECT_EQ("/*\r\n" 22221 "multi line block comments\r\n" 22222 "should not introduce\r\n" 22223 "an extra carriage return\r\n" 22224 "*/\r\n", 22225 format("/*\r\n" 22226 "multi line block comments\r\n" 22227 "should not introduce\r\n" 22228 "an extra carriage return\r\n" 22229 "*/\r\n")); 22230 EXPECT_EQ("/*\r\n" 22231 "\r\n" 22232 "*/", 22233 format("/*\r\n" 22234 " \r\r\r\n" 22235 "*/")); 22236 22237 FormatStyle style = getLLVMStyle(); 22238 22239 style.DeriveLineEnding = true; 22240 style.UseCRLF = false; 22241 EXPECT_EQ("union FooBarBazQux {\n" 22242 " int foo;\n" 22243 " int bar;\n" 22244 " int baz;\n" 22245 "};", 22246 format("union FooBarBazQux {\r\n" 22247 " int foo;\n" 22248 " int bar;\r\n" 22249 " int baz;\n" 22250 "};", 22251 style)); 22252 style.UseCRLF = true; 22253 EXPECT_EQ("union FooBarBazQux {\r\n" 22254 " int foo;\r\n" 22255 " int bar;\r\n" 22256 " int baz;\r\n" 22257 "};", 22258 format("union FooBarBazQux {\r\n" 22259 " int foo;\n" 22260 " int bar;\r\n" 22261 " int baz;\n" 22262 "};", 22263 style)); 22264 22265 style.DeriveLineEnding = false; 22266 style.UseCRLF = false; 22267 EXPECT_EQ("union FooBarBazQux {\n" 22268 " int foo;\n" 22269 " int bar;\n" 22270 " int baz;\n" 22271 " int qux;\n" 22272 "};", 22273 format("union FooBarBazQux {\r\n" 22274 " int foo;\n" 22275 " int bar;\r\n" 22276 " int baz;\n" 22277 " int qux;\r\n" 22278 "};", 22279 style)); 22280 style.UseCRLF = true; 22281 EXPECT_EQ("union FooBarBazQux {\r\n" 22282 " int foo;\r\n" 22283 " int bar;\r\n" 22284 " int baz;\r\n" 22285 " int qux;\r\n" 22286 "};", 22287 format("union FooBarBazQux {\r\n" 22288 " int foo;\n" 22289 " int bar;\r\n" 22290 " int baz;\n" 22291 " int qux;\n" 22292 "};", 22293 style)); 22294 22295 style.DeriveLineEnding = true; 22296 style.UseCRLF = false; 22297 EXPECT_EQ("union FooBarBazQux {\r\n" 22298 " int foo;\r\n" 22299 " int bar;\r\n" 22300 " int baz;\r\n" 22301 " int qux;\r\n" 22302 "};", 22303 format("union FooBarBazQux {\r\n" 22304 " int foo;\n" 22305 " int bar;\r\n" 22306 " int baz;\n" 22307 " int qux;\r\n" 22308 "};", 22309 style)); 22310 style.UseCRLF = true; 22311 EXPECT_EQ("union FooBarBazQux {\n" 22312 " int foo;\n" 22313 " int bar;\n" 22314 " int baz;\n" 22315 " int qux;\n" 22316 "};", 22317 format("union FooBarBazQux {\r\n" 22318 " int foo;\n" 22319 " int bar;\r\n" 22320 " int baz;\n" 22321 " int qux;\n" 22322 "};", 22323 style)); 22324 } 22325 22326 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22327 verifyFormat("MY_CLASS(C) {\n" 22328 " int i;\n" 22329 " int j;\n" 22330 "};"); 22331 } 22332 22333 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22334 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22335 TwoIndent.ContinuationIndentWidth = 2; 22336 22337 EXPECT_EQ("int i =\n" 22338 " longFunction(\n" 22339 " arg);", 22340 format("int i = longFunction(arg);", TwoIndent)); 22341 22342 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22343 SixIndent.ContinuationIndentWidth = 6; 22344 22345 EXPECT_EQ("int i =\n" 22346 " longFunction(\n" 22347 " arg);", 22348 format("int i = longFunction(arg);", SixIndent)); 22349 } 22350 22351 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22352 FormatStyle Style = getLLVMStyle(); 22353 verifyFormat("int Foo::getter(\n" 22354 " //\n" 22355 ") const {\n" 22356 " return foo;\n" 22357 "}", 22358 Style); 22359 verifyFormat("void Foo::setter(\n" 22360 " //\n" 22361 ") {\n" 22362 " foo = 1;\n" 22363 "}", 22364 Style); 22365 } 22366 22367 TEST_F(FormatTest, SpacesInAngles) { 22368 FormatStyle Spaces = getLLVMStyle(); 22369 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22370 22371 verifyFormat("vector< ::std::string > x1;", Spaces); 22372 verifyFormat("Foo< int, Bar > x2;", Spaces); 22373 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22374 22375 verifyFormat("static_cast< int >(arg);", Spaces); 22376 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22377 verifyFormat("f< int, float >();", Spaces); 22378 verifyFormat("template <> g() {}", Spaces); 22379 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22380 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22381 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22382 Spaces); 22383 22384 Spaces.Standard = FormatStyle::LS_Cpp03; 22385 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22386 verifyFormat("A< A< int > >();", Spaces); 22387 22388 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22389 verifyFormat("A<A<int> >();", Spaces); 22390 22391 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22392 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22393 Spaces); 22394 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22395 Spaces); 22396 22397 verifyFormat("A<A<int> >();", Spaces); 22398 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22399 verifyFormat("A< A< int > >();", Spaces); 22400 22401 Spaces.Standard = FormatStyle::LS_Cpp11; 22402 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22403 verifyFormat("A< A< int > >();", Spaces); 22404 22405 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22406 verifyFormat("vector<::std::string> x4;", Spaces); 22407 verifyFormat("vector<int> x5;", Spaces); 22408 verifyFormat("Foo<int, Bar> x6;", Spaces); 22409 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22410 22411 verifyFormat("A<A<int>>();", Spaces); 22412 22413 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22414 verifyFormat("vector<::std::string> x4;", Spaces); 22415 verifyFormat("vector< ::std::string > x4;", Spaces); 22416 verifyFormat("vector<int> x5;", Spaces); 22417 verifyFormat("vector< int > x5;", Spaces); 22418 verifyFormat("Foo<int, Bar> x6;", Spaces); 22419 verifyFormat("Foo< int, Bar > x6;", Spaces); 22420 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22421 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22422 22423 verifyFormat("A<A<int>>();", Spaces); 22424 verifyFormat("A< A< int > >();", Spaces); 22425 verifyFormat("A<A<int > >();", Spaces); 22426 verifyFormat("A< A< int>>();", Spaces); 22427 22428 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22429 verifyFormat("// clang-format off\n" 22430 "foo<<<1, 1>>>();\n" 22431 "// clang-format on\n", 22432 Spaces); 22433 verifyFormat("// clang-format off\n" 22434 "foo< < <1, 1> > >();\n" 22435 "// clang-format on\n", 22436 Spaces); 22437 } 22438 22439 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22440 FormatStyle Style = getLLVMStyle(); 22441 Style.SpaceAfterTemplateKeyword = false; 22442 verifyFormat("template<int> void foo();", Style); 22443 } 22444 22445 TEST_F(FormatTest, TripleAngleBrackets) { 22446 verifyFormat("f<<<1, 1>>>();"); 22447 verifyFormat("f<<<1, 1, 1, s>>>();"); 22448 verifyFormat("f<<<a, b, c, d>>>();"); 22449 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22450 verifyFormat("f<param><<<1, 1>>>();"); 22451 verifyFormat("f<1><<<1, 1>>>();"); 22452 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22453 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22454 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22455 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22456 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22457 } 22458 22459 TEST_F(FormatTest, MergeLessLessAtEnd) { 22460 verifyFormat("<<"); 22461 EXPECT_EQ("< < <", format("\\\n<<<")); 22462 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22463 "aaallvm::outs() <<"); 22464 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22465 "aaaallvm::outs()\n <<"); 22466 } 22467 22468 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22469 std::string code = "#if A\n" 22470 "#if B\n" 22471 "a.\n" 22472 "#endif\n" 22473 " a = 1;\n" 22474 "#else\n" 22475 "#endif\n" 22476 "#if C\n" 22477 "#else\n" 22478 "#endif\n"; 22479 EXPECT_EQ(code, format(code)); 22480 } 22481 22482 TEST_F(FormatTest, HandleConflictMarkers) { 22483 // Git/SVN conflict markers. 22484 EXPECT_EQ("int a;\n" 22485 "void f() {\n" 22486 " callme(some(parameter1,\n" 22487 "<<<<<<< text by the vcs\n" 22488 " parameter2),\n" 22489 "||||||| text by the vcs\n" 22490 " parameter2),\n" 22491 " parameter3,\n" 22492 "======= text by the vcs\n" 22493 " parameter2, parameter3),\n" 22494 ">>>>>>> text by the vcs\n" 22495 " otherparameter);\n", 22496 format("int a;\n" 22497 "void f() {\n" 22498 " callme(some(parameter1,\n" 22499 "<<<<<<< text by the vcs\n" 22500 " parameter2),\n" 22501 "||||||| text by the vcs\n" 22502 " parameter2),\n" 22503 " parameter3,\n" 22504 "======= text by the vcs\n" 22505 " parameter2,\n" 22506 " parameter3),\n" 22507 ">>>>>>> text by the vcs\n" 22508 " otherparameter);\n")); 22509 22510 // Perforce markers. 22511 EXPECT_EQ("void f() {\n" 22512 " function(\n" 22513 ">>>> text by the vcs\n" 22514 " parameter,\n" 22515 "==== text by the vcs\n" 22516 " parameter,\n" 22517 "==== text by the vcs\n" 22518 " parameter,\n" 22519 "<<<< text by the vcs\n" 22520 " parameter);\n", 22521 format("void f() {\n" 22522 " function(\n" 22523 ">>>> text by the vcs\n" 22524 " parameter,\n" 22525 "==== text by the vcs\n" 22526 " parameter,\n" 22527 "==== text by the vcs\n" 22528 " parameter,\n" 22529 "<<<< text by the vcs\n" 22530 " parameter);\n")); 22531 22532 EXPECT_EQ("<<<<<<<\n" 22533 "|||||||\n" 22534 "=======\n" 22535 ">>>>>>>", 22536 format("<<<<<<<\n" 22537 "|||||||\n" 22538 "=======\n" 22539 ">>>>>>>")); 22540 22541 EXPECT_EQ("<<<<<<<\n" 22542 "|||||||\n" 22543 "int i;\n" 22544 "=======\n" 22545 ">>>>>>>", 22546 format("<<<<<<<\n" 22547 "|||||||\n" 22548 "int i;\n" 22549 "=======\n" 22550 ">>>>>>>")); 22551 22552 // FIXME: Handle parsing of macros around conflict markers correctly: 22553 EXPECT_EQ("#define Macro \\\n" 22554 "<<<<<<<\n" 22555 "Something \\\n" 22556 "|||||||\n" 22557 "Else \\\n" 22558 "=======\n" 22559 "Other \\\n" 22560 ">>>>>>>\n" 22561 " End int i;\n", 22562 format("#define Macro \\\n" 22563 "<<<<<<<\n" 22564 " Something \\\n" 22565 "|||||||\n" 22566 " Else \\\n" 22567 "=======\n" 22568 " Other \\\n" 22569 ">>>>>>>\n" 22570 " End\n" 22571 "int i;\n")); 22572 22573 verifyFormat(R"(==== 22574 #ifdef A 22575 a 22576 #else 22577 b 22578 #endif 22579 )"); 22580 } 22581 22582 TEST_F(FormatTest, DisableRegions) { 22583 EXPECT_EQ("int i;\n" 22584 "// clang-format off\n" 22585 " int j;\n" 22586 "// clang-format on\n" 22587 "int k;", 22588 format(" int i;\n" 22589 " // clang-format off\n" 22590 " int j;\n" 22591 " // clang-format on\n" 22592 " int k;")); 22593 EXPECT_EQ("int i;\n" 22594 "/* clang-format off */\n" 22595 " int j;\n" 22596 "/* clang-format on */\n" 22597 "int k;", 22598 format(" int i;\n" 22599 " /* clang-format off */\n" 22600 " int j;\n" 22601 " /* clang-format on */\n" 22602 " int k;")); 22603 22604 // Don't reflow comments within disabled regions. 22605 EXPECT_EQ("// clang-format off\n" 22606 "// long long long long long long line\n" 22607 "/* clang-format on */\n" 22608 "/* long long long\n" 22609 " * long long long\n" 22610 " * line */\n" 22611 "int i;\n" 22612 "/* clang-format off */\n" 22613 "/* long long long long long long line */\n", 22614 format("// clang-format off\n" 22615 "// long long long long long long line\n" 22616 "/* clang-format on */\n" 22617 "/* long long long long long long line */\n" 22618 "int i;\n" 22619 "/* clang-format off */\n" 22620 "/* long long long long long long line */\n", 22621 getLLVMStyleWithColumns(20))); 22622 } 22623 22624 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22625 format("? ) ="); 22626 verifyNoCrash("#define a\\\n /**/}"); 22627 } 22628 22629 TEST_F(FormatTest, FormatsTableGenCode) { 22630 FormatStyle Style = getLLVMStyle(); 22631 Style.Language = FormatStyle::LK_TableGen; 22632 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22633 } 22634 22635 TEST_F(FormatTest, ArrayOfTemplates) { 22636 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22637 format("auto a = new unique_ptr<int > [ 10];")); 22638 22639 FormatStyle Spaces = getLLVMStyle(); 22640 Spaces.SpacesInSquareBrackets = true; 22641 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22642 format("auto a = new unique_ptr<int > [10];", Spaces)); 22643 } 22644 22645 TEST_F(FormatTest, ArrayAsTemplateType) { 22646 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22647 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22648 22649 FormatStyle Spaces = getLLVMStyle(); 22650 Spaces.SpacesInSquareBrackets = true; 22651 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22652 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22653 } 22654 22655 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22656 22657 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22658 llvm::vfs::InMemoryFileSystem FS; 22659 auto Style1 = getStyle("file", "", "Google", "", &FS); 22660 ASSERT_TRUE((bool)Style1); 22661 ASSERT_EQ(*Style1, getGoogleStyle()); 22662 } 22663 22664 TEST(FormatStyle, GetStyleOfFile) { 22665 llvm::vfs::InMemoryFileSystem FS; 22666 // Test 1: format file in the same directory. 22667 ASSERT_TRUE( 22668 FS.addFile("/a/.clang-format", 0, 22669 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22670 ASSERT_TRUE( 22671 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22672 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22673 ASSERT_TRUE((bool)Style1); 22674 ASSERT_EQ(*Style1, getLLVMStyle()); 22675 22676 // Test 2.1: fallback to default. 22677 ASSERT_TRUE( 22678 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22679 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22680 ASSERT_TRUE((bool)Style2); 22681 ASSERT_EQ(*Style2, getMozillaStyle()); 22682 22683 // Test 2.2: no format on 'none' fallback style. 22684 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22685 ASSERT_TRUE((bool)Style2); 22686 ASSERT_EQ(*Style2, getNoStyle()); 22687 22688 // Test 2.3: format if config is found with no based style while fallback is 22689 // 'none'. 22690 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22691 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22692 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22693 ASSERT_TRUE((bool)Style2); 22694 ASSERT_EQ(*Style2, getLLVMStyle()); 22695 22696 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22697 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22698 ASSERT_TRUE((bool)Style2); 22699 ASSERT_EQ(*Style2, getLLVMStyle()); 22700 22701 // Test 3: format file in parent directory. 22702 ASSERT_TRUE( 22703 FS.addFile("/c/.clang-format", 0, 22704 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22705 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22706 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22707 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22708 ASSERT_TRUE((bool)Style3); 22709 ASSERT_EQ(*Style3, getGoogleStyle()); 22710 22711 // Test 4: error on invalid fallback style 22712 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22713 ASSERT_FALSE((bool)Style4); 22714 llvm::consumeError(Style4.takeError()); 22715 22716 // Test 5: error on invalid yaml on command line 22717 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22718 ASSERT_FALSE((bool)Style5); 22719 llvm::consumeError(Style5.takeError()); 22720 22721 // Test 6: error on invalid style 22722 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22723 ASSERT_FALSE((bool)Style6); 22724 llvm::consumeError(Style6.takeError()); 22725 22726 // Test 7: found config file, error on parsing it 22727 ASSERT_TRUE( 22728 FS.addFile("/d/.clang-format", 0, 22729 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22730 "InvalidKey: InvalidValue"))); 22731 ASSERT_TRUE( 22732 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22733 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22734 ASSERT_FALSE((bool)Style7a); 22735 llvm::consumeError(Style7a.takeError()); 22736 22737 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22738 ASSERT_TRUE((bool)Style7b); 22739 22740 // Test 8: inferred per-language defaults apply. 22741 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22742 ASSERT_TRUE((bool)StyleTd); 22743 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22744 22745 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22746 // fallback style. 22747 ASSERT_TRUE(FS.addFile( 22748 "/e/sub/.clang-format", 0, 22749 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22750 "ColumnLimit: 20"))); 22751 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22752 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22753 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22754 ASSERT_TRUE(static_cast<bool>(Style9)); 22755 ASSERT_EQ(*Style9, [] { 22756 auto Style = getNoStyle(); 22757 Style.ColumnLimit = 20; 22758 return Style; 22759 }()); 22760 22761 // Test 9.1.2: propagate more than one level with no parent file. 22762 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22763 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22764 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22765 llvm::MemoryBuffer::getMemBuffer( 22766 "BasedOnStyle: InheritParentConfig\n" 22767 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22768 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22769 22770 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22771 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22772 ASSERT_TRUE(static_cast<bool>(Style9)); 22773 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22774 auto Style = getNoStyle(); 22775 Style.ColumnLimit = 20; 22776 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22777 return Style; 22778 }()); 22779 22780 // Test 9.2: with LLVM fallback style 22781 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22782 ASSERT_TRUE(static_cast<bool>(Style9)); 22783 ASSERT_EQ(*Style9, [] { 22784 auto Style = getLLVMStyle(); 22785 Style.ColumnLimit = 20; 22786 return Style; 22787 }()); 22788 22789 // Test 9.3: with a parent file 22790 ASSERT_TRUE( 22791 FS.addFile("/e/.clang-format", 0, 22792 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22793 "UseTab: Always"))); 22794 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22795 ASSERT_TRUE(static_cast<bool>(Style9)); 22796 ASSERT_EQ(*Style9, [] { 22797 auto Style = getGoogleStyle(); 22798 Style.ColumnLimit = 20; 22799 Style.UseTab = FormatStyle::UT_Always; 22800 return Style; 22801 }()); 22802 22803 // Test 9.4: propagate more than one level with a parent file. 22804 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22805 auto Style = getGoogleStyle(); 22806 Style.ColumnLimit = 20; 22807 Style.UseTab = FormatStyle::UT_Always; 22808 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22809 return Style; 22810 }(); 22811 22812 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22813 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22814 ASSERT_TRUE(static_cast<bool>(Style9)); 22815 ASSERT_EQ(*Style9, SubSubStyle); 22816 22817 // Test 9.5: use InheritParentConfig as style name 22818 Style9 = 22819 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22820 ASSERT_TRUE(static_cast<bool>(Style9)); 22821 ASSERT_EQ(*Style9, SubSubStyle); 22822 22823 // Test 9.6: use command line style with inheritance 22824 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22825 "none", "", &FS); 22826 ASSERT_TRUE(static_cast<bool>(Style9)); 22827 ASSERT_EQ(*Style9, SubSubStyle); 22828 22829 // Test 9.7: use command line style with inheritance and own config 22830 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22831 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22832 "/e/sub/code.cpp", "none", "", &FS); 22833 ASSERT_TRUE(static_cast<bool>(Style9)); 22834 ASSERT_EQ(*Style9, SubSubStyle); 22835 22836 // Test 9.8: use inheritance from a file without BasedOnStyle 22837 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22838 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22839 ASSERT_TRUE( 22840 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22841 llvm::MemoryBuffer::getMemBuffer( 22842 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22843 // Make sure we do not use the fallback style 22844 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22845 ASSERT_TRUE(static_cast<bool>(Style9)); 22846 ASSERT_EQ(*Style9, [] { 22847 auto Style = getLLVMStyle(); 22848 Style.ColumnLimit = 123; 22849 return Style; 22850 }()); 22851 22852 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22853 ASSERT_TRUE(static_cast<bool>(Style9)); 22854 ASSERT_EQ(*Style9, [] { 22855 auto Style = getLLVMStyle(); 22856 Style.ColumnLimit = 123; 22857 Style.IndentWidth = 7; 22858 return Style; 22859 }()); 22860 22861 // Test 9.9: use inheritance from a specific config file. 22862 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22863 "none", "", &FS); 22864 ASSERT_TRUE(static_cast<bool>(Style9)); 22865 ASSERT_EQ(*Style9, SubSubStyle); 22866 } 22867 22868 TEST(FormatStyle, GetStyleOfSpecificFile) { 22869 llvm::vfs::InMemoryFileSystem FS; 22870 // Specify absolute path to a format file in a parent directory. 22871 ASSERT_TRUE( 22872 FS.addFile("/e/.clang-format", 0, 22873 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22874 ASSERT_TRUE( 22875 FS.addFile("/e/explicit.clang-format", 0, 22876 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22877 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22878 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22879 auto Style = getStyle("file:/e/explicit.clang-format", 22880 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22881 ASSERT_TRUE(static_cast<bool>(Style)); 22882 ASSERT_EQ(*Style, getGoogleStyle()); 22883 22884 // Specify relative path to a format file. 22885 ASSERT_TRUE( 22886 FS.addFile("../../e/explicit.clang-format", 0, 22887 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22888 Style = getStyle("file:../../e/explicit.clang-format", 22889 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22890 ASSERT_TRUE(static_cast<bool>(Style)); 22891 ASSERT_EQ(*Style, getGoogleStyle()); 22892 22893 // Specify path to a format file that does not exist. 22894 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22895 "LLVM", "", &FS); 22896 ASSERT_FALSE(static_cast<bool>(Style)); 22897 llvm::consumeError(Style.takeError()); 22898 22899 // Specify path to a file on the filesystem. 22900 SmallString<128> FormatFilePath; 22901 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22902 "FormatFileTest", "tpl", FormatFilePath); 22903 EXPECT_FALSE((bool)ECF); 22904 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22905 EXPECT_FALSE((bool)ECF); 22906 FormatFileTest << "BasedOnStyle: Google\n"; 22907 FormatFileTest.close(); 22908 22909 SmallString<128> TestFilePath; 22910 std::error_code ECT = 22911 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22912 EXPECT_FALSE((bool)ECT); 22913 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22914 CodeFileTest << "int i;\n"; 22915 CodeFileTest.close(); 22916 22917 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22918 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22919 22920 llvm::sys::fs::remove(FormatFilePath.c_str()); 22921 llvm::sys::fs::remove(TestFilePath.c_str()); 22922 ASSERT_TRUE(static_cast<bool>(Style)); 22923 ASSERT_EQ(*Style, getGoogleStyle()); 22924 } 22925 22926 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22927 // Column limit is 20. 22928 std::string Code = "Type *a =\n" 22929 " new Type();\n" 22930 "g(iiiii, 0, jjjjj,\n" 22931 " 0, kkkkk, 0, mm);\n" 22932 "int bad = format ;"; 22933 std::string Expected = "auto a = new Type();\n" 22934 "g(iiiii, nullptr,\n" 22935 " jjjjj, nullptr,\n" 22936 " kkkkk, nullptr,\n" 22937 " mm);\n" 22938 "int bad = format ;"; 22939 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22940 tooling::Replacements Replaces = toReplacements( 22941 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22942 "auto "), 22943 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22944 "nullptr"), 22945 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22946 "nullptr"), 22947 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22948 "nullptr")}); 22949 22950 FormatStyle Style = getLLVMStyle(); 22951 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22952 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22953 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22954 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22955 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22956 EXPECT_TRUE(static_cast<bool>(Result)); 22957 EXPECT_EQ(Expected, *Result); 22958 } 22959 22960 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22961 std::string Code = "#include \"a.h\"\n" 22962 "#include \"c.h\"\n" 22963 "\n" 22964 "int main() {\n" 22965 " return 0;\n" 22966 "}"; 22967 std::string Expected = "#include \"a.h\"\n" 22968 "#include \"b.h\"\n" 22969 "#include \"c.h\"\n" 22970 "\n" 22971 "int main() {\n" 22972 " return 0;\n" 22973 "}"; 22974 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22975 tooling::Replacements Replaces = toReplacements( 22976 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22977 "#include \"b.h\"\n")}); 22978 22979 FormatStyle Style = getLLVMStyle(); 22980 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22981 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22982 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22983 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22984 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22985 EXPECT_TRUE(static_cast<bool>(Result)); 22986 EXPECT_EQ(Expected, *Result); 22987 } 22988 22989 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22990 EXPECT_EQ("using std::cin;\n" 22991 "using std::cout;", 22992 format("using std::cout;\n" 22993 "using std::cin;", 22994 getGoogleStyle())); 22995 } 22996 22997 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22998 FormatStyle Style = getLLVMStyle(); 22999 Style.Standard = FormatStyle::LS_Cpp03; 23000 // cpp03 recognize this string as identifier u8 and literal character 'a' 23001 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 23002 } 23003 23004 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 23005 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 23006 // all modes, including C++11, C++14 and C++17 23007 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 23008 } 23009 23010 TEST_F(FormatTest, DoNotFormatLikelyXml) { 23011 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 23012 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 23013 } 23014 23015 TEST_F(FormatTest, StructuredBindings) { 23016 // Structured bindings is a C++17 feature. 23017 // all modes, including C++11, C++14 and C++17 23018 verifyFormat("auto [a, b] = f();"); 23019 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 23020 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 23021 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 23022 EXPECT_EQ("auto const volatile [a, b] = f();", 23023 format("auto const volatile[a, b] = f();")); 23024 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 23025 EXPECT_EQ("auto &[a, b, c] = f();", 23026 format("auto &[ a , b,c ] = f();")); 23027 EXPECT_EQ("auto &&[a, b, c] = f();", 23028 format("auto &&[ a , b,c ] = f();")); 23029 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 23030 EXPECT_EQ("auto const volatile &&[a, b] = f();", 23031 format("auto const volatile &&[a, b] = f();")); 23032 EXPECT_EQ("auto const &&[a, b] = f();", 23033 format("auto const && [a, b] = f();")); 23034 EXPECT_EQ("const auto &[a, b] = f();", 23035 format("const auto & [a, b] = f();")); 23036 EXPECT_EQ("const auto volatile &&[a, b] = f();", 23037 format("const auto volatile &&[a, b] = f();")); 23038 EXPECT_EQ("volatile const auto &&[a, b] = f();", 23039 format("volatile const auto &&[a, b] = f();")); 23040 EXPECT_EQ("const auto &&[a, b] = f();", 23041 format("const auto && [a, b] = f();")); 23042 23043 // Make sure we don't mistake structured bindings for lambdas. 23044 FormatStyle PointerMiddle = getLLVMStyle(); 23045 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 23046 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 23047 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 23048 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 23049 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 23050 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 23051 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 23052 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 23053 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 23054 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 23055 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 23056 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 23057 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 23058 23059 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 23060 format("for (const auto && [a, b] : some_range) {\n}")); 23061 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 23062 format("for (const auto & [a, b] : some_range) {\n}")); 23063 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 23064 format("for (const auto[a, b] : some_range) {\n}")); 23065 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 23066 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 23067 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 23068 EXPECT_EQ("auto const &[x, y](expr);", 23069 format("auto const & [x,y] (expr);")); 23070 EXPECT_EQ("auto const &&[x, y](expr);", 23071 format("auto const && [x,y] (expr);")); 23072 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 23073 EXPECT_EQ("auto const &[x, y]{expr};", 23074 format("auto const & [x,y] {expr};")); 23075 EXPECT_EQ("auto const &&[x, y]{expr};", 23076 format("auto const && [x,y] {expr};")); 23077 23078 FormatStyle Spaces = getLLVMStyle(); 23079 Spaces.SpacesInSquareBrackets = true; 23080 verifyFormat("auto [ a, b ] = f();", Spaces); 23081 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23082 verifyFormat("auto &[ a, b ] = f();", Spaces); 23083 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23084 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23085 } 23086 23087 TEST_F(FormatTest, FileAndCode) { 23088 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23089 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23090 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23091 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23092 EXPECT_EQ(FormatStyle::LK_ObjC, 23093 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23094 EXPECT_EQ( 23095 FormatStyle::LK_ObjC, 23096 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23097 EXPECT_EQ(FormatStyle::LK_ObjC, 23098 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23099 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23100 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23101 EXPECT_EQ(FormatStyle::LK_ObjC, 23102 guessLanguage("foo", "@interface Foo\n@end\n")); 23103 EXPECT_EQ(FormatStyle::LK_ObjC, 23104 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23105 EXPECT_EQ( 23106 FormatStyle::LK_ObjC, 23107 guessLanguage("foo.h", 23108 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23109 EXPECT_EQ( 23110 FormatStyle::LK_Cpp, 23111 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23112 // Only one of the two preprocessor regions has ObjC-like code. 23113 EXPECT_EQ(FormatStyle::LK_ObjC, 23114 guessLanguage("foo.h", "#if A\n" 23115 "#define B() C\n" 23116 "#else\n" 23117 "#define B() [NSString a:@\"\"]\n" 23118 "#endif\n")); 23119 } 23120 23121 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23122 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23123 EXPECT_EQ(FormatStyle::LK_ObjC, 23124 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23125 EXPECT_EQ(FormatStyle::LK_Cpp, 23126 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23127 EXPECT_EQ( 23128 FormatStyle::LK_Cpp, 23129 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23130 EXPECT_EQ(FormatStyle::LK_ObjC, 23131 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23132 EXPECT_EQ(FormatStyle::LK_Cpp, 23133 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23134 EXPECT_EQ(FormatStyle::LK_ObjC, 23135 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23136 EXPECT_EQ(FormatStyle::LK_Cpp, 23137 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23138 EXPECT_EQ(FormatStyle::LK_Cpp, 23139 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23140 EXPECT_EQ(FormatStyle::LK_ObjC, 23141 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23142 EXPECT_EQ(FormatStyle::LK_Cpp, 23143 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23144 EXPECT_EQ( 23145 FormatStyle::LK_Cpp, 23146 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23147 EXPECT_EQ( 23148 FormatStyle::LK_Cpp, 23149 guessLanguage("foo.h", 23150 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23151 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23152 } 23153 23154 TEST_F(FormatTest, GuessLanguageWithCaret) { 23155 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23156 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23157 EXPECT_EQ(FormatStyle::LK_ObjC, 23158 guessLanguage("foo.h", "int(^)(char, float);")); 23159 EXPECT_EQ(FormatStyle::LK_ObjC, 23160 guessLanguage("foo.h", "int(^foo)(char, float);")); 23161 EXPECT_EQ(FormatStyle::LK_ObjC, 23162 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23163 EXPECT_EQ(FormatStyle::LK_ObjC, 23164 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23165 EXPECT_EQ( 23166 FormatStyle::LK_ObjC, 23167 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23168 } 23169 23170 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23171 EXPECT_EQ(FormatStyle::LK_Cpp, 23172 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23173 EXPECT_EQ(FormatStyle::LK_Cpp, 23174 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23175 EXPECT_EQ(FormatStyle::LK_Cpp, 23176 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23177 } 23178 23179 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23180 // ASM symbolic names are identifiers that must be surrounded by [] without 23181 // space in between: 23182 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23183 23184 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23185 verifyFormat(R"(// 23186 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23187 )"); 23188 23189 // A list of several ASM symbolic names. 23190 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23191 23192 // ASM symbolic names in inline ASM with inputs and outputs. 23193 verifyFormat(R"(// 23194 asm("cmoveq %1, %2, %[result]" 23195 : [result] "=r"(result) 23196 : "r"(test), "r"(new), "[result]"(old)); 23197 )"); 23198 23199 // ASM symbolic names in inline ASM with no outputs. 23200 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23201 } 23202 23203 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23204 EXPECT_EQ(FormatStyle::LK_Cpp, 23205 guessLanguage("foo.h", "void f() {\n" 23206 " asm (\"mov %[e], %[d]\"\n" 23207 " : [d] \"=rm\" (d)\n" 23208 " [e] \"rm\" (*e));\n" 23209 "}")); 23210 EXPECT_EQ(FormatStyle::LK_Cpp, 23211 guessLanguage("foo.h", "void f() {\n" 23212 " _asm (\"mov %[e], %[d]\"\n" 23213 " : [d] \"=rm\" (d)\n" 23214 " [e] \"rm\" (*e));\n" 23215 "}")); 23216 EXPECT_EQ(FormatStyle::LK_Cpp, 23217 guessLanguage("foo.h", "void f() {\n" 23218 " __asm (\"mov %[e], %[d]\"\n" 23219 " : [d] \"=rm\" (d)\n" 23220 " [e] \"rm\" (*e));\n" 23221 "}")); 23222 EXPECT_EQ(FormatStyle::LK_Cpp, 23223 guessLanguage("foo.h", "void f() {\n" 23224 " __asm__ (\"mov %[e], %[d]\"\n" 23225 " : [d] \"=rm\" (d)\n" 23226 " [e] \"rm\" (*e));\n" 23227 "}")); 23228 EXPECT_EQ(FormatStyle::LK_Cpp, 23229 guessLanguage("foo.h", "void f() {\n" 23230 " asm (\"mov %[e], %[d]\"\n" 23231 " : [d] \"=rm\" (d),\n" 23232 " [e] \"rm\" (*e));\n" 23233 "}")); 23234 EXPECT_EQ(FormatStyle::LK_Cpp, 23235 guessLanguage("foo.h", "void f() {\n" 23236 " asm volatile (\"mov %[e], %[d]\"\n" 23237 " : [d] \"=rm\" (d)\n" 23238 " [e] \"rm\" (*e));\n" 23239 "}")); 23240 } 23241 23242 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23243 EXPECT_EQ(FormatStyle::LK_Cpp, 23244 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23245 EXPECT_EQ(FormatStyle::LK_ObjC, 23246 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23247 EXPECT_EQ( 23248 FormatStyle::LK_Cpp, 23249 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23250 EXPECT_EQ( 23251 FormatStyle::LK_ObjC, 23252 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23253 } 23254 23255 TEST_F(FormatTest, TypenameMacros) { 23256 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23257 23258 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23259 FormatStyle Google = getGoogleStyleWithColumns(0); 23260 Google.TypenameMacros = TypenameMacros; 23261 verifyFormat("struct foo {\n" 23262 " int bar;\n" 23263 " TAILQ_ENTRY(a) bleh;\n" 23264 "};", 23265 Google); 23266 23267 FormatStyle Macros = getLLVMStyle(); 23268 Macros.TypenameMacros = TypenameMacros; 23269 23270 verifyFormat("STACK_OF(int) a;", Macros); 23271 verifyFormat("STACK_OF(int) *a;", Macros); 23272 verifyFormat("STACK_OF(int const *) *a;", Macros); 23273 verifyFormat("STACK_OF(int *const) *a;", Macros); 23274 verifyFormat("STACK_OF(int, string) a;", Macros); 23275 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23276 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23277 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23278 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23279 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23280 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23281 23282 Macros.PointerAlignment = FormatStyle::PAS_Left; 23283 verifyFormat("STACK_OF(int)* a;", Macros); 23284 verifyFormat("STACK_OF(int*)* a;", Macros); 23285 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23286 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23287 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23288 } 23289 23290 TEST_F(FormatTest, AtomicQualifier) { 23291 // Check that we treate _Atomic as a type and not a function call 23292 FormatStyle Google = getGoogleStyleWithColumns(0); 23293 verifyFormat("struct foo {\n" 23294 " int a1;\n" 23295 " _Atomic(a) a2;\n" 23296 " _Atomic(_Atomic(int) *const) a3;\n" 23297 "};", 23298 Google); 23299 verifyFormat("_Atomic(uint64_t) a;"); 23300 verifyFormat("_Atomic(uint64_t) *a;"); 23301 verifyFormat("_Atomic(uint64_t const *) *a;"); 23302 verifyFormat("_Atomic(uint64_t *const) *a;"); 23303 verifyFormat("_Atomic(const uint64_t *) *a;"); 23304 verifyFormat("_Atomic(uint64_t) a;"); 23305 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23306 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23307 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23308 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23309 23310 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23311 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23312 FormatStyle Style = getLLVMStyle(); 23313 Style.PointerAlignment = FormatStyle::PAS_Left; 23314 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23315 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23316 verifyFormat("_Atomic(int)* a;", Style); 23317 verifyFormat("_Atomic(int*)* a;", Style); 23318 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23319 23320 Style.SpacesInCStyleCastParentheses = true; 23321 Style.SpacesInParentheses = false; 23322 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23323 Style.SpacesInCStyleCastParentheses = false; 23324 Style.SpacesInParentheses = true; 23325 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23326 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23327 } 23328 23329 TEST_F(FormatTest, AmbersandInLamda) { 23330 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23331 FormatStyle AlignStyle = getLLVMStyle(); 23332 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23333 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23334 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23335 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23336 } 23337 23338 TEST_F(FormatTest, SpacesInConditionalStatement) { 23339 FormatStyle Spaces = getLLVMStyle(); 23340 Spaces.IfMacros.clear(); 23341 Spaces.IfMacros.push_back("MYIF"); 23342 Spaces.SpacesInConditionalStatement = true; 23343 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23344 verifyFormat("if ( !a )\n return;", Spaces); 23345 verifyFormat("if ( a )\n return;", Spaces); 23346 verifyFormat("if constexpr ( a )\n return;", Spaces); 23347 verifyFormat("MYIF ( a )\n return;", Spaces); 23348 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23349 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23350 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23351 verifyFormat("while ( a )\n return;", Spaces); 23352 verifyFormat("while ( (a && b) )\n return;", Spaces); 23353 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23354 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23355 // Check that space on the left of "::" is inserted as expected at beginning 23356 // of condition. 23357 verifyFormat("while ( ::func() )\n return;", Spaces); 23358 23359 // Check impact of ControlStatementsExceptControlMacros is honored. 23360 Spaces.SpaceBeforeParens = 23361 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23362 verifyFormat("MYIF( a )\n return;", Spaces); 23363 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23364 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23365 } 23366 23367 TEST_F(FormatTest, AlternativeOperators) { 23368 // Test case for ensuring alternate operators are not 23369 // combined with their right most neighbour. 23370 verifyFormat("int a and b;"); 23371 verifyFormat("int a and_eq b;"); 23372 verifyFormat("int a bitand b;"); 23373 verifyFormat("int a bitor b;"); 23374 verifyFormat("int a compl b;"); 23375 verifyFormat("int a not b;"); 23376 verifyFormat("int a not_eq b;"); 23377 verifyFormat("int a or b;"); 23378 verifyFormat("int a xor b;"); 23379 verifyFormat("int a xor_eq b;"); 23380 verifyFormat("return this not_eq bitand other;"); 23381 verifyFormat("bool operator not_eq(const X bitand other)"); 23382 23383 verifyFormat("int a and 5;"); 23384 verifyFormat("int a and_eq 5;"); 23385 verifyFormat("int a bitand 5;"); 23386 verifyFormat("int a bitor 5;"); 23387 verifyFormat("int a compl 5;"); 23388 verifyFormat("int a not 5;"); 23389 verifyFormat("int a not_eq 5;"); 23390 verifyFormat("int a or 5;"); 23391 verifyFormat("int a xor 5;"); 23392 verifyFormat("int a xor_eq 5;"); 23393 23394 verifyFormat("int a compl(5);"); 23395 verifyFormat("int a not(5);"); 23396 23397 /* FIXME handle alternate tokens 23398 * https://en.cppreference.com/w/cpp/language/operator_alternative 23399 // alternative tokens 23400 verifyFormat("compl foo();"); // ~foo(); 23401 verifyFormat("foo() <%%>;"); // foo(); 23402 verifyFormat("void foo() <%%>;"); // void foo(){} 23403 verifyFormat("int a <:1:>;"); // int a[1];[ 23404 verifyFormat("%:define ABC abc"); // #define ABC abc 23405 verifyFormat("%:%:"); // ## 23406 */ 23407 } 23408 23409 TEST_F(FormatTest, STLWhileNotDefineChed) { 23410 verifyFormat("#if defined(while)\n" 23411 "#define while EMIT WARNING C4005\n" 23412 "#endif // while"); 23413 } 23414 23415 TEST_F(FormatTest, OperatorSpacing) { 23416 FormatStyle Style = getLLVMStyle(); 23417 Style.PointerAlignment = FormatStyle::PAS_Right; 23418 verifyFormat("Foo::operator*();", Style); 23419 verifyFormat("Foo::operator void *();", Style); 23420 verifyFormat("Foo::operator void **();", Style); 23421 verifyFormat("Foo::operator void *&();", Style); 23422 verifyFormat("Foo::operator void *&&();", Style); 23423 verifyFormat("Foo::operator void const *();", Style); 23424 verifyFormat("Foo::operator void const **();", Style); 23425 verifyFormat("Foo::operator void const *&();", Style); 23426 verifyFormat("Foo::operator void const *&&();", Style); 23427 verifyFormat("Foo::operator()(void *);", Style); 23428 verifyFormat("Foo::operator*(void *);", Style); 23429 verifyFormat("Foo::operator*();", Style); 23430 verifyFormat("Foo::operator**();", Style); 23431 verifyFormat("Foo::operator&();", Style); 23432 verifyFormat("Foo::operator<int> *();", Style); 23433 verifyFormat("Foo::operator<Foo> *();", Style); 23434 verifyFormat("Foo::operator<int> **();", Style); 23435 verifyFormat("Foo::operator<Foo> **();", Style); 23436 verifyFormat("Foo::operator<int> &();", Style); 23437 verifyFormat("Foo::operator<Foo> &();", Style); 23438 verifyFormat("Foo::operator<int> &&();", Style); 23439 verifyFormat("Foo::operator<Foo> &&();", Style); 23440 verifyFormat("Foo::operator<int> *&();", Style); 23441 verifyFormat("Foo::operator<Foo> *&();", Style); 23442 verifyFormat("Foo::operator<int> *&&();", Style); 23443 verifyFormat("Foo::operator<Foo> *&&();", Style); 23444 verifyFormat("operator*(int (*)(), class Foo);", Style); 23445 23446 verifyFormat("Foo::operator&();", Style); 23447 verifyFormat("Foo::operator void &();", Style); 23448 verifyFormat("Foo::operator void const &();", Style); 23449 verifyFormat("Foo::operator()(void &);", Style); 23450 verifyFormat("Foo::operator&(void &);", Style); 23451 verifyFormat("Foo::operator&();", Style); 23452 verifyFormat("operator&(int (&)(), class Foo);", Style); 23453 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23454 23455 verifyFormat("Foo::operator&&();", Style); 23456 verifyFormat("Foo::operator**();", Style); 23457 verifyFormat("Foo::operator void &&();", Style); 23458 verifyFormat("Foo::operator void const &&();", Style); 23459 verifyFormat("Foo::operator()(void &&);", Style); 23460 verifyFormat("Foo::operator&&(void &&);", Style); 23461 verifyFormat("Foo::operator&&();", Style); 23462 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23463 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23464 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23465 Style); 23466 verifyFormat("operator void **()", Style); 23467 verifyFormat("operator const FooRight<Object> &()", Style); 23468 verifyFormat("operator const FooRight<Object> *()", Style); 23469 verifyFormat("operator const FooRight<Object> **()", Style); 23470 verifyFormat("operator const FooRight<Object> *&()", Style); 23471 verifyFormat("operator const FooRight<Object> *&&()", Style); 23472 23473 Style.PointerAlignment = FormatStyle::PAS_Left; 23474 verifyFormat("Foo::operator*();", Style); 23475 verifyFormat("Foo::operator**();", Style); 23476 verifyFormat("Foo::operator void*();", Style); 23477 verifyFormat("Foo::operator void**();", Style); 23478 verifyFormat("Foo::operator void*&();", Style); 23479 verifyFormat("Foo::operator void*&&();", Style); 23480 verifyFormat("Foo::operator void const*();", Style); 23481 verifyFormat("Foo::operator void const**();", Style); 23482 verifyFormat("Foo::operator void const*&();", Style); 23483 verifyFormat("Foo::operator void const*&&();", Style); 23484 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23485 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23486 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23487 verifyFormat("Foo::operator()(void*);", Style); 23488 verifyFormat("Foo::operator*(void*);", Style); 23489 verifyFormat("Foo::operator*();", Style); 23490 verifyFormat("Foo::operator<int>*();", Style); 23491 verifyFormat("Foo::operator<Foo>*();", Style); 23492 verifyFormat("Foo::operator<int>**();", Style); 23493 verifyFormat("Foo::operator<Foo>**();", Style); 23494 verifyFormat("Foo::operator<Foo>*&();", Style); 23495 verifyFormat("Foo::operator<int>&();", Style); 23496 verifyFormat("Foo::operator<Foo>&();", Style); 23497 verifyFormat("Foo::operator<int>&&();", Style); 23498 verifyFormat("Foo::operator<Foo>&&();", Style); 23499 verifyFormat("Foo::operator<int>*&();", Style); 23500 verifyFormat("Foo::operator<Foo>*&();", Style); 23501 verifyFormat("operator*(int (*)(), class Foo);", Style); 23502 23503 verifyFormat("Foo::operator&();", Style); 23504 verifyFormat("Foo::operator void&();", Style); 23505 verifyFormat("Foo::operator void const&();", Style); 23506 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23507 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23508 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23509 verifyFormat("Foo::operator()(void&);", Style); 23510 verifyFormat("Foo::operator&(void&);", Style); 23511 verifyFormat("Foo::operator&();", Style); 23512 verifyFormat("operator&(int (&)(), class Foo);", Style); 23513 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23514 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23515 23516 verifyFormat("Foo::operator&&();", Style); 23517 verifyFormat("Foo::operator void&&();", Style); 23518 verifyFormat("Foo::operator void const&&();", Style); 23519 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23520 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23521 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23522 verifyFormat("Foo::operator()(void&&);", Style); 23523 verifyFormat("Foo::operator&&(void&&);", Style); 23524 verifyFormat("Foo::operator&&();", Style); 23525 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23526 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23527 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23528 Style); 23529 verifyFormat("operator void**()", Style); 23530 verifyFormat("operator const FooLeft<Object>&()", Style); 23531 verifyFormat("operator const FooLeft<Object>*()", Style); 23532 verifyFormat("operator const FooLeft<Object>**()", Style); 23533 verifyFormat("operator const FooLeft<Object>*&()", Style); 23534 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23535 23536 // PR45107 23537 verifyFormat("operator Vector<String>&();", Style); 23538 verifyFormat("operator const Vector<String>&();", Style); 23539 verifyFormat("operator foo::Bar*();", Style); 23540 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23541 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23542 Style); 23543 23544 Style.PointerAlignment = FormatStyle::PAS_Middle; 23545 verifyFormat("Foo::operator*();", Style); 23546 verifyFormat("Foo::operator void *();", Style); 23547 verifyFormat("Foo::operator()(void *);", Style); 23548 verifyFormat("Foo::operator*(void *);", Style); 23549 verifyFormat("Foo::operator*();", Style); 23550 verifyFormat("operator*(int (*)(), class Foo);", Style); 23551 23552 verifyFormat("Foo::operator&();", Style); 23553 verifyFormat("Foo::operator void &();", Style); 23554 verifyFormat("Foo::operator void const &();", Style); 23555 verifyFormat("Foo::operator()(void &);", Style); 23556 verifyFormat("Foo::operator&(void &);", Style); 23557 verifyFormat("Foo::operator&();", Style); 23558 verifyFormat("operator&(int (&)(), class Foo);", Style); 23559 23560 verifyFormat("Foo::operator&&();", Style); 23561 verifyFormat("Foo::operator void &&();", Style); 23562 verifyFormat("Foo::operator void const &&();", Style); 23563 verifyFormat("Foo::operator()(void &&);", Style); 23564 verifyFormat("Foo::operator&&(void &&);", Style); 23565 verifyFormat("Foo::operator&&();", Style); 23566 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23567 } 23568 23569 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23570 FormatStyle Style = getLLVMStyle(); 23571 // PR46157 23572 verifyFormat("foo(operator+, -42);", Style); 23573 verifyFormat("foo(operator++, -42);", Style); 23574 verifyFormat("foo(operator--, -42);", Style); 23575 verifyFormat("foo(-42, operator--);", Style); 23576 verifyFormat("foo(-42, operator, );", Style); 23577 verifyFormat("foo(operator, , -42);", Style); 23578 } 23579 23580 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23581 FormatStyle Style = getLLVMStyle(); 23582 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23583 23584 // Don't use the helpers here, since 'mess up' will change the whitespace 23585 // and these are all whitespace sensitive by definition 23586 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23587 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23588 EXPECT_EQ( 23589 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23590 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23591 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23592 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23593 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23594 " Still=Intentional);", 23595 format("FOO(String-ized&Messy+But,: :\n" 23596 " Still=Intentional);", 23597 Style)); 23598 Style.AlignConsecutiveAssignments.Enabled = true; 23599 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23600 " Still=Intentional);", 23601 format("FOO(String-ized=&Messy+But,: :\n" 23602 " Still=Intentional);", 23603 Style)); 23604 23605 Style.ColumnLimit = 21; 23606 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23607 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23608 } 23609 23610 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23611 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23612 // test its interaction with line wrapping 23613 FormatStyle Style = getLLVMStyleWithColumns(80); 23614 verifyFormat("namespace {\n" 23615 "int i;\n" 23616 "int j;\n" 23617 "} // namespace", 23618 Style); 23619 23620 verifyFormat("namespace AAA {\n" 23621 "int i;\n" 23622 "int j;\n" 23623 "} // namespace AAA", 23624 Style); 23625 23626 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23627 "int i;\n" 23628 "int j;\n" 23629 "} // namespace Averyveryveryverylongnamespace", 23630 format("namespace Averyveryveryverylongnamespace {\n" 23631 "int i;\n" 23632 "int j;\n" 23633 "}", 23634 Style)); 23635 23636 EXPECT_EQ( 23637 "namespace " 23638 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23639 " went::mad::now {\n" 23640 "int i;\n" 23641 "int j;\n" 23642 "} // namespace\n" 23643 " // " 23644 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23645 "went::mad::now", 23646 format("namespace " 23647 "would::it::save::you::a::lot::of::time::if_::i::" 23648 "just::gave::up::and_::went::mad::now {\n" 23649 "int i;\n" 23650 "int j;\n" 23651 "}", 23652 Style)); 23653 23654 // This used to duplicate the comment again and again on subsequent runs 23655 EXPECT_EQ( 23656 "namespace " 23657 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23658 " went::mad::now {\n" 23659 "int i;\n" 23660 "int j;\n" 23661 "} // namespace\n" 23662 " // " 23663 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23664 "went::mad::now", 23665 format("namespace " 23666 "would::it::save::you::a::lot::of::time::if_::i::" 23667 "just::gave::up::and_::went::mad::now {\n" 23668 "int i;\n" 23669 "int j;\n" 23670 "} // namespace\n" 23671 " // " 23672 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23673 "and_::went::mad::now", 23674 Style)); 23675 } 23676 23677 TEST_F(FormatTest, LikelyUnlikely) { 23678 FormatStyle Style = getLLVMStyle(); 23679 23680 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23681 " return 29;\n" 23682 "}", 23683 Style); 23684 23685 verifyFormat("if (argc > 5) [[likely]] {\n" 23686 " return 29;\n" 23687 "}", 23688 Style); 23689 23690 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23691 " return 29;\n" 23692 "} else [[likely]] {\n" 23693 " return 42;\n" 23694 "}\n", 23695 Style); 23696 23697 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23698 " return 29;\n" 23699 "} else if (argc > 10) [[likely]] {\n" 23700 " return 99;\n" 23701 "} else {\n" 23702 " return 42;\n" 23703 "}\n", 23704 Style); 23705 23706 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23707 " return 29;\n" 23708 "}", 23709 Style); 23710 23711 verifyFormat("if (argc > 5) [[unlikely]]\n" 23712 " return 29;\n", 23713 Style); 23714 verifyFormat("if (argc > 5) [[likely]]\n" 23715 " return 29;\n", 23716 Style); 23717 23718 Style.AttributeMacros.push_back("UNLIKELY"); 23719 Style.AttributeMacros.push_back("LIKELY"); 23720 verifyFormat("if (argc > 5) UNLIKELY\n" 23721 " return 29;\n", 23722 Style); 23723 23724 verifyFormat("if (argc > 5) UNLIKELY {\n" 23725 " return 29;\n" 23726 "}", 23727 Style); 23728 verifyFormat("if (argc > 5) UNLIKELY {\n" 23729 " return 29;\n" 23730 "} else [[likely]] {\n" 23731 " return 42;\n" 23732 "}\n", 23733 Style); 23734 verifyFormat("if (argc > 5) UNLIKELY {\n" 23735 " return 29;\n" 23736 "} else LIKELY {\n" 23737 " return 42;\n" 23738 "}\n", 23739 Style); 23740 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23741 " return 29;\n" 23742 "} else LIKELY {\n" 23743 " return 42;\n" 23744 "}\n", 23745 Style); 23746 } 23747 23748 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23749 verifyFormat("Constructor()\n" 23750 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23751 " aaaa(aaaaaaaaaaaaaaaaaa, " 23752 "aaaaaaaaaaaaaaaaaat))"); 23753 verifyFormat("Constructor()\n" 23754 " : aaaaaaaaaaaaa(aaaaaa), " 23755 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23756 23757 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23758 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23759 verifyFormat("Constructor()\n" 23760 " : aaaaaa(aaaaaa),\n" 23761 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23762 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23763 StyleWithWhitespacePenalty); 23764 verifyFormat("Constructor()\n" 23765 " : aaaaaaaaaaaaa(aaaaaa), " 23766 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23767 StyleWithWhitespacePenalty); 23768 } 23769 23770 TEST_F(FormatTest, LLVMDefaultStyle) { 23771 FormatStyle Style = getLLVMStyle(); 23772 verifyFormat("extern \"C\" {\n" 23773 "int foo();\n" 23774 "}", 23775 Style); 23776 } 23777 TEST_F(FormatTest, GNUDefaultStyle) { 23778 FormatStyle Style = getGNUStyle(); 23779 verifyFormat("extern \"C\"\n" 23780 "{\n" 23781 " int foo ();\n" 23782 "}", 23783 Style); 23784 } 23785 TEST_F(FormatTest, MozillaDefaultStyle) { 23786 FormatStyle Style = getMozillaStyle(); 23787 verifyFormat("extern \"C\"\n" 23788 "{\n" 23789 " int foo();\n" 23790 "}", 23791 Style); 23792 } 23793 TEST_F(FormatTest, GoogleDefaultStyle) { 23794 FormatStyle Style = getGoogleStyle(); 23795 verifyFormat("extern \"C\" {\n" 23796 "int foo();\n" 23797 "}", 23798 Style); 23799 } 23800 TEST_F(FormatTest, ChromiumDefaultStyle) { 23801 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23802 verifyFormat("extern \"C\" {\n" 23803 "int foo();\n" 23804 "}", 23805 Style); 23806 } 23807 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23808 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23809 verifyFormat("extern \"C\"\n" 23810 "{\n" 23811 " int foo();\n" 23812 "}", 23813 Style); 23814 } 23815 TEST_F(FormatTest, WebKitDefaultStyle) { 23816 FormatStyle Style = getWebKitStyle(); 23817 verifyFormat("extern \"C\" {\n" 23818 "int foo();\n" 23819 "}", 23820 Style); 23821 } 23822 23823 TEST_F(FormatTest, Concepts) { 23824 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23825 FormatStyle::BBCDS_Always); 23826 verifyFormat("template <typename T>\n" 23827 "concept True = true;"); 23828 23829 verifyFormat("template <typename T>\n" 23830 "concept C = ((false || foo()) && C2<T>) ||\n" 23831 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23832 getLLVMStyleWithColumns(60)); 23833 23834 verifyFormat("template <typename T>\n" 23835 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23836 "sizeof(T) <= 8;"); 23837 23838 verifyFormat("template <typename T>\n" 23839 "concept DelayedCheck = true && requires(T t) {\n" 23840 " t.bar();\n" 23841 " t.baz();\n" 23842 " } && sizeof(T) <= 8;"); 23843 23844 verifyFormat("template <typename T>\n" 23845 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23846 " t.bar();\n" 23847 " t.baz();\n" 23848 " } && sizeof(T) <= 8;"); 23849 23850 verifyFormat("template <typename T>\n" 23851 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23852 "sizeof(T) <= 8;"); 23853 23854 verifyFormat("template <typename T>\n" 23855 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23856 "&& sizeof(T) <= 8;"); 23857 23858 verifyFormat( 23859 "template <typename T>\n" 23860 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23861 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23862 23863 verifyFormat("template <typename T>\n" 23864 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23865 "&& sizeof(T) <= 8;"); 23866 23867 verifyFormat( 23868 "template <typename T>\n" 23869 "concept DelayedCheck = (bool)(0) ||\n" 23870 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23871 23872 verifyFormat("template <typename T>\n" 23873 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23874 "&& sizeof(T) <= 8;"); 23875 23876 verifyFormat("template <typename T>\n" 23877 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23878 "sizeof(T) <= 8;"); 23879 23880 verifyFormat("template <typename T>\n" 23881 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23882 " requires(T t) {\n" 23883 " t.bar();\n" 23884 " t.baz();\n" 23885 " } && sizeof(T) <= 8 && !(4 < 3);", 23886 getLLVMStyleWithColumns(60)); 23887 23888 verifyFormat("template <typename T>\n" 23889 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23890 23891 verifyFormat("template <typename T>\n" 23892 "concept C = foo();"); 23893 23894 verifyFormat("template <typename T>\n" 23895 "concept C = foo(T());"); 23896 23897 verifyFormat("template <typename T>\n" 23898 "concept C = foo(T{});"); 23899 23900 verifyFormat("template <typename T>\n" 23901 "concept Size = V<sizeof(T)>::Value > 5;"); 23902 23903 verifyFormat("template <typename T>\n" 23904 "concept True = S<T>::Value;"); 23905 23906 verifyFormat( 23907 "template <typename T>\n" 23908 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23909 " sizeof(T) <= 8;"); 23910 23911 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23912 // the lambda l square. 23913 verifyFormat("template <typename T>\n" 23914 "concept C = [] -> bool { return true; }() && requires(T t) { " 23915 "t.bar(); } &&\n" 23916 " sizeof(T) <= 8;"); 23917 23918 verifyFormat( 23919 "template <typename T>\n" 23920 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23921 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23922 23923 verifyFormat("template <typename T>\n" 23924 "concept C = decltype([]() { return std::true_type{}; " 23925 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23926 getLLVMStyleWithColumns(120)); 23927 23928 verifyFormat("template <typename T>\n" 23929 "concept C = decltype([]() -> std::true_type { return {}; " 23930 "}())::value &&\n" 23931 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23932 23933 verifyFormat("template <typename T>\n" 23934 "concept C = true;\n" 23935 "Foo Bar;"); 23936 23937 verifyFormat("template <typename T>\n" 23938 "concept Hashable = requires(T a) {\n" 23939 " { std::hash<T>{}(a) } -> " 23940 "std::convertible_to<std::size_t>;\n" 23941 " };"); 23942 23943 verifyFormat( 23944 "template <typename T>\n" 23945 "concept EqualityComparable = requires(T a, T b) {\n" 23946 " { a == b } -> std::same_as<bool>;\n" 23947 " };"); 23948 23949 verifyFormat( 23950 "template <typename T>\n" 23951 "concept EqualityComparable = requires(T a, T b) {\n" 23952 " { a == b } -> std::same_as<bool>;\n" 23953 " { a != b } -> std::same_as<bool>;\n" 23954 " };"); 23955 23956 verifyFormat("template <typename T>\n" 23957 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23958 " { a == b };\n" 23959 " { a != b };\n" 23960 " };"); 23961 23962 verifyFormat("template <typename T>\n" 23963 "concept HasSizeT = requires { typename T::size_t; };"); 23964 23965 verifyFormat("template <typename T>\n" 23966 "concept Semiregular =\n" 23967 " DefaultConstructible<T> && CopyConstructible<T> && " 23968 "CopyAssignable<T> &&\n" 23969 " requires(T a, std::size_t n) {\n" 23970 " requires Same<T *, decltype(&a)>;\n" 23971 " { a.~T() } noexcept;\n" 23972 " requires Same<T *, decltype(new T)>;\n" 23973 " requires Same<T *, decltype(new T[n])>;\n" 23974 " { delete new T; };\n" 23975 " { delete new T[n]; };\n" 23976 " };"); 23977 23978 verifyFormat("template <typename T>\n" 23979 "concept Semiregular =\n" 23980 " requires(T a, std::size_t n) {\n" 23981 " requires Same<T *, decltype(&a)>;\n" 23982 " { a.~T() } noexcept;\n" 23983 " requires Same<T *, decltype(new T)>;\n" 23984 " requires Same<T *, decltype(new T[n])>;\n" 23985 " { delete new T; };\n" 23986 " { delete new T[n]; };\n" 23987 " { new T } -> std::same_as<T *>;\n" 23988 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23989 "CopyAssignable<T>;"); 23990 23991 verifyFormat( 23992 "template <typename T>\n" 23993 "concept Semiregular =\n" 23994 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23995 " requires Same<T *, decltype(&a)>;\n" 23996 " { a.~T() } noexcept;\n" 23997 " requires Same<T *, decltype(new T)>;\n" 23998 " requires Same<T *, decltype(new " 23999 "T[n])>;\n" 24000 " { delete new T; };\n" 24001 " { delete new T[n]; };\n" 24002 " } && CopyConstructible<T> && " 24003 "CopyAssignable<T>;"); 24004 24005 verifyFormat("template <typename T>\n" 24006 "concept Two = requires(T t) {\n" 24007 " { t.foo() } -> std::same_as<Bar>;\n" 24008 " } && requires(T &&t) {\n" 24009 " { t.foo() } -> std::same_as<Bar &&>;\n" 24010 " };"); 24011 24012 verifyFormat( 24013 "template <typename T>\n" 24014 "concept C = requires(T x) {\n" 24015 " { *x } -> std::convertible_to<typename T::inner>;\n" 24016 " { x + 1 } noexcept -> std::same_as<int>;\n" 24017 " { x * 1 } -> std::convertible_to<T>;\n" 24018 " };"); 24019 24020 verifyFormat( 24021 "template <typename T, typename U = T>\n" 24022 "concept Swappable = requires(T &&t, U &&u) {\n" 24023 " swap(std::forward<T>(t), std::forward<U>(u));\n" 24024 " swap(std::forward<U>(u), std::forward<T>(t));\n" 24025 " };"); 24026 24027 verifyFormat("template <typename T, typename U>\n" 24028 "concept Common = requires(T &&t, U &&u) {\n" 24029 " typename CommonType<T, U>;\n" 24030 " { CommonType<T, U>(std::forward<T>(t)) };\n" 24031 " };"); 24032 24033 verifyFormat("template <typename T, typename U>\n" 24034 "concept Common = requires(T &&t, U &&u) {\n" 24035 " typename CommonType<T, U>;\n" 24036 " { CommonType<T, U>{std::forward<T>(t)} };\n" 24037 " };"); 24038 24039 verifyFormat( 24040 "template <typename T>\n" 24041 "concept C = requires(T t) {\n" 24042 " requires Bar<T> && Foo<T>;\n" 24043 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24044 " };"); 24045 24046 verifyFormat("template <typename T>\n" 24047 "concept HasFoo = requires(T t) {\n" 24048 " { t.foo() };\n" 24049 " t.foo();\n" 24050 " };\n" 24051 "template <typename T>\n" 24052 "concept HasBar = requires(T t) {\n" 24053 " { t.bar() };\n" 24054 " t.bar();\n" 24055 " };"); 24056 24057 verifyFormat("template <typename T>\n" 24058 "concept Large = sizeof(T) > 10;"); 24059 24060 verifyFormat("template <typename T, typename U>\n" 24061 "concept FooableWith = requires(T t, U u) {\n" 24062 " typename T::foo_type;\n" 24063 " { t.foo(u) } -> typename T::foo_type;\n" 24064 " t++;\n" 24065 " };\n" 24066 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 24067 24068 verifyFormat("template <typename T>\n" 24069 "concept Context = is_specialization_of_v<context, T>;"); 24070 24071 verifyFormat("template <typename T>\n" 24072 "concept Node = std::is_object_v<T>;"); 24073 24074 verifyFormat("template <class T>\n" 24075 "concept integral = __is_integral(T);"); 24076 24077 verifyFormat("template <class T>\n" 24078 "concept is2D = __array_extent(T, 1) == 2;"); 24079 24080 verifyFormat("template <class T>\n" 24081 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24082 24083 verifyFormat("template <class T, class T2>\n" 24084 "concept Same = __is_same_as<T, T2>;"); 24085 24086 auto Style = getLLVMStyle(); 24087 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24088 24089 verifyFormat( 24090 "template <typename T>\n" 24091 "concept C = requires(T t) {\n" 24092 " requires Bar<T> && Foo<T>;\n" 24093 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24094 " };", 24095 Style); 24096 24097 verifyFormat("template <typename T>\n" 24098 "concept HasFoo = requires(T t) {\n" 24099 " { t.foo() };\n" 24100 " t.foo();\n" 24101 " };\n" 24102 "template <typename T>\n" 24103 "concept HasBar = requires(T t) {\n" 24104 " { t.bar() };\n" 24105 " t.bar();\n" 24106 " };", 24107 Style); 24108 24109 verifyFormat("template <typename T> concept True = true;", Style); 24110 24111 verifyFormat("template <typename T>\n" 24112 "concept C = decltype([]() -> std::true_type { return {}; " 24113 "}())::value &&\n" 24114 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24115 Style); 24116 24117 verifyFormat("template <typename T>\n" 24118 "concept Semiregular =\n" 24119 " DefaultConstructible<T> && CopyConstructible<T> && " 24120 "CopyAssignable<T> &&\n" 24121 " requires(T a, std::size_t n) {\n" 24122 " requires Same<T *, decltype(&a)>;\n" 24123 " { a.~T() } noexcept;\n" 24124 " requires Same<T *, decltype(new T)>;\n" 24125 " requires Same<T *, decltype(new T[n])>;\n" 24126 " { delete new T; };\n" 24127 " { delete new T[n]; };\n" 24128 " };", 24129 Style); 24130 24131 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24132 24133 verifyFormat("template <typename T> concept C =\n" 24134 " requires(T t) {\n" 24135 " requires Bar<T> && Foo<T>;\n" 24136 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24137 " };", 24138 Style); 24139 24140 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24141 " { t.foo() };\n" 24142 " t.foo();\n" 24143 " };\n" 24144 "template <typename T> concept HasBar = requires(T t) {\n" 24145 " { t.bar() };\n" 24146 " t.bar();\n" 24147 " };", 24148 Style); 24149 24150 verifyFormat("template <typename T> concept True = true;", Style); 24151 24152 verifyFormat( 24153 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24154 " return {};\n" 24155 " }())::value &&\n" 24156 " requires(T t) { t.bar(); } && " 24157 "sizeof(T) <= 8;", 24158 Style); 24159 24160 verifyFormat("template <typename T> concept Semiregular =\n" 24161 " DefaultConstructible<T> && CopyConstructible<T> && " 24162 "CopyAssignable<T> &&\n" 24163 " requires(T a, std::size_t n) {\n" 24164 " requires Same<T *, decltype(&a)>;\n" 24165 " { a.~T() } noexcept;\n" 24166 " requires Same<T *, decltype(new T)>;\n" 24167 " requires Same<T *, decltype(new T[n])>;\n" 24168 " { delete new T; };\n" 24169 " { delete new T[n]; };\n" 24170 " };", 24171 Style); 24172 24173 // The following tests are invalid C++, we just want to make sure we don't 24174 // assert. 24175 verifyFormat("template <typename T>\n" 24176 "concept C = requires C2<T>;"); 24177 24178 verifyFormat("template <typename T>\n" 24179 "concept C = 5 + 4;"); 24180 24181 verifyFormat("template <typename T>\n" 24182 "concept C =\n" 24183 "class X;"); 24184 24185 verifyFormat("template <typename T>\n" 24186 "concept C = [] && true;"); 24187 24188 verifyFormat("template <typename T>\n" 24189 "concept C = [] && requires(T t) { typename T::size_type; };"); 24190 } 24191 24192 TEST_F(FormatTest, RequiresClausesPositions) { 24193 auto Style = getLLVMStyle(); 24194 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24195 EXPECT_EQ(Style.IndentRequiresClause, true); 24196 24197 verifyFormat("template <typename T>\n" 24198 " requires(Foo<T> && std::trait<T>)\n" 24199 "struct Bar;", 24200 Style); 24201 24202 verifyFormat("template <typename T>\n" 24203 " requires(Foo<T> && std::trait<T>)\n" 24204 "class Bar {\n" 24205 "public:\n" 24206 " Bar(T t);\n" 24207 " bool baz();\n" 24208 "};", 24209 Style); 24210 24211 verifyFormat( 24212 "template <typename T>\n" 24213 " requires requires(T &&t) {\n" 24214 " typename T::I;\n" 24215 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24216 " }\n" 24217 "Bar(T) -> Bar<typename T::I>;", 24218 Style); 24219 24220 verifyFormat("template <typename T>\n" 24221 " requires(Foo<T> && std::trait<T>)\n" 24222 "constexpr T MyGlobal;", 24223 Style); 24224 24225 verifyFormat("template <typename T>\n" 24226 " requires Foo<T> && requires(T t) {\n" 24227 " { t.baz() } -> std::same_as<bool>;\n" 24228 " requires std::same_as<T::Factor, int>;\n" 24229 " }\n" 24230 "inline int bar(T t) {\n" 24231 " return t.baz() ? T::Factor : 5;\n" 24232 "}", 24233 Style); 24234 24235 verifyFormat("template <typename T>\n" 24236 "inline int bar(T t)\n" 24237 " requires Foo<T> && requires(T t) {\n" 24238 " { t.baz() } -> std::same_as<bool>;\n" 24239 " requires std::same_as<T::Factor, int>;\n" 24240 " }\n" 24241 "{\n" 24242 " return t.baz() ? T::Factor : 5;\n" 24243 "}", 24244 Style); 24245 24246 verifyFormat("template <typename T>\n" 24247 " requires F<T>\n" 24248 "int bar(T t) {\n" 24249 " return 5;\n" 24250 "}", 24251 Style); 24252 24253 verifyFormat("template <typename T>\n" 24254 "int bar(T t)\n" 24255 " requires F<T>\n" 24256 "{\n" 24257 " return 5;\n" 24258 "}", 24259 Style); 24260 24261 verifyFormat("template <typename T>\n" 24262 "int bar(T t)\n" 24263 " requires F<T>;", 24264 Style); 24265 24266 Style.IndentRequiresClause = false; 24267 verifyFormat("template <typename T>\n" 24268 "requires F<T>\n" 24269 "int bar(T t) {\n" 24270 " return 5;\n" 24271 "}", 24272 Style); 24273 24274 verifyFormat("template <typename T>\n" 24275 "int bar(T t)\n" 24276 "requires F<T>\n" 24277 "{\n" 24278 " return 5;\n" 24279 "}", 24280 Style); 24281 24282 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24283 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24284 "template <typename T> requires Foo<T> void bar() {}\n" 24285 "template <typename T> void bar() requires Foo<T> {}\n" 24286 "template <typename T> void bar() requires Foo<T>;\n" 24287 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24288 Style); 24289 24290 auto ColumnStyle = Style; 24291 ColumnStyle.ColumnLimit = 40; 24292 verifyFormat("template <typename AAAAAAA>\n" 24293 "requires Foo<T> struct Bar {};\n" 24294 "template <typename AAAAAAA>\n" 24295 "requires Foo<T> void bar() {}\n" 24296 "template <typename AAAAAAA>\n" 24297 "void bar() requires Foo<T> {}\n" 24298 "template <typename AAAAAAA>\n" 24299 "requires Foo<T> Baz(T) -> Baz<T>;", 24300 ColumnStyle); 24301 24302 verifyFormat("template <typename T>\n" 24303 "requires Foo<AAAAAAA> struct Bar {};\n" 24304 "template <typename T>\n" 24305 "requires Foo<AAAAAAA> void bar() {}\n" 24306 "template <typename T>\n" 24307 "void bar() requires Foo<AAAAAAA> {}\n" 24308 "template <typename T>\n" 24309 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24310 ColumnStyle); 24311 24312 verifyFormat("template <typename AAAAAAA>\n" 24313 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24314 "struct Bar {};\n" 24315 "template <typename AAAAAAA>\n" 24316 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24317 "void bar() {}\n" 24318 "template <typename AAAAAAA>\n" 24319 "void bar()\n" 24320 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24321 "template <typename AAAAAAA>\n" 24322 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24323 "template <typename AAAAAAA>\n" 24324 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24325 "Bar(T) -> Bar<T>;", 24326 ColumnStyle); 24327 24328 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24329 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24330 24331 verifyFormat("template <typename T>\n" 24332 "requires Foo<T> struct Bar {};\n" 24333 "template <typename T>\n" 24334 "requires Foo<T> void bar() {}\n" 24335 "template <typename T>\n" 24336 "void bar()\n" 24337 "requires Foo<T> {}\n" 24338 "template <typename T>\n" 24339 "void bar()\n" 24340 "requires Foo<T>;\n" 24341 "template <typename T>\n" 24342 "requires Foo<T> Bar(T) -> Bar<T>;", 24343 Style); 24344 24345 verifyFormat("template <typename AAAAAAA>\n" 24346 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24347 "struct Bar {};\n" 24348 "template <typename AAAAAAA>\n" 24349 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24350 "void bar() {}\n" 24351 "template <typename AAAAAAA>\n" 24352 "void bar()\n" 24353 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24354 "template <typename AAAAAAA>\n" 24355 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24356 "template <typename AAAAAAA>\n" 24357 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24358 "Bar(T) -> Bar<T>;", 24359 ColumnStyle); 24360 24361 Style.IndentRequiresClause = true; 24362 ColumnStyle.IndentRequiresClause = true; 24363 24364 verifyFormat("template <typename T>\n" 24365 " requires Foo<T> struct Bar {};\n" 24366 "template <typename T>\n" 24367 " requires Foo<T> void bar() {}\n" 24368 "template <typename T>\n" 24369 "void bar()\n" 24370 " requires Foo<T> {}\n" 24371 "template <typename T>\n" 24372 " requires Foo<T> Bar(T) -> Bar<T>;", 24373 Style); 24374 24375 verifyFormat("template <typename AAAAAAA>\n" 24376 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24377 "struct Bar {};\n" 24378 "template <typename AAAAAAA>\n" 24379 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24380 "void bar() {}\n" 24381 "template <typename AAAAAAA>\n" 24382 "void bar()\n" 24383 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24384 "template <typename AAAAAAA>\n" 24385 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24386 "template <typename AAAAAAA>\n" 24387 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24388 "Bar(T) -> Bar<T>;", 24389 ColumnStyle); 24390 24391 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24392 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24393 24394 verifyFormat("template <typename T> requires Foo<T>\n" 24395 "struct Bar {};\n" 24396 "template <typename T> requires Foo<T>\n" 24397 "void bar() {}\n" 24398 "template <typename T>\n" 24399 "void bar() requires Foo<T>\n" 24400 "{}\n" 24401 "template <typename T> void bar() requires Foo<T>;\n" 24402 "template <typename T> requires Foo<T>\n" 24403 "Bar(T) -> Bar<T>;", 24404 Style); 24405 24406 verifyFormat("template <typename AAAAAAA>\n" 24407 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24408 "struct Bar {};\n" 24409 "template <typename AAAAAAA>\n" 24410 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24411 "void bar() {}\n" 24412 "template <typename AAAAAAA>\n" 24413 "void bar()\n" 24414 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24415 "{}\n" 24416 "template <typename AAAAAAA>\n" 24417 "requires Foo<AAAAAAAA>\n" 24418 "Bar(T) -> Bar<T>;\n" 24419 "template <typename AAAAAAA>\n" 24420 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24421 "Bar(T) -> Bar<T>;", 24422 ColumnStyle); 24423 } 24424 24425 TEST_F(FormatTest, RequiresClauses) { 24426 verifyFormat("struct [[nodiscard]] zero_t {\n" 24427 " template <class T>\n" 24428 " requires requires { number_zero_v<T>; }\n" 24429 " [[nodiscard]] constexpr operator T() const {\n" 24430 " return number_zero_v<T>;\n" 24431 " }\n" 24432 "};"); 24433 24434 auto Style = getLLVMStyle(); 24435 24436 verifyFormat( 24437 "template <typename T>\n" 24438 " requires is_default_constructible_v<hash<T>> and\n" 24439 " is_copy_constructible_v<hash<T>> and\n" 24440 " is_move_constructible_v<hash<T>> and\n" 24441 " is_copy_assignable_v<hash<T>> and " 24442 "is_move_assignable_v<hash<T>> and\n" 24443 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24444 " is_callable_v<hash<T>(T)> and\n" 24445 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24446 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24447 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24448 "struct S {};", 24449 Style); 24450 24451 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24452 verifyFormat( 24453 "template <typename T>\n" 24454 " requires is_default_constructible_v<hash<T>>\n" 24455 " and is_copy_constructible_v<hash<T>>\n" 24456 " and is_move_constructible_v<hash<T>>\n" 24457 " and is_copy_assignable_v<hash<T>> and " 24458 "is_move_assignable_v<hash<T>>\n" 24459 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24460 " and is_callable_v<hash<T>(T)>\n" 24461 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24462 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24463 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24464 "&>()))>\n" 24465 "struct S {};", 24466 Style); 24467 24468 // Not a clause, but we once hit an assert. 24469 verifyFormat("#if 0\n" 24470 "#else\n" 24471 "foo();\n" 24472 "#endif\n" 24473 "bar(requires);"); 24474 } 24475 24476 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24477 FormatStyle Style = getLLVMStyle(); 24478 StringRef Source = "void Foo::slot() {\n" 24479 " unsigned char MyChar = 'x';\n" 24480 " emit signal(MyChar);\n" 24481 " Q_EMIT signal(MyChar);\n" 24482 "}"; 24483 24484 EXPECT_EQ(Source, format(Source, Style)); 24485 24486 Style.AlignConsecutiveDeclarations.Enabled = true; 24487 EXPECT_EQ("void Foo::slot() {\n" 24488 " unsigned char MyChar = 'x';\n" 24489 " emit signal(MyChar);\n" 24490 " Q_EMIT signal(MyChar);\n" 24491 "}", 24492 format(Source, Style)); 24493 24494 Style.StatementAttributeLikeMacros.push_back("emit"); 24495 EXPECT_EQ(Source, format(Source, Style)); 24496 24497 Style.StatementAttributeLikeMacros = {}; 24498 EXPECT_EQ("void Foo::slot() {\n" 24499 " unsigned char MyChar = 'x';\n" 24500 " emit signal(MyChar);\n" 24501 " Q_EMIT signal(MyChar);\n" 24502 "}", 24503 format(Source, Style)); 24504 } 24505 24506 TEST_F(FormatTest, IndentAccessModifiers) { 24507 FormatStyle Style = getLLVMStyle(); 24508 Style.IndentAccessModifiers = true; 24509 // Members are *two* levels below the record; 24510 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24511 verifyFormat("class C {\n" 24512 " int i;\n" 24513 "};\n", 24514 Style); 24515 verifyFormat("union C {\n" 24516 " int i;\n" 24517 " unsigned u;\n" 24518 "};\n", 24519 Style); 24520 // Access modifiers should be indented one level below the record. 24521 verifyFormat("class C {\n" 24522 " public:\n" 24523 " int i;\n" 24524 "};\n", 24525 Style); 24526 verifyFormat("struct S {\n" 24527 " private:\n" 24528 " class C {\n" 24529 " int j;\n" 24530 "\n" 24531 " public:\n" 24532 " C();\n" 24533 " };\n" 24534 "\n" 24535 " public:\n" 24536 " int i;\n" 24537 "};\n", 24538 Style); 24539 // Enumerations are not records and should be unaffected. 24540 Style.AllowShortEnumsOnASingleLine = false; 24541 verifyFormat("enum class E {\n" 24542 " A,\n" 24543 " B\n" 24544 "};\n", 24545 Style); 24546 // Test with a different indentation width; 24547 // also proves that the result is Style.AccessModifierOffset agnostic. 24548 Style.IndentWidth = 3; 24549 verifyFormat("class C {\n" 24550 " public:\n" 24551 " int i;\n" 24552 "};\n", 24553 Style); 24554 } 24555 24556 TEST_F(FormatTest, LimitlessStringsAndComments) { 24557 auto Style = getLLVMStyleWithColumns(0); 24558 constexpr StringRef Code = 24559 "/**\n" 24560 " * This is a multiline comment with quite some long lines, at least for " 24561 "the LLVM Style.\n" 24562 " * We will redo this with strings and line comments. Just to check if " 24563 "everything is working.\n" 24564 " */\n" 24565 "bool foo() {\n" 24566 " /* Single line multi line comment. */\n" 24567 " const std::string String = \"This is a multiline string with quite " 24568 "some long lines, at least for the LLVM Style.\"\n" 24569 " \"We already did it with multi line " 24570 "comments, and we will do it with line comments. Just to check if " 24571 "everything is working.\";\n" 24572 " // This is a line comment (block) with quite some long lines, at " 24573 "least for the LLVM Style.\n" 24574 " // We already did this with multi line comments and strings. Just to " 24575 "check if everything is working.\n" 24576 " const std::string SmallString = \"Hello World\";\n" 24577 " // Small line comment\n" 24578 " return String.size() > SmallString.size();\n" 24579 "}"; 24580 EXPECT_EQ(Code, format(Code, Style)); 24581 } 24582 24583 TEST_F(FormatTest, FormatDecayCopy) { 24584 // error cases from unit tests 24585 verifyFormat("foo(auto())"); 24586 verifyFormat("foo(auto{})"); 24587 verifyFormat("foo(auto({}))"); 24588 verifyFormat("foo(auto{{}})"); 24589 24590 verifyFormat("foo(auto(1))"); 24591 verifyFormat("foo(auto{1})"); 24592 verifyFormat("foo(new auto(1))"); 24593 verifyFormat("foo(new auto{1})"); 24594 verifyFormat("decltype(auto(1)) x;"); 24595 verifyFormat("decltype(auto{1}) x;"); 24596 verifyFormat("auto(x);"); 24597 verifyFormat("auto{x};"); 24598 verifyFormat("new auto{x};"); 24599 verifyFormat("auto{x} = y;"); 24600 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24601 // the user's own fault 24602 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24603 // clearly the user's own fault 24604 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24605 } 24606 24607 TEST_F(FormatTest, Cpp20ModulesSupport) { 24608 FormatStyle Style = getLLVMStyle(); 24609 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24610 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24611 24612 verifyFormat("export import foo;", Style); 24613 verifyFormat("export import foo:bar;", Style); 24614 verifyFormat("export import foo.bar;", Style); 24615 verifyFormat("export import foo.bar:baz;", Style); 24616 verifyFormat("export import :bar;", Style); 24617 verifyFormat("export module foo:bar;", Style); 24618 verifyFormat("export module foo;", Style); 24619 verifyFormat("export module foo.bar;", Style); 24620 verifyFormat("export module foo.bar:baz;", Style); 24621 verifyFormat("export import <string_view>;", Style); 24622 24623 verifyFormat("export type_name var;", Style); 24624 verifyFormat("template <class T> export using A = B<T>;", Style); 24625 verifyFormat("export using A = B;", Style); 24626 verifyFormat("export int func() {\n" 24627 " foo();\n" 24628 "}", 24629 Style); 24630 verifyFormat("export struct {\n" 24631 " int foo;\n" 24632 "};", 24633 Style); 24634 verifyFormat("export {\n" 24635 " int foo;\n" 24636 "};", 24637 Style); 24638 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24639 24640 verifyFormat("import bar;", Style); 24641 verifyFormat("import foo.bar;", Style); 24642 verifyFormat("import foo:bar;", Style); 24643 verifyFormat("import :bar;", Style); 24644 verifyFormat("import <ctime>;", Style); 24645 verifyFormat("import \"header\";", Style); 24646 24647 verifyFormat("module foo;", Style); 24648 verifyFormat("module foo:bar;", Style); 24649 verifyFormat("module foo.bar;", Style); 24650 verifyFormat("module;", Style); 24651 24652 verifyFormat("export namespace hi {\n" 24653 "const char *sayhi();\n" 24654 "}", 24655 Style); 24656 24657 verifyFormat("module :private;", Style); 24658 verifyFormat("import <foo/bar.h>;", Style); 24659 verifyFormat("import foo...bar;", Style); 24660 verifyFormat("import ..........;", Style); 24661 verifyFormat("module foo:private;", Style); 24662 verifyFormat("import a", Style); 24663 verifyFormat("module a", Style); 24664 verifyFormat("export import a", Style); 24665 verifyFormat("export module a", Style); 24666 24667 verifyFormat("import", Style); 24668 verifyFormat("module", Style); 24669 verifyFormat("export", Style); 24670 } 24671 24672 TEST_F(FormatTest, CoroutineForCoawait) { 24673 FormatStyle Style = getLLVMStyle(); 24674 verifyFormat("for co_await (auto x : range())\n ;"); 24675 verifyFormat("for (auto i : arr) {\n" 24676 "}", 24677 Style); 24678 verifyFormat("for co_await (auto i : arr) {\n" 24679 "}", 24680 Style); 24681 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24682 "}", 24683 Style); 24684 } 24685 24686 TEST_F(FormatTest, CoroutineCoAwait) { 24687 verifyFormat("int x = co_await foo();"); 24688 verifyFormat("int x = (co_await foo());"); 24689 verifyFormat("co_await (42);"); 24690 verifyFormat("void operator co_await(int);"); 24691 verifyFormat("void operator co_await(a);"); 24692 verifyFormat("co_await a;"); 24693 verifyFormat("co_await missing_await_resume{};"); 24694 verifyFormat("co_await a; // comment"); 24695 verifyFormat("void test0() { co_await a; }"); 24696 verifyFormat("co_await co_await co_await foo();"); 24697 verifyFormat("co_await foo().bar();"); 24698 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24699 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24700 "foo(); }(x, y);"); 24701 24702 FormatStyle Style = getLLVMStyleWithColumns(40); 24703 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24704 " co_return co_await foo();\n" 24705 "}(x, y);", 24706 Style); 24707 verifyFormat("co_await;"); 24708 } 24709 24710 TEST_F(FormatTest, CoroutineCoYield) { 24711 verifyFormat("int x = co_yield foo();"); 24712 verifyFormat("int x = (co_yield foo());"); 24713 verifyFormat("co_yield (42);"); 24714 verifyFormat("co_yield {42};"); 24715 verifyFormat("co_yield 42;"); 24716 verifyFormat("co_yield n++;"); 24717 verifyFormat("co_yield ++n;"); 24718 verifyFormat("co_yield;"); 24719 } 24720 24721 TEST_F(FormatTest, CoroutineCoReturn) { 24722 verifyFormat("co_return (42);"); 24723 verifyFormat("co_return;"); 24724 verifyFormat("co_return {};"); 24725 verifyFormat("co_return x;"); 24726 verifyFormat("co_return co_await foo();"); 24727 verifyFormat("co_return co_yield foo();"); 24728 } 24729 24730 TEST_F(FormatTest, EmptyShortBlock) { 24731 auto Style = getLLVMStyle(); 24732 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24733 24734 verifyFormat("try {\n" 24735 " doA();\n" 24736 "} catch (Exception &e) {\n" 24737 " e.printStackTrace();\n" 24738 "}\n", 24739 Style); 24740 24741 verifyFormat("try {\n" 24742 " doA();\n" 24743 "} catch (Exception &e) {}\n", 24744 Style); 24745 } 24746 24747 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24748 auto Style = getLLVMStyle(); 24749 24750 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24751 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24752 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24753 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24754 24755 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24756 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24757 } 24758 24759 TEST_F(FormatTest, InsertBraces) { 24760 FormatStyle Style = getLLVMStyle(); 24761 Style.InsertBraces = true; 24762 24763 verifyFormat("// clang-format off\n" 24764 "// comment\n" 24765 "if (a) f();\n" 24766 "// clang-format on\n" 24767 "if (b) {\n" 24768 " g();\n" 24769 "}", 24770 "// clang-format off\n" 24771 "// comment\n" 24772 "if (a) f();\n" 24773 "// clang-format on\n" 24774 "if (b) g();", 24775 Style); 24776 24777 verifyFormat("if (a) {\n" 24778 " switch (b) {\n" 24779 " case 1:\n" 24780 " c = 0;\n" 24781 " break;\n" 24782 " default:\n" 24783 " c = 1;\n" 24784 " }\n" 24785 "}", 24786 "if (a)\n" 24787 " switch (b) {\n" 24788 " case 1:\n" 24789 " c = 0;\n" 24790 " break;\n" 24791 " default:\n" 24792 " c = 1;\n" 24793 " }", 24794 Style); 24795 24796 verifyFormat("for (auto node : nodes) {\n" 24797 " if (node) {\n" 24798 " break;\n" 24799 " }\n" 24800 "}", 24801 "for (auto node : nodes)\n" 24802 " if (node)\n" 24803 " break;", 24804 Style); 24805 24806 verifyFormat("for (auto node : nodes) {\n" 24807 " if (node)\n" 24808 "}", 24809 "for (auto node : nodes)\n" 24810 " if (node)", 24811 Style); 24812 24813 verifyFormat("do {\n" 24814 " --a;\n" 24815 "} while (a);", 24816 "do\n" 24817 " --a;\n" 24818 "while (a);", 24819 Style); 24820 24821 verifyFormat("if (i) {\n" 24822 " ++i;\n" 24823 "} else {\n" 24824 " --i;\n" 24825 "}", 24826 "if (i)\n" 24827 " ++i;\n" 24828 "else {\n" 24829 " --i;\n" 24830 "}", 24831 Style); 24832 24833 verifyFormat("void f() {\n" 24834 " while (j--) {\n" 24835 " while (i) {\n" 24836 " --i;\n" 24837 " }\n" 24838 " }\n" 24839 "}", 24840 "void f() {\n" 24841 " while (j--)\n" 24842 " while (i)\n" 24843 " --i;\n" 24844 "}", 24845 Style); 24846 24847 verifyFormat("f({\n" 24848 " if (a) {\n" 24849 " g();\n" 24850 " }\n" 24851 "});", 24852 "f({\n" 24853 " if (a)\n" 24854 " g();\n" 24855 "});", 24856 Style); 24857 24858 verifyFormat("if (a) {\n" 24859 " f();\n" 24860 "} else if (b) {\n" 24861 " g();\n" 24862 "} else {\n" 24863 " h();\n" 24864 "}", 24865 "if (a)\n" 24866 " f();\n" 24867 "else if (b)\n" 24868 " g();\n" 24869 "else\n" 24870 " h();", 24871 Style); 24872 24873 verifyFormat("if (a) {\n" 24874 " f();\n" 24875 "}\n" 24876 "// comment\n" 24877 "/* comment */", 24878 "if (a)\n" 24879 " f();\n" 24880 "// comment\n" 24881 "/* comment */", 24882 Style); 24883 24884 verifyFormat("if (a) {\n" 24885 " // foo\n" 24886 " // bar\n" 24887 " f();\n" 24888 "}", 24889 "if (a)\n" 24890 " // foo\n" 24891 " // bar\n" 24892 " f();", 24893 Style); 24894 24895 verifyFormat("if (a) { // comment\n" 24896 " // comment\n" 24897 " f();\n" 24898 "}", 24899 "if (a) // comment\n" 24900 " // comment\n" 24901 " f();", 24902 Style); 24903 24904 verifyFormat("if (a) {\n" 24905 " f(); // comment\n" 24906 "}", 24907 "if (a)\n" 24908 " f(); // comment", 24909 Style); 24910 24911 verifyFormat("if (a) {\n" 24912 " f();\n" 24913 "}\n" 24914 "#undef A\n" 24915 "#undef B", 24916 "if (a)\n" 24917 " f();\n" 24918 "#undef A\n" 24919 "#undef B", 24920 Style); 24921 24922 verifyFormat("if (a)\n" 24923 "#ifdef A\n" 24924 " f();\n" 24925 "#else\n" 24926 " g();\n" 24927 "#endif", 24928 Style); 24929 24930 verifyFormat("#if 0\n" 24931 "#elif 1\n" 24932 "#endif\n" 24933 "void f() {\n" 24934 " if (a) {\n" 24935 " g();\n" 24936 " }\n" 24937 "}", 24938 "#if 0\n" 24939 "#elif 1\n" 24940 "#endif\n" 24941 "void f() {\n" 24942 " if (a) g();\n" 24943 "}", 24944 Style); 24945 24946 Style.ColumnLimit = 15; 24947 24948 verifyFormat("#define A \\\n" 24949 " if (a) \\\n" 24950 " f();", 24951 Style); 24952 24953 verifyFormat("if (a + b >\n" 24954 " c) {\n" 24955 " f();\n" 24956 "}", 24957 "if (a + b > c)\n" 24958 " f();", 24959 Style); 24960 } 24961 24962 TEST_F(FormatTest, RemoveBraces) { 24963 FormatStyle Style = getLLVMStyle(); 24964 Style.RemoveBracesLLVM = true; 24965 24966 // The following eight test cases are fully-braced versions of the examples at 24967 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24968 // statement-bodies-of-if-else-loop-statements". 24969 24970 // 1. Omit the braces, since the body is simple and clearly associated with 24971 // the if. 24972 verifyFormat("if (isa<FunctionDecl>(D))\n" 24973 " handleFunctionDecl(D);\n" 24974 "else if (isa<VarDecl>(D))\n" 24975 " handleVarDecl(D);", 24976 "if (isa<FunctionDecl>(D)) {\n" 24977 " handleFunctionDecl(D);\n" 24978 "} else if (isa<VarDecl>(D)) {\n" 24979 " handleVarDecl(D);\n" 24980 "}", 24981 Style); 24982 24983 // 2. Here we document the condition itself and not the body. 24984 verifyFormat("if (isa<VarDecl>(D)) {\n" 24985 " // It is necessary that we explain the situation with this\n" 24986 " // surprisingly long comment, so it would be unclear\n" 24987 " // without the braces whether the following statement is in\n" 24988 " // the scope of the `if`.\n" 24989 " // Because the condition is documented, we can't really\n" 24990 " // hoist this comment that applies to the body above the\n" 24991 " // if.\n" 24992 " handleOtherDecl(D);\n" 24993 "}", 24994 Style); 24995 24996 // 3. Use braces on the outer `if` to avoid a potential dangling else 24997 // situation. 24998 verifyFormat("if (isa<VarDecl>(D)) {\n" 24999 " for (auto *A : D.attrs())\n" 25000 " if (shouldProcessAttr(A))\n" 25001 " handleAttr(A);\n" 25002 "}", 25003 "if (isa<VarDecl>(D)) {\n" 25004 " for (auto *A : D.attrs()) {\n" 25005 " if (shouldProcessAttr(A)) {\n" 25006 " handleAttr(A);\n" 25007 " }\n" 25008 " }\n" 25009 "}", 25010 Style); 25011 25012 // 4. Use braces for the `if` block to keep it uniform with the else block. 25013 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25014 " handleFunctionDecl(D);\n" 25015 "} else {\n" 25016 " // In this else case, it is necessary that we explain the\n" 25017 " // situation with this surprisingly long comment, so it\n" 25018 " // would be unclear without the braces whether the\n" 25019 " // following statement is in the scope of the `if`.\n" 25020 " handleOtherDecl(D);\n" 25021 "}", 25022 Style); 25023 25024 // 5. This should also omit braces. The `for` loop contains only a single 25025 // statement, so it shouldn't have braces. The `if` also only contains a 25026 // single simple statement (the for loop), so it also should omit braces. 25027 verifyFormat("if (isa<FunctionDecl>(D))\n" 25028 " for (auto *A : D.attrs())\n" 25029 " handleAttr(A);", 25030 "if (isa<FunctionDecl>(D)) {\n" 25031 " for (auto *A : D.attrs()) {\n" 25032 " handleAttr(A);\n" 25033 " }\n" 25034 "}", 25035 Style); 25036 25037 // 6. Use braces for the outer `if` since the nested `for` is braced. 25038 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25039 " for (auto *A : D.attrs()) {\n" 25040 " // In this for loop body, it is necessary that we explain\n" 25041 " // the situation with this surprisingly long comment,\n" 25042 " // forcing braces on the `for` block.\n" 25043 " handleAttr(A);\n" 25044 " }\n" 25045 "}", 25046 Style); 25047 25048 // 7. Use braces on the outer block because there are more than two levels of 25049 // nesting. 25050 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25051 " for (auto *A : D.attrs())\n" 25052 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 25053 " handleAttrOnDecl(D, A, i);\n" 25054 "}", 25055 "if (isa<FunctionDecl>(D)) {\n" 25056 " for (auto *A : D.attrs()) {\n" 25057 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 25058 " handleAttrOnDecl(D, A, i);\n" 25059 " }\n" 25060 " }\n" 25061 "}", 25062 Style); 25063 25064 // 8. Use braces on the outer block because of a nested `if`, otherwise the 25065 // compiler would warn: `add explicit braces to avoid dangling else` 25066 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25067 " if (shouldProcess(D))\n" 25068 " handleVarDecl(D);\n" 25069 " else\n" 25070 " markAsIgnored(D);\n" 25071 "}", 25072 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25073 " if (shouldProcess(D)) {\n" 25074 " handleVarDecl(D);\n" 25075 " } else {\n" 25076 " markAsIgnored(D);\n" 25077 " }\n" 25078 "}", 25079 Style); 25080 25081 verifyFormat("// clang-format off\n" 25082 "// comment\n" 25083 "while (i > 0) { --i; }\n" 25084 "// clang-format on\n" 25085 "while (j < 0)\n" 25086 " ++j;", 25087 "// clang-format off\n" 25088 "// comment\n" 25089 "while (i > 0) { --i; }\n" 25090 "// clang-format on\n" 25091 "while (j < 0) { ++j; }", 25092 Style); 25093 25094 verifyFormat("if (a)\n" 25095 " b; // comment\n" 25096 "else if (c)\n" 25097 " d; /* comment */\n" 25098 "else\n" 25099 " e;", 25100 "if (a) {\n" 25101 " b; // comment\n" 25102 "} else if (c) {\n" 25103 " d; /* comment */\n" 25104 "} else {\n" 25105 " e;\n" 25106 "}", 25107 Style); 25108 25109 verifyFormat("if (a) {\n" 25110 " b;\n" 25111 " c;\n" 25112 "} else if (d) {\n" 25113 " e;\n" 25114 "}", 25115 Style); 25116 25117 verifyFormat("if (a) {\n" 25118 "#undef NDEBUG\n" 25119 " b;\n" 25120 "} else {\n" 25121 " c;\n" 25122 "}", 25123 Style); 25124 25125 verifyFormat("if (a) {\n" 25126 " // comment\n" 25127 "} else if (b) {\n" 25128 " c;\n" 25129 "}", 25130 Style); 25131 25132 verifyFormat("if (a) {\n" 25133 " b;\n" 25134 "} else {\n" 25135 " { c; }\n" 25136 "}", 25137 Style); 25138 25139 verifyFormat("if (a) {\n" 25140 " if (b) // comment\n" 25141 " c;\n" 25142 "} else if (d) {\n" 25143 " e;\n" 25144 "}", 25145 "if (a) {\n" 25146 " if (b) { // comment\n" 25147 " c;\n" 25148 " }\n" 25149 "} else if (d) {\n" 25150 " e;\n" 25151 "}", 25152 Style); 25153 25154 verifyFormat("if (a) {\n" 25155 " if (b) {\n" 25156 " c;\n" 25157 " // comment\n" 25158 " } else if (d) {\n" 25159 " e;\n" 25160 " }\n" 25161 "}", 25162 Style); 25163 25164 verifyFormat("if (a) {\n" 25165 " if (b)\n" 25166 " c;\n" 25167 "}", 25168 "if (a) {\n" 25169 " if (b) {\n" 25170 " c;\n" 25171 " }\n" 25172 "}", 25173 Style); 25174 25175 verifyFormat("if (a)\n" 25176 " if (b)\n" 25177 " c;\n" 25178 " else\n" 25179 " d;\n" 25180 "else\n" 25181 " e;", 25182 "if (a) {\n" 25183 " if (b) {\n" 25184 " c;\n" 25185 " } else {\n" 25186 " d;\n" 25187 " }\n" 25188 "} else {\n" 25189 " e;\n" 25190 "}", 25191 Style); 25192 25193 verifyFormat("if (a) {\n" 25194 " // comment\n" 25195 " if (b)\n" 25196 " c;\n" 25197 " else if (d)\n" 25198 " e;\n" 25199 "} else {\n" 25200 " g;\n" 25201 "}", 25202 "if (a) {\n" 25203 " // comment\n" 25204 " if (b) {\n" 25205 " c;\n" 25206 " } else if (d) {\n" 25207 " e;\n" 25208 " }\n" 25209 "} else {\n" 25210 " g;\n" 25211 "}", 25212 Style); 25213 25214 verifyFormat("if (a)\n" 25215 " b;\n" 25216 "else if (c)\n" 25217 " d;\n" 25218 "else\n" 25219 " e;", 25220 "if (a) {\n" 25221 " b;\n" 25222 "} else {\n" 25223 " if (c) {\n" 25224 " d;\n" 25225 " } else {\n" 25226 " e;\n" 25227 " }\n" 25228 "}", 25229 Style); 25230 25231 verifyFormat("if (a) {\n" 25232 " if (b)\n" 25233 " c;\n" 25234 " else if (d)\n" 25235 " e;\n" 25236 "} else {\n" 25237 " g;\n" 25238 "}", 25239 "if (a) {\n" 25240 " if (b)\n" 25241 " c;\n" 25242 " else {\n" 25243 " if (d)\n" 25244 " e;\n" 25245 " }\n" 25246 "} else {\n" 25247 " g;\n" 25248 "}", 25249 Style); 25250 25251 verifyFormat("if (a)\n" 25252 " b;\n" 25253 "else if (c)\n" 25254 " while (d)\n" 25255 " e;\n" 25256 "// comment", 25257 "if (a)\n" 25258 "{\n" 25259 " b;\n" 25260 "} else if (c) {\n" 25261 " while (d) {\n" 25262 " e;\n" 25263 " }\n" 25264 "}\n" 25265 "// comment", 25266 Style); 25267 25268 verifyFormat("if (a) {\n" 25269 " b;\n" 25270 "} else if (c) {\n" 25271 " d;\n" 25272 "} else {\n" 25273 " e;\n" 25274 " g;\n" 25275 "}", 25276 Style); 25277 25278 verifyFormat("if (a) {\n" 25279 " b;\n" 25280 "} else if (c) {\n" 25281 " d;\n" 25282 "} else {\n" 25283 " e;\n" 25284 "} // comment", 25285 Style); 25286 25287 verifyFormat("int abs = [](int i) {\n" 25288 " if (i >= 0)\n" 25289 " return i;\n" 25290 " return -i;\n" 25291 "};", 25292 "int abs = [](int i) {\n" 25293 " if (i >= 0) {\n" 25294 " return i;\n" 25295 " }\n" 25296 " return -i;\n" 25297 "};", 25298 Style); 25299 25300 verifyFormat("if (a)\n" 25301 " foo();\n" 25302 "else\n" 25303 " bar();", 25304 "if (a)\n" 25305 "{\n" 25306 " foo();\n" 25307 "}\n" 25308 "else\n" 25309 "{\n" 25310 " bar();\n" 25311 "}", 25312 Style); 25313 25314 verifyFormat("if (a) {\n" 25315 "Label:\n" 25316 "}", 25317 Style); 25318 25319 verifyFormat("if (a) {\n" 25320 "Label:\n" 25321 " f();\n" 25322 "}", 25323 Style); 25324 25325 verifyFormat("if (a) {\n" 25326 " f();\n" 25327 "Label:\n" 25328 "}", 25329 Style); 25330 25331 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 25332 #if 0 25333 Style.ColumnLimit = 65; 25334 25335 verifyFormat("if (condition) {\n" 25336 " ff(Indices,\n" 25337 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25338 "} else {\n" 25339 " ff(Indices,\n" 25340 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25341 "}", 25342 Style); 25343 25344 Style.ColumnLimit = 20; 25345 25346 verifyFormat("if (a) {\n" 25347 " b = c + // 1 -\n" 25348 " d;\n" 25349 "}", 25350 Style); 25351 25352 verifyFormat("if (a) {\n" 25353 " b = c >= 0 ? d\n" 25354 " : e;\n" 25355 "}", 25356 "if (a) {\n" 25357 " b = c >= 0 ? d : e;\n" 25358 "}", 25359 Style); 25360 #endif 25361 25362 Style.ColumnLimit = 20; 25363 25364 verifyFormat("if (a)\n" 25365 " b = c > 0 ? d : e;", 25366 "if (a) {\n" 25367 " b = c > 0 ? d : e;\n" 25368 "}", 25369 Style); 25370 25371 Style.ColumnLimit = 0; 25372 25373 verifyFormat("if (a)\n" 25374 " b234567890223456789032345678904234567890 = " 25375 "c234567890223456789032345678904234567890;", 25376 "if (a) {\n" 25377 " b234567890223456789032345678904234567890 = " 25378 "c234567890223456789032345678904234567890;\n" 25379 "}", 25380 Style); 25381 } 25382 25383 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25384 auto Style = getLLVMStyle(); 25385 25386 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25387 "void functionDecl(int a, int b, int c);"; 25388 25389 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25390 "paramF, paramG, paramH, paramI);\n" 25391 "void functionDecl(int argumentA, int argumentB, int " 25392 "argumentC, int argumentD, int argumentE);"; 25393 25394 verifyFormat(Short, Style); 25395 25396 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25397 "paramF, paramG, paramH,\n" 25398 " paramI);\n" 25399 "void functionDecl(int argumentA, int argumentB, int " 25400 "argumentC, int argumentD,\n" 25401 " int argumentE);"; 25402 25403 verifyFormat(NoBreak, Medium, Style); 25404 verifyFormat(NoBreak, 25405 "functionCall(\n" 25406 " paramA,\n" 25407 " paramB,\n" 25408 " paramC,\n" 25409 " paramD,\n" 25410 " paramE,\n" 25411 " paramF,\n" 25412 " paramG,\n" 25413 " paramH,\n" 25414 " paramI\n" 25415 ");\n" 25416 "void functionDecl(\n" 25417 " int argumentA,\n" 25418 " int argumentB,\n" 25419 " int argumentC,\n" 25420 " int argumentD,\n" 25421 " int argumentE\n" 25422 ");", 25423 Style); 25424 25425 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25426 " nestedLongFunctionCall(argument1, " 25427 "argument2, argument3,\n" 25428 " argument4, " 25429 "argument5));", 25430 Style); 25431 25432 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25433 25434 verifyFormat(Short, Style); 25435 verifyFormat( 25436 "functionCall(\n" 25437 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25438 "paramI\n" 25439 ");\n" 25440 "void functionDecl(\n" 25441 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25442 "argumentE\n" 25443 ");", 25444 Medium, Style); 25445 25446 Style.AllowAllArgumentsOnNextLine = false; 25447 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25448 25449 verifyFormat(Short, Style); 25450 verifyFormat( 25451 "functionCall(\n" 25452 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25453 "paramI\n" 25454 ");\n" 25455 "void functionDecl(\n" 25456 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25457 "argumentE\n" 25458 ");", 25459 Medium, Style); 25460 25461 Style.BinPackArguments = false; 25462 Style.BinPackParameters = false; 25463 25464 verifyFormat(Short, Style); 25465 25466 verifyFormat("functionCall(\n" 25467 " paramA,\n" 25468 " paramB,\n" 25469 " paramC,\n" 25470 " paramD,\n" 25471 " paramE,\n" 25472 " paramF,\n" 25473 " paramG,\n" 25474 " paramH,\n" 25475 " paramI\n" 25476 ");\n" 25477 "void functionDecl(\n" 25478 " int argumentA,\n" 25479 " int argumentB,\n" 25480 " int argumentC,\n" 25481 " int argumentD,\n" 25482 " int argumentE\n" 25483 ");", 25484 Medium, Style); 25485 25486 verifyFormat("outerFunctionCall(\n" 25487 " nestedFunctionCall(argument1),\n" 25488 " nestedLongFunctionCall(\n" 25489 " argument1,\n" 25490 " argument2,\n" 25491 " argument3,\n" 25492 " argument4,\n" 25493 " argument5\n" 25494 " )\n" 25495 ");", 25496 Style); 25497 25498 verifyFormat("int a = (int)b;", Style); 25499 verifyFormat("int a = (int)b;", 25500 "int a = (\n" 25501 " int\n" 25502 ") b;", 25503 Style); 25504 25505 verifyFormat("return (true);", Style); 25506 verifyFormat("return (true);", 25507 "return (\n" 25508 " true\n" 25509 ");", 25510 Style); 25511 25512 verifyFormat("void foo();", Style); 25513 verifyFormat("void foo();", 25514 "void foo(\n" 25515 ");", 25516 Style); 25517 25518 verifyFormat("void foo() {}", Style); 25519 verifyFormat("void foo() {}", 25520 "void foo(\n" 25521 ") {\n" 25522 "}", 25523 Style); 25524 25525 verifyFormat("auto string = std::string();", Style); 25526 verifyFormat("auto string = std::string();", 25527 "auto string = std::string(\n" 25528 ");", 25529 Style); 25530 25531 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25532 verifyFormat("void (*functionPointer)() = nullptr;", 25533 "void (\n" 25534 " *functionPointer\n" 25535 ")\n" 25536 "(\n" 25537 ") = nullptr;", 25538 Style); 25539 } 25540 25541 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25542 auto Style = getLLVMStyle(); 25543 25544 verifyFormat("if (foo()) {\n" 25545 " return;\n" 25546 "}", 25547 Style); 25548 25549 verifyFormat("if (quitelongarg !=\n" 25550 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25551 "comment\n" 25552 " return;\n" 25553 "}", 25554 Style); 25555 25556 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25557 25558 verifyFormat("if (foo()) {\n" 25559 " return;\n" 25560 "}", 25561 Style); 25562 25563 verifyFormat("if (quitelongarg !=\n" 25564 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25565 "comment\n" 25566 " return;\n" 25567 "}", 25568 Style); 25569 } 25570 25571 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25572 auto Style = getLLVMStyle(); 25573 25574 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25575 " doSomething();\n" 25576 "}", 25577 Style); 25578 25579 verifyFormat("for (int myReallyLongCountVariable = 0; " 25580 "myReallyLongCountVariable < count;\n" 25581 " myReallyLongCountVariable++) {\n" 25582 " doSomething();\n" 25583 "}", 25584 Style); 25585 25586 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25587 25588 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25589 " doSomething();\n" 25590 "}", 25591 Style); 25592 25593 verifyFormat("for (int myReallyLongCountVariable = 0; " 25594 "myReallyLongCountVariable < count;\n" 25595 " myReallyLongCountVariable++) {\n" 25596 " doSomething();\n" 25597 "}", 25598 Style); 25599 } 25600 25601 TEST_F(FormatTest, UnderstandsDigraphs) { 25602 verifyFormat("int arr<:5:> = {};"); 25603 verifyFormat("int arr[5] = <%%>;"); 25604 verifyFormat("int arr<:::qualified_variable:> = {};"); 25605 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25606 verifyFormat("%:include <header>"); 25607 verifyFormat("%:define A x##y"); 25608 verifyFormat("#define A x%:%:y"); 25609 } 25610 25611 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 25612 auto Style = getLLVMStyle(); 25613 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 25614 Style.AlignConsecutiveAssignments.Enabled = true; 25615 Style.AlignConsecutiveDeclarations.Enabled = true; 25616 25617 // The AlignArray code is incorrect for non square Arrays and can cause 25618 // crashes, these tests assert that the array is not changed but will 25619 // also act as regression tests for when it is properly fixed 25620 verifyFormat("struct test demo[] = {\n" 25621 " {1, 2},\n" 25622 " {3, 4, 5},\n" 25623 " {6, 7, 8}\n" 25624 "};", 25625 Style); 25626 verifyFormat("struct test demo[] = {\n" 25627 " {1, 2, 3, 4, 5},\n" 25628 " {3, 4, 5},\n" 25629 " {6, 7, 8}\n" 25630 "};", 25631 Style); 25632 verifyFormat("struct test demo[] = {\n" 25633 " {1, 2, 3, 4, 5},\n" 25634 " {3, 4, 5},\n" 25635 " {6, 7, 8, 9, 10, 11, 12}\n" 25636 "};", 25637 Style); 25638 verifyFormat("struct test demo[] = {\n" 25639 " {1, 2, 3},\n" 25640 " {3, 4, 5},\n" 25641 " {6, 7, 8, 9, 10, 11, 12}\n" 25642 "};", 25643 Style); 25644 25645 verifyFormat("S{\n" 25646 " {},\n" 25647 " {},\n" 25648 " {a, b}\n" 25649 "};", 25650 Style); 25651 verifyFormat("S{\n" 25652 " {},\n" 25653 " {},\n" 25654 " {a, b},\n" 25655 "};", 25656 Style); 25657 verifyFormat("void foo() {\n" 25658 " auto thing = test{\n" 25659 " {\n" 25660 " {13}, {something}, // A\n" 25661 " }\n" 25662 " };\n" 25663 "}", 25664 "void foo() {\n" 25665 " auto thing = test{\n" 25666 " {\n" 25667 " {13},\n" 25668 " {something}, // A\n" 25669 " }\n" 25670 " };\n" 25671 "}", 25672 Style); 25673 } 25674 25675 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 25676 auto Style = getLLVMStyle(); 25677 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 25678 Style.AlignConsecutiveAssignments.Enabled = true; 25679 Style.AlignConsecutiveDeclarations.Enabled = true; 25680 25681 // The AlignArray code is incorrect for non square Arrays and can cause 25682 // crashes, these tests assert that the array is not changed but will 25683 // also act as regression tests for when it is properly fixed 25684 verifyFormat("struct test demo[] = {\n" 25685 " {1, 2},\n" 25686 " {3, 4, 5},\n" 25687 " {6, 7, 8}\n" 25688 "};", 25689 Style); 25690 verifyFormat("struct test demo[] = {\n" 25691 " {1, 2, 3, 4, 5},\n" 25692 " {3, 4, 5},\n" 25693 " {6, 7, 8}\n" 25694 "};", 25695 Style); 25696 verifyFormat("struct test demo[] = {\n" 25697 " {1, 2, 3, 4, 5},\n" 25698 " {3, 4, 5},\n" 25699 " {6, 7, 8, 9, 10, 11, 12}\n" 25700 "};", 25701 Style); 25702 verifyFormat("struct test demo[] = {\n" 25703 " {1, 2, 3},\n" 25704 " {3, 4, 5},\n" 25705 " {6, 7, 8, 9, 10, 11, 12}\n" 25706 "};", 25707 Style); 25708 25709 verifyFormat("S{\n" 25710 " {},\n" 25711 " {},\n" 25712 " {a, b}\n" 25713 "};", 25714 Style); 25715 verifyFormat("S{\n" 25716 " {},\n" 25717 " {},\n" 25718 " {a, b},\n" 25719 "};", 25720 Style); 25721 verifyFormat("void foo() {\n" 25722 " auto thing = test{\n" 25723 " {\n" 25724 " {13}, {something}, // A\n" 25725 " }\n" 25726 " };\n" 25727 "}", 25728 "void foo() {\n" 25729 " auto thing = test{\n" 25730 " {\n" 25731 " {13},\n" 25732 " {something}, // A\n" 25733 " }\n" 25734 " };\n" 25735 "}", 25736 Style); 25737 } 25738 25739 TEST_F(FormatTest, FormatsVariableTemplates) { 25740 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 25741 verifyFormat("template <typename T> " 25742 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 25743 } 25744 25745 } // namespace 25746 } // namespace format 25747 } // namespace clang 25748