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 3341 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3342 EXPECT_EQ("class A {\n" 3343 "public:\n" 3344 " void f();\n" 3345 "\n" 3346 "private:\n" 3347 " void g() {}\n" 3348 " // test\n" 3349 "protected:\n" 3350 " int h;\n" 3351 "};", 3352 format("class A {\n" 3353 "public:\n" 3354 "void f();\n" 3355 "private:\n" 3356 "void g() {}\n" 3357 "// test\n" 3358 "protected:\n" 3359 "int h;\n" 3360 "};")); 3361 EXPECT_EQ("class A {\n" 3362 "protected:\n" 3363 "public:\n" 3364 " void f();\n" 3365 "};", 3366 format("class A {\n" 3367 "protected:\n" 3368 "\n" 3369 "public:\n" 3370 "\n" 3371 " void f();\n" 3372 "};")); 3373 3374 // Even ensure proper spacing inside macros. 3375 EXPECT_EQ("#define B \\\n" 3376 " class A { \\\n" 3377 " protected: \\\n" 3378 " public: \\\n" 3379 " void f(); \\\n" 3380 " };", 3381 format("#define B \\\n" 3382 " class A { \\\n" 3383 " protected: \\\n" 3384 " \\\n" 3385 " public: \\\n" 3386 " \\\n" 3387 " void f(); \\\n" 3388 " };", 3389 getGoogleStyle())); 3390 // But don't remove empty lines after macros ending in access specifiers. 3391 EXPECT_EQ("#define A private:\n" 3392 "\n" 3393 "int i;", 3394 format("#define A private:\n" 3395 "\n" 3396 "int i;")); 3397 } 3398 3399 TEST_F(FormatTest, FormatsClasses) { 3400 verifyFormat("class A : public B {};"); 3401 verifyFormat("class A : public ::B {};"); 3402 3403 verifyFormat( 3404 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3405 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3406 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3407 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3408 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3409 verifyFormat( 3410 "class A : public B, public C, public D, public E, public F {};"); 3411 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3412 " public C,\n" 3413 " public D,\n" 3414 " public E,\n" 3415 " public F,\n" 3416 " public G {};"); 3417 3418 verifyFormat("class\n" 3419 " ReallyReallyLongClassName {\n" 3420 " int i;\n" 3421 "};", 3422 getLLVMStyleWithColumns(32)); 3423 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3424 " aaaaaaaaaaaaaaaa> {};"); 3425 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3426 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3427 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3428 verifyFormat("template <class R, class C>\n" 3429 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3430 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3431 verifyFormat("class ::A::B {};"); 3432 } 3433 3434 TEST_F(FormatTest, BreakInheritanceStyle) { 3435 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3436 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3437 FormatStyle::BILS_BeforeComma; 3438 verifyFormat("class MyClass : public X {};", 3439 StyleWithInheritanceBreakBeforeComma); 3440 verifyFormat("class MyClass\n" 3441 " : public X\n" 3442 " , public Y {};", 3443 StyleWithInheritanceBreakBeforeComma); 3444 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3445 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3446 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3447 StyleWithInheritanceBreakBeforeComma); 3448 verifyFormat("struct aaaaaaaaaaaaa\n" 3449 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3450 " aaaaaaaaaaaaaaaa> {};", 3451 StyleWithInheritanceBreakBeforeComma); 3452 3453 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3454 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3455 FormatStyle::BILS_AfterColon; 3456 verifyFormat("class MyClass : public X {};", 3457 StyleWithInheritanceBreakAfterColon); 3458 verifyFormat("class MyClass : public X, public Y {};", 3459 StyleWithInheritanceBreakAfterColon); 3460 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3461 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3462 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3463 StyleWithInheritanceBreakAfterColon); 3464 verifyFormat("struct aaaaaaaaaaaaa :\n" 3465 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3466 " aaaaaaaaaaaaaaaa> {};", 3467 StyleWithInheritanceBreakAfterColon); 3468 3469 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3470 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3471 FormatStyle::BILS_AfterComma; 3472 verifyFormat("class MyClass : public X {};", 3473 StyleWithInheritanceBreakAfterComma); 3474 verifyFormat("class MyClass : public X,\n" 3475 " public Y {};", 3476 StyleWithInheritanceBreakAfterComma); 3477 verifyFormat( 3478 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3479 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3480 "{};", 3481 StyleWithInheritanceBreakAfterComma); 3482 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3483 " aaaaaaaaaaaaaaaa> {};", 3484 StyleWithInheritanceBreakAfterComma); 3485 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3486 " : public OnceBreak,\n" 3487 " public AlwaysBreak,\n" 3488 " EvenBasesFitInOneLine {};", 3489 StyleWithInheritanceBreakAfterComma); 3490 } 3491 3492 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3493 verifyFormat("class A {\n} a, b;"); 3494 verifyFormat("struct A {\n} a, b;"); 3495 verifyFormat("union A {\n} a, b;"); 3496 3497 verifyFormat("constexpr class A {\n} a, b;"); 3498 verifyFormat("constexpr struct A {\n} a, b;"); 3499 verifyFormat("constexpr union A {\n} a, b;"); 3500 3501 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3502 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3503 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3504 3505 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3506 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3507 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3508 3509 verifyFormat("namespace ns {\n" 3510 "class {\n" 3511 "} a, b;\n" 3512 "} // namespace ns"); 3513 verifyFormat("namespace ns {\n" 3514 "const class {\n" 3515 "} a, b;\n" 3516 "} // namespace ns"); 3517 verifyFormat("namespace ns {\n" 3518 "constexpr class C {\n" 3519 "} a, b;\n" 3520 "} // namespace ns"); 3521 verifyFormat("namespace ns {\n" 3522 "class { /* comment */\n" 3523 "} a, b;\n" 3524 "} // namespace ns"); 3525 verifyFormat("namespace ns {\n" 3526 "const class { /* comment */\n" 3527 "} a, b;\n" 3528 "} // namespace ns"); 3529 } 3530 3531 TEST_F(FormatTest, FormatsEnum) { 3532 verifyFormat("enum {\n" 3533 " Zero,\n" 3534 " One = 1,\n" 3535 " Two = One + 1,\n" 3536 " Three = (One + Two),\n" 3537 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3538 " Five = (One, Two, Three, Four, 5)\n" 3539 "};"); 3540 verifyGoogleFormat("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 verifyFormat("enum Enum {};"); 3549 verifyFormat("enum {};"); 3550 verifyFormat("enum X E {} d;"); 3551 verifyFormat("enum __attribute__((...)) E {} d;"); 3552 verifyFormat("enum __declspec__((...)) E {} d;"); 3553 verifyFormat("enum {\n" 3554 " Bar = Foo<int, int>::value\n" 3555 "};", 3556 getLLVMStyleWithColumns(30)); 3557 3558 verifyFormat("enum ShortEnum { A, B, C };"); 3559 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3560 3561 EXPECT_EQ("enum KeepEmptyLines {\n" 3562 " ONE,\n" 3563 "\n" 3564 " TWO,\n" 3565 "\n" 3566 " THREE\n" 3567 "}", 3568 format("enum KeepEmptyLines {\n" 3569 " ONE,\n" 3570 "\n" 3571 " TWO,\n" 3572 "\n" 3573 "\n" 3574 " THREE\n" 3575 "}")); 3576 verifyFormat("enum E { // comment\n" 3577 " ONE,\n" 3578 " TWO\n" 3579 "};\n" 3580 "int i;"); 3581 3582 FormatStyle EightIndent = getLLVMStyle(); 3583 EightIndent.IndentWidth = 8; 3584 verifyFormat("enum {\n" 3585 " VOID,\n" 3586 " CHAR,\n" 3587 " SHORT,\n" 3588 " INT,\n" 3589 " LONG,\n" 3590 " SIGNED,\n" 3591 " UNSIGNED,\n" 3592 " BOOL,\n" 3593 " FLOAT,\n" 3594 " DOUBLE,\n" 3595 " COMPLEX\n" 3596 "};", 3597 EightIndent); 3598 3599 // Not enums. 3600 verifyFormat("enum X f() {\n" 3601 " a();\n" 3602 " return 42;\n" 3603 "}"); 3604 verifyFormat("enum X Type::f() {\n" 3605 " a();\n" 3606 " return 42;\n" 3607 "}"); 3608 verifyFormat("enum ::X f() {\n" 3609 " a();\n" 3610 " return 42;\n" 3611 "}"); 3612 verifyFormat("enum ns::X f() {\n" 3613 " a();\n" 3614 " return 42;\n" 3615 "}"); 3616 } 3617 3618 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3619 verifyFormat("enum Type {\n" 3620 " One = 0; // These semicolons should be commas.\n" 3621 " Two = 1;\n" 3622 "};"); 3623 verifyFormat("namespace n {\n" 3624 "enum Type {\n" 3625 " One,\n" 3626 " Two, // missing };\n" 3627 " int i;\n" 3628 "}\n" 3629 "void g() {}"); 3630 } 3631 3632 TEST_F(FormatTest, FormatsEnumStruct) { 3633 verifyFormat("enum struct {\n" 3634 " Zero,\n" 3635 " One = 1,\n" 3636 " Two = One + 1,\n" 3637 " Three = (One + Two),\n" 3638 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3639 " Five = (One, Two, Three, Four, 5)\n" 3640 "};"); 3641 verifyFormat("enum struct Enum {};"); 3642 verifyFormat("enum struct {};"); 3643 verifyFormat("enum struct X E {} d;"); 3644 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3645 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3646 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3647 } 3648 3649 TEST_F(FormatTest, FormatsEnumClass) { 3650 verifyFormat("enum class {\n" 3651 " Zero,\n" 3652 " One = 1,\n" 3653 " Two = One + 1,\n" 3654 " Three = (One + Two),\n" 3655 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3656 " Five = (One, Two, Three, Four, 5)\n" 3657 "};"); 3658 verifyFormat("enum class Enum {};"); 3659 verifyFormat("enum class {};"); 3660 verifyFormat("enum class X E {} d;"); 3661 verifyFormat("enum class __attribute__((...)) E {} d;"); 3662 verifyFormat("enum class __declspec__((...)) E {} d;"); 3663 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3664 } 3665 3666 TEST_F(FormatTest, FormatsEnumTypes) { 3667 verifyFormat("enum X : int {\n" 3668 " A, // Force multiple lines.\n" 3669 " B\n" 3670 "};"); 3671 verifyFormat("enum X : int { A, B };"); 3672 verifyFormat("enum X : std::uint32_t { A, B };"); 3673 } 3674 3675 TEST_F(FormatTest, FormatsTypedefEnum) { 3676 FormatStyle Style = getLLVMStyleWithColumns(40); 3677 verifyFormat("typedef enum {} EmptyEnum;"); 3678 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3679 verifyFormat("typedef enum {\n" 3680 " ZERO = 0,\n" 3681 " ONE = 1,\n" 3682 " TWO = 2,\n" 3683 " THREE = 3\n" 3684 "} LongEnum;", 3685 Style); 3686 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3687 Style.BraceWrapping.AfterEnum = true; 3688 verifyFormat("typedef enum {} EmptyEnum;"); 3689 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3690 verifyFormat("typedef enum\n" 3691 "{\n" 3692 " ZERO = 0,\n" 3693 " ONE = 1,\n" 3694 " TWO = 2,\n" 3695 " THREE = 3\n" 3696 "} LongEnum;", 3697 Style); 3698 } 3699 3700 TEST_F(FormatTest, FormatsNSEnums) { 3701 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3702 verifyGoogleFormat( 3703 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3704 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3705 " // Information about someDecentlyLongValue.\n" 3706 " someDecentlyLongValue,\n" 3707 " // Information about anotherDecentlyLongValue.\n" 3708 " anotherDecentlyLongValue,\n" 3709 " // Information about aThirdDecentlyLongValue.\n" 3710 " aThirdDecentlyLongValue\n" 3711 "};"); 3712 verifyGoogleFormat("typedef NS_CLOSED_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_OPTIONS(NSInteger, MyType) {\n" 3721 " a = 1,\n" 3722 " b = 2,\n" 3723 " c = 3,\n" 3724 "};"); 3725 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3726 " a = 1,\n" 3727 " b = 2,\n" 3728 " c = 3,\n" 3729 "};"); 3730 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3731 " a = 1,\n" 3732 " b = 2,\n" 3733 " c = 3,\n" 3734 "};"); 3735 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3736 " a = 1,\n" 3737 " b = 2,\n" 3738 " c = 3,\n" 3739 "};"); 3740 } 3741 3742 TEST_F(FormatTest, FormatsBitfields) { 3743 verifyFormat("struct Bitfields {\n" 3744 " unsigned sClass : 8;\n" 3745 " unsigned ValueKind : 2;\n" 3746 "};"); 3747 verifyFormat("struct A {\n" 3748 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3749 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3750 "};"); 3751 verifyFormat("struct MyStruct {\n" 3752 " uchar data;\n" 3753 " uchar : 8;\n" 3754 " uchar : 8;\n" 3755 " uchar other;\n" 3756 "};"); 3757 FormatStyle Style = getLLVMStyle(); 3758 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3759 verifyFormat("struct Bitfields {\n" 3760 " unsigned sClass:8;\n" 3761 " unsigned ValueKind:2;\n" 3762 " uchar other;\n" 3763 "};", 3764 Style); 3765 verifyFormat("struct A {\n" 3766 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3767 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3768 "};", 3769 Style); 3770 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3771 verifyFormat("struct Bitfields {\n" 3772 " unsigned sClass :8;\n" 3773 " unsigned ValueKind :2;\n" 3774 " uchar other;\n" 3775 "};", 3776 Style); 3777 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3778 verifyFormat("struct Bitfields {\n" 3779 " unsigned sClass: 8;\n" 3780 " unsigned ValueKind: 2;\n" 3781 " uchar other;\n" 3782 "};", 3783 Style); 3784 } 3785 3786 TEST_F(FormatTest, FormatsNamespaces) { 3787 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3788 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3789 3790 verifyFormat("namespace some_namespace {\n" 3791 "class A {};\n" 3792 "void f() { f(); }\n" 3793 "}", 3794 LLVMWithNoNamespaceFix); 3795 verifyFormat("#define M(x) x##x\n" 3796 "namespace M(x) {\n" 3797 "class A {};\n" 3798 "void f() { f(); }\n" 3799 "}", 3800 LLVMWithNoNamespaceFix); 3801 verifyFormat("#define M(x) x##x\n" 3802 "namespace N::inline M(x) {\n" 3803 "class A {};\n" 3804 "void f() { f(); }\n" 3805 "}", 3806 LLVMWithNoNamespaceFix); 3807 verifyFormat("#define M(x) x##x\n" 3808 "namespace M(x)::inline N {\n" 3809 "class A {};\n" 3810 "void f() { f(); }\n" 3811 "}", 3812 LLVMWithNoNamespaceFix); 3813 verifyFormat("#define M(x) x##x\n" 3814 "namespace N::M(x) {\n" 3815 "class A {};\n" 3816 "void f() { f(); }\n" 3817 "}", 3818 LLVMWithNoNamespaceFix); 3819 verifyFormat("#define M(x) x##x\n" 3820 "namespace M::N(x) {\n" 3821 "class A {};\n" 3822 "void f() { f(); }\n" 3823 "}", 3824 LLVMWithNoNamespaceFix); 3825 verifyFormat("namespace N::inline D {\n" 3826 "class A {};\n" 3827 "void f() { f(); }\n" 3828 "}", 3829 LLVMWithNoNamespaceFix); 3830 verifyFormat("namespace N::inline D::E {\n" 3831 "class A {};\n" 3832 "void f() { f(); }\n" 3833 "}", 3834 LLVMWithNoNamespaceFix); 3835 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3836 "class A {};\n" 3837 "void f() { f(); }\n" 3838 "}", 3839 LLVMWithNoNamespaceFix); 3840 verifyFormat("/* something */ namespace some_namespace {\n" 3841 "class A {};\n" 3842 "void f() { f(); }\n" 3843 "}", 3844 LLVMWithNoNamespaceFix); 3845 verifyFormat("namespace {\n" 3846 "class A {};\n" 3847 "void f() { f(); }\n" 3848 "}", 3849 LLVMWithNoNamespaceFix); 3850 verifyFormat("/* something */ namespace {\n" 3851 "class A {};\n" 3852 "void f() { f(); }\n" 3853 "}", 3854 LLVMWithNoNamespaceFix); 3855 verifyFormat("inline namespace X {\n" 3856 "class A {};\n" 3857 "void f() { f(); }\n" 3858 "}", 3859 LLVMWithNoNamespaceFix); 3860 verifyFormat("/* something */ inline namespace X {\n" 3861 "class A {};\n" 3862 "void f() { f(); }\n" 3863 "}", 3864 LLVMWithNoNamespaceFix); 3865 verifyFormat("export namespace X {\n" 3866 "class A {};\n" 3867 "void f() { f(); }\n" 3868 "}", 3869 LLVMWithNoNamespaceFix); 3870 verifyFormat("using namespace some_namespace;\n" 3871 "class A {};\n" 3872 "void f() { f(); }", 3873 LLVMWithNoNamespaceFix); 3874 3875 // This code is more common than we thought; if we 3876 // layout this correctly the semicolon will go into 3877 // its own line, which is undesirable. 3878 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3879 verifyFormat("namespace {\n" 3880 "class A {};\n" 3881 "};", 3882 LLVMWithNoNamespaceFix); 3883 3884 verifyFormat("namespace {\n" 3885 "int SomeVariable = 0; // comment\n" 3886 "} // namespace", 3887 LLVMWithNoNamespaceFix); 3888 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3889 "#define HEADER_GUARD\n" 3890 "namespace my_namespace {\n" 3891 "int i;\n" 3892 "} // my_namespace\n" 3893 "#endif // HEADER_GUARD", 3894 format("#ifndef HEADER_GUARD\n" 3895 " #define HEADER_GUARD\n" 3896 " namespace my_namespace {\n" 3897 "int i;\n" 3898 "} // my_namespace\n" 3899 "#endif // HEADER_GUARD", 3900 LLVMWithNoNamespaceFix)); 3901 3902 EXPECT_EQ("namespace A::B {\n" 3903 "class C {};\n" 3904 "}", 3905 format("namespace A::B {\n" 3906 "class C {};\n" 3907 "}", 3908 LLVMWithNoNamespaceFix)); 3909 3910 FormatStyle Style = getLLVMStyle(); 3911 Style.NamespaceIndentation = FormatStyle::NI_All; 3912 EXPECT_EQ("namespace out {\n" 3913 " int i;\n" 3914 " namespace in {\n" 3915 " int i;\n" 3916 " } // namespace in\n" 3917 "} // namespace out", 3918 format("namespace out {\n" 3919 "int i;\n" 3920 "namespace in {\n" 3921 "int i;\n" 3922 "} // namespace in\n" 3923 "} // namespace out", 3924 Style)); 3925 3926 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3927 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3928 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3929 FormatStyle::SFS_Inline; 3930 verifyFormat("namespace {\n" 3931 " void f() {\n" 3932 " return;\n" 3933 " }\n" 3934 "} // namespace\n", 3935 ShortInlineFunctions); 3936 verifyFormat("namespace { /* comment */\n" 3937 " void f() {\n" 3938 " return;\n" 3939 " }\n" 3940 "} // namespace\n", 3941 ShortInlineFunctions); 3942 verifyFormat("namespace { // comment\n" 3943 " void f() {\n" 3944 " return;\n" 3945 " }\n" 3946 "} // namespace\n", 3947 ShortInlineFunctions); 3948 verifyFormat("namespace {\n" 3949 " int some_int;\n" 3950 " void f() {\n" 3951 " return;\n" 3952 " }\n" 3953 "} // namespace\n", 3954 ShortInlineFunctions); 3955 verifyFormat("namespace interface {\n" 3956 " void f() {\n" 3957 " return;\n" 3958 " }\n" 3959 "} // namespace interface\n", 3960 ShortInlineFunctions); 3961 verifyFormat("namespace {\n" 3962 " class X {\n" 3963 " void f() { return; }\n" 3964 " };\n" 3965 "} // namespace\n", 3966 ShortInlineFunctions); 3967 verifyFormat("namespace {\n" 3968 " class X { /* comment */\n" 3969 " void f() { return; }\n" 3970 " };\n" 3971 "} // namespace\n", 3972 ShortInlineFunctions); 3973 verifyFormat("namespace {\n" 3974 " class X { // comment\n" 3975 " void f() { return; }\n" 3976 " };\n" 3977 "} // namespace\n", 3978 ShortInlineFunctions); 3979 verifyFormat("namespace {\n" 3980 " struct X {\n" 3981 " void f() { return; }\n" 3982 " };\n" 3983 "} // namespace\n", 3984 ShortInlineFunctions); 3985 verifyFormat("namespace {\n" 3986 " union X {\n" 3987 " void f() { return; }\n" 3988 " };\n" 3989 "} // namespace\n", 3990 ShortInlineFunctions); 3991 verifyFormat("extern \"C\" {\n" 3992 "void f() {\n" 3993 " return;\n" 3994 "}\n" 3995 "} // namespace\n", 3996 ShortInlineFunctions); 3997 verifyFormat("namespace {\n" 3998 " class X {\n" 3999 " void f() { return; }\n" 4000 " } x;\n" 4001 "} // namespace\n", 4002 ShortInlineFunctions); 4003 verifyFormat("namespace {\n" 4004 " [[nodiscard]] class X {\n" 4005 " void f() { return; }\n" 4006 " };\n" 4007 "} // namespace\n", 4008 ShortInlineFunctions); 4009 verifyFormat("namespace {\n" 4010 " static class X {\n" 4011 " void f() { return; }\n" 4012 " } x;\n" 4013 "} // namespace\n", 4014 ShortInlineFunctions); 4015 verifyFormat("namespace {\n" 4016 " constexpr class X {\n" 4017 " void f() { return; }\n" 4018 " } x;\n" 4019 "} // namespace\n", 4020 ShortInlineFunctions); 4021 4022 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4023 verifyFormat("extern \"C\" {\n" 4024 " void f() {\n" 4025 " return;\n" 4026 " }\n" 4027 "} // namespace\n", 4028 ShortInlineFunctions); 4029 4030 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4031 EXPECT_EQ("namespace out {\n" 4032 "int i;\n" 4033 "namespace in {\n" 4034 " int i;\n" 4035 "} // namespace in\n" 4036 "} // namespace out", 4037 format("namespace out {\n" 4038 "int i;\n" 4039 "namespace in {\n" 4040 "int i;\n" 4041 "} // namespace in\n" 4042 "} // namespace out", 4043 Style)); 4044 4045 Style.NamespaceIndentation = FormatStyle::NI_None; 4046 verifyFormat("template <class T>\n" 4047 "concept a_concept = X<>;\n" 4048 "namespace B {\n" 4049 "struct b_struct {};\n" 4050 "} // namespace B\n", 4051 Style); 4052 verifyFormat("template <int I>\n" 4053 "constexpr void foo()\n" 4054 " requires(I == 42)\n" 4055 "{}\n" 4056 "namespace ns {\n" 4057 "void foo() {}\n" 4058 "} // namespace ns\n", 4059 Style); 4060 } 4061 4062 TEST_F(FormatTest, NamespaceMacros) { 4063 FormatStyle Style = getLLVMStyle(); 4064 Style.NamespaceMacros.push_back("TESTSUITE"); 4065 4066 verifyFormat("TESTSUITE(A) {\n" 4067 "int foo();\n" 4068 "} // TESTSUITE(A)", 4069 Style); 4070 4071 verifyFormat("TESTSUITE(A, B) {\n" 4072 "int foo();\n" 4073 "} // TESTSUITE(A)", 4074 Style); 4075 4076 // Properly indent according to NamespaceIndentation style 4077 Style.NamespaceIndentation = FormatStyle::NI_All; 4078 verifyFormat("TESTSUITE(A) {\n" 4079 " int foo();\n" 4080 "} // TESTSUITE(A)", 4081 Style); 4082 verifyFormat("TESTSUITE(A) {\n" 4083 " namespace B {\n" 4084 " int foo();\n" 4085 " } // namespace B\n" 4086 "} // TESTSUITE(A)", 4087 Style); 4088 verifyFormat("namespace A {\n" 4089 " TESTSUITE(B) {\n" 4090 " int foo();\n" 4091 " } // TESTSUITE(B)\n" 4092 "} // namespace A", 4093 Style); 4094 4095 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4096 verifyFormat("TESTSUITE(A) {\n" 4097 "TESTSUITE(B) {\n" 4098 " int foo();\n" 4099 "} // TESTSUITE(B)\n" 4100 "} // TESTSUITE(A)", 4101 Style); 4102 verifyFormat("TESTSUITE(A) {\n" 4103 "namespace B {\n" 4104 " int foo();\n" 4105 "} // namespace B\n" 4106 "} // TESTSUITE(A)", 4107 Style); 4108 verifyFormat("namespace A {\n" 4109 "TESTSUITE(B) {\n" 4110 " int foo();\n" 4111 "} // TESTSUITE(B)\n" 4112 "} // namespace A", 4113 Style); 4114 4115 // Properly merge namespace-macros blocks in CompactNamespaces mode 4116 Style.NamespaceIndentation = FormatStyle::NI_None; 4117 Style.CompactNamespaces = true; 4118 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4119 "}} // TESTSUITE(A::B)", 4120 Style); 4121 4122 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4123 "}} // TESTSUITE(out::in)", 4124 format("TESTSUITE(out) {\n" 4125 "TESTSUITE(in) {\n" 4126 "} // TESTSUITE(in)\n" 4127 "} // TESTSUITE(out)", 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 // Do not merge different namespaces/macros 4139 EXPECT_EQ("namespace out {\n" 4140 "TESTSUITE(in) {\n" 4141 "} // TESTSUITE(in)\n" 4142 "} // namespace out", 4143 format("namespace out {\n" 4144 "TESTSUITE(in) {\n" 4145 "} // TESTSUITE(in)\n" 4146 "} // namespace out", 4147 Style)); 4148 EXPECT_EQ("TESTSUITE(out) {\n" 4149 "namespace in {\n" 4150 "} // namespace in\n" 4151 "} // TESTSUITE(out)", 4152 format("TESTSUITE(out) {\n" 4153 "namespace in {\n" 4154 "} // namespace in\n" 4155 "} // TESTSUITE(out)", 4156 Style)); 4157 Style.NamespaceMacros.push_back("FOOBAR"); 4158 EXPECT_EQ("TESTSUITE(out) {\n" 4159 "FOOBAR(in) {\n" 4160 "} // FOOBAR(in)\n" 4161 "} // TESTSUITE(out)", 4162 format("TESTSUITE(out) {\n" 4163 "FOOBAR(in) {\n" 4164 "} // FOOBAR(in)\n" 4165 "} // TESTSUITE(out)", 4166 Style)); 4167 } 4168 4169 TEST_F(FormatTest, FormatsCompactNamespaces) { 4170 FormatStyle Style = getLLVMStyle(); 4171 Style.CompactNamespaces = true; 4172 Style.NamespaceMacros.push_back("TESTSUITE"); 4173 4174 verifyFormat("namespace A { namespace B {\n" 4175 "}} // namespace A::B", 4176 Style); 4177 4178 EXPECT_EQ("namespace out { namespace in {\n" 4179 "}} // namespace out::in", 4180 format("namespace out {\n" 4181 "namespace in {\n" 4182 "} // namespace in\n" 4183 "} // namespace out", 4184 Style)); 4185 4186 // Only namespaces which have both consecutive opening and end get compacted 4187 EXPECT_EQ("namespace out {\n" 4188 "namespace in1 {\n" 4189 "} // namespace in1\n" 4190 "namespace in2 {\n" 4191 "} // namespace in2\n" 4192 "} // namespace out", 4193 format("namespace out {\n" 4194 "namespace in1 {\n" 4195 "} // namespace in1\n" 4196 "namespace in2 {\n" 4197 "} // namespace in2\n" 4198 "} // namespace out", 4199 Style)); 4200 4201 EXPECT_EQ("namespace out {\n" 4202 "int i;\n" 4203 "namespace in {\n" 4204 "int j;\n" 4205 "} // namespace in\n" 4206 "int k;\n" 4207 "} // namespace out", 4208 format("namespace out { int i;\n" 4209 "namespace in { int j; } // namespace in\n" 4210 "int k; } // namespace out", 4211 Style)); 4212 4213 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4214 "}}} // namespace A::B::C\n", 4215 format("namespace A { namespace B {\n" 4216 "namespace C {\n" 4217 "}} // namespace B::C\n" 4218 "} // namespace A\n", 4219 Style)); 4220 4221 Style.ColumnLimit = 40; 4222 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4223 "namespace bbbbbbbbbb {\n" 4224 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4225 format("namespace aaaaaaaaaa {\n" 4226 "namespace bbbbbbbbbb {\n" 4227 "} // namespace bbbbbbbbbb\n" 4228 "} // namespace aaaaaaaaaa", 4229 Style)); 4230 4231 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4232 "namespace cccccc {\n" 4233 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4234 format("namespace aaaaaa {\n" 4235 "namespace bbbbbb {\n" 4236 "namespace cccccc {\n" 4237 "} // namespace cccccc\n" 4238 "} // namespace bbbbbb\n" 4239 "} // namespace aaaaaa", 4240 Style)); 4241 Style.ColumnLimit = 80; 4242 4243 // Extra semicolon after 'inner' closing brace prevents merging 4244 EXPECT_EQ("namespace out { namespace in {\n" 4245 "}; } // namespace out::in", 4246 format("namespace out {\n" 4247 "namespace in {\n" 4248 "}; // namespace in\n" 4249 "} // namespace out", 4250 Style)); 4251 4252 // Extra semicolon after 'outer' closing brace is conserved 4253 EXPECT_EQ("namespace out { namespace in {\n" 4254 "}}; // namespace out::in", 4255 format("namespace out {\n" 4256 "namespace in {\n" 4257 "} // namespace in\n" 4258 "}; // namespace out", 4259 Style)); 4260 4261 Style.NamespaceIndentation = FormatStyle::NI_All; 4262 EXPECT_EQ("namespace out { namespace in {\n" 4263 " int i;\n" 4264 "}} // namespace out::in", 4265 format("namespace out {\n" 4266 "namespace in {\n" 4267 "int i;\n" 4268 "} // namespace in\n" 4269 "} // namespace out", 4270 Style)); 4271 EXPECT_EQ("namespace out { namespace mid {\n" 4272 " namespace in {\n" 4273 " int j;\n" 4274 " } // namespace in\n" 4275 " int k;\n" 4276 "}} // namespace out::mid", 4277 format("namespace out { namespace mid {\n" 4278 "namespace in { int j; } // namespace in\n" 4279 "int k; }} // namespace out::mid", 4280 Style)); 4281 4282 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4283 EXPECT_EQ("namespace out { namespace in {\n" 4284 " int i;\n" 4285 "}} // namespace out::in", 4286 format("namespace out {\n" 4287 "namespace in {\n" 4288 "int i;\n" 4289 "} // namespace in\n" 4290 "} // namespace out", 4291 Style)); 4292 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4293 " int i;\n" 4294 "}}} // namespace out::mid::in", 4295 format("namespace out {\n" 4296 "namespace mid {\n" 4297 "namespace in {\n" 4298 "int i;\n" 4299 "} // namespace in\n" 4300 "} // namespace mid\n" 4301 "} // namespace out", 4302 Style)); 4303 4304 Style.CompactNamespaces = true; 4305 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4306 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4307 Style.BraceWrapping.BeforeLambdaBody = true; 4308 verifyFormat("namespace out { namespace in {\n" 4309 "}} // namespace out::in", 4310 Style); 4311 EXPECT_EQ("namespace out { namespace in {\n" 4312 "}} // namespace out::in", 4313 format("namespace out {\n" 4314 "namespace in {\n" 4315 "} // namespace in\n" 4316 "} // namespace out", 4317 Style)); 4318 } 4319 4320 TEST_F(FormatTest, FormatsExternC) { 4321 verifyFormat("extern \"C\" {\nint a;"); 4322 verifyFormat("extern \"C\" {}"); 4323 verifyFormat("extern \"C\" {\n" 4324 "int foo();\n" 4325 "}"); 4326 verifyFormat("extern \"C\" int foo() {}"); 4327 verifyFormat("extern \"C\" int foo();"); 4328 verifyFormat("extern \"C\" int foo() {\n" 4329 " int i = 42;\n" 4330 " return i;\n" 4331 "}"); 4332 4333 FormatStyle Style = getLLVMStyle(); 4334 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4335 Style.BraceWrapping.AfterFunction = true; 4336 verifyFormat("extern \"C\" int foo() {}", Style); 4337 verifyFormat("extern \"C\" int foo();", Style); 4338 verifyFormat("extern \"C\" int foo()\n" 4339 "{\n" 4340 " int i = 42;\n" 4341 " return i;\n" 4342 "}", 4343 Style); 4344 4345 Style.BraceWrapping.AfterExternBlock = true; 4346 Style.BraceWrapping.SplitEmptyRecord = false; 4347 verifyFormat("extern \"C\"\n" 4348 "{}", 4349 Style); 4350 verifyFormat("extern \"C\"\n" 4351 "{\n" 4352 " int foo();\n" 4353 "}", 4354 Style); 4355 } 4356 4357 TEST_F(FormatTest, IndentExternBlockStyle) { 4358 FormatStyle Style = getLLVMStyle(); 4359 Style.IndentWidth = 2; 4360 4361 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4362 verifyFormat("extern \"C\" { /*9*/\n" 4363 "}", 4364 Style); 4365 verifyFormat("extern \"C\" {\n" 4366 " int foo10();\n" 4367 "}", 4368 Style); 4369 4370 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4371 verifyFormat("extern \"C\" { /*11*/\n" 4372 "}", 4373 Style); 4374 verifyFormat("extern \"C\" {\n" 4375 "int foo12();\n" 4376 "}", 4377 Style); 4378 4379 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4380 Style.BraceWrapping.AfterExternBlock = true; 4381 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4382 verifyFormat("extern \"C\"\n" 4383 "{ /*13*/\n" 4384 "}", 4385 Style); 4386 verifyFormat("extern \"C\"\n{\n" 4387 " int foo14();\n" 4388 "}", 4389 Style); 4390 4391 Style.BraceWrapping.AfterExternBlock = false; 4392 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4393 verifyFormat("extern \"C\" { /*15*/\n" 4394 "}", 4395 Style); 4396 verifyFormat("extern \"C\" {\n" 4397 "int foo16();\n" 4398 "}", 4399 Style); 4400 4401 Style.BraceWrapping.AfterExternBlock = true; 4402 verifyFormat("extern \"C\"\n" 4403 "{ /*13*/\n" 4404 "}", 4405 Style); 4406 verifyFormat("extern \"C\"\n" 4407 "{\n" 4408 "int foo14();\n" 4409 "}", 4410 Style); 4411 4412 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4413 verifyFormat("extern \"C\"\n" 4414 "{ /*13*/\n" 4415 "}", 4416 Style); 4417 verifyFormat("extern \"C\"\n" 4418 "{\n" 4419 " int foo14();\n" 4420 "}", 4421 Style); 4422 } 4423 4424 TEST_F(FormatTest, FormatsInlineASM) { 4425 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4426 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4427 verifyFormat( 4428 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4429 " \"cpuid\\n\\t\"\n" 4430 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4431 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4432 " : \"a\"(value));"); 4433 EXPECT_EQ( 4434 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4435 " __asm {\n" 4436 " mov edx,[that] // vtable in edx\n" 4437 " mov eax,methodIndex\n" 4438 " call [edx][eax*4] // stdcall\n" 4439 " }\n" 4440 "}", 4441 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4442 " __asm {\n" 4443 " mov edx,[that] // vtable in edx\n" 4444 " mov eax,methodIndex\n" 4445 " call [edx][eax*4] // stdcall\n" 4446 " }\n" 4447 "}")); 4448 EXPECT_EQ("_asm {\n" 4449 " xor eax, eax;\n" 4450 " cpuid;\n" 4451 "}", 4452 format("_asm {\n" 4453 " xor eax, eax;\n" 4454 " cpuid;\n" 4455 "}")); 4456 verifyFormat("void function() {\n" 4457 " // comment\n" 4458 " asm(\"\");\n" 4459 "}"); 4460 EXPECT_EQ("__asm {\n" 4461 "}\n" 4462 "int i;", 4463 format("__asm {\n" 4464 "}\n" 4465 "int i;")); 4466 } 4467 4468 TEST_F(FormatTest, FormatTryCatch) { 4469 verifyFormat("try {\n" 4470 " throw a * b;\n" 4471 "} catch (int a) {\n" 4472 " // Do nothing.\n" 4473 "} catch (...) {\n" 4474 " exit(42);\n" 4475 "}"); 4476 4477 // Function-level try statements. 4478 verifyFormat("int f() try { return 4; } catch (...) {\n" 4479 " return 5;\n" 4480 "}"); 4481 verifyFormat("class A {\n" 4482 " int a;\n" 4483 " A() try : a(0) {\n" 4484 " } catch (...) {\n" 4485 " throw;\n" 4486 " }\n" 4487 "};\n"); 4488 verifyFormat("class A {\n" 4489 " int a;\n" 4490 " A() try : a(0), b{1} {\n" 4491 " } catch (...) {\n" 4492 " throw;\n" 4493 " }\n" 4494 "};\n"); 4495 verifyFormat("class A {\n" 4496 " int a;\n" 4497 " A() try : a(0), b{1}, c{2} {\n" 4498 " } catch (...) {\n" 4499 " throw;\n" 4500 " }\n" 4501 "};\n"); 4502 verifyFormat("class A {\n" 4503 " int a;\n" 4504 " A() try : a(0), b{1}, c{2} {\n" 4505 " { // New scope.\n" 4506 " }\n" 4507 " } catch (...) {\n" 4508 " throw;\n" 4509 " }\n" 4510 "};\n"); 4511 4512 // Incomplete try-catch blocks. 4513 verifyIncompleteFormat("try {} catch ("); 4514 } 4515 4516 TEST_F(FormatTest, FormatTryAsAVariable) { 4517 verifyFormat("int try;"); 4518 verifyFormat("int try, size;"); 4519 verifyFormat("try = foo();"); 4520 verifyFormat("if (try < size) {\n return true;\n}"); 4521 4522 verifyFormat("int catch;"); 4523 verifyFormat("int catch, size;"); 4524 verifyFormat("catch = foo();"); 4525 verifyFormat("if (catch < size) {\n return true;\n}"); 4526 4527 FormatStyle Style = getLLVMStyle(); 4528 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4529 Style.BraceWrapping.AfterFunction = true; 4530 Style.BraceWrapping.BeforeCatch = true; 4531 verifyFormat("try {\n" 4532 " int bar = 1;\n" 4533 "}\n" 4534 "catch (...) {\n" 4535 " int bar = 1;\n" 4536 "}", 4537 Style); 4538 verifyFormat("#if NO_EX\n" 4539 "try\n" 4540 "#endif\n" 4541 "{\n" 4542 "}\n" 4543 "#if NO_EX\n" 4544 "catch (...) {\n" 4545 "}", 4546 Style); 4547 verifyFormat("try /* abc */ {\n" 4548 " int bar = 1;\n" 4549 "}\n" 4550 "catch (...) {\n" 4551 " int bar = 1;\n" 4552 "}", 4553 Style); 4554 verifyFormat("try\n" 4555 "// abc\n" 4556 "{\n" 4557 " int bar = 1;\n" 4558 "}\n" 4559 "catch (...) {\n" 4560 " int bar = 1;\n" 4561 "}", 4562 Style); 4563 } 4564 4565 TEST_F(FormatTest, FormatSEHTryCatch) { 4566 verifyFormat("__try {\n" 4567 " int a = b * c;\n" 4568 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4569 " // Do nothing.\n" 4570 "}"); 4571 4572 verifyFormat("__try {\n" 4573 " int a = b * c;\n" 4574 "} __finally {\n" 4575 " // Do nothing.\n" 4576 "}"); 4577 4578 verifyFormat("DEBUG({\n" 4579 " __try {\n" 4580 " } __finally {\n" 4581 " }\n" 4582 "});\n"); 4583 } 4584 4585 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4586 verifyFormat("try {\n" 4587 " f();\n" 4588 "} catch {\n" 4589 " g();\n" 4590 "}"); 4591 verifyFormat("try {\n" 4592 " f();\n" 4593 "} catch (A a) MACRO(x) {\n" 4594 " g();\n" 4595 "} catch (B b) MACRO(x) {\n" 4596 " g();\n" 4597 "}"); 4598 } 4599 4600 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4601 FormatStyle Style = getLLVMStyle(); 4602 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4603 FormatStyle::BS_WebKit}) { 4604 Style.BreakBeforeBraces = BraceStyle; 4605 verifyFormat("try {\n" 4606 " // something\n" 4607 "} catch (...) {\n" 4608 " // something\n" 4609 "}", 4610 Style); 4611 } 4612 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4613 verifyFormat("try {\n" 4614 " // something\n" 4615 "}\n" 4616 "catch (...) {\n" 4617 " // something\n" 4618 "}", 4619 Style); 4620 verifyFormat("__try {\n" 4621 " // something\n" 4622 "}\n" 4623 "__finally {\n" 4624 " // something\n" 4625 "}", 4626 Style); 4627 verifyFormat("@try {\n" 4628 " // something\n" 4629 "}\n" 4630 "@finally {\n" 4631 " // something\n" 4632 "}", 4633 Style); 4634 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4635 verifyFormat("try\n" 4636 "{\n" 4637 " // something\n" 4638 "}\n" 4639 "catch (...)\n" 4640 "{\n" 4641 " // something\n" 4642 "}", 4643 Style); 4644 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4645 verifyFormat("try\n" 4646 " {\n" 4647 " // something white\n" 4648 " }\n" 4649 "catch (...)\n" 4650 " {\n" 4651 " // something white\n" 4652 " }", 4653 Style); 4654 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4655 verifyFormat("try\n" 4656 " {\n" 4657 " // something\n" 4658 " }\n" 4659 "catch (...)\n" 4660 " {\n" 4661 " // something\n" 4662 " }", 4663 Style); 4664 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4665 Style.BraceWrapping.BeforeCatch = true; 4666 verifyFormat("try {\n" 4667 " // something\n" 4668 "}\n" 4669 "catch (...) {\n" 4670 " // something\n" 4671 "}", 4672 Style); 4673 } 4674 4675 TEST_F(FormatTest, StaticInitializers) { 4676 verifyFormat("static SomeClass SC = {1, 'a'};"); 4677 4678 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4679 " 100000000, " 4680 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4681 4682 // Here, everything other than the "}" would fit on a line. 4683 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4684 " 10000000000000000000000000};"); 4685 EXPECT_EQ("S s = {a,\n" 4686 "\n" 4687 " b};", 4688 format("S s = {\n" 4689 " a,\n" 4690 "\n" 4691 " b\n" 4692 "};")); 4693 4694 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4695 // line. However, the formatting looks a bit off and this probably doesn't 4696 // happen often in practice. 4697 verifyFormat("static int Variable[1] = {\n" 4698 " {1000000000000000000000000000000000000}};", 4699 getLLVMStyleWithColumns(40)); 4700 } 4701 4702 TEST_F(FormatTest, DesignatedInitializers) { 4703 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4704 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4705 " .bbbbbbbbbb = 2,\n" 4706 " .cccccccccc = 3,\n" 4707 " .dddddddddd = 4,\n" 4708 " .eeeeeeeeee = 5};"); 4709 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4710 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4711 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4712 " .ccccccccccccccccccccccccccc = 3,\n" 4713 " .ddddddddddddddddddddddddddd = 4,\n" 4714 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4715 4716 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4717 4718 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4719 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4720 " [2] = bbbbbbbbbb,\n" 4721 " [3] = cccccccccc,\n" 4722 " [4] = dddddddddd,\n" 4723 " [5] = eeeeeeeeee};"); 4724 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4725 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4726 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4727 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4728 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4729 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4730 } 4731 4732 TEST_F(FormatTest, NestedStaticInitializers) { 4733 verifyFormat("static A x = {{{}}};\n"); 4734 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4735 " {init1, init2, init3, init4}}};", 4736 getLLVMStyleWithColumns(50)); 4737 4738 verifyFormat("somes Status::global_reps[3] = {\n" 4739 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4740 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4741 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4742 getLLVMStyleWithColumns(60)); 4743 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4744 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4745 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4746 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4747 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4748 " {rect.fRight - rect.fLeft, rect.fBottom - " 4749 "rect.fTop}};"); 4750 4751 verifyFormat( 4752 "SomeArrayOfSomeType a = {\n" 4753 " {{1, 2, 3},\n" 4754 " {1, 2, 3},\n" 4755 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4756 " 333333333333333333333333333333},\n" 4757 " {1, 2, 3},\n" 4758 " {1, 2, 3}}};"); 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 4768 verifyFormat("struct {\n" 4769 " unsigned bit;\n" 4770 " const char *const name;\n" 4771 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4772 " {kOsWin, \"Windows\"},\n" 4773 " {kOsLinux, \"Linux\"},\n" 4774 " {kOsCrOS, \"Chrome OS\"}};"); 4775 verifyFormat("struct {\n" 4776 " unsigned bit;\n" 4777 " const char *const name;\n" 4778 "} kBitsToOs[] = {\n" 4779 " {kOsMac, \"Mac\"},\n" 4780 " {kOsWin, \"Windows\"},\n" 4781 " {kOsLinux, \"Linux\"},\n" 4782 " {kOsCrOS, \"Chrome OS\"},\n" 4783 "};"); 4784 } 4785 4786 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4787 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4788 " \\\n" 4789 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4790 } 4791 4792 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4793 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4794 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4795 4796 // Do break defaulted and deleted functions. 4797 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4798 " default;", 4799 getLLVMStyleWithColumns(40)); 4800 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4801 " delete;", 4802 getLLVMStyleWithColumns(40)); 4803 } 4804 4805 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4806 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4807 getLLVMStyleWithColumns(40)); 4808 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4809 getLLVMStyleWithColumns(40)); 4810 EXPECT_EQ("#define Q \\\n" 4811 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4812 " \"aaaaaaaa.cpp\"", 4813 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4814 getLLVMStyleWithColumns(40))); 4815 } 4816 4817 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4818 EXPECT_EQ("# 123 \"A string literal\"", 4819 format(" # 123 \"A string literal\"")); 4820 } 4821 4822 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4823 EXPECT_EQ("#;", format("#;")); 4824 verifyFormat("#\n;\n;\n;"); 4825 } 4826 4827 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4828 EXPECT_EQ("#line 42 \"test\"\n", 4829 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4830 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4831 getLLVMStyleWithColumns(12))); 4832 } 4833 4834 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4835 EXPECT_EQ("#line 42 \"test\"", 4836 format("# \\\n line \\\n 42 \\\n \"test\"")); 4837 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4838 } 4839 4840 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4841 verifyFormat("#define A \\x20"); 4842 verifyFormat("#define A \\ x20"); 4843 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4844 verifyFormat("#define A ''"); 4845 verifyFormat("#define A ''qqq"); 4846 verifyFormat("#define A `qqq"); 4847 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4848 EXPECT_EQ("const char *c = STRINGIFY(\n" 4849 "\\na : b);", 4850 format("const char * c = STRINGIFY(\n" 4851 "\\na : b);")); 4852 4853 verifyFormat("a\r\\"); 4854 verifyFormat("a\v\\"); 4855 verifyFormat("a\f\\"); 4856 } 4857 4858 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4859 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4860 style.IndentWidth = 4; 4861 style.PPIndentWidth = 1; 4862 4863 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4864 verifyFormat("#ifdef __linux__\n" 4865 "void foo() {\n" 4866 " int x = 0;\n" 4867 "}\n" 4868 "#define FOO\n" 4869 "#endif\n" 4870 "void bar() {\n" 4871 " int y = 0;\n" 4872 "}\n", 4873 style); 4874 4875 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4876 verifyFormat("#ifdef __linux__\n" 4877 "void foo() {\n" 4878 " int x = 0;\n" 4879 "}\n" 4880 "# define FOO foo\n" 4881 "#endif\n" 4882 "void bar() {\n" 4883 " int y = 0;\n" 4884 "}\n", 4885 style); 4886 4887 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4888 verifyFormat("#ifdef __linux__\n" 4889 "void foo() {\n" 4890 " int x = 0;\n" 4891 "}\n" 4892 " #define FOO foo\n" 4893 "#endif\n" 4894 "void bar() {\n" 4895 " int y = 0;\n" 4896 "}\n", 4897 style); 4898 } 4899 4900 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4901 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4902 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4903 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4904 // FIXME: We never break before the macro name. 4905 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4906 4907 verifyFormat("#define A A\n#define A A"); 4908 verifyFormat("#define A(X) A\n#define A A"); 4909 4910 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4911 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4912 } 4913 4914 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4915 EXPECT_EQ("// somecomment\n" 4916 "#include \"a.h\"\n" 4917 "#define A( \\\n" 4918 " A, B)\n" 4919 "#include \"b.h\"\n" 4920 "// somecomment\n", 4921 format(" // somecomment\n" 4922 " #include \"a.h\"\n" 4923 "#define A(A,\\\n" 4924 " B)\n" 4925 " #include \"b.h\"\n" 4926 " // somecomment\n", 4927 getLLVMStyleWithColumns(13))); 4928 } 4929 4930 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4931 4932 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4933 EXPECT_EQ("#define A \\\n" 4934 " c; \\\n" 4935 " e;\n" 4936 "f;", 4937 format("#define A c; e;\n" 4938 "f;", 4939 getLLVMStyleWithColumns(14))); 4940 } 4941 4942 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4943 4944 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4945 EXPECT_EQ("int x,\n" 4946 "#define A\n" 4947 " y;", 4948 format("int x,\n#define A\ny;")); 4949 } 4950 4951 TEST_F(FormatTest, HashInMacroDefinition) { 4952 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4953 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4954 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4955 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4956 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4957 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4958 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4959 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4960 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4961 verifyFormat("#define A \\\n" 4962 " { \\\n" 4963 " f(#c); \\\n" 4964 " }", 4965 getLLVMStyleWithColumns(11)); 4966 4967 verifyFormat("#define A(X) \\\n" 4968 " void function##X()", 4969 getLLVMStyleWithColumns(22)); 4970 4971 verifyFormat("#define A(a, b, c) \\\n" 4972 " void a##b##c()", 4973 getLLVMStyleWithColumns(22)); 4974 4975 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4976 } 4977 4978 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4979 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4980 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4981 4982 FormatStyle Style = getLLVMStyle(); 4983 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4984 verifyFormat("#define true ((foo)1)", Style); 4985 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4986 verifyFormat("#define false((foo)0)", Style); 4987 } 4988 4989 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4990 EXPECT_EQ("#define A b;", format("#define A \\\n" 4991 " \\\n" 4992 " b;", 4993 getLLVMStyleWithColumns(25))); 4994 EXPECT_EQ("#define A \\\n" 4995 " \\\n" 4996 " a; \\\n" 4997 " b;", 4998 format("#define A \\\n" 4999 " \\\n" 5000 " a; \\\n" 5001 " b;", 5002 getLLVMStyleWithColumns(11))); 5003 EXPECT_EQ("#define A \\\n" 5004 " a; \\\n" 5005 " \\\n" 5006 " b;", 5007 format("#define A \\\n" 5008 " a; \\\n" 5009 " \\\n" 5010 " b;", 5011 getLLVMStyleWithColumns(11))); 5012 } 5013 5014 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5015 verifyIncompleteFormat("#define A :"); 5016 verifyFormat("#define SOMECASES \\\n" 5017 " case 1: \\\n" 5018 " case 2\n", 5019 getLLVMStyleWithColumns(20)); 5020 verifyFormat("#define MACRO(a) \\\n" 5021 " if (a) \\\n" 5022 " f(); \\\n" 5023 " else \\\n" 5024 " g()", 5025 getLLVMStyleWithColumns(18)); 5026 verifyFormat("#define A template <typename T>"); 5027 verifyIncompleteFormat("#define STR(x) #x\n" 5028 "f(STR(this_is_a_string_literal{));"); 5029 verifyFormat("#pragma omp threadprivate( \\\n" 5030 " y)), // expected-warning", 5031 getLLVMStyleWithColumns(28)); 5032 verifyFormat("#d, = };"); 5033 verifyFormat("#if \"a"); 5034 verifyIncompleteFormat("({\n" 5035 "#define b \\\n" 5036 " } \\\n" 5037 " a\n" 5038 "a", 5039 getLLVMStyleWithColumns(15)); 5040 verifyFormat("#define A \\\n" 5041 " { \\\n" 5042 " {\n" 5043 "#define B \\\n" 5044 " } \\\n" 5045 " }", 5046 getLLVMStyleWithColumns(15)); 5047 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5048 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5049 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5050 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5051 } 5052 5053 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5054 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5055 EXPECT_EQ("class A : public QObject {\n" 5056 " Q_OBJECT\n" 5057 "\n" 5058 " A() {}\n" 5059 "};", 5060 format("class A : public QObject {\n" 5061 " Q_OBJECT\n" 5062 "\n" 5063 " A() {\n}\n" 5064 "} ;")); 5065 EXPECT_EQ("MACRO\n" 5066 "/*static*/ int i;", 5067 format("MACRO\n" 5068 " /*static*/ int i;")); 5069 EXPECT_EQ("SOME_MACRO\n" 5070 "namespace {\n" 5071 "void f();\n" 5072 "} // namespace", 5073 format("SOME_MACRO\n" 5074 " namespace {\n" 5075 "void f( );\n" 5076 "} // namespace")); 5077 // Only if the identifier contains at least 5 characters. 5078 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5079 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5080 // Only if everything is upper case. 5081 EXPECT_EQ("class A : public QObject {\n" 5082 " Q_Object A() {}\n" 5083 "};", 5084 format("class A : public QObject {\n" 5085 " Q_Object\n" 5086 " A() {\n}\n" 5087 "} ;")); 5088 5089 // Only if the next line can actually start an unwrapped line. 5090 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5091 format("SOME_WEIRD_LOG_MACRO\n" 5092 "<< SomeThing;")); 5093 5094 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5095 "(n, buffers))\n", 5096 getChromiumStyle(FormatStyle::LK_Cpp)); 5097 5098 // See PR41483 5099 EXPECT_EQ("/**/ FOO(a)\n" 5100 "FOO(b)", 5101 format("/**/ FOO(a)\n" 5102 "FOO(b)")); 5103 } 5104 5105 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5106 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5107 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5108 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5109 "class X {};\n" 5110 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5111 "int *createScopDetectionPass() { return 0; }", 5112 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5113 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5114 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5115 " class X {};\n" 5116 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5117 " int *createScopDetectionPass() { return 0; }")); 5118 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5119 // braces, so that inner block is indented one level more. 5120 EXPECT_EQ("int q() {\n" 5121 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5122 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5123 " IPC_END_MESSAGE_MAP()\n" 5124 "}", 5125 format("int q() {\n" 5126 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5127 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5128 " IPC_END_MESSAGE_MAP()\n" 5129 "}")); 5130 5131 // Same inside macros. 5132 EXPECT_EQ("#define LIST(L) \\\n" 5133 " L(A) \\\n" 5134 " L(B) \\\n" 5135 " L(C)", 5136 format("#define LIST(L) \\\n" 5137 " L(A) \\\n" 5138 " L(B) \\\n" 5139 " L(C)", 5140 getGoogleStyle())); 5141 5142 // These must not be recognized as macros. 5143 EXPECT_EQ("int q() {\n" 5144 " f(x);\n" 5145 " f(x) {}\n" 5146 " f(x)->g();\n" 5147 " f(x)->*g();\n" 5148 " f(x).g();\n" 5149 " f(x) = x;\n" 5150 " f(x) += x;\n" 5151 " f(x) -= x;\n" 5152 " f(x) *= x;\n" 5153 " f(x) /= x;\n" 5154 " f(x) %= x;\n" 5155 " f(x) &= x;\n" 5156 " f(x) |= x;\n" 5157 " f(x) ^= x;\n" 5158 " f(x) >>= x;\n" 5159 " f(x) <<= x;\n" 5160 " f(x)[y].z();\n" 5161 " LOG(INFO) << x;\n" 5162 " ifstream(x) >> x;\n" 5163 "}\n", 5164 format("int q() {\n" 5165 " f(x)\n;\n" 5166 " f(x)\n {}\n" 5167 " f(x)\n->g();\n" 5168 " f(x)\n->*g();\n" 5169 " f(x)\n.g();\n" 5170 " f(x)\n = x;\n" 5171 " f(x)\n += x;\n" 5172 " f(x)\n -= x;\n" 5173 " f(x)\n *= x;\n" 5174 " f(x)\n /= x;\n" 5175 " f(x)\n %= x;\n" 5176 " f(x)\n &= x;\n" 5177 " f(x)\n |= x;\n" 5178 " f(x)\n ^= x;\n" 5179 " f(x)\n >>= x;\n" 5180 " f(x)\n <<= x;\n" 5181 " f(x)\n[y].z();\n" 5182 " LOG(INFO)\n << x;\n" 5183 " ifstream(x)\n >> x;\n" 5184 "}\n")); 5185 EXPECT_EQ("int q() {\n" 5186 " F(x)\n" 5187 " if (1) {\n" 5188 " }\n" 5189 " F(x)\n" 5190 " while (1) {\n" 5191 " }\n" 5192 " F(x)\n" 5193 " G(x);\n" 5194 " F(x)\n" 5195 " try {\n" 5196 " Q();\n" 5197 " } catch (...) {\n" 5198 " }\n" 5199 "}\n", 5200 format("int q() {\n" 5201 "F(x)\n" 5202 "if (1) {}\n" 5203 "F(x)\n" 5204 "while (1) {}\n" 5205 "F(x)\n" 5206 "G(x);\n" 5207 "F(x)\n" 5208 "try { Q(); } catch (...) {}\n" 5209 "}\n")); 5210 EXPECT_EQ("class A {\n" 5211 " A() : t(0) {}\n" 5212 " A(int i) noexcept() : {}\n" 5213 " A(X x)\n" // FIXME: function-level try blocks are broken. 5214 " try : t(0) {\n" 5215 " } catch (...) {\n" 5216 " }\n" 5217 "};", 5218 format("class A {\n" 5219 " A()\n : t(0) {}\n" 5220 " A(int i)\n noexcept() : {}\n" 5221 " A(X x)\n" 5222 " try : t(0) {} catch (...) {}\n" 5223 "};")); 5224 FormatStyle Style = getLLVMStyle(); 5225 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5226 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5227 Style.BraceWrapping.AfterFunction = true; 5228 EXPECT_EQ("void f()\n" 5229 "try\n" 5230 "{\n" 5231 "}", 5232 format("void f() try {\n" 5233 "}", 5234 Style)); 5235 EXPECT_EQ("class SomeClass {\n" 5236 "public:\n" 5237 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5238 "};", 5239 format("class SomeClass {\n" 5240 "public:\n" 5241 " SomeClass()\n" 5242 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5243 "};")); 5244 EXPECT_EQ("class SomeClass {\n" 5245 "public:\n" 5246 " SomeClass()\n" 5247 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5248 "};", 5249 format("class SomeClass {\n" 5250 "public:\n" 5251 " SomeClass()\n" 5252 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5253 "};", 5254 getLLVMStyleWithColumns(40))); 5255 5256 verifyFormat("MACRO(>)"); 5257 5258 // Some macros contain an implicit semicolon. 5259 Style = getLLVMStyle(); 5260 Style.StatementMacros.push_back("FOO"); 5261 verifyFormat("FOO(a) int b = 0;"); 5262 verifyFormat("FOO(a)\n" 5263 "int b = 0;", 5264 Style); 5265 verifyFormat("FOO(a);\n" 5266 "int b = 0;", 5267 Style); 5268 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5269 "int b = 0;", 5270 Style); 5271 verifyFormat("FOO()\n" 5272 "int b = 0;", 5273 Style); 5274 verifyFormat("FOO\n" 5275 "int b = 0;", 5276 Style); 5277 verifyFormat("void f() {\n" 5278 " FOO(a)\n" 5279 " return a;\n" 5280 "}", 5281 Style); 5282 verifyFormat("FOO(a)\n" 5283 "FOO(b)", 5284 Style); 5285 verifyFormat("int a = 0;\n" 5286 "FOO(b)\n" 5287 "int c = 0;", 5288 Style); 5289 verifyFormat("int a = 0;\n" 5290 "int x = FOO(a)\n" 5291 "int b = 0;", 5292 Style); 5293 verifyFormat("void foo(int a) { FOO(a) }\n" 5294 "uint32_t bar() {}", 5295 Style); 5296 } 5297 5298 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5299 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5300 5301 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5302 ZeroColumn); 5303 } 5304 5305 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5306 verifyFormat("#define A \\\n" 5307 " f({ \\\n" 5308 " g(); \\\n" 5309 " });", 5310 getLLVMStyleWithColumns(11)); 5311 } 5312 5313 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5314 FormatStyle Style = getLLVMStyleWithColumns(40); 5315 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5316 verifyFormat("#ifdef _WIN32\n" 5317 "#define A 0\n" 5318 "#ifdef VAR2\n" 5319 "#define B 1\n" 5320 "#include <someheader.h>\n" 5321 "#define MACRO \\\n" 5322 " some_very_long_func_aaaaaaaaaa();\n" 5323 "#endif\n" 5324 "#else\n" 5325 "#define A 1\n" 5326 "#endif", 5327 Style); 5328 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5329 verifyFormat("#ifdef _WIN32\n" 5330 "# define A 0\n" 5331 "# ifdef VAR2\n" 5332 "# define B 1\n" 5333 "# include <someheader.h>\n" 5334 "# define MACRO \\\n" 5335 " some_very_long_func_aaaaaaaaaa();\n" 5336 "# endif\n" 5337 "#else\n" 5338 "# define A 1\n" 5339 "#endif", 5340 Style); 5341 verifyFormat("#if A\n" 5342 "# define MACRO \\\n" 5343 " void a(int x) { \\\n" 5344 " b(); \\\n" 5345 " c(); \\\n" 5346 " d(); \\\n" 5347 " e(); \\\n" 5348 " f(); \\\n" 5349 " }\n" 5350 "#endif", 5351 Style); 5352 // Comments before include guard. 5353 verifyFormat("// file comment\n" 5354 "// file comment\n" 5355 "#ifndef HEADER_H\n" 5356 "#define HEADER_H\n" 5357 "code();\n" 5358 "#endif", 5359 Style); 5360 // Test with include guards. 5361 verifyFormat("#ifndef HEADER_H\n" 5362 "#define HEADER_H\n" 5363 "code();\n" 5364 "#endif", 5365 Style); 5366 // Include guards must have a #define with the same variable immediately 5367 // after #ifndef. 5368 verifyFormat("#ifndef NOT_GUARD\n" 5369 "# define FOO\n" 5370 "code();\n" 5371 "#endif", 5372 Style); 5373 5374 // Include guards must cover the entire file. 5375 verifyFormat("code();\n" 5376 "code();\n" 5377 "#ifndef NOT_GUARD\n" 5378 "# define NOT_GUARD\n" 5379 "code();\n" 5380 "#endif", 5381 Style); 5382 verifyFormat("#ifndef NOT_GUARD\n" 5383 "# define NOT_GUARD\n" 5384 "code();\n" 5385 "#endif\n" 5386 "code();", 5387 Style); 5388 // Test with trailing blank lines. 5389 verifyFormat("#ifndef HEADER_H\n" 5390 "#define HEADER_H\n" 5391 "code();\n" 5392 "#endif\n", 5393 Style); 5394 // Include guards don't have #else. 5395 verifyFormat("#ifndef NOT_GUARD\n" 5396 "# define NOT_GUARD\n" 5397 "code();\n" 5398 "#else\n" 5399 "#endif", 5400 Style); 5401 verifyFormat("#ifndef NOT_GUARD\n" 5402 "# define NOT_GUARD\n" 5403 "code();\n" 5404 "#elif FOO\n" 5405 "#endif", 5406 Style); 5407 // Non-identifier #define after potential include guard. 5408 verifyFormat("#ifndef FOO\n" 5409 "# define 1\n" 5410 "#endif\n", 5411 Style); 5412 // #if closes past last non-preprocessor line. 5413 verifyFormat("#ifndef FOO\n" 5414 "#define FOO\n" 5415 "#if 1\n" 5416 "int i;\n" 5417 "# define A 0\n" 5418 "#endif\n" 5419 "#endif\n", 5420 Style); 5421 // Don't crash if there is an #elif directive without a condition. 5422 verifyFormat("#if 1\n" 5423 "int x;\n" 5424 "#elif\n" 5425 "int y;\n" 5426 "#else\n" 5427 "int z;\n" 5428 "#endif", 5429 Style); 5430 // FIXME: This doesn't handle the case where there's code between the 5431 // #ifndef and #define but all other conditions hold. This is because when 5432 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5433 // previous code line yet, so we can't detect it. 5434 EXPECT_EQ("#ifndef NOT_GUARD\n" 5435 "code();\n" 5436 "#define NOT_GUARD\n" 5437 "code();\n" 5438 "#endif", 5439 format("#ifndef NOT_GUARD\n" 5440 "code();\n" 5441 "# define NOT_GUARD\n" 5442 "code();\n" 5443 "#endif", 5444 Style)); 5445 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5446 // be outside an include guard. Examples are #pragma once and 5447 // #pragma GCC diagnostic, or anything else that does not change the meaning 5448 // of the file if it's included multiple times. 5449 EXPECT_EQ("#ifdef WIN32\n" 5450 "# pragma once\n" 5451 "#endif\n" 5452 "#ifndef HEADER_H\n" 5453 "# define HEADER_H\n" 5454 "code();\n" 5455 "#endif", 5456 format("#ifdef WIN32\n" 5457 "# pragma once\n" 5458 "#endif\n" 5459 "#ifndef HEADER_H\n" 5460 "#define HEADER_H\n" 5461 "code();\n" 5462 "#endif", 5463 Style)); 5464 // FIXME: This does not detect when there is a single non-preprocessor line 5465 // in front of an include-guard-like structure where other conditions hold 5466 // because ScopedLineState hides the line. 5467 EXPECT_EQ("code();\n" 5468 "#ifndef HEADER_H\n" 5469 "#define HEADER_H\n" 5470 "code();\n" 5471 "#endif", 5472 format("code();\n" 5473 "#ifndef HEADER_H\n" 5474 "# define HEADER_H\n" 5475 "code();\n" 5476 "#endif", 5477 Style)); 5478 // Keep comments aligned with #, otherwise indent comments normally. These 5479 // tests cannot use verifyFormat because messUp manipulates leading 5480 // whitespace. 5481 { 5482 const char *Expected = "" 5483 "void f() {\n" 5484 "#if 1\n" 5485 "// Preprocessor aligned.\n" 5486 "# define A 0\n" 5487 " // Code. Separated by blank line.\n" 5488 "\n" 5489 "# define B 0\n" 5490 " // Code. Not aligned with #\n" 5491 "# define C 0\n" 5492 "#endif"; 5493 const char *ToFormat = "" 5494 "void f() {\n" 5495 "#if 1\n" 5496 "// Preprocessor aligned.\n" 5497 "# define A 0\n" 5498 "// Code. Separated by blank line.\n" 5499 "\n" 5500 "# define B 0\n" 5501 " // Code. Not aligned with #\n" 5502 "# define C 0\n" 5503 "#endif"; 5504 EXPECT_EQ(Expected, format(ToFormat, Style)); 5505 EXPECT_EQ(Expected, format(Expected, Style)); 5506 } 5507 // Keep block quotes aligned. 5508 { 5509 const char *Expected = "" 5510 "void f() {\n" 5511 "#if 1\n" 5512 "/* Preprocessor aligned. */\n" 5513 "# define A 0\n" 5514 " /* Code. Separated by blank line. */\n" 5515 "\n" 5516 "# define B 0\n" 5517 " /* Code. Not aligned with # */\n" 5518 "# define C 0\n" 5519 "#endif"; 5520 const char *ToFormat = "" 5521 "void f() {\n" 5522 "#if 1\n" 5523 "/* Preprocessor aligned. */\n" 5524 "# define A 0\n" 5525 "/* Code. Separated by blank line. */\n" 5526 "\n" 5527 "# define B 0\n" 5528 " /* Code. Not aligned with # */\n" 5529 "# define C 0\n" 5530 "#endif"; 5531 EXPECT_EQ(Expected, format(ToFormat, Style)); 5532 EXPECT_EQ(Expected, format(Expected, Style)); 5533 } 5534 // Keep comments aligned with un-indented directives. 5535 { 5536 const char *Expected = "" 5537 "void f() {\n" 5538 "// Preprocessor aligned.\n" 5539 "#define A 0\n" 5540 " // Code. Separated by blank line.\n" 5541 "\n" 5542 "#define B 0\n" 5543 " // Code. Not aligned with #\n" 5544 "#define C 0\n"; 5545 const char *ToFormat = "" 5546 "void f() {\n" 5547 "// Preprocessor aligned.\n" 5548 "#define A 0\n" 5549 "// Code. Separated by blank line.\n" 5550 "\n" 5551 "#define B 0\n" 5552 " // Code. Not aligned with #\n" 5553 "#define C 0\n"; 5554 EXPECT_EQ(Expected, format(ToFormat, Style)); 5555 EXPECT_EQ(Expected, format(Expected, Style)); 5556 } 5557 // Test AfterHash with tabs. 5558 { 5559 FormatStyle Tabbed = Style; 5560 Tabbed.UseTab = FormatStyle::UT_Always; 5561 Tabbed.IndentWidth = 8; 5562 Tabbed.TabWidth = 8; 5563 verifyFormat("#ifdef _WIN32\n" 5564 "#\tdefine A 0\n" 5565 "#\tifdef VAR2\n" 5566 "#\t\tdefine B 1\n" 5567 "#\t\tinclude <someheader.h>\n" 5568 "#\t\tdefine MACRO \\\n" 5569 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5570 "#\tendif\n" 5571 "#else\n" 5572 "#\tdefine A 1\n" 5573 "#endif", 5574 Tabbed); 5575 } 5576 5577 // Regression test: Multiline-macro inside include guards. 5578 verifyFormat("#ifndef HEADER_H\n" 5579 "#define HEADER_H\n" 5580 "#define A() \\\n" 5581 " int i; \\\n" 5582 " int j;\n" 5583 "#endif // HEADER_H", 5584 getLLVMStyleWithColumns(20)); 5585 5586 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5587 // Basic before hash indent tests 5588 verifyFormat("#ifdef _WIN32\n" 5589 " #define A 0\n" 5590 " #ifdef VAR2\n" 5591 " #define B 1\n" 5592 " #include <someheader.h>\n" 5593 " #define MACRO \\\n" 5594 " some_very_long_func_aaaaaaaaaa();\n" 5595 " #endif\n" 5596 "#else\n" 5597 " #define A 1\n" 5598 "#endif", 5599 Style); 5600 verifyFormat("#if A\n" 5601 " #define MACRO \\\n" 5602 " void a(int x) { \\\n" 5603 " b(); \\\n" 5604 " c(); \\\n" 5605 " d(); \\\n" 5606 " e(); \\\n" 5607 " f(); \\\n" 5608 " }\n" 5609 "#endif", 5610 Style); 5611 // Keep comments aligned with indented directives. These 5612 // tests cannot use verifyFormat because messUp manipulates leading 5613 // whitespace. 5614 { 5615 const char *Expected = "void f() {\n" 5616 "// Aligned to preprocessor.\n" 5617 "#if 1\n" 5618 " // Aligned to code.\n" 5619 " int a;\n" 5620 " #if 1\n" 5621 " // Aligned to preprocessor.\n" 5622 " #define A 0\n" 5623 " // Aligned to code.\n" 5624 " int b;\n" 5625 " #endif\n" 5626 "#endif\n" 5627 "}"; 5628 const char *ToFormat = "void f() {\n" 5629 "// Aligned to preprocessor.\n" 5630 "#if 1\n" 5631 "// Aligned to code.\n" 5632 "int a;\n" 5633 "#if 1\n" 5634 "// Aligned to preprocessor.\n" 5635 "#define A 0\n" 5636 "// Aligned to code.\n" 5637 "int b;\n" 5638 "#endif\n" 5639 "#endif\n" 5640 "}"; 5641 EXPECT_EQ(Expected, format(ToFormat, Style)); 5642 EXPECT_EQ(Expected, format(Expected, Style)); 5643 } 5644 { 5645 const char *Expected = "void f() {\n" 5646 "/* Aligned to preprocessor. */\n" 5647 "#if 1\n" 5648 " /* Aligned to code. */\n" 5649 " int a;\n" 5650 " #if 1\n" 5651 " /* Aligned to preprocessor. */\n" 5652 " #define A 0\n" 5653 " /* Aligned to code. */\n" 5654 " int b;\n" 5655 " #endif\n" 5656 "#endif\n" 5657 "}"; 5658 const char *ToFormat = "void f() {\n" 5659 "/* Aligned to preprocessor. */\n" 5660 "#if 1\n" 5661 "/* Aligned to code. */\n" 5662 "int a;\n" 5663 "#if 1\n" 5664 "/* Aligned to preprocessor. */\n" 5665 "#define A 0\n" 5666 "/* Aligned to code. */\n" 5667 "int b;\n" 5668 "#endif\n" 5669 "#endif\n" 5670 "}"; 5671 EXPECT_EQ(Expected, format(ToFormat, Style)); 5672 EXPECT_EQ(Expected, format(Expected, Style)); 5673 } 5674 5675 // Test single comment before preprocessor 5676 verifyFormat("// Comment\n" 5677 "\n" 5678 "#if 1\n" 5679 "#endif", 5680 Style); 5681 } 5682 5683 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5684 verifyFormat("{\n { a #c; }\n}"); 5685 } 5686 5687 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5688 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5689 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5690 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5691 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5692 } 5693 5694 TEST_F(FormatTest, EscapedNewlines) { 5695 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5696 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5697 format("#define A \\\nint i;\\\n int j;", Narrow)); 5698 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5699 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5700 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5701 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5702 5703 FormatStyle AlignLeft = getLLVMStyle(); 5704 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5705 EXPECT_EQ("#define MACRO(x) \\\n" 5706 "private: \\\n" 5707 " int x(int a);\n", 5708 format("#define MACRO(x) \\\n" 5709 "private: \\\n" 5710 " int x(int a);\n", 5711 AlignLeft)); 5712 5713 // CRLF line endings 5714 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5715 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5716 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5717 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5718 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5719 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5720 EXPECT_EQ("#define MACRO(x) \\\r\n" 5721 "private: \\\r\n" 5722 " int x(int a);\r\n", 5723 format("#define MACRO(x) \\\r\n" 5724 "private: \\\r\n" 5725 " int x(int a);\r\n", 5726 AlignLeft)); 5727 5728 FormatStyle DontAlign = getLLVMStyle(); 5729 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5730 DontAlign.MaxEmptyLinesToKeep = 3; 5731 // FIXME: can't use verifyFormat here because the newline before 5732 // "public:" is not inserted the first time it's reformatted 5733 EXPECT_EQ("#define A \\\n" 5734 " class Foo { \\\n" 5735 " void bar(); \\\n" 5736 "\\\n" 5737 "\\\n" 5738 "\\\n" 5739 " public: \\\n" 5740 " void baz(); \\\n" 5741 " };", 5742 format("#define A \\\n" 5743 " class Foo { \\\n" 5744 " void bar(); \\\n" 5745 "\\\n" 5746 "\\\n" 5747 "\\\n" 5748 " public: \\\n" 5749 " void baz(); \\\n" 5750 " };", 5751 DontAlign)); 5752 } 5753 5754 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5755 verifyFormat("#define A \\\n" 5756 " int v( \\\n" 5757 " a); \\\n" 5758 " int i;", 5759 getLLVMStyleWithColumns(11)); 5760 } 5761 5762 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5763 EXPECT_EQ( 5764 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5765 " \\\n" 5766 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5767 "\n" 5768 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5769 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5770 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5771 "\\\n" 5772 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5773 " \n" 5774 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5775 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5776 } 5777 5778 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5779 EXPECT_EQ("int\n" 5780 "#define A\n" 5781 " a;", 5782 format("int\n#define A\na;")); 5783 verifyFormat("functionCallTo(\n" 5784 " someOtherFunction(\n" 5785 " withSomeParameters, whichInSequence,\n" 5786 " areLongerThanALine(andAnotherCall,\n" 5787 "#define A B\n" 5788 " withMoreParamters,\n" 5789 " whichStronglyInfluenceTheLayout),\n" 5790 " andMoreParameters),\n" 5791 " trailing);", 5792 getLLVMStyleWithColumns(69)); 5793 verifyFormat("Foo::Foo()\n" 5794 "#ifdef BAR\n" 5795 " : baz(0)\n" 5796 "#endif\n" 5797 "{\n" 5798 "}"); 5799 verifyFormat("void f() {\n" 5800 " if (true)\n" 5801 "#ifdef A\n" 5802 " f(42);\n" 5803 " x();\n" 5804 "#else\n" 5805 " g();\n" 5806 " x();\n" 5807 "#endif\n" 5808 "}"); 5809 verifyFormat("void f(param1, param2,\n" 5810 " param3,\n" 5811 "#ifdef A\n" 5812 " param4(param5,\n" 5813 "#ifdef A1\n" 5814 " param6,\n" 5815 "#ifdef A2\n" 5816 " param7),\n" 5817 "#else\n" 5818 " param8),\n" 5819 " param9,\n" 5820 "#endif\n" 5821 " param10,\n" 5822 "#endif\n" 5823 " param11)\n" 5824 "#else\n" 5825 " param12)\n" 5826 "#endif\n" 5827 "{\n" 5828 " x();\n" 5829 "}", 5830 getLLVMStyleWithColumns(28)); 5831 verifyFormat("#if 1\n" 5832 "int i;"); 5833 verifyFormat("#if 1\n" 5834 "#endif\n" 5835 "#if 1\n" 5836 "#else\n" 5837 "#endif\n"); 5838 verifyFormat("DEBUG({\n" 5839 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5840 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5841 "});\n" 5842 "#if a\n" 5843 "#else\n" 5844 "#endif"); 5845 5846 verifyIncompleteFormat("void f(\n" 5847 "#if A\n" 5848 ");\n" 5849 "#else\n" 5850 "#endif"); 5851 } 5852 5853 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5854 verifyFormat("#endif\n" 5855 "#if B"); 5856 } 5857 5858 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5859 FormatStyle SingleLine = getLLVMStyle(); 5860 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5861 verifyFormat("#if 0\n" 5862 "#elif 1\n" 5863 "#endif\n" 5864 "void foo() {\n" 5865 " if (test) foo2();\n" 5866 "}", 5867 SingleLine); 5868 } 5869 5870 TEST_F(FormatTest, LayoutBlockInsideParens) { 5871 verifyFormat("functionCall({ int i; });"); 5872 verifyFormat("functionCall({\n" 5873 " int i;\n" 5874 " int j;\n" 5875 "});"); 5876 verifyFormat("functionCall(\n" 5877 " {\n" 5878 " int i;\n" 5879 " int j;\n" 5880 " },\n" 5881 " aaaa, bbbb, cccc);"); 5882 verifyFormat("functionA(functionB({\n" 5883 " int i;\n" 5884 " int j;\n" 5885 " }),\n" 5886 " aaaa, bbbb, cccc);"); 5887 verifyFormat("functionCall(\n" 5888 " {\n" 5889 " int i;\n" 5890 " int j;\n" 5891 " },\n" 5892 " aaaa, bbbb, // comment\n" 5893 " cccc);"); 5894 verifyFormat("functionA(functionB({\n" 5895 " int i;\n" 5896 " int j;\n" 5897 " }),\n" 5898 " aaaa, bbbb, // comment\n" 5899 " cccc);"); 5900 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5901 verifyFormat("functionCall(aaaa, bbbb, {\n" 5902 " int i;\n" 5903 " int j;\n" 5904 "});"); 5905 verifyFormat( 5906 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5907 " {\n" 5908 " int i; // break\n" 5909 " },\n" 5910 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5911 " ccccccccccccccccc));"); 5912 verifyFormat("DEBUG({\n" 5913 " if (a)\n" 5914 " f();\n" 5915 "});"); 5916 } 5917 5918 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5919 EXPECT_EQ("SOME_MACRO { int i; }\n" 5920 "int i;", 5921 format(" SOME_MACRO {int i;} int i;")); 5922 } 5923 5924 TEST_F(FormatTest, LayoutNestedBlocks) { 5925 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5926 " struct s {\n" 5927 " int i;\n" 5928 " };\n" 5929 " s kBitsToOs[] = {{10}};\n" 5930 " for (int i = 0; i < 10; ++i)\n" 5931 " return;\n" 5932 "}"); 5933 verifyFormat("call(parameter, {\n" 5934 " something();\n" 5935 " // Comment using all columns.\n" 5936 " somethingelse();\n" 5937 "});", 5938 getLLVMStyleWithColumns(40)); 5939 verifyFormat("DEBUG( //\n" 5940 " { f(); }, a);"); 5941 verifyFormat("DEBUG( //\n" 5942 " {\n" 5943 " f(); //\n" 5944 " },\n" 5945 " a);"); 5946 5947 EXPECT_EQ("call(parameter, {\n" 5948 " something();\n" 5949 " // Comment too\n" 5950 " // looooooooooong.\n" 5951 " somethingElse();\n" 5952 "});", 5953 format("call(parameter, {\n" 5954 " something();\n" 5955 " // Comment too looooooooooong.\n" 5956 " somethingElse();\n" 5957 "});", 5958 getLLVMStyleWithColumns(29))); 5959 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5960 EXPECT_EQ("DEBUG({ // comment\n" 5961 " int i;\n" 5962 "});", 5963 format("DEBUG({ // comment\n" 5964 "int i;\n" 5965 "});")); 5966 EXPECT_EQ("DEBUG({\n" 5967 " int i;\n" 5968 "\n" 5969 " // comment\n" 5970 " int j;\n" 5971 "});", 5972 format("DEBUG({\n" 5973 " int i;\n" 5974 "\n" 5975 " // comment\n" 5976 " int j;\n" 5977 "});")); 5978 5979 verifyFormat("DEBUG({\n" 5980 " if (a)\n" 5981 " return;\n" 5982 "});"); 5983 verifyGoogleFormat("DEBUG({\n" 5984 " if (a) return;\n" 5985 "});"); 5986 FormatStyle Style = getGoogleStyle(); 5987 Style.ColumnLimit = 45; 5988 verifyFormat("Debug(\n" 5989 " aaaaa,\n" 5990 " {\n" 5991 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5992 " },\n" 5993 " a);", 5994 Style); 5995 5996 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5997 5998 verifyNoCrash("^{v^{a}}"); 5999 } 6000 6001 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6002 EXPECT_EQ("#define MACRO() \\\n" 6003 " Debug(aaa, /* force line break */ \\\n" 6004 " { \\\n" 6005 " int i; \\\n" 6006 " int j; \\\n" 6007 " })", 6008 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6009 " { int i; int j; })", 6010 getGoogleStyle())); 6011 6012 EXPECT_EQ("#define A \\\n" 6013 " [] { \\\n" 6014 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6015 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6016 " }", 6017 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6018 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6019 getGoogleStyle())); 6020 } 6021 6022 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6023 EXPECT_EQ("{}", format("{}")); 6024 verifyFormat("enum E {};"); 6025 verifyFormat("enum E {}"); 6026 FormatStyle Style = getLLVMStyle(); 6027 Style.SpaceInEmptyBlock = true; 6028 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6029 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6030 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6031 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6032 Style.BraceWrapping.BeforeElse = false; 6033 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6034 verifyFormat("if (a)\n" 6035 "{\n" 6036 "} else if (b)\n" 6037 "{\n" 6038 "} else\n" 6039 "{ }", 6040 Style); 6041 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6042 verifyFormat("if (a) {\n" 6043 "} else if (b) {\n" 6044 "} else {\n" 6045 "}", 6046 Style); 6047 Style.BraceWrapping.BeforeElse = true; 6048 verifyFormat("if (a) { }\n" 6049 "else if (b) { }\n" 6050 "else { }", 6051 Style); 6052 } 6053 6054 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6055 FormatStyle Style = getLLVMStyle(); 6056 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6057 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6058 verifyFormat("FOO_BEGIN\n" 6059 " FOO_ENTRY\n" 6060 "FOO_END", 6061 Style); 6062 verifyFormat("FOO_BEGIN\n" 6063 " NESTED_FOO_BEGIN\n" 6064 " NESTED_FOO_ENTRY\n" 6065 " NESTED_FOO_END\n" 6066 "FOO_END", 6067 Style); 6068 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6069 " int x;\n" 6070 " x = 1;\n" 6071 "FOO_END(Baz)", 6072 Style); 6073 } 6074 6075 //===----------------------------------------------------------------------===// 6076 // Line break tests. 6077 //===----------------------------------------------------------------------===// 6078 6079 TEST_F(FormatTest, PreventConfusingIndents) { 6080 verifyFormat( 6081 "void f() {\n" 6082 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6083 " parameter, parameter, parameter)),\n" 6084 " SecondLongCall(parameter));\n" 6085 "}"); 6086 verifyFormat( 6087 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6088 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6089 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6090 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6091 verifyFormat( 6092 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6093 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6094 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6095 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6096 verifyFormat( 6097 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6098 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6099 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6100 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6101 verifyFormat("int a = bbbb && ccc &&\n" 6102 " fffff(\n" 6103 "#define A Just forcing a new line\n" 6104 " ddd);"); 6105 } 6106 6107 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6108 verifyFormat( 6109 "bool aaaaaaa =\n" 6110 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6111 " bbbbbbbb();"); 6112 verifyFormat( 6113 "bool aaaaaaa =\n" 6114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6115 " bbbbbbbb();"); 6116 6117 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6119 " ccccccccc == ddddddddddd;"); 6120 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6121 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6122 " ccccccccc == ddddddddddd;"); 6123 verifyFormat( 6124 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6125 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6126 " ccccccccc == ddddddddddd;"); 6127 6128 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6129 " aaaaaa) &&\n" 6130 " bbbbbb && cccccc;"); 6131 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6132 " aaaaaa) >>\n" 6133 " bbbbbb;"); 6134 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6135 " SourceMgr.getSpellingColumnNumber(\n" 6136 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6137 " 1);"); 6138 6139 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6140 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6141 " cccccc) {\n}"); 6142 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6143 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6144 " cccccc) {\n}"); 6145 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6146 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6147 " cccccc) {\n}"); 6148 verifyFormat("b = a &&\n" 6149 " // Comment\n" 6150 " b.c && d;"); 6151 6152 // If the LHS of a comparison is not a binary expression itself, the 6153 // additional linebreak confuses many people. 6154 verifyFormat( 6155 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6156 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6157 "}"); 6158 verifyFormat( 6159 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6161 "}"); 6162 verifyFormat( 6163 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6164 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6165 "}"); 6166 verifyFormat( 6167 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6168 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6169 "}"); 6170 // Even explicit parentheses stress the precedence enough to make the 6171 // additional break unnecessary. 6172 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6174 "}"); 6175 // This cases is borderline, but with the indentation it is still readable. 6176 verifyFormat( 6177 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6178 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6179 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6180 "}", 6181 getLLVMStyleWithColumns(75)); 6182 6183 // If the LHS is a binary expression, we should still use the additional break 6184 // as otherwise the formatting hides the operator precedence. 6185 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6186 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6187 " 5) {\n" 6188 "}"); 6189 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6190 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6191 " 5) {\n" 6192 "}"); 6193 6194 FormatStyle OnePerLine = getLLVMStyle(); 6195 OnePerLine.BinPackParameters = false; 6196 verifyFormat( 6197 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6200 OnePerLine); 6201 6202 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6203 " .aaa(aaaaaaaaaaaaa) *\n" 6204 " aaaaaaa +\n" 6205 " aaaaaaa;", 6206 getLLVMStyleWithColumns(40)); 6207 } 6208 6209 TEST_F(FormatTest, ExpressionIndentation) { 6210 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6211 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6212 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6213 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6214 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6215 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6216 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6217 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6218 " ccccccccccccccccccccccccccccccccccccccccc;"); 6219 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6220 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6222 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6223 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6224 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6225 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6226 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6227 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6229 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6230 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6231 verifyFormat("if () {\n" 6232 "} else if (aaaaa && bbbbb > // break\n" 6233 " ccccc) {\n" 6234 "}"); 6235 verifyFormat("if () {\n" 6236 "} else if constexpr (aaaaa && bbbbb > // break\n" 6237 " ccccc) {\n" 6238 "}"); 6239 verifyFormat("if () {\n" 6240 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6241 " ccccc) {\n" 6242 "}"); 6243 verifyFormat("if () {\n" 6244 "} else if (aaaaa &&\n" 6245 " bbbbb > // break\n" 6246 " ccccc &&\n" 6247 " ddddd) {\n" 6248 "}"); 6249 6250 // Presence of a trailing comment used to change indentation of b. 6251 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6252 " b;\n" 6253 "return aaaaaaaaaaaaaaaaaaa +\n" 6254 " b; //", 6255 getLLVMStyleWithColumns(30)); 6256 } 6257 6258 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6259 // Not sure what the best system is here. Like this, the LHS can be found 6260 // immediately above an operator (everything with the same or a higher 6261 // indent). The RHS is aligned right of the operator and so compasses 6262 // everything until something with the same indent as the operator is found. 6263 // FIXME: Is this a good system? 6264 FormatStyle Style = getLLVMStyle(); 6265 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6266 verifyFormat( 6267 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6268 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6269 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6270 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6271 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6272 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6273 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6274 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6275 " > ccccccccccccccccccccccccccccccccccccccccc;", 6276 Style); 6277 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6278 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6279 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6280 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6281 Style); 6282 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6283 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6284 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6285 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6286 Style); 6287 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6288 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6289 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6290 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6291 Style); 6292 verifyFormat("if () {\n" 6293 "} else if (aaaaa\n" 6294 " && bbbbb // break\n" 6295 " > ccccc) {\n" 6296 "}", 6297 Style); 6298 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6299 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6300 Style); 6301 verifyFormat("return (a)\n" 6302 " // comment\n" 6303 " + b;", 6304 Style); 6305 verifyFormat( 6306 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6307 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6308 " + cc;", 6309 Style); 6310 6311 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6312 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6313 Style); 6314 6315 // Forced by comments. 6316 verifyFormat( 6317 "unsigned ContentSize =\n" 6318 " sizeof(int16_t) // DWARF ARange version number\n" 6319 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6320 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6321 " + sizeof(int8_t); // Segment Size (in bytes)"); 6322 6323 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6324 " == boost::fusion::at_c<1>(iiii).second;", 6325 Style); 6326 6327 Style.ColumnLimit = 60; 6328 verifyFormat("zzzzzzzzzz\n" 6329 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6330 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6331 Style); 6332 6333 Style.ColumnLimit = 80; 6334 Style.IndentWidth = 4; 6335 Style.TabWidth = 4; 6336 Style.UseTab = FormatStyle::UT_Always; 6337 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6338 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6339 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6340 "\t&& (someOtherLongishConditionPart1\n" 6341 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6342 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6343 "(someOtherLongishConditionPart1 || " 6344 "someOtherEvenLongerNestedConditionPart2);", 6345 Style)); 6346 } 6347 6348 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6349 FormatStyle Style = getLLVMStyle(); 6350 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6351 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6352 6353 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6354 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6355 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6356 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6357 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6358 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6359 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6360 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6361 " > ccccccccccccccccccccccccccccccccccccccccc;", 6362 Style); 6363 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6364 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6365 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6366 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6367 Style); 6368 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6369 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6370 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6371 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6372 Style); 6373 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6374 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6375 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6376 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6377 Style); 6378 verifyFormat("if () {\n" 6379 "} else if (aaaaa\n" 6380 " && bbbbb // break\n" 6381 " > ccccc) {\n" 6382 "}", 6383 Style); 6384 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6385 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6386 Style); 6387 verifyFormat("return (a)\n" 6388 " // comment\n" 6389 " + b;", 6390 Style); 6391 verifyFormat( 6392 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6393 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6394 " + cc;", 6395 Style); 6396 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6397 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6398 " : 3333333333333333;", 6399 Style); 6400 verifyFormat( 6401 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6402 " : ccccccccccccccc ? dddddddddddddddddd\n" 6403 " : eeeeeeeeeeeeeeeeee)\n" 6404 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6405 " : 3333333333333333;", 6406 Style); 6407 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6408 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6409 Style); 6410 6411 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6412 " == boost::fusion::at_c<1>(iiii).second;", 6413 Style); 6414 6415 Style.ColumnLimit = 60; 6416 verifyFormat("zzzzzzzzzzzzz\n" 6417 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6418 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6419 Style); 6420 6421 // Forced by comments. 6422 Style.ColumnLimit = 80; 6423 verifyFormat( 6424 "unsigned ContentSize\n" 6425 " = sizeof(int16_t) // DWARF ARange version number\n" 6426 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6427 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6428 " + sizeof(int8_t); // Segment Size (in bytes)", 6429 Style); 6430 6431 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6432 verifyFormat( 6433 "unsigned ContentSize =\n" 6434 " sizeof(int16_t) // DWARF ARange version number\n" 6435 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6436 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6437 " + sizeof(int8_t); // Segment Size (in bytes)", 6438 Style); 6439 6440 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6441 verifyFormat( 6442 "unsigned ContentSize =\n" 6443 " sizeof(int16_t) // DWARF ARange version number\n" 6444 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6445 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6446 " + sizeof(int8_t); // Segment Size (in bytes)", 6447 Style); 6448 } 6449 6450 TEST_F(FormatTest, EnforcedOperatorWraps) { 6451 // Here we'd like to wrap after the || operators, but a comment is forcing an 6452 // earlier wrap. 6453 verifyFormat("bool x = aaaaa //\n" 6454 " || bbbbb\n" 6455 " //\n" 6456 " || cccc;"); 6457 } 6458 6459 TEST_F(FormatTest, NoOperandAlignment) { 6460 FormatStyle Style = getLLVMStyle(); 6461 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6462 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6464 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6465 Style); 6466 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6467 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6468 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6469 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6470 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6471 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6472 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6473 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6474 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6475 " > ccccccccccccccccccccccccccccccccccccccccc;", 6476 Style); 6477 6478 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6479 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6480 " + cc;", 6481 Style); 6482 verifyFormat("int a = aa\n" 6483 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6484 " * cccccccccccccccccccccccccccccccccccc;\n", 6485 Style); 6486 6487 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6488 verifyFormat("return (a > b\n" 6489 " // comment1\n" 6490 " // comment2\n" 6491 " || c);", 6492 Style); 6493 } 6494 6495 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6496 FormatStyle Style = getLLVMStyle(); 6497 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6498 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6499 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6500 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6501 Style); 6502 } 6503 6504 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6505 FormatStyle Style = getLLVMStyleWithColumns(40); 6506 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6507 Style.BinPackArguments = false; 6508 verifyFormat("void test() {\n" 6509 " someFunction(\n" 6510 " this + argument + is + quite\n" 6511 " + long + so + it + gets + wrapped\n" 6512 " + but + remains + bin - packed);\n" 6513 "}", 6514 Style); 6515 verifyFormat("void test() {\n" 6516 " someFunction(arg1,\n" 6517 " this + argument + is\n" 6518 " + quite + long + so\n" 6519 " + it + gets + wrapped\n" 6520 " + but + remains + bin\n" 6521 " - packed,\n" 6522 " arg3);\n" 6523 "}", 6524 Style); 6525 verifyFormat("void test() {\n" 6526 " someFunction(\n" 6527 " arg1,\n" 6528 " this + argument + has\n" 6529 " + anotherFunc(nested,\n" 6530 " calls + whose\n" 6531 " + arguments\n" 6532 " + are + also\n" 6533 " + wrapped,\n" 6534 " in + addition)\n" 6535 " + to + being + bin - packed,\n" 6536 " arg3);\n" 6537 "}", 6538 Style); 6539 6540 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6541 verifyFormat("void test() {\n" 6542 " someFunction(\n" 6543 " arg1,\n" 6544 " this + argument + has +\n" 6545 " anotherFunc(nested,\n" 6546 " calls + whose +\n" 6547 " arguments +\n" 6548 " are + also +\n" 6549 " wrapped,\n" 6550 " in + addition) +\n" 6551 " to + being + bin - packed,\n" 6552 " arg3);\n" 6553 "}", 6554 Style); 6555 } 6556 6557 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6558 auto Style = getLLVMStyleWithColumns(45); 6559 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6560 verifyFormat("bool b =\n" 6561 " is_default_constructible_v<hash<T>> and\n" 6562 " is_copy_constructible_v<hash<T>> and\n" 6563 " is_move_constructible_v<hash<T>> and\n" 6564 " is_copy_assignable_v<hash<T>> and\n" 6565 " is_move_assignable_v<hash<T>> and\n" 6566 " is_destructible_v<hash<T>> and\n" 6567 " is_swappable_v<hash<T>> and\n" 6568 " is_callable_v<hash<T>(T)>;", 6569 Style); 6570 6571 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6572 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6573 " and is_copy_constructible_v<hash<T>>\n" 6574 " and is_move_constructible_v<hash<T>>\n" 6575 " and is_copy_assignable_v<hash<T>>\n" 6576 " and is_move_assignable_v<hash<T>>\n" 6577 " and is_destructible_v<hash<T>>\n" 6578 " and is_swappable_v<hash<T>>\n" 6579 " and is_callable_v<hash<T>(T)>;", 6580 Style); 6581 6582 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6583 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6584 " and is_copy_constructible_v<hash<T>>\n" 6585 " and is_move_constructible_v<hash<T>>\n" 6586 " and is_copy_assignable_v<hash<T>>\n" 6587 " and is_move_assignable_v<hash<T>>\n" 6588 " and is_destructible_v<hash<T>>\n" 6589 " and is_swappable_v<hash<T>>\n" 6590 " and is_callable_v<hash<T>(T)>;", 6591 Style); 6592 } 6593 6594 TEST_F(FormatTest, ConstructorInitializers) { 6595 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6596 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6597 getLLVMStyleWithColumns(45)); 6598 verifyFormat("Constructor()\n" 6599 " : Inttializer(FitsOnTheLine) {}", 6600 getLLVMStyleWithColumns(44)); 6601 verifyFormat("Constructor()\n" 6602 " : Inttializer(FitsOnTheLine) {}", 6603 getLLVMStyleWithColumns(43)); 6604 6605 verifyFormat("template <typename T>\n" 6606 "Constructor() : Initializer(FitsOnTheLine) {}", 6607 getLLVMStyleWithColumns(45)); 6608 6609 verifyFormat( 6610 "SomeClass::Constructor()\n" 6611 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6612 6613 verifyFormat( 6614 "SomeClass::Constructor()\n" 6615 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6616 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6617 verifyFormat( 6618 "SomeClass::Constructor()\n" 6619 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6620 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6621 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6622 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6623 " : aaaaaaaaaa(aaaaaa) {}"); 6624 6625 verifyFormat("Constructor()\n" 6626 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6627 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6628 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6629 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6630 6631 verifyFormat("Constructor()\n" 6632 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6633 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6634 6635 verifyFormat("Constructor(int Parameter = 0)\n" 6636 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6637 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6638 verifyFormat("Constructor()\n" 6639 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6640 "}", 6641 getLLVMStyleWithColumns(60)); 6642 verifyFormat("Constructor()\n" 6643 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6644 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6645 6646 // Here a line could be saved by splitting the second initializer onto two 6647 // lines, but that is not desirable. 6648 verifyFormat("Constructor()\n" 6649 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6650 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6651 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6652 6653 FormatStyle OnePerLine = getLLVMStyle(); 6654 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6655 verifyFormat("MyClass::MyClass()\n" 6656 " : a(a),\n" 6657 " b(b),\n" 6658 " c(c) {}", 6659 OnePerLine); 6660 verifyFormat("MyClass::MyClass()\n" 6661 " : a(a), // comment\n" 6662 " b(b),\n" 6663 " c(c) {}", 6664 OnePerLine); 6665 verifyFormat("MyClass::MyClass(int a)\n" 6666 " : b(a), // comment\n" 6667 " c(a + 1) { // lined up\n" 6668 "}", 6669 OnePerLine); 6670 verifyFormat("Constructor()\n" 6671 " : a(b, b, b) {}", 6672 OnePerLine); 6673 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6674 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6675 verifyFormat("SomeClass::Constructor()\n" 6676 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6677 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6678 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6679 OnePerLine); 6680 verifyFormat("SomeClass::Constructor()\n" 6681 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6682 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6683 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6684 OnePerLine); 6685 verifyFormat("MyClass::MyClass(int var)\n" 6686 " : some_var_(var), // 4 space indent\n" 6687 " some_other_var_(var + 1) { // lined up\n" 6688 "}", 6689 OnePerLine); 6690 verifyFormat("Constructor()\n" 6691 " : aaaaa(aaaaaa),\n" 6692 " aaaaa(aaaaaa),\n" 6693 " aaaaa(aaaaaa),\n" 6694 " aaaaa(aaaaaa),\n" 6695 " aaaaa(aaaaaa) {}", 6696 OnePerLine); 6697 verifyFormat("Constructor()\n" 6698 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6699 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6700 OnePerLine); 6701 OnePerLine.BinPackParameters = false; 6702 verifyFormat( 6703 "Constructor()\n" 6704 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6705 " aaaaaaaaaaa().aaa(),\n" 6706 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6707 OnePerLine); 6708 OnePerLine.ColumnLimit = 60; 6709 verifyFormat("Constructor()\n" 6710 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6711 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6712 OnePerLine); 6713 6714 EXPECT_EQ("Constructor()\n" 6715 " : // Comment forcing unwanted break.\n" 6716 " aaaa(aaaa) {}", 6717 format("Constructor() :\n" 6718 " // Comment forcing unwanted break.\n" 6719 " aaaa(aaaa) {}")); 6720 } 6721 6722 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6723 FormatStyle Style = getLLVMStyleWithColumns(60); 6724 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6725 Style.BinPackParameters = false; 6726 6727 for (int i = 0; i < 4; ++i) { 6728 // Test all combinations of parameters that should not have an effect. 6729 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6730 Style.AllowAllArgumentsOnNextLine = i & 2; 6731 6732 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6733 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6734 verifyFormat("Constructor()\n" 6735 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6736 Style); 6737 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6738 6739 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6740 verifyFormat("Constructor()\n" 6741 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6742 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6743 Style); 6744 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6745 6746 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6747 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6748 verifyFormat("Constructor()\n" 6749 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6750 Style); 6751 6752 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6753 verifyFormat("Constructor()\n" 6754 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6755 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6756 Style); 6757 6758 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6759 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6760 verifyFormat("Constructor() :\n" 6761 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6762 Style); 6763 6764 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6765 verifyFormat("Constructor() :\n" 6766 " aaaaaaaaaaaaaaaaaa(a),\n" 6767 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6768 Style); 6769 } 6770 6771 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6772 // AllowAllConstructorInitializersOnNextLine in all 6773 // BreakConstructorInitializers modes 6774 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6775 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6776 verifyFormat("SomeClassWithALongName::Constructor(\n" 6777 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6778 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6779 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6780 Style); 6781 6782 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6783 verifyFormat("SomeClassWithALongName::Constructor(\n" 6784 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6785 " int bbbbbbbbbbbbb,\n" 6786 " int cccccccccccccccc)\n" 6787 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6788 Style); 6789 6790 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6791 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6792 verifyFormat("SomeClassWithALongName::Constructor(\n" 6793 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6794 " int bbbbbbbbbbbbb)\n" 6795 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6796 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6797 Style); 6798 6799 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6800 6801 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6802 verifyFormat("SomeClassWithALongName::Constructor(\n" 6803 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6804 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6805 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6806 Style); 6807 6808 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6809 verifyFormat("SomeClassWithALongName::Constructor(\n" 6810 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6811 " int bbbbbbbbbbbbb,\n" 6812 " int cccccccccccccccc)\n" 6813 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6814 Style); 6815 6816 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6817 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6818 verifyFormat("SomeClassWithALongName::Constructor(\n" 6819 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6820 " int bbbbbbbbbbbbb)\n" 6821 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6822 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6823 Style); 6824 6825 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6826 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6827 verifyFormat("SomeClassWithALongName::Constructor(\n" 6828 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6829 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6830 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6831 Style); 6832 6833 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6834 verifyFormat("SomeClassWithALongName::Constructor(\n" 6835 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6836 " int bbbbbbbbbbbbb,\n" 6837 " int cccccccccccccccc) :\n" 6838 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6839 Style); 6840 6841 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6842 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6843 verifyFormat("SomeClassWithALongName::Constructor(\n" 6844 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6845 " int bbbbbbbbbbbbb) :\n" 6846 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6847 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6848 Style); 6849 } 6850 6851 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6852 FormatStyle Style = getLLVMStyleWithColumns(60); 6853 Style.BinPackArguments = false; 6854 for (int i = 0; i < 4; ++i) { 6855 // Test all combinations of parameters that should not have an effect. 6856 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6857 Style.PackConstructorInitializers = 6858 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6859 6860 Style.AllowAllArgumentsOnNextLine = true; 6861 verifyFormat("void foo() {\n" 6862 " FunctionCallWithReallyLongName(\n" 6863 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6864 "}", 6865 Style); 6866 Style.AllowAllArgumentsOnNextLine = false; 6867 verifyFormat("void foo() {\n" 6868 " FunctionCallWithReallyLongName(\n" 6869 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6870 " bbbbbbbbbbbb);\n" 6871 "}", 6872 Style); 6873 6874 Style.AllowAllArgumentsOnNextLine = true; 6875 verifyFormat("void foo() {\n" 6876 " auto VariableWithReallyLongName = {\n" 6877 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6878 "}", 6879 Style); 6880 Style.AllowAllArgumentsOnNextLine = false; 6881 verifyFormat("void foo() {\n" 6882 " auto VariableWithReallyLongName = {\n" 6883 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6884 " bbbbbbbbbbbb};\n" 6885 "}", 6886 Style); 6887 } 6888 6889 // This parameter should not affect declarations. 6890 Style.BinPackParameters = false; 6891 Style.AllowAllArgumentsOnNextLine = false; 6892 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6893 verifyFormat("void FunctionCallWithReallyLongName(\n" 6894 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6895 Style); 6896 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6897 verifyFormat("void FunctionCallWithReallyLongName(\n" 6898 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6899 " int bbbbbbbbbbbb);", 6900 Style); 6901 } 6902 6903 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6904 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6905 // and BAS_Align. 6906 FormatStyle Style = getLLVMStyleWithColumns(35); 6907 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6908 "void functionDecl(int A, int B, int C);"; 6909 Style.AllowAllArgumentsOnNextLine = false; 6910 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6911 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6912 " paramC);\n" 6913 "void functionDecl(int A, int B,\n" 6914 " int C);"), 6915 format(Input, Style)); 6916 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6917 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6918 " paramC);\n" 6919 "void functionDecl(int A, int B,\n" 6920 " int C);"), 6921 format(Input, Style)); 6922 // However, BAS_AlwaysBreak should take precedence over 6923 // AllowAllArgumentsOnNextLine. 6924 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6925 EXPECT_EQ(StringRef("functionCall(\n" 6926 " paramA, paramB, paramC);\n" 6927 "void functionDecl(\n" 6928 " int A, int B, int C);"), 6929 format(Input, Style)); 6930 6931 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6932 // first argument. 6933 Style.AllowAllArgumentsOnNextLine = true; 6934 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6935 EXPECT_EQ(StringRef("functionCall(\n" 6936 " paramA, paramB, paramC);\n" 6937 "void functionDecl(\n" 6938 " int A, int B, int C);"), 6939 format(Input, Style)); 6940 // It wouldn't fit on one line with aligned parameters so this setting 6941 // doesn't change anything for BAS_Align. 6942 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6943 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6944 " paramC);\n" 6945 "void functionDecl(int A, int B,\n" 6946 " int C);"), 6947 format(Input, Style)); 6948 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6949 EXPECT_EQ(StringRef("functionCall(\n" 6950 " paramA, paramB, paramC);\n" 6951 "void functionDecl(\n" 6952 " int A, int B, int C);"), 6953 format(Input, Style)); 6954 } 6955 6956 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6957 FormatStyle Style = getLLVMStyle(); 6958 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6959 6960 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6961 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6962 getStyleWithColumns(Style, 45)); 6963 verifyFormat("Constructor() :\n" 6964 " Initializer(FitsOnTheLine) {}", 6965 getStyleWithColumns(Style, 44)); 6966 verifyFormat("Constructor() :\n" 6967 " Initializer(FitsOnTheLine) {}", 6968 getStyleWithColumns(Style, 43)); 6969 6970 verifyFormat("template <typename T>\n" 6971 "Constructor() : Initializer(FitsOnTheLine) {}", 6972 getStyleWithColumns(Style, 50)); 6973 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6974 verifyFormat( 6975 "SomeClass::Constructor() :\n" 6976 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6977 Style); 6978 6979 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6980 verifyFormat( 6981 "SomeClass::Constructor() :\n" 6982 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6983 Style); 6984 6985 verifyFormat( 6986 "SomeClass::Constructor() :\n" 6987 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6988 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6989 Style); 6990 verifyFormat( 6991 "SomeClass::Constructor() :\n" 6992 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6993 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6994 Style); 6995 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6996 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6997 " aaaaaaaaaa(aaaaaa) {}", 6998 Style); 6999 7000 verifyFormat("Constructor() :\n" 7001 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7002 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7003 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7004 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7005 Style); 7006 7007 verifyFormat("Constructor() :\n" 7008 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7009 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7010 Style); 7011 7012 verifyFormat("Constructor(int Parameter = 0) :\n" 7013 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7014 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7015 Style); 7016 verifyFormat("Constructor() :\n" 7017 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7018 "}", 7019 getStyleWithColumns(Style, 60)); 7020 verifyFormat("Constructor() :\n" 7021 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7022 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7023 Style); 7024 7025 // Here a line could be saved by splitting the second initializer onto two 7026 // lines, but that is not desirable. 7027 verifyFormat("Constructor() :\n" 7028 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7029 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7030 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7031 Style); 7032 7033 FormatStyle OnePerLine = Style; 7034 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7035 verifyFormat("SomeClass::Constructor() :\n" 7036 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7037 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7038 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7039 OnePerLine); 7040 verifyFormat("SomeClass::Constructor() :\n" 7041 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7042 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7043 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7044 OnePerLine); 7045 verifyFormat("MyClass::MyClass(int var) :\n" 7046 " some_var_(var), // 4 space indent\n" 7047 " some_other_var_(var + 1) { // lined up\n" 7048 "}", 7049 OnePerLine); 7050 verifyFormat("Constructor() :\n" 7051 " aaaaa(aaaaaa),\n" 7052 " aaaaa(aaaaaa),\n" 7053 " aaaaa(aaaaaa),\n" 7054 " aaaaa(aaaaaa),\n" 7055 " aaaaa(aaaaaa) {}", 7056 OnePerLine); 7057 verifyFormat("Constructor() :\n" 7058 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7059 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7060 OnePerLine); 7061 OnePerLine.BinPackParameters = false; 7062 verifyFormat("Constructor() :\n" 7063 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7064 " aaaaaaaaaaa().aaa(),\n" 7065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7066 OnePerLine); 7067 OnePerLine.ColumnLimit = 60; 7068 verifyFormat("Constructor() :\n" 7069 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7070 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7071 OnePerLine); 7072 7073 EXPECT_EQ("Constructor() :\n" 7074 " // Comment forcing unwanted break.\n" 7075 " aaaa(aaaa) {}", 7076 format("Constructor() :\n" 7077 " // Comment forcing unwanted break.\n" 7078 " aaaa(aaaa) {}", 7079 Style)); 7080 7081 Style.ColumnLimit = 0; 7082 verifyFormat("SomeClass::Constructor() :\n" 7083 " a(a) {}", 7084 Style); 7085 verifyFormat("SomeClass::Constructor() noexcept :\n" 7086 " a(a) {}", 7087 Style); 7088 verifyFormat("SomeClass::Constructor() :\n" 7089 " a(a), b(b), c(c) {}", 7090 Style); 7091 verifyFormat("SomeClass::Constructor() :\n" 7092 " a(a) {\n" 7093 " foo();\n" 7094 " bar();\n" 7095 "}", 7096 Style); 7097 7098 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7099 verifyFormat("SomeClass::Constructor() :\n" 7100 " a(a), b(b), c(c) {\n" 7101 "}", 7102 Style); 7103 verifyFormat("SomeClass::Constructor() :\n" 7104 " a(a) {\n" 7105 "}", 7106 Style); 7107 7108 Style.ColumnLimit = 80; 7109 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7110 Style.ConstructorInitializerIndentWidth = 2; 7111 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7112 verifyFormat("SomeClass::Constructor() :\n" 7113 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7114 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7115 Style); 7116 7117 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7118 // well 7119 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7120 verifyFormat( 7121 "class SomeClass\n" 7122 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7123 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7124 Style); 7125 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7126 verifyFormat( 7127 "class SomeClass\n" 7128 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7129 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7130 Style); 7131 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7132 verifyFormat( 7133 "class SomeClass :\n" 7134 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7135 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7136 Style); 7137 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7138 verifyFormat( 7139 "class SomeClass\n" 7140 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7141 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7142 Style); 7143 } 7144 7145 #ifndef EXPENSIVE_CHECKS 7146 // Expensive checks enables libstdc++ checking which includes validating the 7147 // state of ranges used in std::priority_queue - this blows out the 7148 // runtime/scalability of the function and makes this test unacceptably slow. 7149 TEST_F(FormatTest, MemoizationTests) { 7150 // This breaks if the memoization lookup does not take \c Indent and 7151 // \c LastSpace into account. 7152 verifyFormat( 7153 "extern CFRunLoopTimerRef\n" 7154 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7155 " CFTimeInterval interval, CFOptionFlags flags,\n" 7156 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7157 " CFRunLoopTimerContext *context) {}"); 7158 7159 // Deep nesting somewhat works around our memoization. 7160 verifyFormat( 7161 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7162 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7163 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7164 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7165 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7166 getLLVMStyleWithColumns(65)); 7167 verifyFormat( 7168 "aaaaa(\n" 7169 " aaaaa,\n" 7170 " aaaaa(\n" 7171 " aaaaa,\n" 7172 " aaaaa(\n" 7173 " aaaaa,\n" 7174 " aaaaa(\n" 7175 " aaaaa,\n" 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))))))))))));", 7193 getLLVMStyleWithColumns(65)); 7194 verifyFormat( 7195 "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" 7196 " a),\n" 7197 " a),\n" 7198 " a),\n" 7199 " a),\n" 7200 " a),\n" 7201 " a),\n" 7202 " a),\n" 7203 " 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)", 7213 getLLVMStyleWithColumns(65)); 7214 7215 // This test takes VERY long when memoization is broken. 7216 FormatStyle OnePerLine = getLLVMStyle(); 7217 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7218 OnePerLine.BinPackParameters = false; 7219 std::string input = "Constructor()\n" 7220 " : aaaa(a,\n"; 7221 for (unsigned i = 0, e = 80; i != e; ++i) 7222 input += " a,\n"; 7223 input += " a) {}"; 7224 verifyFormat(input, OnePerLine); 7225 } 7226 #endif 7227 7228 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7229 verifyFormat( 7230 "void f() {\n" 7231 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7232 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7233 " f();\n" 7234 "}"); 7235 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7236 " Intervals[i - 1].getRange().getLast()) {\n}"); 7237 } 7238 7239 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7240 // Principially, we break function declarations in a certain order: 7241 // 1) break amongst arguments. 7242 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7243 " Cccccccccccccc cccccccccccccc);"); 7244 verifyFormat("template <class TemplateIt>\n" 7245 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7246 " TemplateIt *stop) {}"); 7247 7248 // 2) break after return type. 7249 verifyFormat( 7250 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7251 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7252 getGoogleStyle()); 7253 7254 // 3) break after (. 7255 verifyFormat( 7256 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7257 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7258 getGoogleStyle()); 7259 7260 // 4) break before after nested name specifiers. 7261 verifyFormat( 7262 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7263 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7264 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7265 getGoogleStyle()); 7266 7267 // However, there are exceptions, if a sufficient amount of lines can be 7268 // saved. 7269 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7270 // more adjusting. 7271 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7272 " Cccccccccccccc cccccccccc,\n" 7273 " Cccccccccccccc cccccccccc,\n" 7274 " Cccccccccccccc cccccccccc,\n" 7275 " Cccccccccccccc cccccccccc);"); 7276 verifyFormat( 7277 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7278 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7279 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7280 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7281 getGoogleStyle()); 7282 verifyFormat( 7283 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7284 " Cccccccccccccc cccccccccc,\n" 7285 " Cccccccccccccc cccccccccc,\n" 7286 " Cccccccccccccc cccccccccc,\n" 7287 " Cccccccccccccc cccccccccc,\n" 7288 " Cccccccccccccc cccccccccc,\n" 7289 " Cccccccccccccc cccccccccc);"); 7290 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7291 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7292 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7293 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7294 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7295 7296 // Break after multi-line parameters. 7297 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7298 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7299 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7300 " bbbb bbbb);"); 7301 verifyFormat("void SomeLoooooooooooongFunction(\n" 7302 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7303 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7304 " int bbbbbbbbbbbbb);"); 7305 7306 // Treat overloaded operators like other functions. 7307 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7308 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7309 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7310 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7311 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7312 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7313 verifyGoogleFormat( 7314 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7315 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7316 verifyGoogleFormat( 7317 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7318 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7319 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7320 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7321 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7322 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7323 verifyGoogleFormat( 7324 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7325 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7326 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7327 verifyGoogleFormat("template <typename T>\n" 7328 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7329 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7330 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7331 7332 FormatStyle Style = getLLVMStyle(); 7333 Style.PointerAlignment = FormatStyle::PAS_Left; 7334 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7335 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7336 Style); 7337 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7338 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7339 Style); 7340 } 7341 7342 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7343 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7344 // Prefer keeping `::` followed by `operator` together. 7345 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7346 "ccccccccc::operator++() {\n" 7347 " stuff();\n" 7348 "}", 7349 format("const aaaa::bbbbbbb\n" 7350 "&ccccccccc::operator++() { stuff(); }", 7351 getLLVMStyleWithColumns(40))); 7352 } 7353 7354 TEST_F(FormatTest, TrailingReturnType) { 7355 verifyFormat("auto foo() -> int;\n"); 7356 // correct trailing return type spacing 7357 verifyFormat("auto operator->() -> int;\n"); 7358 verifyFormat("auto operator++(int) -> int;\n"); 7359 7360 verifyFormat("struct S {\n" 7361 " auto bar() const -> int;\n" 7362 "};"); 7363 verifyFormat("template <size_t Order, typename T>\n" 7364 "auto load_img(const std::string &filename)\n" 7365 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7366 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7367 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7368 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7369 verifyFormat("template <typename T>\n" 7370 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7371 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7372 7373 // Not trailing return types. 7374 verifyFormat("void f() { auto a = b->c(); }"); 7375 verifyFormat("auto a = p->foo();"); 7376 verifyFormat("int a = p->foo();"); 7377 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7378 } 7379 7380 TEST_F(FormatTest, DeductionGuides) { 7381 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7382 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7383 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7384 verifyFormat( 7385 "template <class... T>\n" 7386 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7387 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7388 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7389 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7390 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7391 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7392 verifyFormat("template <class T> x() -> x<1>;"); 7393 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7394 7395 // Ensure not deduction guides. 7396 verifyFormat("c()->f<int>();"); 7397 verifyFormat("x()->foo<1>;"); 7398 verifyFormat("x = p->foo<3>();"); 7399 verifyFormat("x()->x<1>();"); 7400 verifyFormat("x()->x<1>;"); 7401 } 7402 7403 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7404 // Avoid breaking before trailing 'const' or other trailing annotations, if 7405 // they are not function-like. 7406 FormatStyle Style = getGoogleStyleWithColumns(47); 7407 verifyFormat("void someLongFunction(\n" 7408 " int someLoooooooooooooongParameter) const {\n}", 7409 getLLVMStyleWithColumns(47)); 7410 verifyFormat("LoooooongReturnType\n" 7411 "someLoooooooongFunction() const {}", 7412 getLLVMStyleWithColumns(47)); 7413 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7414 " const {}", 7415 Style); 7416 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7417 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7418 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7419 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7420 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7421 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7422 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7423 " aaaaaaaaaaa aaaaa) const override;"); 7424 verifyGoogleFormat( 7425 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7426 " const override;"); 7427 7428 // Even if the first parameter has to be wrapped. 7429 verifyFormat("void someLongFunction(\n" 7430 " int someLongParameter) const {}", 7431 getLLVMStyleWithColumns(46)); 7432 verifyFormat("void someLongFunction(\n" 7433 " int someLongParameter) const {}", 7434 Style); 7435 verifyFormat("void someLongFunction(\n" 7436 " int someLongParameter) override {}", 7437 Style); 7438 verifyFormat("void someLongFunction(\n" 7439 " int someLongParameter) OVERRIDE {}", 7440 Style); 7441 verifyFormat("void someLongFunction(\n" 7442 " int someLongParameter) final {}", 7443 Style); 7444 verifyFormat("void someLongFunction(\n" 7445 " int someLongParameter) FINAL {}", 7446 Style); 7447 verifyFormat("void someLongFunction(\n" 7448 " int parameter) const override {}", 7449 Style); 7450 7451 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7452 verifyFormat("void someLongFunction(\n" 7453 " int someLongParameter) const\n" 7454 "{\n" 7455 "}", 7456 Style); 7457 7458 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7459 verifyFormat("void someLongFunction(\n" 7460 " int someLongParameter) const\n" 7461 " {\n" 7462 " }", 7463 Style); 7464 7465 // Unless these are unknown annotations. 7466 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7467 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7468 " LONG_AND_UGLY_ANNOTATION;"); 7469 7470 // Breaking before function-like trailing annotations is fine to keep them 7471 // close to their arguments. 7472 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7473 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7474 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7475 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7476 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7477 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7478 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7479 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7480 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7481 7482 verifyFormat( 7483 "void aaaaaaaaaaaaaaaaaa()\n" 7484 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7485 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7486 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7487 " __attribute__((unused));"); 7488 verifyGoogleFormat( 7489 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7490 " GUARDED_BY(aaaaaaaaaaaa);"); 7491 verifyGoogleFormat( 7492 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7493 " GUARDED_BY(aaaaaaaaaaaa);"); 7494 verifyGoogleFormat( 7495 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7496 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7497 verifyGoogleFormat( 7498 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7499 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7500 } 7501 7502 TEST_F(FormatTest, FunctionAnnotations) { 7503 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7504 "int OldFunction(const string ¶meter) {}"); 7505 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7506 "string OldFunction(const string ¶meter) {}"); 7507 verifyFormat("template <typename T>\n" 7508 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7509 "string OldFunction(const string ¶meter) {}"); 7510 7511 // Not function annotations. 7512 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7513 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7514 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7515 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7516 verifyFormat("MACRO(abc).function() // wrap\n" 7517 " << abc;"); 7518 verifyFormat("MACRO(abc)->function() // wrap\n" 7519 " << abc;"); 7520 verifyFormat("MACRO(abc)::function() // wrap\n" 7521 " << abc;"); 7522 } 7523 7524 TEST_F(FormatTest, BreaksDesireably) { 7525 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7526 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7527 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7528 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7529 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7530 "}"); 7531 7532 verifyFormat( 7533 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7534 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7535 7536 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7537 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7538 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7539 7540 verifyFormat( 7541 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7542 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7543 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7544 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7545 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7546 7547 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7548 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7549 7550 verifyFormat( 7551 "void f() {\n" 7552 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7553 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7554 "}"); 7555 verifyFormat( 7556 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7557 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7558 verifyFormat( 7559 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7560 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7561 verifyFormat( 7562 "aaaaaa(aaa,\n" 7563 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7564 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7565 " aaaa);"); 7566 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7567 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7568 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7569 7570 // Indent consistently independent of call expression and unary operator. 7571 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7572 " dddddddddddddddddddddddddddddd));"); 7573 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7574 " dddddddddddddddddddddddddddddd));"); 7575 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7576 " dddddddddddddddddddddddddddddd));"); 7577 7578 // This test case breaks on an incorrect memoization, i.e. an optimization not 7579 // taking into account the StopAt value. 7580 verifyFormat( 7581 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7582 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7583 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7584 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7585 7586 verifyFormat("{\n {\n {\n" 7587 " Annotation.SpaceRequiredBefore =\n" 7588 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7589 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7590 " }\n }\n}"); 7591 7592 // Break on an outer level if there was a break on an inner level. 7593 EXPECT_EQ("f(g(h(a, // comment\n" 7594 " b, c),\n" 7595 " d, e),\n" 7596 " x, y);", 7597 format("f(g(h(a, // comment\n" 7598 " b, c), d, e), x, y);")); 7599 7600 // Prefer breaking similar line breaks. 7601 verifyFormat( 7602 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7603 " NSTrackingMouseEnteredAndExited |\n" 7604 " NSTrackingActiveAlways;"); 7605 } 7606 7607 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7608 FormatStyle NoBinPacking = getGoogleStyle(); 7609 NoBinPacking.BinPackParameters = false; 7610 NoBinPacking.BinPackArguments = true; 7611 verifyFormat("void f() {\n" 7612 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7613 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7614 "}", 7615 NoBinPacking); 7616 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7617 " int aaaaaaaaaaaaaaaaaaaa,\n" 7618 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7619 NoBinPacking); 7620 7621 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7622 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7623 " vector<int> bbbbbbbbbbbbbbb);", 7624 NoBinPacking); 7625 // FIXME: This behavior difference is probably not wanted. However, currently 7626 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7627 // template arguments from BreakBeforeParameter being set because of the 7628 // one-per-line formatting. 7629 verifyFormat( 7630 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7631 " aaaaaaaaaa> aaaaaaaaaa);", 7632 NoBinPacking); 7633 verifyFormat( 7634 "void fffffffffff(\n" 7635 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7636 " aaaaaaaaaa);"); 7637 } 7638 7639 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7640 FormatStyle NoBinPacking = getGoogleStyle(); 7641 NoBinPacking.BinPackParameters = false; 7642 NoBinPacking.BinPackArguments = false; 7643 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7644 " aaaaaaaaaaaaaaaaaaaa,\n" 7645 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7646 NoBinPacking); 7647 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7648 " aaaaaaaaaaaaa,\n" 7649 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7650 NoBinPacking); 7651 verifyFormat( 7652 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7653 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7654 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7655 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7656 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7657 NoBinPacking); 7658 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7659 " .aaaaaaaaaaaaaaaaaa();", 7660 NoBinPacking); 7661 verifyFormat("void f() {\n" 7662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7663 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7664 "}", 7665 NoBinPacking); 7666 7667 verifyFormat( 7668 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7669 " aaaaaaaaaaaa,\n" 7670 " aaaaaaaaaaaa);", 7671 NoBinPacking); 7672 verifyFormat( 7673 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7674 " ddddddddddddddddddddddddddddd),\n" 7675 " test);", 7676 NoBinPacking); 7677 7678 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7679 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7680 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7681 " aaaaaaaaaaaaaaaaaa;", 7682 NoBinPacking); 7683 verifyFormat("a(\"a\"\n" 7684 " \"a\",\n" 7685 " a);"); 7686 7687 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7688 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7689 " aaaaaaaaa,\n" 7690 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7691 NoBinPacking); 7692 verifyFormat( 7693 "void f() {\n" 7694 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7695 " .aaaaaaa();\n" 7696 "}", 7697 NoBinPacking); 7698 verifyFormat( 7699 "template <class SomeType, class SomeOtherType>\n" 7700 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7701 NoBinPacking); 7702 } 7703 7704 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7705 FormatStyle Style = getLLVMStyleWithColumns(15); 7706 Style.ExperimentalAutoDetectBinPacking = true; 7707 EXPECT_EQ("aaa(aaaa,\n" 7708 " aaaa,\n" 7709 " aaaa);\n" 7710 "aaa(aaaa,\n" 7711 " aaaa,\n" 7712 " aaaa);", 7713 format("aaa(aaaa,\n" // one-per-line 7714 " aaaa,\n" 7715 " aaaa );\n" 7716 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7717 Style)); 7718 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7719 " aaaa);\n" 7720 "aaa(aaaa, aaaa,\n" 7721 " aaaa);", 7722 format("aaa(aaaa, aaaa,\n" // bin-packed 7723 " aaaa );\n" 7724 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7725 Style)); 7726 } 7727 7728 TEST_F(FormatTest, FormatsBuilderPattern) { 7729 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7730 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7731 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7732 " .StartsWith(\".init\", ORDER_INIT)\n" 7733 " .StartsWith(\".fini\", ORDER_FINI)\n" 7734 " .StartsWith(\".hash\", ORDER_HASH)\n" 7735 " .Default(ORDER_TEXT);\n"); 7736 7737 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7738 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7739 verifyFormat("aaaaaaa->aaaaaaa\n" 7740 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7741 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7742 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7743 verifyFormat( 7744 "aaaaaaa->aaaaaaa\n" 7745 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7746 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7747 verifyFormat( 7748 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7749 " aaaaaaaaaaaaaa);"); 7750 verifyFormat( 7751 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7752 " aaaaaa->aaaaaaaaaaaa()\n" 7753 " ->aaaaaaaaaaaaaaaa(\n" 7754 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7755 " ->aaaaaaaaaaaaaaaaa();"); 7756 verifyGoogleFormat( 7757 "void f() {\n" 7758 " someo->Add((new util::filetools::Handler(dir))\n" 7759 " ->OnEvent1(NewPermanentCallback(\n" 7760 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7761 " ->OnEvent2(NewPermanentCallback(\n" 7762 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7763 " ->OnEvent3(NewPermanentCallback(\n" 7764 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7765 " ->OnEvent5(NewPermanentCallback(\n" 7766 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7767 " ->OnEvent6(NewPermanentCallback(\n" 7768 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7769 "}"); 7770 7771 verifyFormat( 7772 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7773 verifyFormat("aaaaaaaaaaaaaaa()\n" 7774 " .aaaaaaaaaaaaaaa()\n" 7775 " .aaaaaaaaaaaaaaa()\n" 7776 " .aaaaaaaaaaaaaaa()\n" 7777 " .aaaaaaaaaaaaaaa();"); 7778 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7779 " .aaaaaaaaaaaaaaa()\n" 7780 " .aaaaaaaaaaaaaaa()\n" 7781 " .aaaaaaaaaaaaaaa();"); 7782 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7783 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7784 " .aaaaaaaaaaaaaaa();"); 7785 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7786 " ->aaaaaaaaaaaaaae(0)\n" 7787 " ->aaaaaaaaaaaaaaa();"); 7788 7789 // Don't linewrap after very short segments. 7790 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7791 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7792 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7793 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7794 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7795 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7796 verifyFormat("aaa()\n" 7797 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7798 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7799 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7800 7801 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7802 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7803 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7804 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7805 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7806 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7807 7808 // Prefer not to break after empty parentheses. 7809 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7810 " First->LastNewlineOffset);"); 7811 7812 // Prefer not to create "hanging" indents. 7813 verifyFormat( 7814 "return !soooooooooooooome_map\n" 7815 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7816 " .second;"); 7817 verifyFormat( 7818 "return aaaaaaaaaaaaaaaa\n" 7819 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7820 " .aaaa(aaaaaaaaaaaaaa);"); 7821 // No hanging indent here. 7822 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7823 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7824 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7825 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7826 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7827 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7828 getLLVMStyleWithColumns(60)); 7829 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7830 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7831 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7832 getLLVMStyleWithColumns(59)); 7833 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7834 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7835 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7836 7837 // Dont break if only closing statements before member call 7838 verifyFormat("test() {\n" 7839 " ([]() -> {\n" 7840 " int b = 32;\n" 7841 " return 3;\n" 7842 " }).foo();\n" 7843 "}"); 7844 verifyFormat("test() {\n" 7845 " (\n" 7846 " []() -> {\n" 7847 " int b = 32;\n" 7848 " return 3;\n" 7849 " },\n" 7850 " foo, bar)\n" 7851 " .foo();\n" 7852 "}"); 7853 verifyFormat("test() {\n" 7854 " ([]() -> {\n" 7855 " int b = 32;\n" 7856 " return 3;\n" 7857 " })\n" 7858 " .foo()\n" 7859 " .bar();\n" 7860 "}"); 7861 verifyFormat("test() {\n" 7862 " ([]() -> {\n" 7863 " int b = 32;\n" 7864 " return 3;\n" 7865 " })\n" 7866 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7867 " \"bbbb\");\n" 7868 "}", 7869 getLLVMStyleWithColumns(30)); 7870 } 7871 7872 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7873 verifyFormat( 7874 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7875 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7876 verifyFormat( 7877 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7878 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7879 7880 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7881 " ccccccccccccccccccccccccc) {\n}"); 7882 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7883 " ccccccccccccccccccccccccc) {\n}"); 7884 7885 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7886 " ccccccccccccccccccccccccc) {\n}"); 7887 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7888 " ccccccccccccccccccccccccc) {\n}"); 7889 7890 verifyFormat( 7891 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7892 " ccccccccccccccccccccccccc) {\n}"); 7893 verifyFormat( 7894 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7895 " ccccccccccccccccccccccccc) {\n}"); 7896 7897 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7898 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7899 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7900 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7901 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7902 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7903 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7904 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7905 7906 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7907 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7908 " aaaaaaaaaaaaaaa != aa) {\n}"); 7909 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7910 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7911 " aaaaaaaaaaaaaaa != aa) {\n}"); 7912 } 7913 7914 TEST_F(FormatTest, BreaksAfterAssignments) { 7915 verifyFormat( 7916 "unsigned Cost =\n" 7917 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7918 " SI->getPointerAddressSpaceee());\n"); 7919 verifyFormat( 7920 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7921 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7922 7923 verifyFormat( 7924 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7925 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7926 verifyFormat("unsigned OriginalStartColumn =\n" 7927 " SourceMgr.getSpellingColumnNumber(\n" 7928 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7929 " 1;"); 7930 } 7931 7932 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7933 FormatStyle Style = getLLVMStyle(); 7934 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7935 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7936 Style); 7937 7938 Style.PenaltyBreakAssignment = 20; 7939 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7940 " cccccccccccccccccccccccccc;", 7941 Style); 7942 } 7943 7944 TEST_F(FormatTest, AlignsAfterAssignments) { 7945 verifyFormat( 7946 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7947 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7948 verifyFormat( 7949 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7950 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7951 verifyFormat( 7952 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7953 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7954 verifyFormat( 7955 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7956 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7957 verifyFormat( 7958 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7959 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7960 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7961 } 7962 7963 TEST_F(FormatTest, AlignsAfterReturn) { 7964 verifyFormat( 7965 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7966 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7967 verifyFormat( 7968 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7969 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7970 verifyFormat( 7971 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7972 " aaaaaaaaaaaaaaaaaaaaaa();"); 7973 verifyFormat( 7974 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7975 " aaaaaaaaaaaaaaaaaaaaaa());"); 7976 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7977 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7978 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7979 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7980 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7981 verifyFormat("return\n" 7982 " // true if code is one of a or b.\n" 7983 " code == a || code == b;"); 7984 } 7985 7986 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7987 verifyFormat( 7988 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7989 " aaaaaaaaa aaaaaaa) {}"); 7990 verifyFormat( 7991 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7992 " aaaaaaaaaaa aaaaaaaaa);"); 7993 verifyFormat( 7994 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7995 " aaaaaaaaaaaaaaaaaaaaa));"); 7996 FormatStyle Style = getLLVMStyle(); 7997 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7998 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7999 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8000 Style); 8001 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8002 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8003 Style); 8004 verifyFormat("SomeLongVariableName->someFunction(\n" 8005 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8006 Style); 8007 verifyFormat( 8008 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8009 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8010 Style); 8011 verifyFormat( 8012 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8013 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8014 Style); 8015 verifyFormat( 8016 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8017 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8018 Style); 8019 8020 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8021 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8022 " b));", 8023 Style); 8024 8025 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8026 Style.BinPackArguments = false; 8027 Style.BinPackParameters = false; 8028 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8029 " aaaaaaaaaaa aaaaaaaa,\n" 8030 " aaaaaaaaa aaaaaaa,\n" 8031 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8032 Style); 8033 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8034 " aaaaaaaaaaa aaaaaaaaa,\n" 8035 " aaaaaaaaaaa aaaaaaaaa,\n" 8036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8037 Style); 8038 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8039 " aaaaaaaaaaaaaaa,\n" 8040 " aaaaaaaaaaaaaaaaaaaaa,\n" 8041 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8042 Style); 8043 verifyFormat( 8044 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8045 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8046 Style); 8047 verifyFormat( 8048 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8049 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8050 Style); 8051 verifyFormat( 8052 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8053 " aaaaaaaaaaaaaaaaaaaaa(\n" 8054 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8055 " aaaaaaaaaaaaaaaa);", 8056 Style); 8057 verifyFormat( 8058 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8059 " aaaaaaaaaaaaaaaaaaaaa(\n" 8060 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8061 " aaaaaaaaaaaaaaaa);", 8062 Style); 8063 } 8064 8065 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8066 FormatStyle Style = getLLVMStyleWithColumns(40); 8067 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8068 " bbbbbbbbbbbbbbbbbbbbbb);", 8069 Style); 8070 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8071 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8072 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8073 " bbbbbbbbbbbbbbbbbbbbbb);", 8074 Style); 8075 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8076 Style.AlignOperands = FormatStyle::OAS_Align; 8077 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8078 " bbbbbbbbbbbbbbbbbbbbbb);", 8079 Style); 8080 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8081 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8082 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8083 " bbbbbbbbbbbbbbbbbbbbbb);", 8084 Style); 8085 } 8086 8087 TEST_F(FormatTest, BreaksConditionalExpressions) { 8088 verifyFormat( 8089 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8090 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8091 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8092 verifyFormat( 8093 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8094 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8095 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8096 verifyFormat( 8097 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8098 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8099 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8100 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8101 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8102 verifyFormat( 8103 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8104 " : aaaaaaaaaaaaa);"); 8105 verifyFormat( 8106 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8107 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8108 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8109 " aaaaaaaaaaaaa);"); 8110 verifyFormat( 8111 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8112 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8113 " aaaaaaaaaaaaa);"); 8114 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8115 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8116 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8117 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8119 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8120 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8121 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8122 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8123 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8125 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8126 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8128 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8129 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8130 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8131 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8132 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8133 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8134 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8136 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8137 " : aaaaaaaaaaaaaaaa;"); 8138 verifyFormat( 8139 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8140 " ? aaaaaaaaaaaaaaa\n" 8141 " : aaaaaaaaaaaaaaa;"); 8142 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8143 " aaaaaaaaa\n" 8144 " ? b\n" 8145 " : c);"); 8146 verifyFormat("return aaaa == bbbb\n" 8147 " // comment\n" 8148 " ? aaaa\n" 8149 " : bbbb;"); 8150 verifyFormat("unsigned Indent =\n" 8151 " format(TheLine.First,\n" 8152 " IndentForLevel[TheLine.Level] >= 0\n" 8153 " ? IndentForLevel[TheLine.Level]\n" 8154 " : TheLine * 2,\n" 8155 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8156 getLLVMStyleWithColumns(60)); 8157 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8158 " ? aaaaaaaaaaaaaaa\n" 8159 " : bbbbbbbbbbbbbbb //\n" 8160 " ? ccccccccccccccc\n" 8161 " : ddddddddddddddd;"); 8162 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8163 " ? aaaaaaaaaaaaaaa\n" 8164 " : (bbbbbbbbbbbbbbb //\n" 8165 " ? ccccccccccccccc\n" 8166 " : ddddddddddddddd);"); 8167 verifyFormat( 8168 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8169 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8170 " aaaaaaaaaaaaaaaaaaaaa +\n" 8171 " aaaaaaaaaaaaaaaaaaaaa\n" 8172 " : aaaaaaaaaa;"); 8173 verifyFormat( 8174 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8175 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8176 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8177 8178 FormatStyle NoBinPacking = getLLVMStyle(); 8179 NoBinPacking.BinPackArguments = false; 8180 verifyFormat( 8181 "void f() {\n" 8182 " g(aaa,\n" 8183 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8184 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8185 " ? aaaaaaaaaaaaaaa\n" 8186 " : aaaaaaaaaaaaaaa);\n" 8187 "}", 8188 NoBinPacking); 8189 verifyFormat( 8190 "void f() {\n" 8191 " g(aaa,\n" 8192 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8193 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8194 " ?: aaaaaaaaaaaaaaa);\n" 8195 "}", 8196 NoBinPacking); 8197 8198 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8199 " // comment.\n" 8200 " ccccccccccccccccccccccccccccccccccccccc\n" 8201 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8202 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8203 8204 // Assignments in conditional expressions. Apparently not uncommon :-(. 8205 verifyFormat("return a != b\n" 8206 " // comment\n" 8207 " ? a = b\n" 8208 " : a = b;"); 8209 verifyFormat("return a != b\n" 8210 " // comment\n" 8211 " ? a = a != b\n" 8212 " // comment\n" 8213 " ? a = b\n" 8214 " : a\n" 8215 " : a;\n"); 8216 verifyFormat("return a != b\n" 8217 " // comment\n" 8218 " ? a\n" 8219 " : a = a != b\n" 8220 " // comment\n" 8221 " ? a = b\n" 8222 " : a;"); 8223 8224 // Chained conditionals 8225 FormatStyle Style = getLLVMStyleWithColumns(70); 8226 Style.AlignOperands = FormatStyle::OAS_Align; 8227 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8228 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8229 " : 3333333333333333;", 8230 Style); 8231 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8232 " : bbbbbbbbbb ? 2222222222222222\n" 8233 " : 3333333333333333;", 8234 Style); 8235 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8236 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8237 " : 3333333333333333;", 8238 Style); 8239 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8240 " : bbbbbbbbbbbbbb ? 222222\n" 8241 " : 333333;", 8242 Style); 8243 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8244 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8245 " : cccccccccccccc ? 3333333333333333\n" 8246 " : 4444444444444444;", 8247 Style); 8248 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8249 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8250 " : 3333333333333333;", 8251 Style); 8252 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8253 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8254 " : (aaa ? bbb : ccc);", 8255 Style); 8256 verifyFormat( 8257 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8258 " : cccccccccccccccccc)\n" 8259 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8260 " : 3333333333333333;", 8261 Style); 8262 verifyFormat( 8263 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8264 " : cccccccccccccccccc)\n" 8265 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8266 " : 3333333333333333;", 8267 Style); 8268 verifyFormat( 8269 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8270 " : dddddddddddddddddd)\n" 8271 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8272 " : 3333333333333333;", 8273 Style); 8274 verifyFormat( 8275 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8276 " : dddddddddddddddddd)\n" 8277 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8278 " : 3333333333333333;", 8279 Style); 8280 verifyFormat( 8281 "return aaaaaaaaa ? 1111111111111111\n" 8282 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8283 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8284 " : dddddddddddddddddd)\n", 8285 Style); 8286 verifyFormat( 8287 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8288 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8289 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8290 " : cccccccccccccccccc);", 8291 Style); 8292 verifyFormat( 8293 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8294 " : ccccccccccccccc ? dddddddddddddddddd\n" 8295 " : eeeeeeeeeeeeeeeeee)\n" 8296 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8297 " : 3333333333333333;", 8298 Style); 8299 verifyFormat( 8300 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8301 " : ccccccccccccccc ? dddddddddddddddddd\n" 8302 " : eeeeeeeeeeeeeeeeee)\n" 8303 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8304 " : 3333333333333333;", 8305 Style); 8306 verifyFormat( 8307 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8308 " : cccccccccccc ? dddddddddddddddddd\n" 8309 " : eeeeeeeeeeeeeeeeee)\n" 8310 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8311 " : 3333333333333333;", 8312 Style); 8313 verifyFormat( 8314 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8315 " : cccccccccccccccccc\n" 8316 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8317 " : 3333333333333333;", 8318 Style); 8319 verifyFormat( 8320 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8321 " : cccccccccccccccc ? dddddddddddddddddd\n" 8322 " : eeeeeeeeeeeeeeeeee\n" 8323 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8324 " : 3333333333333333;", 8325 Style); 8326 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8327 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8328 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8329 " : eeeeeeeeeeeeeeeeee)\n" 8330 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8331 " : 3333333333333333;", 8332 Style); 8333 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8334 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8335 " : cccccccccccccccc ? dddddddddddddddddd\n" 8336 " : eeeeeeeeeeeeeeeeee\n" 8337 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8338 " : 3333333333333333;", 8339 Style); 8340 8341 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8342 Style.BreakBeforeTernaryOperators = false; 8343 // FIXME: Aligning the question marks is weird given DontAlign. 8344 // Consider disabling this alignment in this case. Also check whether this 8345 // will render the adjustment from https://reviews.llvm.org/D82199 8346 // unnecessary. 8347 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8348 " bbbb ? cccccccccccccccccc :\n" 8349 " ddddd;\n", 8350 Style); 8351 8352 EXPECT_EQ( 8353 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8354 " /*\n" 8355 " */\n" 8356 " function() {\n" 8357 " try {\n" 8358 " return JJJJJJJJJJJJJJ(\n" 8359 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8360 " }\n" 8361 " } :\n" 8362 " function() {};", 8363 format( 8364 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8365 " /*\n" 8366 " */\n" 8367 " function() {\n" 8368 " try {\n" 8369 " return JJJJJJJJJJJJJJ(\n" 8370 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8371 " }\n" 8372 " } :\n" 8373 " function() {};", 8374 getGoogleStyle(FormatStyle::LK_JavaScript))); 8375 } 8376 8377 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8378 FormatStyle Style = getLLVMStyleWithColumns(70); 8379 Style.BreakBeforeTernaryOperators = false; 8380 verifyFormat( 8381 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8382 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8383 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8384 Style); 8385 verifyFormat( 8386 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8387 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8388 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8389 Style); 8390 verifyFormat( 8391 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8392 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8393 Style); 8394 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8395 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8396 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8397 Style); 8398 verifyFormat( 8399 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8400 " aaaaaaaaaaaaa);", 8401 Style); 8402 verifyFormat( 8403 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8404 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8405 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8406 " aaaaaaaaaaaaa);", 8407 Style); 8408 verifyFormat( 8409 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8410 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8411 " aaaaaaaaaaaaa);", 8412 Style); 8413 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8414 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8415 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8416 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8418 Style); 8419 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8420 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8421 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8422 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8423 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8424 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8425 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8426 Style); 8427 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8428 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8429 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8430 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8431 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8432 Style); 8433 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8434 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8435 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8436 Style); 8437 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8438 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8439 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8440 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8441 Style); 8442 verifyFormat( 8443 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8444 " aaaaaaaaaaaaaaa :\n" 8445 " aaaaaaaaaaaaaaa;", 8446 Style); 8447 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8448 " aaaaaaaaa ?\n" 8449 " b :\n" 8450 " c);", 8451 Style); 8452 verifyFormat("unsigned Indent =\n" 8453 " format(TheLine.First,\n" 8454 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8455 " IndentForLevel[TheLine.Level] :\n" 8456 " TheLine * 2,\n" 8457 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8458 Style); 8459 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8460 " aaaaaaaaaaaaaaa :\n" 8461 " bbbbbbbbbbbbbbb ? //\n" 8462 " ccccccccccccccc :\n" 8463 " ddddddddddddddd;", 8464 Style); 8465 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8466 " aaaaaaaaaaaaaaa :\n" 8467 " (bbbbbbbbbbbbbbb ? //\n" 8468 " ccccccccccccccc :\n" 8469 " ddddddddddddddd);", 8470 Style); 8471 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8472 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8473 " ccccccccccccccccccccccccccc;", 8474 Style); 8475 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8476 " aaaaa :\n" 8477 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8478 Style); 8479 8480 // Chained conditionals 8481 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8482 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8483 " 3333333333333333;", 8484 Style); 8485 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8486 " bbbbbbbbbb ? 2222222222222222 :\n" 8487 " 3333333333333333;", 8488 Style); 8489 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8490 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8491 " 3333333333333333;", 8492 Style); 8493 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8494 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8495 " 333333;", 8496 Style); 8497 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8498 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8499 " cccccccccccccccc ? 3333333333333333 :\n" 8500 " 4444444444444444;", 8501 Style); 8502 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8503 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8504 " 3333333333333333;", 8505 Style); 8506 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8507 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8508 " (aaa ? bbb : ccc);", 8509 Style); 8510 verifyFormat( 8511 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8512 " cccccccccccccccccc) :\n" 8513 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8514 " 3333333333333333;", 8515 Style); 8516 verifyFormat( 8517 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8518 " cccccccccccccccccc) :\n" 8519 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8520 " 3333333333333333;", 8521 Style); 8522 verifyFormat( 8523 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8524 " dddddddddddddddddd) :\n" 8525 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8526 " 3333333333333333;", 8527 Style); 8528 verifyFormat( 8529 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8530 " dddddddddddddddddd) :\n" 8531 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8532 " 3333333333333333;", 8533 Style); 8534 verifyFormat( 8535 "return aaaaaaaaa ? 1111111111111111 :\n" 8536 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8537 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8538 " dddddddddddddddddd)\n", 8539 Style); 8540 verifyFormat( 8541 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8542 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8543 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8544 " cccccccccccccccccc);", 8545 Style); 8546 verifyFormat( 8547 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8548 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8549 " eeeeeeeeeeeeeeeeee) :\n" 8550 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8551 " 3333333333333333;", 8552 Style); 8553 verifyFormat( 8554 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8555 " ccccccccccccc ? dddddddddddddddddd :\n" 8556 " eeeeeeeeeeeeeeeeee) :\n" 8557 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8558 " 3333333333333333;", 8559 Style); 8560 verifyFormat( 8561 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8562 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8563 " eeeeeeeeeeeeeeeeee) :\n" 8564 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8565 " 3333333333333333;", 8566 Style); 8567 verifyFormat( 8568 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8569 " cccccccccccccccccc :\n" 8570 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8571 " 3333333333333333;", 8572 Style); 8573 verifyFormat( 8574 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8575 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8576 " eeeeeeeeeeeeeeeeee :\n" 8577 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8578 " 3333333333333333;", 8579 Style); 8580 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8581 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8582 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8583 " eeeeeeeeeeeeeeeeee) :\n" 8584 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8585 " 3333333333333333;", 8586 Style); 8587 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8588 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8589 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8590 " eeeeeeeeeeeeeeeeee :\n" 8591 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8592 " 3333333333333333;", 8593 Style); 8594 } 8595 8596 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8597 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8598 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8599 verifyFormat("bool a = true, b = false;"); 8600 8601 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8602 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8603 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8604 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8605 verifyFormat( 8606 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8607 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8608 " d = e && f;"); 8609 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8610 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8611 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8612 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8613 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8614 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8615 8616 FormatStyle Style = getGoogleStyle(); 8617 Style.PointerAlignment = FormatStyle::PAS_Left; 8618 Style.DerivePointerAlignment = false; 8619 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8620 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8621 " *b = bbbbbbbbbbbbbbbbbbb;", 8622 Style); 8623 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8624 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8625 Style); 8626 verifyFormat("vector<int*> a, b;", Style); 8627 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8628 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8629 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8630 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8631 Style); 8632 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8633 Style); 8634 verifyFormat( 8635 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8636 Style); 8637 8638 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8639 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8640 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8641 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8642 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8643 Style); 8644 } 8645 8646 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8647 verifyFormat("arr[foo ? bar : baz];"); 8648 verifyFormat("f()[foo ? bar : baz];"); 8649 verifyFormat("(a + b)[foo ? bar : baz];"); 8650 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8651 } 8652 8653 TEST_F(FormatTest, AlignsStringLiterals) { 8654 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8655 " \"short literal\");"); 8656 verifyFormat( 8657 "looooooooooooooooooooooooongFunction(\n" 8658 " \"short literal\"\n" 8659 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8660 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8661 " \" string literals\",\n" 8662 " and, other, parameters);"); 8663 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8664 " \"5678\";", 8665 format("fun + \"1243\" /* comment */\n" 8666 " \"5678\";", 8667 getLLVMStyleWithColumns(28))); 8668 EXPECT_EQ( 8669 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8670 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8671 " \"aaaaaaaaaaaaaaaa\";", 8672 format("aaaaaa =" 8673 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8674 "aaaaaaaaaaaaaaaaaaaaa\" " 8675 "\"aaaaaaaaaaaaaaaa\";")); 8676 verifyFormat("a = a + \"a\"\n" 8677 " \"a\"\n" 8678 " \"a\";"); 8679 verifyFormat("f(\"a\", \"b\"\n" 8680 " \"c\");"); 8681 8682 verifyFormat( 8683 "#define LL_FORMAT \"ll\"\n" 8684 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8685 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8686 8687 verifyFormat("#define A(X) \\\n" 8688 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8689 " \"ccccc\"", 8690 getLLVMStyleWithColumns(23)); 8691 verifyFormat("#define A \"def\"\n" 8692 "f(\"abc\" A \"ghi\"\n" 8693 " \"jkl\");"); 8694 8695 verifyFormat("f(L\"a\"\n" 8696 " L\"b\");"); 8697 verifyFormat("#define A(X) \\\n" 8698 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8699 " L\"ccccc\"", 8700 getLLVMStyleWithColumns(25)); 8701 8702 verifyFormat("f(@\"a\"\n" 8703 " @\"b\");"); 8704 verifyFormat("NSString s = @\"a\"\n" 8705 " @\"b\"\n" 8706 " @\"c\";"); 8707 verifyFormat("NSString s = @\"a\"\n" 8708 " \"b\"\n" 8709 " \"c\";"); 8710 } 8711 8712 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8713 FormatStyle Style = getLLVMStyle(); 8714 // No declarations or definitions should be moved to own line. 8715 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8716 verifyFormat("class A {\n" 8717 " int f() { return 1; }\n" 8718 " int g();\n" 8719 "};\n" 8720 "int f() { return 1; }\n" 8721 "int g();\n", 8722 Style); 8723 8724 // All declarations and definitions should have the return type moved to its 8725 // own line. 8726 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8727 Style.TypenameMacros = {"LIST"}; 8728 verifyFormat("SomeType\n" 8729 "funcdecl(LIST(uint64_t));", 8730 Style); 8731 verifyFormat("class E {\n" 8732 " int\n" 8733 " f() {\n" 8734 " return 1;\n" 8735 " }\n" 8736 " int\n" 8737 " g();\n" 8738 "};\n" 8739 "int\n" 8740 "f() {\n" 8741 " return 1;\n" 8742 "}\n" 8743 "int\n" 8744 "g();\n", 8745 Style); 8746 8747 // Top-level definitions, and no kinds of declarations should have the 8748 // return type moved to its own line. 8749 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8750 verifyFormat("class B {\n" 8751 " int f() { return 1; }\n" 8752 " int g();\n" 8753 "};\n" 8754 "int\n" 8755 "f() {\n" 8756 " return 1;\n" 8757 "}\n" 8758 "int g();\n", 8759 Style); 8760 8761 // Top-level definitions and declarations should have the return type moved 8762 // to its own line. 8763 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8764 verifyFormat("class C {\n" 8765 " int f() { return 1; }\n" 8766 " int g();\n" 8767 "};\n" 8768 "int\n" 8769 "f() {\n" 8770 " return 1;\n" 8771 "}\n" 8772 "int\n" 8773 "g();\n", 8774 Style); 8775 8776 // All definitions should have the return type moved to its own line, but no 8777 // kinds of declarations. 8778 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8779 verifyFormat("class D {\n" 8780 " int\n" 8781 " f() {\n" 8782 " return 1;\n" 8783 " }\n" 8784 " int g();\n" 8785 "};\n" 8786 "int\n" 8787 "f() {\n" 8788 " return 1;\n" 8789 "}\n" 8790 "int g();\n", 8791 Style); 8792 verifyFormat("const char *\n" 8793 "f(void) {\n" // Break here. 8794 " return \"\";\n" 8795 "}\n" 8796 "const char *bar(void);\n", // No break here. 8797 Style); 8798 verifyFormat("template <class T>\n" 8799 "T *\n" 8800 "f(T &c) {\n" // Break here. 8801 " return NULL;\n" 8802 "}\n" 8803 "template <class T> T *f(T &c);\n", // No break here. 8804 Style); 8805 verifyFormat("class C {\n" 8806 " int\n" 8807 " operator+() {\n" 8808 " return 1;\n" 8809 " }\n" 8810 " int\n" 8811 " operator()() {\n" 8812 " return 1;\n" 8813 " }\n" 8814 "};\n", 8815 Style); 8816 verifyFormat("void\n" 8817 "A::operator()() {}\n" 8818 "void\n" 8819 "A::operator>>() {}\n" 8820 "void\n" 8821 "A::operator+() {}\n" 8822 "void\n" 8823 "A::operator*() {}\n" 8824 "void\n" 8825 "A::operator->() {}\n" 8826 "void\n" 8827 "A::operator void *() {}\n" 8828 "void\n" 8829 "A::operator void &() {}\n" 8830 "void\n" 8831 "A::operator void &&() {}\n" 8832 "void\n" 8833 "A::operator char *() {}\n" 8834 "void\n" 8835 "A::operator[]() {}\n" 8836 "void\n" 8837 "A::operator!() {}\n" 8838 "void\n" 8839 "A::operator**() {}\n" 8840 "void\n" 8841 "A::operator<Foo> *() {}\n" 8842 "void\n" 8843 "A::operator<Foo> **() {}\n" 8844 "void\n" 8845 "A::operator<Foo> &() {}\n" 8846 "void\n" 8847 "A::operator void **() {}\n", 8848 Style); 8849 verifyFormat("constexpr auto\n" 8850 "operator()() const -> reference {}\n" 8851 "constexpr auto\n" 8852 "operator>>() const -> reference {}\n" 8853 "constexpr auto\n" 8854 "operator+() const -> reference {}\n" 8855 "constexpr auto\n" 8856 "operator*() const -> reference {}\n" 8857 "constexpr auto\n" 8858 "operator->() const -> reference {}\n" 8859 "constexpr auto\n" 8860 "operator++() const -> reference {}\n" 8861 "constexpr auto\n" 8862 "operator void *() const -> reference {}\n" 8863 "constexpr auto\n" 8864 "operator void **() const -> reference {}\n" 8865 "constexpr auto\n" 8866 "operator void *() const -> reference {}\n" 8867 "constexpr auto\n" 8868 "operator void &() const -> reference {}\n" 8869 "constexpr auto\n" 8870 "operator void &&() const -> reference {}\n" 8871 "constexpr auto\n" 8872 "operator char *() const -> reference {}\n" 8873 "constexpr auto\n" 8874 "operator!() const -> reference {}\n" 8875 "constexpr auto\n" 8876 "operator[]() const -> reference {}\n", 8877 Style); 8878 verifyFormat("void *operator new(std::size_t s);", // No break here. 8879 Style); 8880 verifyFormat("void *\n" 8881 "operator new(std::size_t s) {}", 8882 Style); 8883 verifyFormat("void *\n" 8884 "operator delete[](void *ptr) {}", 8885 Style); 8886 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8887 verifyFormat("const char *\n" 8888 "f(void)\n" // Break here. 8889 "{\n" 8890 " return \"\";\n" 8891 "}\n" 8892 "const char *bar(void);\n", // No break here. 8893 Style); 8894 verifyFormat("template <class T>\n" 8895 "T *\n" // Problem here: no line break 8896 "f(T &c)\n" // Break here. 8897 "{\n" 8898 " return NULL;\n" 8899 "}\n" 8900 "template <class T> T *f(T &c);\n", // No break here. 8901 Style); 8902 verifyFormat("int\n" 8903 "foo(A<bool> a)\n" 8904 "{\n" 8905 " return a;\n" 8906 "}\n", 8907 Style); 8908 verifyFormat("int\n" 8909 "foo(A<8> a)\n" 8910 "{\n" 8911 " return a;\n" 8912 "}\n", 8913 Style); 8914 verifyFormat("int\n" 8915 "foo(A<B<bool>, 8> a)\n" 8916 "{\n" 8917 " return a;\n" 8918 "}\n", 8919 Style); 8920 verifyFormat("int\n" 8921 "foo(A<B<8>, bool> a)\n" 8922 "{\n" 8923 " return a;\n" 8924 "}\n", 8925 Style); 8926 verifyFormat("int\n" 8927 "foo(A<B<bool>, bool> a)\n" 8928 "{\n" 8929 " return a;\n" 8930 "}\n", 8931 Style); 8932 verifyFormat("int\n" 8933 "foo(A<B<8>, 8> a)\n" 8934 "{\n" 8935 " return a;\n" 8936 "}\n", 8937 Style); 8938 8939 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8940 Style.BraceWrapping.AfterFunction = true; 8941 verifyFormat("int f(i);\n" // No break here. 8942 "int\n" // Break here. 8943 "f(i)\n" 8944 "{\n" 8945 " return i + 1;\n" 8946 "}\n" 8947 "int\n" // Break here. 8948 "f(i)\n" 8949 "{\n" 8950 " return i + 1;\n" 8951 "};", 8952 Style); 8953 verifyFormat("int f(a, b, c);\n" // No break here. 8954 "int\n" // Break here. 8955 "f(a, b, c)\n" // Break here. 8956 "short a, b;\n" 8957 "float c;\n" 8958 "{\n" 8959 " return a + b < c;\n" 8960 "}\n" 8961 "int\n" // Break here. 8962 "f(a, b, c)\n" // Break here. 8963 "short a, b;\n" 8964 "float c;\n" 8965 "{\n" 8966 " return a + b < c;\n" 8967 "};", 8968 Style); 8969 verifyFormat("byte *\n" // Break here. 8970 "f(a)\n" // Break here. 8971 "byte a[];\n" 8972 "{\n" 8973 " return a;\n" 8974 "}", 8975 Style); 8976 verifyFormat("bool f(int a, int) override;\n" 8977 "Bar g(int a, Bar) final;\n" 8978 "Bar h(a, Bar) final;", 8979 Style); 8980 verifyFormat("int\n" 8981 "f(a)", 8982 Style); 8983 verifyFormat("bool\n" 8984 "f(size_t = 0, bool b = false)\n" 8985 "{\n" 8986 " return !b;\n" 8987 "}", 8988 Style); 8989 8990 // The return breaking style doesn't affect: 8991 // * function and object definitions with attribute-like macros 8992 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8993 " ABSL_GUARDED_BY(mutex) = {};", 8994 getGoogleStyleWithColumns(40)); 8995 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8996 " ABSL_GUARDED_BY(mutex); // comment", 8997 getGoogleStyleWithColumns(40)); 8998 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8999 " ABSL_GUARDED_BY(mutex1)\n" 9000 " ABSL_GUARDED_BY(mutex2);", 9001 getGoogleStyleWithColumns(40)); 9002 verifyFormat("Tttttt f(int a, int b)\n" 9003 " ABSL_GUARDED_BY(mutex1)\n" 9004 " ABSL_GUARDED_BY(mutex2);", 9005 getGoogleStyleWithColumns(40)); 9006 // * typedefs 9007 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9008 9009 Style = getGNUStyle(); 9010 9011 // Test for comments at the end of function declarations. 9012 verifyFormat("void\n" 9013 "foo (int a, /*abc*/ int b) // def\n" 9014 "{\n" 9015 "}\n", 9016 Style); 9017 9018 verifyFormat("void\n" 9019 "foo (int a, /* abc */ int b) /* def */\n" 9020 "{\n" 9021 "}\n", 9022 Style); 9023 9024 // Definitions that should not break after return type 9025 verifyFormat("void foo (int a, int b); // def\n", Style); 9026 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9027 verifyFormat("void foo (int a, int b);\n", Style); 9028 } 9029 9030 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9031 FormatStyle NoBreak = getLLVMStyle(); 9032 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9033 FormatStyle Break = getLLVMStyle(); 9034 Break.AlwaysBreakBeforeMultilineStrings = true; 9035 verifyFormat("aaaa = \"bbbb\"\n" 9036 " \"cccc\";", 9037 NoBreak); 9038 verifyFormat("aaaa =\n" 9039 " \"bbbb\"\n" 9040 " \"cccc\";", 9041 Break); 9042 verifyFormat("aaaa(\"bbbb\"\n" 9043 " \"cccc\");", 9044 NoBreak); 9045 verifyFormat("aaaa(\n" 9046 " \"bbbb\"\n" 9047 " \"cccc\");", 9048 Break); 9049 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9050 " \"cccc\");", 9051 NoBreak); 9052 verifyFormat("aaaa(qqq,\n" 9053 " \"bbbb\"\n" 9054 " \"cccc\");", 9055 Break); 9056 verifyFormat("aaaa(qqq,\n" 9057 " L\"bbbb\"\n" 9058 " L\"cccc\");", 9059 Break); 9060 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9061 " \"bbbb\"));", 9062 Break); 9063 verifyFormat("string s = someFunction(\n" 9064 " \"abc\"\n" 9065 " \"abc\");", 9066 Break); 9067 9068 // As we break before unary operators, breaking right after them is bad. 9069 verifyFormat("string foo = abc ? \"x\"\n" 9070 " \"blah blah blah blah blah blah\"\n" 9071 " : \"y\";", 9072 Break); 9073 9074 // Don't break if there is no column gain. 9075 verifyFormat("f(\"aaaa\"\n" 9076 " \"bbbb\");", 9077 Break); 9078 9079 // Treat literals with escaped newlines like multi-line string literals. 9080 EXPECT_EQ("x = \"a\\\n" 9081 "b\\\n" 9082 "c\";", 9083 format("x = \"a\\\n" 9084 "b\\\n" 9085 "c\";", 9086 NoBreak)); 9087 EXPECT_EQ("xxxx =\n" 9088 " \"a\\\n" 9089 "b\\\n" 9090 "c\";", 9091 format("xxxx = \"a\\\n" 9092 "b\\\n" 9093 "c\";", 9094 Break)); 9095 9096 EXPECT_EQ("NSString *const kString =\n" 9097 " @\"aaaa\"\n" 9098 " @\"bbbb\";", 9099 format("NSString *const kString = @\"aaaa\"\n" 9100 "@\"bbbb\";", 9101 Break)); 9102 9103 Break.ColumnLimit = 0; 9104 verifyFormat("const char *hello = \"hello llvm\";", Break); 9105 } 9106 9107 TEST_F(FormatTest, AlignsPipes) { 9108 verifyFormat( 9109 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9110 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9111 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9112 verifyFormat( 9113 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9114 " << aaaaaaaaaaaaaaaaaaaa;"); 9115 verifyFormat( 9116 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9117 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9118 verifyFormat( 9119 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9120 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9121 verifyFormat( 9122 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9123 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9124 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9125 verifyFormat( 9126 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9127 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9128 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9129 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9130 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9131 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9132 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9133 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9134 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9135 verifyFormat( 9136 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9137 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9138 verifyFormat( 9139 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9140 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9141 9142 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9143 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9144 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9145 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9146 " aaaaaaaaaaaaaaaaaaaaa)\n" 9147 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9148 verifyFormat("LOG_IF(aaa == //\n" 9149 " bbb)\n" 9150 " << a << b;"); 9151 9152 // But sometimes, breaking before the first "<<" is desirable. 9153 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9154 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9155 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9156 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9157 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9158 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9159 " << BEF << IsTemplate << Description << E->getType();"); 9160 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9161 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9162 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9163 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9164 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9165 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9166 " << aaa;"); 9167 9168 verifyFormat( 9169 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9170 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9171 9172 // Incomplete string literal. 9173 EXPECT_EQ("llvm::errs() << \"\n" 9174 " << a;", 9175 format("llvm::errs() << \"\n<<a;")); 9176 9177 verifyFormat("void f() {\n" 9178 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9179 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9180 "}"); 9181 9182 // Handle 'endl'. 9183 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9184 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9185 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9186 9187 // Handle '\n'. 9188 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9189 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9190 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9191 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9192 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9193 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9194 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9195 } 9196 9197 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9198 verifyFormat("return out << \"somepacket = {\\n\"\n" 9199 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9200 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9201 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9202 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9203 " << \"}\";"); 9204 9205 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9206 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9207 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9208 verifyFormat( 9209 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9210 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9211 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9212 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9213 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9214 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9215 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9216 verifyFormat( 9217 "void f() {\n" 9218 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9219 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9220 "}"); 9221 9222 // Breaking before the first "<<" is generally not desirable. 9223 verifyFormat( 9224 "llvm::errs()\n" 9225 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9226 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9227 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9228 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9229 getLLVMStyleWithColumns(70)); 9230 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9231 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9232 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9233 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9234 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9235 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9236 getLLVMStyleWithColumns(70)); 9237 9238 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9239 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9240 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9241 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9242 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9243 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9244 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9245 " (aaaa + aaaa);", 9246 getLLVMStyleWithColumns(40)); 9247 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9248 " (aaaaaaa + aaaaa));", 9249 getLLVMStyleWithColumns(40)); 9250 verifyFormat( 9251 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9252 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9253 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9254 } 9255 9256 TEST_F(FormatTest, UnderstandsEquals) { 9257 verifyFormat( 9258 "aaaaaaaaaaaaaaaaa =\n" 9259 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9260 verifyFormat( 9261 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9262 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9263 verifyFormat( 9264 "if (a) {\n" 9265 " f();\n" 9266 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9267 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9268 "}"); 9269 9270 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9271 " 100000000 + 10000000) {\n}"); 9272 } 9273 9274 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9275 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9276 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9277 9278 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9279 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9280 9281 verifyFormat( 9282 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9283 " Parameter2);"); 9284 9285 verifyFormat( 9286 "ShortObject->shortFunction(\n" 9287 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9288 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9289 9290 verifyFormat("loooooooooooooongFunction(\n" 9291 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9292 9293 verifyFormat( 9294 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9295 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9296 9297 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9298 " .WillRepeatedly(Return(SomeValue));"); 9299 verifyFormat("void f() {\n" 9300 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9301 " .Times(2)\n" 9302 " .WillRepeatedly(Return(SomeValue));\n" 9303 "}"); 9304 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9305 " ccccccccccccccccccccccc);"); 9306 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9308 " .aaaaa(aaaaa),\n" 9309 " aaaaaaaaaaaaaaaaaaaaa);"); 9310 verifyFormat("void f() {\n" 9311 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9312 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9313 "}"); 9314 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9316 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9317 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9318 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9319 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9320 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9321 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9322 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9323 "}"); 9324 9325 // Here, it is not necessary to wrap at "." or "->". 9326 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9327 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9328 verifyFormat( 9329 "aaaaaaaaaaa->aaaaaaaaa(\n" 9330 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9331 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9332 9333 verifyFormat( 9334 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9335 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9336 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9337 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9338 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9339 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9340 9341 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9342 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9343 " .a();"); 9344 9345 FormatStyle NoBinPacking = getLLVMStyle(); 9346 NoBinPacking.BinPackParameters = false; 9347 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9348 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9349 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9350 " aaaaaaaaaaaaaaaaaaa,\n" 9351 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9352 NoBinPacking); 9353 9354 // If there is a subsequent call, change to hanging indentation. 9355 verifyFormat( 9356 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9357 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9358 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9359 verifyFormat( 9360 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9361 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9362 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9363 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9364 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9365 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9367 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9368 } 9369 9370 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9371 verifyFormat("template <typename T>\n" 9372 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9373 verifyFormat("template <typename T>\n" 9374 "// T should be one of {A, B}.\n" 9375 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9376 verifyFormat( 9377 "template <typename T>\n" 9378 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9379 verifyFormat("template <typename T>\n" 9380 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9381 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9382 verifyFormat( 9383 "template <typename T>\n" 9384 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9385 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9386 verifyFormat( 9387 "template <typename T>\n" 9388 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9389 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9390 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9391 verifyFormat("template <typename T>\n" 9392 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9393 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9394 verifyFormat( 9395 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9396 " typename T4 = char>\n" 9397 "void f();"); 9398 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9399 " template <typename> class cccccccccccccccccccccc,\n" 9400 " typename ddddddddddddd>\n" 9401 "class C {};"); 9402 verifyFormat( 9403 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9404 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9405 9406 verifyFormat("void f() {\n" 9407 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9408 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9409 "}"); 9410 9411 verifyFormat("template <typename T> class C {};"); 9412 verifyFormat("template <typename T> void f();"); 9413 verifyFormat("template <typename T> void f() {}"); 9414 verifyFormat( 9415 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9416 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9418 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9419 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9420 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9421 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9422 getLLVMStyleWithColumns(72)); 9423 EXPECT_EQ("static_cast<A< //\n" 9424 " B> *>(\n" 9425 "\n" 9426 ");", 9427 format("static_cast<A<//\n" 9428 " B>*>(\n" 9429 "\n" 9430 " );")); 9431 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9432 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9433 9434 FormatStyle AlwaysBreak = getLLVMStyle(); 9435 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9436 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9437 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9438 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9439 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9440 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9441 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9442 verifyFormat("template <template <typename> class Fooooooo,\n" 9443 " template <typename> class Baaaaaaar>\n" 9444 "struct C {};", 9445 AlwaysBreak); 9446 verifyFormat("template <typename T> // T can be A, B or C.\n" 9447 "struct C {};", 9448 AlwaysBreak); 9449 verifyFormat("template <enum E> class A {\n" 9450 "public:\n" 9451 " E *f();\n" 9452 "};"); 9453 9454 FormatStyle NeverBreak = getLLVMStyle(); 9455 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9456 verifyFormat("template <typename T> class C {};", NeverBreak); 9457 verifyFormat("template <typename T> void f();", NeverBreak); 9458 verifyFormat("template <typename T> void f() {}", NeverBreak); 9459 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9460 "bbbbbbbbbbbbbbbbbbbb) {}", 9461 NeverBreak); 9462 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9463 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9464 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9465 NeverBreak); 9466 verifyFormat("template <template <typename> class Fooooooo,\n" 9467 " template <typename> class Baaaaaaar>\n" 9468 "struct C {};", 9469 NeverBreak); 9470 verifyFormat("template <typename T> // T can be A, B or C.\n" 9471 "struct C {};", 9472 NeverBreak); 9473 verifyFormat("template <enum E> class A {\n" 9474 "public:\n" 9475 " E *f();\n" 9476 "};", 9477 NeverBreak); 9478 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9479 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9480 "bbbbbbbbbbbbbbbbbbbb) {}", 9481 NeverBreak); 9482 } 9483 9484 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9485 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9486 Style.ColumnLimit = 60; 9487 EXPECT_EQ("// Baseline - no comments.\n" 9488 "template <\n" 9489 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9490 "void f() {}", 9491 format("// Baseline - no comments.\n" 9492 "template <\n" 9493 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9494 "void f() {}", 9495 Style)); 9496 9497 EXPECT_EQ("template <\n" 9498 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9499 "void f() {}", 9500 format("template <\n" 9501 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9502 "void f() {}", 9503 Style)); 9504 9505 EXPECT_EQ( 9506 "template <\n" 9507 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9508 "void f() {}", 9509 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9510 "void f() {}", 9511 Style)); 9512 9513 EXPECT_EQ( 9514 "template <\n" 9515 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9516 " // multiline\n" 9517 "void f() {}", 9518 format("template <\n" 9519 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9520 " // multiline\n" 9521 "void f() {}", 9522 Style)); 9523 9524 EXPECT_EQ( 9525 "template <typename aaaaaaaaaa<\n" 9526 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9527 "void f() {}", 9528 format( 9529 "template <\n" 9530 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9531 "void f() {}", 9532 Style)); 9533 } 9534 9535 TEST_F(FormatTest, WrapsTemplateParameters) { 9536 FormatStyle Style = getLLVMStyle(); 9537 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9538 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9539 verifyFormat( 9540 "template <typename... a> struct q {};\n" 9541 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9542 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9543 " y;", 9544 Style); 9545 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9546 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9547 verifyFormat( 9548 "template <typename... a> struct r {};\n" 9549 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9550 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9551 " y;", 9552 Style); 9553 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9554 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9555 verifyFormat("template <typename... a> struct s {};\n" 9556 "extern s<\n" 9557 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9558 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9559 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9560 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9561 " y;", 9562 Style); 9563 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9564 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9565 verifyFormat("template <typename... a> struct t {};\n" 9566 "extern t<\n" 9567 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9568 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9569 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9570 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9571 " y;", 9572 Style); 9573 } 9574 9575 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9576 verifyFormat( 9577 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9578 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9579 verifyFormat( 9580 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9581 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9582 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9583 9584 // FIXME: Should we have the extra indent after the second break? 9585 verifyFormat( 9586 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9587 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9588 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9589 9590 verifyFormat( 9591 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9592 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9593 9594 // Breaking at nested name specifiers is generally not desirable. 9595 verifyFormat( 9596 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9597 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9598 9599 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9600 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9601 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9602 " aaaaaaaaaaaaaaaaaaaaa);", 9603 getLLVMStyleWithColumns(74)); 9604 9605 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9606 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9607 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9608 } 9609 9610 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9611 verifyFormat("A<int> a;"); 9612 verifyFormat("A<A<A<int>>> a;"); 9613 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9614 verifyFormat("bool x = a < 1 || 2 > a;"); 9615 verifyFormat("bool x = 5 < f<int>();"); 9616 verifyFormat("bool x = f<int>() > 5;"); 9617 verifyFormat("bool x = 5 < a<int>::x;"); 9618 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9619 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9620 9621 verifyGoogleFormat("A<A<int>> a;"); 9622 verifyGoogleFormat("A<A<A<int>>> a;"); 9623 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9624 verifyGoogleFormat("A<A<int> > a;"); 9625 verifyGoogleFormat("A<A<A<int> > > a;"); 9626 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9627 verifyGoogleFormat("A<::A<int>> a;"); 9628 verifyGoogleFormat("A<::A> a;"); 9629 verifyGoogleFormat("A< ::A> a;"); 9630 verifyGoogleFormat("A< ::A<int> > a;"); 9631 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9632 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9633 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9634 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9635 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9636 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9637 9638 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9639 9640 // template closer followed by a token that starts with > or = 9641 verifyFormat("bool b = a<1> > 1;"); 9642 verifyFormat("bool b = a<1> >= 1;"); 9643 verifyFormat("int i = a<1> >> 1;"); 9644 FormatStyle Style = getLLVMStyle(); 9645 Style.SpaceBeforeAssignmentOperators = false; 9646 verifyFormat("bool b= a<1> == 1;", Style); 9647 verifyFormat("a<int> = 1;", Style); 9648 verifyFormat("a<int> >>= 1;", Style); 9649 9650 verifyFormat("test < a | b >> c;"); 9651 verifyFormat("test<test<a | b>> c;"); 9652 verifyFormat("test >> a >> b;"); 9653 verifyFormat("test << a >> b;"); 9654 9655 verifyFormat("f<int>();"); 9656 verifyFormat("template <typename T> void f() {}"); 9657 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9658 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9659 "sizeof(char)>::type>;"); 9660 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9661 verifyFormat("f(a.operator()<A>());"); 9662 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9663 " .template operator()<A>());", 9664 getLLVMStyleWithColumns(35)); 9665 verifyFormat("bool_constant<a && noexcept(f())>"); 9666 verifyFormat("bool_constant<a || noexcept(f())>"); 9667 9668 // Not template parameters. 9669 verifyFormat("return a < b && c > d;"); 9670 verifyFormat("void f() {\n" 9671 " while (a < b && c > d) {\n" 9672 " }\n" 9673 "}"); 9674 verifyFormat("template <typename... Types>\n" 9675 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9676 9677 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9678 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9679 getLLVMStyleWithColumns(60)); 9680 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9681 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9682 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9683 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9684 } 9685 9686 TEST_F(FormatTest, UnderstandsShiftOperators) { 9687 verifyFormat("if (i < x >> 1)"); 9688 verifyFormat("while (i < x >> 1)"); 9689 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9690 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9691 verifyFormat( 9692 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9693 verifyFormat("Foo.call<Bar<Function>>()"); 9694 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9695 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9696 "++i, v = v >> 1)"); 9697 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9698 } 9699 9700 TEST_F(FormatTest, BitshiftOperatorWidth) { 9701 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9702 " bar */", 9703 format("int a=1<<2; /* foo\n" 9704 " bar */")); 9705 9706 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9707 " bar */", 9708 format("int b =256>>1 ; /* foo\n" 9709 " bar */")); 9710 } 9711 9712 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9713 verifyFormat("COMPARE(a, ==, b);"); 9714 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9715 } 9716 9717 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9718 verifyFormat("int A::*x;"); 9719 verifyFormat("int (S::*func)(void *);"); 9720 verifyFormat("void f() { int (S::*func)(void *); }"); 9721 verifyFormat("typedef bool *(Class::*Member)() const;"); 9722 verifyFormat("void f() {\n" 9723 " (a->*f)();\n" 9724 " a->*x;\n" 9725 " (a.*f)();\n" 9726 " ((*a).*f)();\n" 9727 " a.*x;\n" 9728 "}"); 9729 verifyFormat("void f() {\n" 9730 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9731 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9732 "}"); 9733 verifyFormat( 9734 "(aaaaaaaaaa->*bbbbbbb)(\n" 9735 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9736 FormatStyle Style = getLLVMStyle(); 9737 Style.PointerAlignment = FormatStyle::PAS_Left; 9738 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9739 } 9740 9741 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9742 verifyFormat("int a = -2;"); 9743 verifyFormat("f(-1, -2, -3);"); 9744 verifyFormat("a[-1] = 5;"); 9745 verifyFormat("int a = 5 + -2;"); 9746 verifyFormat("if (i == -1) {\n}"); 9747 verifyFormat("if (i != -1) {\n}"); 9748 verifyFormat("if (i > -1) {\n}"); 9749 verifyFormat("if (i < -1) {\n}"); 9750 verifyFormat("++(a->f());"); 9751 verifyFormat("--(a->f());"); 9752 verifyFormat("(a->f())++;"); 9753 verifyFormat("a[42]++;"); 9754 verifyFormat("if (!(a->f())) {\n}"); 9755 verifyFormat("if (!+i) {\n}"); 9756 verifyFormat("~&a;"); 9757 9758 verifyFormat("a-- > b;"); 9759 verifyFormat("b ? -a : c;"); 9760 verifyFormat("n * sizeof char16;"); 9761 verifyFormat("n * alignof char16;", getGoogleStyle()); 9762 verifyFormat("sizeof(char);"); 9763 verifyFormat("alignof(char);", getGoogleStyle()); 9764 9765 verifyFormat("return -1;"); 9766 verifyFormat("throw -1;"); 9767 verifyFormat("switch (a) {\n" 9768 "case -1:\n" 9769 " break;\n" 9770 "}"); 9771 verifyFormat("#define X -1"); 9772 verifyFormat("#define X -kConstant"); 9773 9774 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9775 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9776 9777 verifyFormat("int a = /* confusing comment */ -1;"); 9778 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9779 verifyFormat("int a = i /* confusing comment */++;"); 9780 9781 verifyFormat("co_yield -1;"); 9782 verifyFormat("co_return -1;"); 9783 9784 // Check that * is not treated as a binary operator when we set 9785 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9786 FormatStyle PASLeftStyle = getLLVMStyle(); 9787 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9788 verifyFormat("co_return *a;", PASLeftStyle); 9789 verifyFormat("co_await *a;", PASLeftStyle); 9790 verifyFormat("co_yield *a", PASLeftStyle); 9791 verifyFormat("return *a;", PASLeftStyle); 9792 } 9793 9794 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9795 verifyFormat("if (!aaaaaaaaaa( // break\n" 9796 " aaaaa)) {\n" 9797 "}"); 9798 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9799 " aaaaa));"); 9800 verifyFormat("*aaa = aaaaaaa( // break\n" 9801 " bbbbbb);"); 9802 } 9803 9804 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9805 verifyFormat("bool operator<();"); 9806 verifyFormat("bool operator>();"); 9807 verifyFormat("bool operator=();"); 9808 verifyFormat("bool operator==();"); 9809 verifyFormat("bool operator!=();"); 9810 verifyFormat("int operator+();"); 9811 verifyFormat("int operator++();"); 9812 verifyFormat("int operator++(int) volatile noexcept;"); 9813 verifyFormat("bool operator,();"); 9814 verifyFormat("bool operator();"); 9815 verifyFormat("bool operator()();"); 9816 verifyFormat("bool operator[]();"); 9817 verifyFormat("operator bool();"); 9818 verifyFormat("operator int();"); 9819 verifyFormat("operator void *();"); 9820 verifyFormat("operator SomeType<int>();"); 9821 verifyFormat("operator SomeType<int, int>();"); 9822 verifyFormat("operator SomeType<SomeType<int>>();"); 9823 verifyFormat("operator< <>();"); 9824 verifyFormat("operator<< <>();"); 9825 verifyFormat("< <>"); 9826 9827 verifyFormat("void *operator new(std::size_t size);"); 9828 verifyFormat("void *operator new[](std::size_t size);"); 9829 verifyFormat("void operator delete(void *ptr);"); 9830 verifyFormat("void operator delete[](void *ptr);"); 9831 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9832 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9833 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9834 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9835 9836 verifyFormat( 9837 "ostream &operator<<(ostream &OutputStream,\n" 9838 " SomeReallyLongType WithSomeReallyLongValue);"); 9839 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9840 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9841 " return left.group < right.group;\n" 9842 "}"); 9843 verifyFormat("SomeType &operator=(const SomeType &S);"); 9844 verifyFormat("f.template operator()<int>();"); 9845 9846 verifyGoogleFormat("operator void*();"); 9847 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9848 verifyGoogleFormat("operator ::A();"); 9849 9850 verifyFormat("using A::operator+;"); 9851 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9852 "int i;"); 9853 9854 // Calling an operator as a member function. 9855 verifyFormat("void f() { a.operator*(); }"); 9856 verifyFormat("void f() { a.operator*(b & b); }"); 9857 verifyFormat("void f() { a->operator&(a * b); }"); 9858 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9859 // TODO: Calling an operator as a non-member function is hard to distinguish. 9860 // https://llvm.org/PR50629 9861 // verifyFormat("void f() { operator*(a & a); }"); 9862 // verifyFormat("void f() { operator&(a, b * b); }"); 9863 9864 verifyFormat("::operator delete(foo);"); 9865 verifyFormat("::operator new(n * sizeof(foo));"); 9866 verifyFormat("foo() { ::operator delete(foo); }"); 9867 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9868 } 9869 9870 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9871 verifyFormat("void A::b() && {}"); 9872 verifyFormat("void A::b() &&noexcept {}"); 9873 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9874 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9875 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9876 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9877 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9878 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9879 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9880 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9881 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9882 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9883 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9884 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9885 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9886 verifyFormat("void Fn(T const &) const &;"); 9887 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9888 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9889 verifyFormat("template <typename T>\n" 9890 "void F(T) && = delete;", 9891 getGoogleStyle()); 9892 verifyFormat("template <typename T> void operator=(T) &;"); 9893 verifyFormat("template <typename T> void operator=(T) const &;"); 9894 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9895 verifyFormat("template <typename T> void operator=(T) & = default;"); 9896 verifyFormat("template <typename T> void operator=(T) &&;"); 9897 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9898 verifyFormat("template <typename T> void operator=(T) & {}"); 9899 verifyFormat("template <typename T> void operator=(T) && {}"); 9900 9901 FormatStyle AlignLeft = getLLVMStyle(); 9902 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9903 verifyFormat("void A::b() && {}", AlignLeft); 9904 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9905 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9906 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9907 AlignLeft); 9908 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9909 AlignLeft); 9910 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9911 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9912 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9913 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9914 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9915 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9916 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9917 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9918 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9919 AlignLeft); 9920 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 9921 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 9922 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9923 AlignLeft); 9924 verifyFormat("template <typename T> void operator=(T) & = default;", 9925 AlignLeft); 9926 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9927 verifyFormat("template <typename T> void operator=(T) && = delete;", 9928 AlignLeft); 9929 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9930 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9931 9932 FormatStyle AlignMiddle = getLLVMStyle(); 9933 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9934 verifyFormat("void A::b() && {}", AlignMiddle); 9935 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9936 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9937 AlignMiddle); 9938 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9939 AlignMiddle); 9940 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9941 AlignMiddle); 9942 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9943 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9944 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9945 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9946 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9947 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9948 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9949 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9950 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9951 AlignMiddle); 9952 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 9953 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 9954 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9955 AlignMiddle); 9956 verifyFormat("template <typename T> void operator=(T) & = default;", 9957 AlignMiddle); 9958 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 9959 verifyFormat("template <typename T> void operator=(T) && = delete;", 9960 AlignMiddle); 9961 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 9962 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 9963 9964 FormatStyle Spaces = getLLVMStyle(); 9965 Spaces.SpacesInCStyleCastParentheses = true; 9966 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9967 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9968 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9969 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9970 9971 Spaces.SpacesInCStyleCastParentheses = false; 9972 Spaces.SpacesInParentheses = true; 9973 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9974 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9975 Spaces); 9976 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9977 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9978 9979 FormatStyle BreakTemplate = getLLVMStyle(); 9980 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9981 9982 verifyFormat("struct f {\n" 9983 " template <class T>\n" 9984 " int &foo(const std::string &str) &noexcept {}\n" 9985 "};", 9986 BreakTemplate); 9987 9988 verifyFormat("struct f {\n" 9989 " template <class T>\n" 9990 " int &foo(const std::string &str) &&noexcept {}\n" 9991 "};", 9992 BreakTemplate); 9993 9994 verifyFormat("struct f {\n" 9995 " template <class T>\n" 9996 " int &foo(const std::string &str) const &noexcept {}\n" 9997 "};", 9998 BreakTemplate); 9999 10000 verifyFormat("struct f {\n" 10001 " template <class T>\n" 10002 " int &foo(const std::string &str) const &noexcept {}\n" 10003 "};", 10004 BreakTemplate); 10005 10006 verifyFormat("struct f {\n" 10007 " template <class T>\n" 10008 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10009 "};", 10010 BreakTemplate); 10011 10012 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10013 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10014 FormatStyle::BTDS_Yes; 10015 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10016 10017 verifyFormat("struct f {\n" 10018 " template <class T>\n" 10019 " int& foo(const std::string& str) & noexcept {}\n" 10020 "};", 10021 AlignLeftBreakTemplate); 10022 10023 verifyFormat("struct f {\n" 10024 " template <class T>\n" 10025 " int& foo(const std::string& str) && noexcept {}\n" 10026 "};", 10027 AlignLeftBreakTemplate); 10028 10029 verifyFormat("struct f {\n" 10030 " template <class T>\n" 10031 " int& foo(const std::string& str) const& noexcept {}\n" 10032 "};", 10033 AlignLeftBreakTemplate); 10034 10035 verifyFormat("struct f {\n" 10036 " template <class T>\n" 10037 " int& foo(const std::string& str) const&& noexcept {}\n" 10038 "};", 10039 AlignLeftBreakTemplate); 10040 10041 verifyFormat("struct f {\n" 10042 " template <class T>\n" 10043 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10044 "};", 10045 AlignLeftBreakTemplate); 10046 10047 // The `&` in `Type&` should not be confused with a trailing `&` of 10048 // DEPRECATED(reason) member function. 10049 verifyFormat("struct f {\n" 10050 " template <class T>\n" 10051 " DEPRECATED(reason)\n" 10052 " Type &foo(arguments) {}\n" 10053 "};", 10054 BreakTemplate); 10055 10056 verifyFormat("struct f {\n" 10057 " template <class T>\n" 10058 " DEPRECATED(reason)\n" 10059 " Type& foo(arguments) {}\n" 10060 "};", 10061 AlignLeftBreakTemplate); 10062 10063 verifyFormat("void (*foopt)(int) = &func;"); 10064 10065 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10066 DerivePointerAlignment.DerivePointerAlignment = true; 10067 // There's always a space between the function and its trailing qualifiers. 10068 // This isn't evidence for PAS_Right (or for PAS_Left). 10069 std::string Prefix = "void a() &;\n" 10070 "void b() &;\n"; 10071 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10072 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10073 // Same if the function is an overloaded operator, and with &&. 10074 Prefix = "void operator()() &&;\n" 10075 "void operator()() &&;\n"; 10076 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10077 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10078 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10079 Prefix = "void a() const &;\n" 10080 "void b() const &;\n"; 10081 EXPECT_EQ(Prefix + "int *x;", 10082 format(Prefix + "int* x;", DerivePointerAlignment)); 10083 } 10084 10085 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10086 verifyFormat("void f() {\n" 10087 " A *a = new A;\n" 10088 " A *a = new (placement) A;\n" 10089 " delete a;\n" 10090 " delete (A *)a;\n" 10091 "}"); 10092 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10093 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10094 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10095 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10096 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10097 verifyFormat("delete[] h->p;"); 10098 verifyFormat("delete[] (void *)p;"); 10099 10100 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10101 verifyFormat("void operator new(void *foo) ATTRIB;"); 10102 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10103 verifyFormat("void operator delete(void *ptr) noexcept;"); 10104 10105 EXPECT_EQ("void new(link p);\n" 10106 "void delete(link p);\n", 10107 format("void new (link p);\n" 10108 "void delete (link p);\n")); 10109 } 10110 10111 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10112 verifyFormat("int *f(int *a) {}"); 10113 verifyFormat("int main(int argc, char **argv) {}"); 10114 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10115 verifyIndependentOfContext("f(a, *a);"); 10116 verifyFormat("void g() { f(*a); }"); 10117 verifyIndependentOfContext("int a = b * 10;"); 10118 verifyIndependentOfContext("int a = 10 * b;"); 10119 verifyIndependentOfContext("int a = b * c;"); 10120 verifyIndependentOfContext("int a += b * c;"); 10121 verifyIndependentOfContext("int a -= b * c;"); 10122 verifyIndependentOfContext("int a *= b * c;"); 10123 verifyIndependentOfContext("int a /= b * c;"); 10124 verifyIndependentOfContext("int a = *b;"); 10125 verifyIndependentOfContext("int a = *b * c;"); 10126 verifyIndependentOfContext("int a = b * *c;"); 10127 verifyIndependentOfContext("int a = b * (10);"); 10128 verifyIndependentOfContext("S << b * (10);"); 10129 verifyIndependentOfContext("return 10 * b;"); 10130 verifyIndependentOfContext("return *b * *c;"); 10131 verifyIndependentOfContext("return a & ~b;"); 10132 verifyIndependentOfContext("f(b ? *c : *d);"); 10133 verifyIndependentOfContext("int a = b ? *c : *d;"); 10134 verifyIndependentOfContext("*b = a;"); 10135 verifyIndependentOfContext("a * ~b;"); 10136 verifyIndependentOfContext("a * !b;"); 10137 verifyIndependentOfContext("a * +b;"); 10138 verifyIndependentOfContext("a * -b;"); 10139 verifyIndependentOfContext("a * ++b;"); 10140 verifyIndependentOfContext("a * --b;"); 10141 verifyIndependentOfContext("a[4] * b;"); 10142 verifyIndependentOfContext("a[a * a] = 1;"); 10143 verifyIndependentOfContext("f() * b;"); 10144 verifyIndependentOfContext("a * [self dostuff];"); 10145 verifyIndependentOfContext("int x = a * (a + b);"); 10146 verifyIndependentOfContext("(a *)(a + b);"); 10147 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10148 verifyIndependentOfContext("int *pa = (int *)&a;"); 10149 verifyIndependentOfContext("return sizeof(int **);"); 10150 verifyIndependentOfContext("return sizeof(int ******);"); 10151 verifyIndependentOfContext("return (int **&)a;"); 10152 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10153 verifyFormat("void f(Type (*parameter)[10]) {}"); 10154 verifyFormat("void f(Type (¶meter)[10]) {}"); 10155 verifyGoogleFormat("return sizeof(int**);"); 10156 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10157 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10158 verifyFormat("auto a = [](int **&, int ***) {};"); 10159 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10160 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10161 verifyFormat("[](const decltype(*a) &value) {}"); 10162 verifyFormat("[](const typeof(*a) &value) {}"); 10163 verifyFormat("[](const _Atomic(a *) &value) {}"); 10164 verifyFormat("[](const __underlying_type(a) &value) {}"); 10165 verifyFormat("decltype(a * b) F();"); 10166 verifyFormat("typeof(a * b) F();"); 10167 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10168 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10169 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10170 verifyIndependentOfContext("int i{a * b};"); 10171 verifyIndependentOfContext("aaa && aaa->f();"); 10172 verifyIndependentOfContext("int x = ~*p;"); 10173 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10174 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10175 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10176 verifyFormat("void f() { f(a, c * d); }"); 10177 verifyFormat("void f() { f(new a(), c * d); }"); 10178 verifyFormat("void f(const MyOverride &override);"); 10179 verifyFormat("void f(const MyFinal &final);"); 10180 verifyIndependentOfContext("bool a = f() && override.f();"); 10181 verifyIndependentOfContext("bool a = f() && final.f();"); 10182 10183 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10184 10185 verifyIndependentOfContext("A<int *> a;"); 10186 verifyIndependentOfContext("A<int **> a;"); 10187 verifyIndependentOfContext("A<int *, int *> a;"); 10188 verifyIndependentOfContext("A<int *[]> a;"); 10189 verifyIndependentOfContext( 10190 "const char *const p = reinterpret_cast<const char *const>(q);"); 10191 verifyIndependentOfContext("A<int **, int **> a;"); 10192 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10193 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10194 verifyFormat("for (; a && b;) {\n}"); 10195 verifyFormat("bool foo = true && [] { return false; }();"); 10196 10197 verifyFormat( 10198 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10200 10201 verifyGoogleFormat("int const* a = &b;"); 10202 verifyGoogleFormat("**outparam = 1;"); 10203 verifyGoogleFormat("*outparam = a * b;"); 10204 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10205 verifyGoogleFormat("A<int*> a;"); 10206 verifyGoogleFormat("A<int**> a;"); 10207 verifyGoogleFormat("A<int*, int*> a;"); 10208 verifyGoogleFormat("A<int**, int**> a;"); 10209 verifyGoogleFormat("f(b ? *c : *d);"); 10210 verifyGoogleFormat("int a = b ? *c : *d;"); 10211 verifyGoogleFormat("Type* t = **x;"); 10212 verifyGoogleFormat("Type* t = *++*x;"); 10213 verifyGoogleFormat("*++*x;"); 10214 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10215 verifyGoogleFormat("Type* t = x++ * y;"); 10216 verifyGoogleFormat( 10217 "const char* const p = reinterpret_cast<const char* const>(q);"); 10218 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10219 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10220 verifyGoogleFormat("template <typename T>\n" 10221 "void f(int i = 0, SomeType** temps = NULL);"); 10222 10223 FormatStyle Left = getLLVMStyle(); 10224 Left.PointerAlignment = FormatStyle::PAS_Left; 10225 verifyFormat("x = *a(x) = *a(y);", Left); 10226 verifyFormat("for (;; *a = b) {\n}", Left); 10227 verifyFormat("return *this += 1;", Left); 10228 verifyFormat("throw *x;", Left); 10229 verifyFormat("delete *x;", Left); 10230 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10231 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10232 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10233 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10234 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10235 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10236 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10237 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10238 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10239 10240 verifyIndependentOfContext("a = *(x + y);"); 10241 verifyIndependentOfContext("a = &(x + y);"); 10242 verifyIndependentOfContext("*(x + y).call();"); 10243 verifyIndependentOfContext("&(x + y)->call();"); 10244 verifyFormat("void f() { &(*I).first; }"); 10245 10246 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10247 verifyFormat("f(* /* confusing comment */ foo);"); 10248 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10249 verifyFormat("void foo(int * // this is the first paramters\n" 10250 " ,\n" 10251 " int second);"); 10252 verifyFormat("double term = a * // first\n" 10253 " b;"); 10254 verifyFormat( 10255 "int *MyValues = {\n" 10256 " *A, // Operator detection might be confused by the '{'\n" 10257 " *BB // Operator detection might be confused by previous comment\n" 10258 "};"); 10259 10260 verifyIndependentOfContext("if (int *a = &b)"); 10261 verifyIndependentOfContext("if (int &a = *b)"); 10262 verifyIndependentOfContext("if (a & b[i])"); 10263 verifyIndependentOfContext("if constexpr (a & b[i])"); 10264 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10265 verifyIndependentOfContext("if (a * (b * c))"); 10266 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10267 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10268 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10269 verifyIndependentOfContext("if (*b[i])"); 10270 verifyIndependentOfContext("if (int *a = (&b))"); 10271 verifyIndependentOfContext("while (int *a = &b)"); 10272 verifyIndependentOfContext("while (a * (b * c))"); 10273 verifyIndependentOfContext("size = sizeof *a;"); 10274 verifyIndependentOfContext("if (a && (b = c))"); 10275 verifyFormat("void f() {\n" 10276 " for (const int &v : Values) {\n" 10277 " }\n" 10278 "}"); 10279 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10280 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10281 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10282 10283 verifyFormat("#define A (!a * b)"); 10284 verifyFormat("#define MACRO \\\n" 10285 " int *i = a * b; \\\n" 10286 " void f(a *b);", 10287 getLLVMStyleWithColumns(19)); 10288 10289 verifyIndependentOfContext("A = new SomeType *[Length];"); 10290 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10291 verifyIndependentOfContext("T **t = new T *;"); 10292 verifyIndependentOfContext("T **t = new T *();"); 10293 verifyGoogleFormat("A = new SomeType*[Length]();"); 10294 verifyGoogleFormat("A = new SomeType*[Length];"); 10295 verifyGoogleFormat("T** t = new T*;"); 10296 verifyGoogleFormat("T** t = new T*();"); 10297 10298 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10299 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10300 verifyFormat("template <bool a, bool b> " 10301 "typename t::if<x && y>::type f() {}"); 10302 verifyFormat("template <int *y> f() {}"); 10303 verifyFormat("vector<int *> v;"); 10304 verifyFormat("vector<int *const> v;"); 10305 verifyFormat("vector<int *const **const *> v;"); 10306 verifyFormat("vector<int *volatile> v;"); 10307 verifyFormat("vector<a *_Nonnull> v;"); 10308 verifyFormat("vector<a *_Nullable> v;"); 10309 verifyFormat("vector<a *_Null_unspecified> v;"); 10310 verifyFormat("vector<a *__ptr32> v;"); 10311 verifyFormat("vector<a *__ptr64> v;"); 10312 verifyFormat("vector<a *__capability> v;"); 10313 FormatStyle TypeMacros = getLLVMStyle(); 10314 TypeMacros.TypenameMacros = {"LIST"}; 10315 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10316 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10317 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10318 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10319 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10320 10321 FormatStyle CustomQualifier = getLLVMStyle(); 10322 // Add identifiers that should not be parsed as a qualifier by default. 10323 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10324 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10325 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10326 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10327 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10328 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10329 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10330 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10331 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10332 verifyFormat("vector<a * _NotAQualifier> v;"); 10333 verifyFormat("vector<a * __not_a_qualifier> v;"); 10334 verifyFormat("vector<a * b> v;"); 10335 verifyFormat("foo<b && false>();"); 10336 verifyFormat("foo<b & 1>();"); 10337 verifyFormat("foo<b & (1)>();"); 10338 verifyFormat("foo<b & (~0)>();"); 10339 verifyFormat("foo<b & (true)>();"); 10340 verifyFormat("foo<b & ((1))>();"); 10341 verifyFormat("foo<b & (/*comment*/ 1)>();"); 10342 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10343 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10344 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10345 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10346 verifyFormat( 10347 "template <class T, class = typename std::enable_if<\n" 10348 " std::is_integral<T>::value &&\n" 10349 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10350 "void F();", 10351 getLLVMStyleWithColumns(70)); 10352 verifyFormat("template <class T,\n" 10353 " class = typename std::enable_if<\n" 10354 " std::is_integral<T>::value &&\n" 10355 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10356 " class U>\n" 10357 "void F();", 10358 getLLVMStyleWithColumns(70)); 10359 verifyFormat( 10360 "template <class T,\n" 10361 " class = typename ::std::enable_if<\n" 10362 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10363 "void F();", 10364 getGoogleStyleWithColumns(68)); 10365 10366 verifyIndependentOfContext("MACRO(int *i);"); 10367 verifyIndependentOfContext("MACRO(auto *a);"); 10368 verifyIndependentOfContext("MACRO(const A *a);"); 10369 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10370 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10371 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10372 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10373 verifyIndependentOfContext("MACRO(A *const a);"); 10374 verifyIndependentOfContext("MACRO(A *restrict a);"); 10375 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10376 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10377 verifyIndependentOfContext("MACRO(A *volatile a);"); 10378 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10379 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10380 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10381 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10382 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10383 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10384 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10385 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10386 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10387 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10388 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10389 verifyIndependentOfContext("MACRO(A *__capability);"); 10390 verifyIndependentOfContext("MACRO(A &__capability);"); 10391 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10392 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10393 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10394 // a type declaration: 10395 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10396 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10397 // Also check that TypenameMacros prevents parsing it as multiplication: 10398 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10399 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10400 10401 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10402 verifyFormat("void f() { f(float{1}, a * a); }"); 10403 verifyFormat("void f() { f(float(1), a * a); }"); 10404 10405 verifyFormat("f((void (*)(int))g);"); 10406 verifyFormat("f((void (&)(int))g);"); 10407 verifyFormat("f((void (^)(int))g);"); 10408 10409 // FIXME: Is there a way to make this work? 10410 // verifyIndependentOfContext("MACRO(A *a);"); 10411 verifyFormat("MACRO(A &B);"); 10412 verifyFormat("MACRO(A *B);"); 10413 verifyFormat("void f() { MACRO(A * B); }"); 10414 verifyFormat("void f() { MACRO(A & B); }"); 10415 10416 // This lambda was mis-formatted after D88956 (treating it as a binop): 10417 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10418 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10419 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10420 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10421 10422 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10423 verifyFormat("return options != nullptr && operator==(*options);"); 10424 10425 EXPECT_EQ("#define OP(x) \\\n" 10426 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10427 " return s << a.DebugString(); \\\n" 10428 " }", 10429 format("#define OP(x) \\\n" 10430 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10431 " return s << a.DebugString(); \\\n" 10432 " }", 10433 getLLVMStyleWithColumns(50))); 10434 10435 // FIXME: We cannot handle this case yet; we might be able to figure out that 10436 // foo<x> d > v; doesn't make sense. 10437 verifyFormat("foo<a<b && c> d> v;"); 10438 10439 FormatStyle PointerMiddle = getLLVMStyle(); 10440 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10441 verifyFormat("delete *x;", PointerMiddle); 10442 verifyFormat("int * x;", PointerMiddle); 10443 verifyFormat("int *[] x;", PointerMiddle); 10444 verifyFormat("template <int * y> f() {}", PointerMiddle); 10445 verifyFormat("int * f(int * a) {}", PointerMiddle); 10446 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10447 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10448 verifyFormat("A<int *> a;", PointerMiddle); 10449 verifyFormat("A<int **> a;", PointerMiddle); 10450 verifyFormat("A<int *, int *> a;", PointerMiddle); 10451 verifyFormat("A<int *[]> a;", PointerMiddle); 10452 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10453 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10454 verifyFormat("T ** t = new T *;", PointerMiddle); 10455 10456 // Member function reference qualifiers aren't binary operators. 10457 verifyFormat("string // break\n" 10458 "operator()() & {}"); 10459 verifyFormat("string // break\n" 10460 "operator()() && {}"); 10461 verifyGoogleFormat("template <typename T>\n" 10462 "auto x() & -> int {}"); 10463 10464 // Should be binary operators when used as an argument expression (overloaded 10465 // operator invoked as a member function). 10466 verifyFormat("void f() { a.operator()(a * a); }"); 10467 verifyFormat("void f() { a->operator()(a & a); }"); 10468 verifyFormat("void f() { a.operator()(*a & *a); }"); 10469 verifyFormat("void f() { a->operator()(*a * *a); }"); 10470 10471 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10472 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10473 } 10474 10475 TEST_F(FormatTest, UnderstandsAttributes) { 10476 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10477 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10478 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10479 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10480 FormatStyle AfterType = getLLVMStyle(); 10481 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10482 verifyFormat("__attribute__((nodebug)) void\n" 10483 "foo() {}\n", 10484 AfterType); 10485 verifyFormat("__unused void\n" 10486 "foo() {}", 10487 AfterType); 10488 10489 FormatStyle CustomAttrs = getLLVMStyle(); 10490 CustomAttrs.AttributeMacros.push_back("__unused"); 10491 CustomAttrs.AttributeMacros.push_back("__attr1"); 10492 CustomAttrs.AttributeMacros.push_back("__attr2"); 10493 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10494 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10495 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10496 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10497 // Check that it is parsed as a multiplication without AttributeMacros and 10498 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10499 verifyFormat("vector<SomeType * __attr1> v;"); 10500 verifyFormat("vector<SomeType __attr1 *> v;"); 10501 verifyFormat("vector<SomeType __attr1 *const> v;"); 10502 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10503 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10504 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10505 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10506 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10507 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10508 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10509 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10510 10511 // Check that these are not parsed as function declarations: 10512 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10513 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10514 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10515 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10516 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10517 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10518 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10519 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10520 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10521 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10522 } 10523 10524 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10525 // Check that qualifiers on pointers don't break parsing of casts. 10526 verifyFormat("x = (foo *const)*v;"); 10527 verifyFormat("x = (foo *volatile)*v;"); 10528 verifyFormat("x = (foo *restrict)*v;"); 10529 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10530 verifyFormat("x = (foo *_Nonnull)*v;"); 10531 verifyFormat("x = (foo *_Nullable)*v;"); 10532 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10533 verifyFormat("x = (foo *_Nonnull)*v;"); 10534 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10535 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10536 verifyFormat("x = (foo *__ptr32)*v;"); 10537 verifyFormat("x = (foo *__ptr64)*v;"); 10538 verifyFormat("x = (foo *__capability)*v;"); 10539 10540 // Check that we handle multiple trailing qualifiers and skip them all to 10541 // determine that the expression is a cast to a pointer type. 10542 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10543 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10544 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10545 StringRef AllQualifiers = 10546 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10547 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10548 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10549 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10550 10551 // Also check that address-of is not parsed as a binary bitwise-and: 10552 verifyFormat("x = (foo *const)&v;"); 10553 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10554 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10555 10556 // Check custom qualifiers: 10557 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10558 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10559 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10560 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10561 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10562 CustomQualifier); 10563 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10564 CustomQualifier); 10565 10566 // Check that unknown identifiers result in binary operator parsing: 10567 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10568 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10569 } 10570 10571 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10572 verifyFormat("SomeType s [[unused]] (InitValue);"); 10573 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10574 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10575 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10576 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10577 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10578 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10579 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10580 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10581 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10582 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10583 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10584 10585 // Make sure we do not mistake attributes for array subscripts. 10586 verifyFormat("int a() {}\n" 10587 "[[unused]] int b() {}\n"); 10588 verifyFormat("NSArray *arr;\n" 10589 "arr[[Foo() bar]];"); 10590 10591 // On the other hand, we still need to correctly find array subscripts. 10592 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10593 10594 // Make sure that we do not mistake Objective-C method inside array literals 10595 // as attributes, even if those method names are also keywords. 10596 verifyFormat("@[ [foo bar] ];"); 10597 verifyFormat("@[ [NSArray class] ];"); 10598 verifyFormat("@[ [foo enum] ];"); 10599 10600 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10601 10602 // Make sure we do not parse attributes as lambda introducers. 10603 FormatStyle MultiLineFunctions = getLLVMStyle(); 10604 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10605 verifyFormat("[[unused]] int b() {\n" 10606 " return 42;\n" 10607 "}\n", 10608 MultiLineFunctions); 10609 } 10610 10611 TEST_F(FormatTest, AttributeClass) { 10612 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10613 verifyFormat("class S {\n" 10614 " S(S&&) = default;\n" 10615 "};", 10616 Style); 10617 verifyFormat("class [[nodiscard]] S {\n" 10618 " S(S&&) = default;\n" 10619 "};", 10620 Style); 10621 verifyFormat("class __attribute((maybeunused)) S {\n" 10622 " S(S&&) = default;\n" 10623 "};", 10624 Style); 10625 verifyFormat("struct S {\n" 10626 " S(S&&) = default;\n" 10627 "};", 10628 Style); 10629 verifyFormat("struct [[nodiscard]] S {\n" 10630 " S(S&&) = default;\n" 10631 "};", 10632 Style); 10633 } 10634 10635 TEST_F(FormatTest, AttributesAfterMacro) { 10636 FormatStyle Style = getLLVMStyle(); 10637 verifyFormat("MACRO;\n" 10638 "__attribute__((maybe_unused)) int foo() {\n" 10639 " //...\n" 10640 "}"); 10641 10642 verifyFormat("MACRO;\n" 10643 "[[nodiscard]] int foo() {\n" 10644 " //...\n" 10645 "}"); 10646 10647 EXPECT_EQ("MACRO\n\n" 10648 "__attribute__((maybe_unused)) int foo() {\n" 10649 " //...\n" 10650 "}", 10651 format("MACRO\n\n" 10652 "__attribute__((maybe_unused)) int foo() {\n" 10653 " //...\n" 10654 "}")); 10655 10656 EXPECT_EQ("MACRO\n\n" 10657 "[[nodiscard]] int foo() {\n" 10658 " //...\n" 10659 "}", 10660 format("MACRO\n\n" 10661 "[[nodiscard]] int foo() {\n" 10662 " //...\n" 10663 "}")); 10664 } 10665 10666 TEST_F(FormatTest, AttributePenaltyBreaking) { 10667 FormatStyle Style = getLLVMStyle(); 10668 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10669 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10670 Style); 10671 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10672 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10673 Style); 10674 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10675 "shared_ptr<ALongTypeName> &C d) {\n}", 10676 Style); 10677 } 10678 10679 TEST_F(FormatTest, UnderstandsEllipsis) { 10680 FormatStyle Style = getLLVMStyle(); 10681 verifyFormat("int printf(const char *fmt, ...);"); 10682 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10683 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10684 10685 verifyFormat("template <int *...PP> a;", Style); 10686 10687 Style.PointerAlignment = FormatStyle::PAS_Left; 10688 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10689 10690 verifyFormat("template <int*... PP> a;", Style); 10691 10692 Style.PointerAlignment = FormatStyle::PAS_Middle; 10693 verifyFormat("template <int *... PP> a;", Style); 10694 } 10695 10696 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10697 EXPECT_EQ("int *a;\n" 10698 "int *a;\n" 10699 "int *a;", 10700 format("int *a;\n" 10701 "int* a;\n" 10702 "int *a;", 10703 getGoogleStyle())); 10704 EXPECT_EQ("int* a;\n" 10705 "int* a;\n" 10706 "int* a;", 10707 format("int* a;\n" 10708 "int* a;\n" 10709 "int *a;", 10710 getGoogleStyle())); 10711 EXPECT_EQ("int *a;\n" 10712 "int *a;\n" 10713 "int *a;", 10714 format("int *a;\n" 10715 "int * a;\n" 10716 "int * a;", 10717 getGoogleStyle())); 10718 EXPECT_EQ("auto x = [] {\n" 10719 " int *a;\n" 10720 " int *a;\n" 10721 " int *a;\n" 10722 "};", 10723 format("auto x=[]{int *a;\n" 10724 "int * a;\n" 10725 "int * a;};", 10726 getGoogleStyle())); 10727 } 10728 10729 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10730 verifyFormat("int f(int &&a) {}"); 10731 verifyFormat("int f(int a, char &&b) {}"); 10732 verifyFormat("void f() { int &&a = b; }"); 10733 verifyGoogleFormat("int f(int a, char&& b) {}"); 10734 verifyGoogleFormat("void f() { int&& a = b; }"); 10735 10736 verifyIndependentOfContext("A<int &&> a;"); 10737 verifyIndependentOfContext("A<int &&, int &&> a;"); 10738 verifyGoogleFormat("A<int&&> a;"); 10739 verifyGoogleFormat("A<int&&, int&&> a;"); 10740 10741 // Not rvalue references: 10742 verifyFormat("template <bool B, bool C> class A {\n" 10743 " static_assert(B && C, \"Something is wrong\");\n" 10744 "};"); 10745 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10746 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10747 verifyFormat("#define A(a, b) (a && b)"); 10748 } 10749 10750 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10751 verifyFormat("void f() {\n" 10752 " x[aaaaaaaaa -\n" 10753 " b] = 23;\n" 10754 "}", 10755 getLLVMStyleWithColumns(15)); 10756 } 10757 10758 TEST_F(FormatTest, FormatsCasts) { 10759 verifyFormat("Type *A = static_cast<Type *>(P);"); 10760 verifyFormat("static_cast<Type *>(P);"); 10761 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10762 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10763 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10764 // Check that static_cast<...>(...) does not require the next token to be on 10765 // the same line. 10766 verifyFormat("some_loooong_output << something_something__ << " 10767 "static_cast<const void *>(R)\n" 10768 " << something;"); 10769 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10770 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10771 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10772 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10773 verifyFormat("Type *A = (Type *)P;"); 10774 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10775 verifyFormat("int a = (int)(2.0f);"); 10776 verifyFormat("int a = (int)2.0f;"); 10777 verifyFormat("x[(int32)y];"); 10778 verifyFormat("x = (int32)y;"); 10779 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10780 verifyFormat("int a = (int)*b;"); 10781 verifyFormat("int a = (int)2.0f;"); 10782 verifyFormat("int a = (int)~0;"); 10783 verifyFormat("int a = (int)++a;"); 10784 verifyFormat("int a = (int)sizeof(int);"); 10785 verifyFormat("int a = (int)+2;"); 10786 verifyFormat("my_int a = (my_int)2.0f;"); 10787 verifyFormat("my_int a = (my_int)sizeof(int);"); 10788 verifyFormat("return (my_int)aaa;"); 10789 verifyFormat("#define x ((int)-1)"); 10790 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10791 verifyFormat("#define p(q) ((int *)&q)"); 10792 verifyFormat("fn(a)(b) + 1;"); 10793 10794 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10795 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10796 verifyFormat("my_int a = (my_int)~0;"); 10797 verifyFormat("my_int a = (my_int)++a;"); 10798 verifyFormat("my_int a = (my_int)-2;"); 10799 verifyFormat("my_int a = (my_int)1;"); 10800 verifyFormat("my_int a = (my_int *)1;"); 10801 verifyFormat("my_int a = (const my_int)-1;"); 10802 verifyFormat("my_int a = (const my_int *)-1;"); 10803 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10804 verifyFormat("my_int a = (ns::my_int)-2;"); 10805 verifyFormat("case (my_int)ONE:"); 10806 verifyFormat("auto x = (X)this;"); 10807 // Casts in Obj-C style calls used to not be recognized as such. 10808 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10809 10810 // FIXME: single value wrapped with paren will be treated as cast. 10811 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10812 10813 verifyFormat("{ (void)F; }"); 10814 10815 // Don't break after a cast's 10816 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10817 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10818 " bbbbbbbbbbbbbbbbbbbbbb);"); 10819 10820 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10821 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10822 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10823 verifyFormat("bool *y = (bool *)(void *)(x);"); 10824 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10825 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10826 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10827 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10828 10829 // These are not casts. 10830 verifyFormat("void f(int *) {}"); 10831 verifyFormat("f(foo)->b;"); 10832 verifyFormat("f(foo).b;"); 10833 verifyFormat("f(foo)(b);"); 10834 verifyFormat("f(foo)[b];"); 10835 verifyFormat("[](foo) { return 4; }(bar);"); 10836 verifyFormat("(*funptr)(foo)[4];"); 10837 verifyFormat("funptrs[4](foo)[4];"); 10838 verifyFormat("void f(int *);"); 10839 verifyFormat("void f(int *) = 0;"); 10840 verifyFormat("void f(SmallVector<int>) {}"); 10841 verifyFormat("void f(SmallVector<int>);"); 10842 verifyFormat("void f(SmallVector<int>) = 0;"); 10843 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10844 verifyFormat("int a = sizeof(int) * b;"); 10845 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10846 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10847 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10848 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10849 10850 // These are not casts, but at some point were confused with casts. 10851 verifyFormat("virtual void foo(int *) override;"); 10852 verifyFormat("virtual void foo(char &) const;"); 10853 verifyFormat("virtual void foo(int *a, char *) const;"); 10854 verifyFormat("int a = sizeof(int *) + b;"); 10855 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10856 verifyFormat("bool b = f(g<int>) && c;"); 10857 verifyFormat("typedef void (*f)(int i) func;"); 10858 verifyFormat("void operator++(int) noexcept;"); 10859 verifyFormat("void operator++(int &) noexcept;"); 10860 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10861 "&) noexcept;"); 10862 verifyFormat( 10863 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10864 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10865 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10866 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10867 verifyFormat("void operator delete(foo &) noexcept;"); 10868 verifyFormat("void operator delete(foo) noexcept;"); 10869 verifyFormat("void operator delete(int) noexcept;"); 10870 verifyFormat("void operator delete(int &) noexcept;"); 10871 verifyFormat("void operator delete(int &) volatile noexcept;"); 10872 verifyFormat("void operator delete(int &) const"); 10873 verifyFormat("void operator delete(int &) = default"); 10874 verifyFormat("void operator delete(int &) = delete"); 10875 verifyFormat("void operator delete(int &) [[noreturn]]"); 10876 verifyFormat("void operator delete(int &) throw();"); 10877 verifyFormat("void operator delete(int &) throw(int);"); 10878 verifyFormat("auto operator delete(int &) -> int;"); 10879 verifyFormat("auto operator delete(int &) override"); 10880 verifyFormat("auto operator delete(int &) final"); 10881 10882 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10883 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10884 // FIXME: The indentation here is not ideal. 10885 verifyFormat( 10886 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10887 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10888 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10889 } 10890 10891 TEST_F(FormatTest, FormatsFunctionTypes) { 10892 verifyFormat("A<bool()> a;"); 10893 verifyFormat("A<SomeType()> a;"); 10894 verifyFormat("A<void (*)(int, std::string)> a;"); 10895 verifyFormat("A<void *(int)>;"); 10896 verifyFormat("void *(*a)(int *, SomeType *);"); 10897 verifyFormat("int (*func)(void *);"); 10898 verifyFormat("void f() { int (*func)(void *); }"); 10899 verifyFormat("template <class CallbackClass>\n" 10900 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10901 10902 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10903 verifyGoogleFormat("void* (*a)(int);"); 10904 verifyGoogleFormat( 10905 "template <class CallbackClass>\n" 10906 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10907 10908 // Other constructs can look somewhat like function types: 10909 verifyFormat("A<sizeof(*x)> a;"); 10910 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10911 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10912 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10913 verifyFormat("int x = f(&h)();"); 10914 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10915 verifyFormat("std::function<\n" 10916 " LooooooooooongTemplatedType<\n" 10917 " SomeType>*(\n" 10918 " LooooooooooooooooongType type)>\n" 10919 " function;", 10920 getGoogleStyleWithColumns(40)); 10921 } 10922 10923 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10924 verifyFormat("A (*foo_)[6];"); 10925 verifyFormat("vector<int> (*foo_)[6];"); 10926 } 10927 10928 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10929 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10930 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10931 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10932 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10933 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10934 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10935 10936 // Different ways of ()-initializiation. 10937 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10938 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10939 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10940 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10941 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10942 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10943 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10944 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10945 10946 // Lambdas should not confuse the variable declaration heuristic. 10947 verifyFormat("LooooooooooooooooongType\n" 10948 " variable(nullptr, [](A *a) {});", 10949 getLLVMStyleWithColumns(40)); 10950 } 10951 10952 TEST_F(FormatTest, BreaksLongDeclarations) { 10953 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10954 " AnotherNameForTheLongType;"); 10955 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10956 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10957 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10958 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10959 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10960 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10961 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10962 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10963 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10964 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10965 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10966 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10967 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10968 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10969 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10970 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10971 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10972 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10973 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10974 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10975 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10976 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10977 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10978 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10979 FormatStyle Indented = getLLVMStyle(); 10980 Indented.IndentWrappedFunctionNames = true; 10981 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10982 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10983 Indented); 10984 verifyFormat( 10985 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10986 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10987 Indented); 10988 verifyFormat( 10989 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10990 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10991 Indented); 10992 verifyFormat( 10993 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10994 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10995 Indented); 10996 10997 // FIXME: Without the comment, this breaks after "(". 10998 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10999 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 11000 getGoogleStyle()); 11001 11002 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 11003 " int LoooooooooooooooooooongParam2) {}"); 11004 verifyFormat( 11005 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 11006 " SourceLocation L, IdentifierIn *II,\n" 11007 " Type *T) {}"); 11008 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 11009 "ReallyReaaallyLongFunctionName(\n" 11010 " const std::string &SomeParameter,\n" 11011 " const SomeType<string, SomeOtherTemplateParameter>\n" 11012 " &ReallyReallyLongParameterName,\n" 11013 " const SomeType<string, SomeOtherTemplateParameter>\n" 11014 " &AnotherLongParameterName) {}"); 11015 verifyFormat("template <typename A>\n" 11016 "SomeLoooooooooooooooooooooongType<\n" 11017 " typename some_namespace::SomeOtherType<A>::Type>\n" 11018 "Function() {}"); 11019 11020 verifyGoogleFormat( 11021 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11022 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11023 verifyGoogleFormat( 11024 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11025 " SourceLocation L) {}"); 11026 verifyGoogleFormat( 11027 "some_namespace::LongReturnType\n" 11028 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11029 " int first_long_parameter, int second_parameter) {}"); 11030 11031 verifyGoogleFormat("template <typename T>\n" 11032 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11033 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11034 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11035 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11036 11037 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11038 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11039 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11040 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11041 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11042 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11043 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11044 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11045 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11046 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11047 11048 verifyFormat("template <typename T> // Templates on own line.\n" 11049 "static int // Some comment.\n" 11050 "MyFunction(int a);", 11051 getLLVMStyle()); 11052 } 11053 11054 TEST_F(FormatTest, FormatsAccessModifiers) { 11055 FormatStyle Style = getLLVMStyle(); 11056 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11057 FormatStyle::ELBAMS_LogicalBlock); 11058 verifyFormat("struct foo {\n" 11059 "private:\n" 11060 " void f() {}\n" 11061 "\n" 11062 "private:\n" 11063 " int i;\n" 11064 "\n" 11065 "protected:\n" 11066 " int j;\n" 11067 "};\n", 11068 Style); 11069 verifyFormat("struct foo {\n" 11070 "private:\n" 11071 " void f() {}\n" 11072 "\n" 11073 "private:\n" 11074 " int i;\n" 11075 "\n" 11076 "protected:\n" 11077 " int j;\n" 11078 "};\n", 11079 "struct foo {\n" 11080 "private:\n" 11081 " void f() {}\n" 11082 "private:\n" 11083 " int i;\n" 11084 "protected:\n" 11085 " int j;\n" 11086 "};\n", 11087 Style); 11088 verifyFormat("struct foo { /* comment */\n" 11089 "private:\n" 11090 " int i;\n" 11091 " // comment\n" 11092 "private:\n" 11093 " int j;\n" 11094 "};\n", 11095 Style); 11096 verifyFormat("struct foo {\n" 11097 "#ifdef FOO\n" 11098 "#endif\n" 11099 "private:\n" 11100 " int i;\n" 11101 "#ifdef FOO\n" 11102 "private:\n" 11103 "#endif\n" 11104 " int j;\n" 11105 "};\n", 11106 Style); 11107 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11108 verifyFormat("struct foo {\n" 11109 "private:\n" 11110 " void f() {}\n" 11111 "private:\n" 11112 " int i;\n" 11113 "protected:\n" 11114 " int j;\n" 11115 "};\n", 11116 Style); 11117 verifyFormat("struct foo {\n" 11118 "private:\n" 11119 " void f() {}\n" 11120 "private:\n" 11121 " int i;\n" 11122 "protected:\n" 11123 " int j;\n" 11124 "};\n", 11125 "struct foo {\n" 11126 "\n" 11127 "private:\n" 11128 " void f() {}\n" 11129 "\n" 11130 "private:\n" 11131 " int i;\n" 11132 "\n" 11133 "protected:\n" 11134 " int j;\n" 11135 "};\n", 11136 Style); 11137 verifyFormat("struct foo { /* comment */\n" 11138 "private:\n" 11139 " int i;\n" 11140 " // comment\n" 11141 "private:\n" 11142 " int j;\n" 11143 "};\n", 11144 "struct foo { /* comment */\n" 11145 "\n" 11146 "private:\n" 11147 " int i;\n" 11148 " // comment\n" 11149 "\n" 11150 "private:\n" 11151 " int j;\n" 11152 "};\n", 11153 Style); 11154 verifyFormat("struct foo {\n" 11155 "#ifdef FOO\n" 11156 "#endif\n" 11157 "private:\n" 11158 " int i;\n" 11159 "#ifdef FOO\n" 11160 "private:\n" 11161 "#endif\n" 11162 " int j;\n" 11163 "};\n", 11164 "struct foo {\n" 11165 "#ifdef FOO\n" 11166 "#endif\n" 11167 "\n" 11168 "private:\n" 11169 " int i;\n" 11170 "#ifdef FOO\n" 11171 "\n" 11172 "private:\n" 11173 "#endif\n" 11174 " int j;\n" 11175 "};\n", 11176 Style); 11177 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11178 verifyFormat("struct foo {\n" 11179 "private:\n" 11180 " void f() {}\n" 11181 "\n" 11182 "private:\n" 11183 " int i;\n" 11184 "\n" 11185 "protected:\n" 11186 " int j;\n" 11187 "};\n", 11188 Style); 11189 verifyFormat("struct foo {\n" 11190 "private:\n" 11191 " void f() {}\n" 11192 "\n" 11193 "private:\n" 11194 " int i;\n" 11195 "\n" 11196 "protected:\n" 11197 " int j;\n" 11198 "};\n", 11199 "struct foo {\n" 11200 "private:\n" 11201 " void f() {}\n" 11202 "private:\n" 11203 " int i;\n" 11204 "protected:\n" 11205 " int j;\n" 11206 "};\n", 11207 Style); 11208 verifyFormat("struct foo { /* comment */\n" 11209 "private:\n" 11210 " int i;\n" 11211 " // comment\n" 11212 "\n" 11213 "private:\n" 11214 " int j;\n" 11215 "};\n", 11216 "struct foo { /* comment */\n" 11217 "private:\n" 11218 " int i;\n" 11219 " // comment\n" 11220 "\n" 11221 "private:\n" 11222 " int j;\n" 11223 "};\n", 11224 Style); 11225 verifyFormat("struct foo {\n" 11226 "#ifdef FOO\n" 11227 "#endif\n" 11228 "\n" 11229 "private:\n" 11230 " int i;\n" 11231 "#ifdef FOO\n" 11232 "\n" 11233 "private:\n" 11234 "#endif\n" 11235 " int j;\n" 11236 "};\n", 11237 "struct foo {\n" 11238 "#ifdef FOO\n" 11239 "#endif\n" 11240 "private:\n" 11241 " int i;\n" 11242 "#ifdef FOO\n" 11243 "private:\n" 11244 "#endif\n" 11245 " int j;\n" 11246 "};\n", 11247 Style); 11248 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11249 EXPECT_EQ("struct foo {\n" 11250 "\n" 11251 "private:\n" 11252 " void f() {}\n" 11253 "\n" 11254 "private:\n" 11255 " int i;\n" 11256 "\n" 11257 "protected:\n" 11258 " int j;\n" 11259 "};\n", 11260 format("struct foo {\n" 11261 "\n" 11262 "private:\n" 11263 " void f() {}\n" 11264 "\n" 11265 "private:\n" 11266 " int i;\n" 11267 "\n" 11268 "protected:\n" 11269 " int j;\n" 11270 "};\n", 11271 Style)); 11272 verifyFormat("struct foo {\n" 11273 "private:\n" 11274 " void f() {}\n" 11275 "private:\n" 11276 " int i;\n" 11277 "protected:\n" 11278 " int j;\n" 11279 "};\n", 11280 Style); 11281 EXPECT_EQ("struct foo { /* comment */\n" 11282 "\n" 11283 "private:\n" 11284 " int i;\n" 11285 " // comment\n" 11286 "\n" 11287 "private:\n" 11288 " int j;\n" 11289 "};\n", 11290 format("struct foo { /* comment */\n" 11291 "\n" 11292 "private:\n" 11293 " int i;\n" 11294 " // comment\n" 11295 "\n" 11296 "private:\n" 11297 " int j;\n" 11298 "};\n", 11299 Style)); 11300 verifyFormat("struct foo { /* comment */\n" 11301 "private:\n" 11302 " int i;\n" 11303 " // comment\n" 11304 "private:\n" 11305 " int j;\n" 11306 "};\n", 11307 Style); 11308 EXPECT_EQ("struct foo {\n" 11309 "#ifdef FOO\n" 11310 "#endif\n" 11311 "\n" 11312 "private:\n" 11313 " int i;\n" 11314 "#ifdef FOO\n" 11315 "\n" 11316 "private:\n" 11317 "#endif\n" 11318 " int j;\n" 11319 "};\n", 11320 format("struct foo {\n" 11321 "#ifdef FOO\n" 11322 "#endif\n" 11323 "\n" 11324 "private:\n" 11325 " int i;\n" 11326 "#ifdef FOO\n" 11327 "\n" 11328 "private:\n" 11329 "#endif\n" 11330 " int j;\n" 11331 "};\n", 11332 Style)); 11333 verifyFormat("struct foo {\n" 11334 "#ifdef FOO\n" 11335 "#endif\n" 11336 "private:\n" 11337 " int i;\n" 11338 "#ifdef FOO\n" 11339 "private:\n" 11340 "#endif\n" 11341 " int j;\n" 11342 "};\n", 11343 Style); 11344 11345 FormatStyle NoEmptyLines = getLLVMStyle(); 11346 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11347 verifyFormat("struct foo {\n" 11348 "private:\n" 11349 " void f() {}\n" 11350 "\n" 11351 "private:\n" 11352 " int i;\n" 11353 "\n" 11354 "public:\n" 11355 "protected:\n" 11356 " int j;\n" 11357 "};\n", 11358 NoEmptyLines); 11359 11360 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11361 verifyFormat("struct foo {\n" 11362 "private:\n" 11363 " void f() {}\n" 11364 "private:\n" 11365 " int i;\n" 11366 "public:\n" 11367 "protected:\n" 11368 " int j;\n" 11369 "};\n", 11370 NoEmptyLines); 11371 11372 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11373 verifyFormat("struct foo {\n" 11374 "private:\n" 11375 " void f() {}\n" 11376 "\n" 11377 "private:\n" 11378 " int i;\n" 11379 "\n" 11380 "public:\n" 11381 "\n" 11382 "protected:\n" 11383 " int j;\n" 11384 "};\n", 11385 NoEmptyLines); 11386 } 11387 11388 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11389 11390 FormatStyle Style = getLLVMStyle(); 11391 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11392 verifyFormat("struct foo {\n" 11393 "private:\n" 11394 " void f() {}\n" 11395 "\n" 11396 "private:\n" 11397 " int i;\n" 11398 "\n" 11399 "protected:\n" 11400 " int j;\n" 11401 "};\n", 11402 Style); 11403 11404 // Check if lines are removed. 11405 verifyFormat("struct foo {\n" 11406 "private:\n" 11407 " void f() {}\n" 11408 "\n" 11409 "private:\n" 11410 " int i;\n" 11411 "\n" 11412 "protected:\n" 11413 " int j;\n" 11414 "};\n", 11415 "struct foo {\n" 11416 "private:\n" 11417 "\n" 11418 " void f() {}\n" 11419 "\n" 11420 "private:\n" 11421 "\n" 11422 " int i;\n" 11423 "\n" 11424 "protected:\n" 11425 "\n" 11426 " int j;\n" 11427 "};\n", 11428 Style); 11429 11430 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11431 verifyFormat("struct foo {\n" 11432 "private:\n" 11433 "\n" 11434 " void f() {}\n" 11435 "\n" 11436 "private:\n" 11437 "\n" 11438 " int i;\n" 11439 "\n" 11440 "protected:\n" 11441 "\n" 11442 " int j;\n" 11443 "};\n", 11444 Style); 11445 11446 // Check if lines are added. 11447 verifyFormat("struct foo {\n" 11448 "private:\n" 11449 "\n" 11450 " void f() {}\n" 11451 "\n" 11452 "private:\n" 11453 "\n" 11454 " int i;\n" 11455 "\n" 11456 "protected:\n" 11457 "\n" 11458 " int j;\n" 11459 "};\n", 11460 "struct foo {\n" 11461 "private:\n" 11462 " void f() {}\n" 11463 "\n" 11464 "private:\n" 11465 " int i;\n" 11466 "\n" 11467 "protected:\n" 11468 " int j;\n" 11469 "};\n", 11470 Style); 11471 11472 // Leave tests rely on the code layout, test::messUp can not be used. 11473 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11474 Style.MaxEmptyLinesToKeep = 0u; 11475 verifyFormat("struct foo {\n" 11476 "private:\n" 11477 " void f() {}\n" 11478 "\n" 11479 "private:\n" 11480 " int i;\n" 11481 "\n" 11482 "protected:\n" 11483 " int j;\n" 11484 "};\n", 11485 Style); 11486 11487 // Check if MaxEmptyLinesToKeep is respected. 11488 EXPECT_EQ("struct foo {\n" 11489 "private:\n" 11490 " void f() {}\n" 11491 "\n" 11492 "private:\n" 11493 " int i;\n" 11494 "\n" 11495 "protected:\n" 11496 " int j;\n" 11497 "};\n", 11498 format("struct foo {\n" 11499 "private:\n" 11500 "\n\n\n" 11501 " void f() {}\n" 11502 "\n" 11503 "private:\n" 11504 "\n\n\n" 11505 " int i;\n" 11506 "\n" 11507 "protected:\n" 11508 "\n\n\n" 11509 " int j;\n" 11510 "};\n", 11511 Style)); 11512 11513 Style.MaxEmptyLinesToKeep = 1u; 11514 EXPECT_EQ("struct foo {\n" 11515 "private:\n" 11516 "\n" 11517 " void f() {}\n" 11518 "\n" 11519 "private:\n" 11520 "\n" 11521 " int i;\n" 11522 "\n" 11523 "protected:\n" 11524 "\n" 11525 " int j;\n" 11526 "};\n", 11527 format("struct foo {\n" 11528 "private:\n" 11529 "\n" 11530 " void f() {}\n" 11531 "\n" 11532 "private:\n" 11533 "\n" 11534 " int i;\n" 11535 "\n" 11536 "protected:\n" 11537 "\n" 11538 " int j;\n" 11539 "};\n", 11540 Style)); 11541 // Check if no lines are kept. 11542 EXPECT_EQ("struct foo {\n" 11543 "private:\n" 11544 " void f() {}\n" 11545 "\n" 11546 "private:\n" 11547 " int i;\n" 11548 "\n" 11549 "protected:\n" 11550 " int j;\n" 11551 "};\n", 11552 format("struct foo {\n" 11553 "private:\n" 11554 " void f() {}\n" 11555 "\n" 11556 "private:\n" 11557 " int i;\n" 11558 "\n" 11559 "protected:\n" 11560 " int j;\n" 11561 "};\n", 11562 Style)); 11563 // Check if MaxEmptyLinesToKeep is respected. 11564 EXPECT_EQ("struct foo {\n" 11565 "private:\n" 11566 "\n" 11567 " void f() {}\n" 11568 "\n" 11569 "private:\n" 11570 "\n" 11571 " int i;\n" 11572 "\n" 11573 "protected:\n" 11574 "\n" 11575 " int j;\n" 11576 "};\n", 11577 format("struct foo {\n" 11578 "private:\n" 11579 "\n\n\n" 11580 " void f() {}\n" 11581 "\n" 11582 "private:\n" 11583 "\n\n\n" 11584 " int i;\n" 11585 "\n" 11586 "protected:\n" 11587 "\n\n\n" 11588 " int j;\n" 11589 "};\n", 11590 Style)); 11591 11592 Style.MaxEmptyLinesToKeep = 10u; 11593 EXPECT_EQ("struct foo {\n" 11594 "private:\n" 11595 "\n\n\n" 11596 " void f() {}\n" 11597 "\n" 11598 "private:\n" 11599 "\n\n\n" 11600 " int i;\n" 11601 "\n" 11602 "protected:\n" 11603 "\n\n\n" 11604 " int j;\n" 11605 "};\n", 11606 format("struct foo {\n" 11607 "private:\n" 11608 "\n\n\n" 11609 " void f() {}\n" 11610 "\n" 11611 "private:\n" 11612 "\n\n\n" 11613 " int i;\n" 11614 "\n" 11615 "protected:\n" 11616 "\n\n\n" 11617 " int j;\n" 11618 "};\n", 11619 Style)); 11620 11621 // Test with comments. 11622 Style = getLLVMStyle(); 11623 verifyFormat("struct foo {\n" 11624 "private:\n" 11625 " // comment\n" 11626 " void f() {}\n" 11627 "\n" 11628 "private: /* comment */\n" 11629 " int i;\n" 11630 "};\n", 11631 Style); 11632 verifyFormat("struct foo {\n" 11633 "private:\n" 11634 " // comment\n" 11635 " void f() {}\n" 11636 "\n" 11637 "private: /* comment */\n" 11638 " int i;\n" 11639 "};\n", 11640 "struct foo {\n" 11641 "private:\n" 11642 "\n" 11643 " // comment\n" 11644 " void f() {}\n" 11645 "\n" 11646 "private: /* comment */\n" 11647 "\n" 11648 " int i;\n" 11649 "};\n", 11650 Style); 11651 11652 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11653 verifyFormat("struct foo {\n" 11654 "private:\n" 11655 "\n" 11656 " // comment\n" 11657 " void f() {}\n" 11658 "\n" 11659 "private: /* comment */\n" 11660 "\n" 11661 " int i;\n" 11662 "};\n", 11663 "struct foo {\n" 11664 "private:\n" 11665 " // comment\n" 11666 " void f() {}\n" 11667 "\n" 11668 "private: /* comment */\n" 11669 " int i;\n" 11670 "};\n", 11671 Style); 11672 verifyFormat("struct foo {\n" 11673 "private:\n" 11674 "\n" 11675 " // comment\n" 11676 " void f() {}\n" 11677 "\n" 11678 "private: /* comment */\n" 11679 "\n" 11680 " int i;\n" 11681 "};\n", 11682 Style); 11683 11684 // Test with preprocessor defines. 11685 Style = getLLVMStyle(); 11686 verifyFormat("struct foo {\n" 11687 "private:\n" 11688 "#ifdef FOO\n" 11689 "#endif\n" 11690 " void f() {}\n" 11691 "};\n", 11692 Style); 11693 verifyFormat("struct foo {\n" 11694 "private:\n" 11695 "#ifdef FOO\n" 11696 "#endif\n" 11697 " void f() {}\n" 11698 "};\n", 11699 "struct foo {\n" 11700 "private:\n" 11701 "\n" 11702 "#ifdef FOO\n" 11703 "#endif\n" 11704 " void f() {}\n" 11705 "};\n", 11706 Style); 11707 11708 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11709 verifyFormat("struct foo {\n" 11710 "private:\n" 11711 "\n" 11712 "#ifdef FOO\n" 11713 "#endif\n" 11714 " void f() {}\n" 11715 "};\n", 11716 "struct foo {\n" 11717 "private:\n" 11718 "#ifdef FOO\n" 11719 "#endif\n" 11720 " void f() {}\n" 11721 "};\n", 11722 Style); 11723 verifyFormat("struct foo {\n" 11724 "private:\n" 11725 "\n" 11726 "#ifdef FOO\n" 11727 "#endif\n" 11728 " void f() {}\n" 11729 "};\n", 11730 Style); 11731 } 11732 11733 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11734 // Combined tests of EmptyLineAfterAccessModifier and 11735 // EmptyLineBeforeAccessModifier. 11736 FormatStyle Style = getLLVMStyle(); 11737 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11738 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11739 verifyFormat("struct foo {\n" 11740 "private:\n" 11741 "\n" 11742 "protected:\n" 11743 "};\n", 11744 Style); 11745 11746 Style.MaxEmptyLinesToKeep = 10u; 11747 // Both remove all new lines. 11748 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11749 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11750 verifyFormat("struct foo {\n" 11751 "private:\n" 11752 "protected:\n" 11753 "};\n", 11754 "struct foo {\n" 11755 "private:\n" 11756 "\n\n\n" 11757 "protected:\n" 11758 "};\n", 11759 Style); 11760 11761 // Leave tests rely on the code layout, test::messUp can not be used. 11762 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11763 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11764 Style.MaxEmptyLinesToKeep = 10u; 11765 EXPECT_EQ("struct foo {\n" 11766 "private:\n" 11767 "\n\n\n" 11768 "protected:\n" 11769 "};\n", 11770 format("struct foo {\n" 11771 "private:\n" 11772 "\n\n\n" 11773 "protected:\n" 11774 "};\n", 11775 Style)); 11776 Style.MaxEmptyLinesToKeep = 3u; 11777 EXPECT_EQ("struct foo {\n" 11778 "private:\n" 11779 "\n\n\n" 11780 "protected:\n" 11781 "};\n", 11782 format("struct foo {\n" 11783 "private:\n" 11784 "\n\n\n" 11785 "protected:\n" 11786 "};\n", 11787 Style)); 11788 Style.MaxEmptyLinesToKeep = 1u; 11789 EXPECT_EQ("struct foo {\n" 11790 "private:\n" 11791 "\n\n\n" 11792 "protected:\n" 11793 "};\n", 11794 format("struct foo {\n" 11795 "private:\n" 11796 "\n\n\n" 11797 "protected:\n" 11798 "};\n", 11799 Style)); // Based on new lines in original document and not 11800 // on the setting. 11801 11802 Style.MaxEmptyLinesToKeep = 10u; 11803 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11804 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11805 // Newlines are kept if they are greater than zero, 11806 // test::messUp removes all new lines which changes the logic 11807 EXPECT_EQ("struct foo {\n" 11808 "private:\n" 11809 "\n\n\n" 11810 "protected:\n" 11811 "};\n", 11812 format("struct foo {\n" 11813 "private:\n" 11814 "\n\n\n" 11815 "protected:\n" 11816 "};\n", 11817 Style)); 11818 11819 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11820 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11821 // test::messUp removes all new lines which changes the logic 11822 EXPECT_EQ("struct foo {\n" 11823 "private:\n" 11824 "\n\n\n" 11825 "protected:\n" 11826 "};\n", 11827 format("struct foo {\n" 11828 "private:\n" 11829 "\n\n\n" 11830 "protected:\n" 11831 "};\n", 11832 Style)); 11833 11834 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11835 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11836 EXPECT_EQ("struct foo {\n" 11837 "private:\n" 11838 "\n\n\n" 11839 "protected:\n" 11840 "};\n", 11841 format("struct foo {\n" 11842 "private:\n" 11843 "\n\n\n" 11844 "protected:\n" 11845 "};\n", 11846 Style)); // test::messUp removes all new lines which changes 11847 // the logic. 11848 11849 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11850 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11851 verifyFormat("struct foo {\n" 11852 "private:\n" 11853 "protected:\n" 11854 "};\n", 11855 "struct foo {\n" 11856 "private:\n" 11857 "\n\n\n" 11858 "protected:\n" 11859 "};\n", 11860 Style); 11861 11862 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11863 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11864 EXPECT_EQ("struct foo {\n" 11865 "private:\n" 11866 "\n\n\n" 11867 "protected:\n" 11868 "};\n", 11869 format("struct foo {\n" 11870 "private:\n" 11871 "\n\n\n" 11872 "protected:\n" 11873 "};\n", 11874 Style)); // test::messUp removes all new lines which changes 11875 // the logic. 11876 11877 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11878 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11879 verifyFormat("struct foo {\n" 11880 "private:\n" 11881 "protected:\n" 11882 "};\n", 11883 "struct foo {\n" 11884 "private:\n" 11885 "\n\n\n" 11886 "protected:\n" 11887 "};\n", 11888 Style); 11889 11890 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11891 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11892 verifyFormat("struct foo {\n" 11893 "private:\n" 11894 "protected:\n" 11895 "};\n", 11896 "struct foo {\n" 11897 "private:\n" 11898 "\n\n\n" 11899 "protected:\n" 11900 "};\n", 11901 Style); 11902 11903 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11904 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11905 verifyFormat("struct foo {\n" 11906 "private:\n" 11907 "protected:\n" 11908 "};\n", 11909 "struct foo {\n" 11910 "private:\n" 11911 "\n\n\n" 11912 "protected:\n" 11913 "};\n", 11914 Style); 11915 11916 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11917 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11918 verifyFormat("struct foo {\n" 11919 "private:\n" 11920 "protected:\n" 11921 "};\n", 11922 "struct foo {\n" 11923 "private:\n" 11924 "\n\n\n" 11925 "protected:\n" 11926 "};\n", 11927 Style); 11928 } 11929 11930 TEST_F(FormatTest, FormatsArrays) { 11931 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11932 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11933 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11934 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11935 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11936 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11937 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11938 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11939 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11940 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11941 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11942 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11943 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11944 verifyFormat( 11945 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11946 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11947 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11948 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11949 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11950 11951 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11952 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11953 verifyFormat( 11954 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11955 " .aaaaaaa[0]\n" 11956 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11957 verifyFormat("a[::b::c];"); 11958 11959 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11960 11961 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11962 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11963 } 11964 11965 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11966 verifyFormat("(a)->b();"); 11967 verifyFormat("--a;"); 11968 } 11969 11970 TEST_F(FormatTest, HandlesIncludeDirectives) { 11971 verifyFormat("#include <string>\n" 11972 "#include <a/b/c.h>\n" 11973 "#include \"a/b/string\"\n" 11974 "#include \"string.h\"\n" 11975 "#include \"string.h\"\n" 11976 "#include <a-a>\n" 11977 "#include < path with space >\n" 11978 "#include_next <test.h>" 11979 "#include \"abc.h\" // this is included for ABC\n" 11980 "#include \"some long include\" // with a comment\n" 11981 "#include \"some very long include path\"\n" 11982 "#include <some/very/long/include/path>\n", 11983 getLLVMStyleWithColumns(35)); 11984 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11985 EXPECT_EQ("#include <a>", format("#include<a>")); 11986 11987 verifyFormat("#import <string>"); 11988 verifyFormat("#import <a/b/c.h>"); 11989 verifyFormat("#import \"a/b/string\""); 11990 verifyFormat("#import \"string.h\""); 11991 verifyFormat("#import \"string.h\""); 11992 verifyFormat("#if __has_include(<strstream>)\n" 11993 "#include <strstream>\n" 11994 "#endif"); 11995 11996 verifyFormat("#define MY_IMPORT <a/b>"); 11997 11998 verifyFormat("#if __has_include(<a/b>)"); 11999 verifyFormat("#if __has_include_next(<a/b>)"); 12000 verifyFormat("#define F __has_include(<a/b>)"); 12001 verifyFormat("#define F __has_include_next(<a/b>)"); 12002 12003 // Protocol buffer definition or missing "#". 12004 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 12005 getLLVMStyleWithColumns(30)); 12006 12007 FormatStyle Style = getLLVMStyle(); 12008 Style.AlwaysBreakBeforeMultilineStrings = true; 12009 Style.ColumnLimit = 0; 12010 verifyFormat("#import \"abc.h\"", Style); 12011 12012 // But 'import' might also be a regular C++ namespace. 12013 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12014 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12015 } 12016 12017 //===----------------------------------------------------------------------===// 12018 // Error recovery tests. 12019 //===----------------------------------------------------------------------===// 12020 12021 TEST_F(FormatTest, IncompleteParameterLists) { 12022 FormatStyle NoBinPacking = getLLVMStyle(); 12023 NoBinPacking.BinPackParameters = false; 12024 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12025 " double *min_x,\n" 12026 " double *max_x,\n" 12027 " double *min_y,\n" 12028 " double *max_y,\n" 12029 " double *min_z,\n" 12030 " double *max_z, ) {}", 12031 NoBinPacking); 12032 } 12033 12034 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12035 verifyFormat("void f() { return; }\n42"); 12036 verifyFormat("void f() {\n" 12037 " if (0)\n" 12038 " return;\n" 12039 "}\n" 12040 "42"); 12041 verifyFormat("void f() { return }\n42"); 12042 verifyFormat("void f() {\n" 12043 " if (0)\n" 12044 " return\n" 12045 "}\n" 12046 "42"); 12047 } 12048 12049 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12050 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12051 EXPECT_EQ("void f() {\n" 12052 " if (a)\n" 12053 " return\n" 12054 "}", 12055 format("void f ( ) { if ( a ) return }")); 12056 EXPECT_EQ("namespace N {\n" 12057 "void f()\n" 12058 "}", 12059 format("namespace N { void f() }")); 12060 EXPECT_EQ("namespace N {\n" 12061 "void f() {}\n" 12062 "void g()\n" 12063 "} // namespace N", 12064 format("namespace N { void f( ) { } void g( ) }")); 12065 } 12066 12067 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12068 verifyFormat("int aaaaaaaa =\n" 12069 " // Overlylongcomment\n" 12070 " b;", 12071 getLLVMStyleWithColumns(20)); 12072 verifyFormat("function(\n" 12073 " ShortArgument,\n" 12074 " LoooooooooooongArgument);\n", 12075 getLLVMStyleWithColumns(20)); 12076 } 12077 12078 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12079 verifyFormat("public:"); 12080 verifyFormat("class A {\n" 12081 "public\n" 12082 " void f() {}\n" 12083 "};"); 12084 verifyFormat("public\n" 12085 "int qwerty;"); 12086 verifyFormat("public\n" 12087 "B {}"); 12088 verifyFormat("public\n" 12089 "{}"); 12090 verifyFormat("public\n" 12091 "B { int x; }"); 12092 } 12093 12094 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12095 verifyFormat("{"); 12096 verifyFormat("#})"); 12097 verifyNoCrash("(/**/[:!] ?[)."); 12098 } 12099 12100 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12101 // Found by oss-fuzz: 12102 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12103 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12104 Style.ColumnLimit = 60; 12105 verifyNoCrash( 12106 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12107 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12108 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12109 Style); 12110 } 12111 12112 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12113 verifyFormat("do {\n}"); 12114 verifyFormat("do {\n}\n" 12115 "f();"); 12116 verifyFormat("do {\n}\n" 12117 "wheeee(fun);"); 12118 verifyFormat("do {\n" 12119 " f();\n" 12120 "}"); 12121 } 12122 12123 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12124 verifyFormat("if {\n foo;\n foo();\n}"); 12125 verifyFormat("switch {\n foo;\n foo();\n}"); 12126 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12127 verifyIncompleteFormat("ERROR: for target;"); 12128 verifyFormat("while {\n foo;\n foo();\n}"); 12129 verifyFormat("do {\n foo;\n foo();\n} while;"); 12130 } 12131 12132 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12133 verifyIncompleteFormat("namespace {\n" 12134 "class Foo { Foo (\n" 12135 "};\n" 12136 "} // namespace"); 12137 } 12138 12139 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12140 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12141 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12142 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12143 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12144 12145 EXPECT_EQ("{\n" 12146 " {\n" 12147 " breakme(\n" 12148 " qwe);\n" 12149 " }\n", 12150 format("{\n" 12151 " {\n" 12152 " breakme(qwe);\n" 12153 "}\n", 12154 getLLVMStyleWithColumns(10))); 12155 } 12156 12157 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12158 verifyFormat("int x = {\n" 12159 " avariable,\n" 12160 " b(alongervariable)};", 12161 getLLVMStyleWithColumns(25)); 12162 } 12163 12164 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12165 verifyFormat("return (a)(b){1, 2, 3};"); 12166 } 12167 12168 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12169 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12170 verifyFormat("vector<int> x{\n" 12171 " 1,\n" 12172 " 2,\n" 12173 " 3,\n" 12174 " 4,\n" 12175 "};"); 12176 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12177 verifyFormat("f({1, 2});"); 12178 verifyFormat("auto v = Foo{-1};"); 12179 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12180 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12181 verifyFormat("new vector<int>{1, 2, 3};"); 12182 verifyFormat("new int[3]{1, 2, 3};"); 12183 verifyFormat("new int{1};"); 12184 verifyFormat("return {arg1, arg2};"); 12185 verifyFormat("return {arg1, SomeType{parameter}};"); 12186 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12187 verifyFormat("new T{arg1, arg2};"); 12188 verifyFormat("f(MyMap[{composite, key}]);"); 12189 verifyFormat("class Class {\n" 12190 " T member = {arg1, arg2};\n" 12191 "};"); 12192 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12193 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12194 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12195 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12196 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12197 12198 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12199 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12200 verifyFormat("auto i = decltype(x){};"); 12201 verifyFormat("auto i = typeof(x){};"); 12202 verifyFormat("auto i = _Atomic(x){};"); 12203 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12204 verifyFormat("Node n{1, Node{1000}, //\n" 12205 " 2};"); 12206 verifyFormat("Aaaa aaaaaaa{\n" 12207 " {\n" 12208 " aaaa,\n" 12209 " },\n" 12210 "};"); 12211 verifyFormat("class C : public D {\n" 12212 " SomeClass SC{2};\n" 12213 "};"); 12214 verifyFormat("class C : public A {\n" 12215 " class D : public B {\n" 12216 " void f() { int i{2}; }\n" 12217 " };\n" 12218 "};"); 12219 verifyFormat("#define A {a, a},"); 12220 // Don't confuse braced list initializers with compound statements. 12221 verifyFormat( 12222 "class A {\n" 12223 " A() : a{} {}\n" 12224 " A(int b) : b(b) {}\n" 12225 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12226 " int a, b;\n" 12227 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12228 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12229 "{}\n" 12230 "};"); 12231 12232 // Avoid breaking between equal sign and opening brace 12233 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12234 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12235 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12236 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12237 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12238 " {\"ccccccccccccccccccccc\", 2}};", 12239 AvoidBreakingFirstArgument); 12240 12241 // Binpacking only if there is no trailing comma 12242 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12243 " cccccccccc, dddddddddd};", 12244 getLLVMStyleWithColumns(50)); 12245 verifyFormat("const Aaaaaa aaaaa = {\n" 12246 " aaaaaaaaaaa,\n" 12247 " bbbbbbbbbbb,\n" 12248 " ccccccccccc,\n" 12249 " ddddddddddd,\n" 12250 "};", 12251 getLLVMStyleWithColumns(50)); 12252 12253 // Cases where distinguising braced lists and blocks is hard. 12254 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12255 verifyFormat("void f() {\n" 12256 " return; // comment\n" 12257 "}\n" 12258 "SomeType t;"); 12259 verifyFormat("void f() {\n" 12260 " if (a) {\n" 12261 " f();\n" 12262 " }\n" 12263 "}\n" 12264 "SomeType t;"); 12265 12266 // In combination with BinPackArguments = false. 12267 FormatStyle NoBinPacking = getLLVMStyle(); 12268 NoBinPacking.BinPackArguments = false; 12269 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12270 " bbbbb,\n" 12271 " ccccc,\n" 12272 " ddddd,\n" 12273 " eeeee,\n" 12274 " ffffff,\n" 12275 " ggggg,\n" 12276 " hhhhhh,\n" 12277 " iiiiii,\n" 12278 " jjjjjj,\n" 12279 " kkkkkk};", 12280 NoBinPacking); 12281 verifyFormat("const Aaaaaa aaaaa = {\n" 12282 " aaaaa,\n" 12283 " bbbbb,\n" 12284 " ccccc,\n" 12285 " ddddd,\n" 12286 " eeeee,\n" 12287 " ffffff,\n" 12288 " ggggg,\n" 12289 " hhhhhh,\n" 12290 " iiiiii,\n" 12291 " jjjjjj,\n" 12292 " kkkkkk,\n" 12293 "};", 12294 NoBinPacking); 12295 verifyFormat( 12296 "const Aaaaaa aaaaa = {\n" 12297 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12298 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12299 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12300 "};", 12301 NoBinPacking); 12302 12303 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12304 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12305 " CDDDP83848_BMCR_REGISTER,\n" 12306 " CDDDP83848_BMSR_REGISTER,\n" 12307 " CDDDP83848_RBR_REGISTER};", 12308 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12309 " CDDDP83848_BMSR_REGISTER,\n" 12310 " CDDDP83848_RBR_REGISTER};", 12311 NoBinPacking)); 12312 12313 // FIXME: The alignment of these trailing comments might be bad. Then again, 12314 // this might be utterly useless in real code. 12315 verifyFormat("Constructor::Constructor()\n" 12316 " : some_value{ //\n" 12317 " aaaaaaa, //\n" 12318 " bbbbbbb} {}"); 12319 12320 // In braced lists, the first comment is always assumed to belong to the 12321 // first element. Thus, it can be moved to the next or previous line as 12322 // appropriate. 12323 EXPECT_EQ("function({// First element:\n" 12324 " 1,\n" 12325 " // Second element:\n" 12326 " 2});", 12327 format("function({\n" 12328 " // First element:\n" 12329 " 1,\n" 12330 " // Second element:\n" 12331 " 2});")); 12332 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12333 " // First element:\n" 12334 " 1,\n" 12335 " // Second element:\n" 12336 " 2};", 12337 format("std::vector<int> MyNumbers{// First element:\n" 12338 " 1,\n" 12339 " // Second element:\n" 12340 " 2};", 12341 getLLVMStyleWithColumns(30))); 12342 // A trailing comma should still lead to an enforced line break and no 12343 // binpacking. 12344 EXPECT_EQ("vector<int> SomeVector = {\n" 12345 " // aaa\n" 12346 " 1,\n" 12347 " 2,\n" 12348 "};", 12349 format("vector<int> SomeVector = { // aaa\n" 12350 " 1, 2, };")); 12351 12352 // C++11 brace initializer list l-braces should not be treated any differently 12353 // when breaking before lambda bodies is enabled 12354 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12355 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12356 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12357 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12358 verifyFormat( 12359 "std::runtime_error{\n" 12360 " \"Long string which will force a break onto the next line...\"};", 12361 BreakBeforeLambdaBody); 12362 12363 FormatStyle ExtraSpaces = getLLVMStyle(); 12364 ExtraSpaces.Cpp11BracedListStyle = false; 12365 ExtraSpaces.ColumnLimit = 75; 12366 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12367 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12368 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12369 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12370 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12371 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12372 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12373 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12374 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12375 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12376 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12377 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12378 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12379 verifyFormat("class Class {\n" 12380 " T member = { arg1, arg2 };\n" 12381 "};", 12382 ExtraSpaces); 12383 verifyFormat( 12384 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12385 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12386 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12387 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12388 ExtraSpaces); 12389 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12390 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12391 ExtraSpaces); 12392 verifyFormat( 12393 "someFunction(OtherParam,\n" 12394 " BracedList{ // comment 1 (Forcing interesting break)\n" 12395 " param1, param2,\n" 12396 " // comment 2\n" 12397 " param3, param4 });", 12398 ExtraSpaces); 12399 verifyFormat( 12400 "std::this_thread::sleep_for(\n" 12401 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12402 ExtraSpaces); 12403 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12404 " aaaaaaa,\n" 12405 " aaaaaaaaaa,\n" 12406 " aaaaa,\n" 12407 " aaaaaaaaaaaaaaa,\n" 12408 " aaa,\n" 12409 " aaaaaaaaaa,\n" 12410 " a,\n" 12411 " aaaaaaaaaaaaaaaaaaaaa,\n" 12412 " aaaaaaaaaaaa,\n" 12413 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12414 " aaaaaaa,\n" 12415 " a};"); 12416 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12417 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12418 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12419 12420 // Avoid breaking between initializer/equal sign and opening brace 12421 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12422 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12423 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12424 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12425 " { \"ccccccccccccccccccccc\", 2 }\n" 12426 "};", 12427 ExtraSpaces); 12428 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12429 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12430 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12431 " { \"ccccccccccccccccccccc\", 2 }\n" 12432 "};", 12433 ExtraSpaces); 12434 12435 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12436 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12437 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12438 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12439 12440 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12441 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12442 SpaceBetweenBraces.SpacesInParentheses = true; 12443 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12444 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12445 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12446 verifyFormat("vector< int > x{ // comment 1\n" 12447 " 1, 2, 3, 4 };", 12448 SpaceBetweenBraces); 12449 SpaceBetweenBraces.ColumnLimit = 20; 12450 EXPECT_EQ("vector< int > x{\n" 12451 " 1, 2, 3, 4 };", 12452 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12453 SpaceBetweenBraces.ColumnLimit = 24; 12454 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12455 " 3, 4 };", 12456 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12457 EXPECT_EQ("vector< int > x{\n" 12458 " 1,\n" 12459 " 2,\n" 12460 " 3,\n" 12461 " 4,\n" 12462 "};", 12463 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12464 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12465 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12466 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12467 } 12468 12469 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12470 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12471 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12472 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12473 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12474 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12475 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12476 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12477 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12478 " 1, 22, 333, 4444, 55555, //\n" 12479 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12480 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12481 verifyFormat( 12482 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12483 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12484 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12485 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12486 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12487 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12488 " 7777777};"); 12489 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12490 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12491 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12492 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12493 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12494 " // Separating comment.\n" 12495 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12496 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12497 " // Leading comment\n" 12498 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12499 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12500 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12501 " 1, 1, 1, 1};", 12502 getLLVMStyleWithColumns(39)); 12503 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12504 " 1, 1, 1, 1};", 12505 getLLVMStyleWithColumns(38)); 12506 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12507 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12508 getLLVMStyleWithColumns(43)); 12509 verifyFormat( 12510 "static unsigned SomeValues[10][3] = {\n" 12511 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12512 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12513 verifyFormat("static auto fields = new vector<string>{\n" 12514 " \"aaaaaaaaaaaaa\",\n" 12515 " \"aaaaaaaaaaaaa\",\n" 12516 " \"aaaaaaaaaaaa\",\n" 12517 " \"aaaaaaaaaaaaaa\",\n" 12518 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12519 " \"aaaaaaaaaaaa\",\n" 12520 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12521 "};"); 12522 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12523 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12524 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12525 " 3, cccccccccccccccccccccc};", 12526 getLLVMStyleWithColumns(60)); 12527 12528 // Trailing commas. 12529 verifyFormat("vector<int> x = {\n" 12530 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12531 "};", 12532 getLLVMStyleWithColumns(39)); 12533 verifyFormat("vector<int> x = {\n" 12534 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12535 "};", 12536 getLLVMStyleWithColumns(39)); 12537 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12538 " 1, 1, 1, 1,\n" 12539 " /**/ /**/};", 12540 getLLVMStyleWithColumns(39)); 12541 12542 // Trailing comment in the first line. 12543 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12544 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12545 " 111111111, 222222222, 3333333333, 444444444, //\n" 12546 " 11111111, 22222222, 333333333, 44444444};"); 12547 // Trailing comment in the last line. 12548 verifyFormat("int aaaaa[] = {\n" 12549 " 1, 2, 3, // comment\n" 12550 " 4, 5, 6 // comment\n" 12551 "};"); 12552 12553 // With nested lists, we should either format one item per line or all nested 12554 // lists one on line. 12555 // FIXME: For some nested lists, we can do better. 12556 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12557 " {aaaaaaaaaaaaaaaaaaa},\n" 12558 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12559 " {aaaaaaaaaaaaaaaaa}};", 12560 getLLVMStyleWithColumns(60)); 12561 verifyFormat( 12562 "SomeStruct my_struct_array = {\n" 12563 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12564 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12565 " {aaa, aaa},\n" 12566 " {aaa, aaa},\n" 12567 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12568 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12569 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12570 12571 // No column layout should be used here. 12572 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12573 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12574 12575 verifyNoCrash("a<,"); 12576 12577 // No braced initializer here. 12578 verifyFormat("void f() {\n" 12579 " struct Dummy {};\n" 12580 " f(v);\n" 12581 "}"); 12582 12583 // Long lists should be formatted in columns even if they are nested. 12584 verifyFormat( 12585 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12586 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12587 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12588 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12589 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12590 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12591 12592 // Allow "single-column" layout even if that violates the column limit. There 12593 // isn't going to be a better way. 12594 verifyFormat("std::vector<int> a = {\n" 12595 " aaaaaaaa,\n" 12596 " aaaaaaaa,\n" 12597 " aaaaaaaa,\n" 12598 " aaaaaaaa,\n" 12599 " aaaaaaaaaa,\n" 12600 " aaaaaaaa,\n" 12601 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12602 getLLVMStyleWithColumns(30)); 12603 verifyFormat("vector<int> aaaa = {\n" 12604 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12605 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12606 " aaaaaa.aaaaaaa,\n" 12607 " aaaaaa.aaaaaaa,\n" 12608 " aaaaaa.aaaaaaa,\n" 12609 " aaaaaa.aaaaaaa,\n" 12610 "};"); 12611 12612 // Don't create hanging lists. 12613 verifyFormat("someFunction(Param, {List1, List2,\n" 12614 " List3});", 12615 getLLVMStyleWithColumns(35)); 12616 verifyFormat("someFunction(Param, Param,\n" 12617 " {List1, List2,\n" 12618 " List3});", 12619 getLLVMStyleWithColumns(35)); 12620 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12621 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12622 } 12623 12624 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12625 FormatStyle DoNotMerge = getLLVMStyle(); 12626 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12627 12628 verifyFormat("void f() { return 42; }"); 12629 verifyFormat("void f() {\n" 12630 " return 42;\n" 12631 "}", 12632 DoNotMerge); 12633 verifyFormat("void f() {\n" 12634 " // Comment\n" 12635 "}"); 12636 verifyFormat("{\n" 12637 "#error {\n" 12638 " int a;\n" 12639 "}"); 12640 verifyFormat("{\n" 12641 " int a;\n" 12642 "#error {\n" 12643 "}"); 12644 verifyFormat("void f() {} // comment"); 12645 verifyFormat("void f() { int a; } // comment"); 12646 verifyFormat("void f() {\n" 12647 "} // comment", 12648 DoNotMerge); 12649 verifyFormat("void f() {\n" 12650 " int a;\n" 12651 "} // comment", 12652 DoNotMerge); 12653 verifyFormat("void f() {\n" 12654 "} // comment", 12655 getLLVMStyleWithColumns(15)); 12656 12657 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12658 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12659 12660 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12661 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12662 verifyFormat("class C {\n" 12663 " C()\n" 12664 " : iiiiiiii(nullptr),\n" 12665 " kkkkkkk(nullptr),\n" 12666 " mmmmmmm(nullptr),\n" 12667 " nnnnnnn(nullptr) {}\n" 12668 "};", 12669 getGoogleStyle()); 12670 12671 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12672 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12673 EXPECT_EQ("class C {\n" 12674 " A() : b(0) {}\n" 12675 "};", 12676 format("class C{A():b(0){}};", NoColumnLimit)); 12677 EXPECT_EQ("A()\n" 12678 " : b(0) {\n" 12679 "}", 12680 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12681 12682 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12683 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12684 FormatStyle::SFS_None; 12685 EXPECT_EQ("A()\n" 12686 " : b(0) {\n" 12687 "}", 12688 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12689 EXPECT_EQ("A()\n" 12690 " : b(0) {\n" 12691 "}", 12692 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12693 12694 verifyFormat("#define A \\\n" 12695 " void f() { \\\n" 12696 " int i; \\\n" 12697 " }", 12698 getLLVMStyleWithColumns(20)); 12699 verifyFormat("#define A \\\n" 12700 " void f() { int i; }", 12701 getLLVMStyleWithColumns(21)); 12702 verifyFormat("#define A \\\n" 12703 " void f() { \\\n" 12704 " int i; \\\n" 12705 " } \\\n" 12706 " int j;", 12707 getLLVMStyleWithColumns(22)); 12708 verifyFormat("#define A \\\n" 12709 " void f() { int i; } \\\n" 12710 " int j;", 12711 getLLVMStyleWithColumns(23)); 12712 } 12713 12714 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12715 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12716 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12717 verifyFormat("class C {\n" 12718 " int f() {}\n" 12719 "};", 12720 MergeEmptyOnly); 12721 verifyFormat("class C {\n" 12722 " int f() {\n" 12723 " return 42;\n" 12724 " }\n" 12725 "};", 12726 MergeEmptyOnly); 12727 verifyFormat("int f() {}", MergeEmptyOnly); 12728 verifyFormat("int f() {\n" 12729 " return 42;\n" 12730 "}", 12731 MergeEmptyOnly); 12732 12733 // Also verify behavior when BraceWrapping.AfterFunction = true 12734 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12735 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12736 verifyFormat("int f() {}", MergeEmptyOnly); 12737 verifyFormat("class C {\n" 12738 " int f() {}\n" 12739 "};", 12740 MergeEmptyOnly); 12741 } 12742 12743 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12744 FormatStyle MergeInlineOnly = getLLVMStyle(); 12745 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12746 verifyFormat("class C {\n" 12747 " int f() { return 42; }\n" 12748 "};", 12749 MergeInlineOnly); 12750 verifyFormat("int f() {\n" 12751 " return 42;\n" 12752 "}", 12753 MergeInlineOnly); 12754 12755 // SFS_Inline implies SFS_Empty 12756 verifyFormat("class C {\n" 12757 " int f() {}\n" 12758 "};", 12759 MergeInlineOnly); 12760 verifyFormat("int f() {}", MergeInlineOnly); 12761 // https://llvm.org/PR54147 12762 verifyFormat("auto lambda = []() {\n" 12763 " // comment\n" 12764 " f();\n" 12765 " g();\n" 12766 "};", 12767 MergeInlineOnly); 12768 12769 verifyFormat("class C {\n" 12770 "#ifdef A\n" 12771 " int f() { return 42; }\n" 12772 "#endif\n" 12773 "};", 12774 MergeInlineOnly); 12775 12776 verifyFormat("struct S {\n" 12777 "// comment\n" 12778 "#ifdef FOO\n" 12779 " int foo() { bar(); }\n" 12780 "#endif\n" 12781 "};", 12782 MergeInlineOnly); 12783 12784 // Also verify behavior when BraceWrapping.AfterFunction = true 12785 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12786 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12787 verifyFormat("class C {\n" 12788 " int f() { return 42; }\n" 12789 "};", 12790 MergeInlineOnly); 12791 verifyFormat("int f()\n" 12792 "{\n" 12793 " return 42;\n" 12794 "}", 12795 MergeInlineOnly); 12796 12797 // SFS_Inline implies SFS_Empty 12798 verifyFormat("int f() {}", MergeInlineOnly); 12799 verifyFormat("class C {\n" 12800 " int f() {}\n" 12801 "};", 12802 MergeInlineOnly); 12803 12804 MergeInlineOnly.BraceWrapping.AfterClass = true; 12805 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12806 verifyFormat("class C\n" 12807 "{\n" 12808 " int f() { return 42; }\n" 12809 "};", 12810 MergeInlineOnly); 12811 verifyFormat("struct C\n" 12812 "{\n" 12813 " int f() { return 42; }\n" 12814 "};", 12815 MergeInlineOnly); 12816 verifyFormat("int f()\n" 12817 "{\n" 12818 " return 42;\n" 12819 "}", 12820 MergeInlineOnly); 12821 verifyFormat("int f() {}", MergeInlineOnly); 12822 verifyFormat("class C\n" 12823 "{\n" 12824 " int f() { return 42; }\n" 12825 "};", 12826 MergeInlineOnly); 12827 verifyFormat("struct C\n" 12828 "{\n" 12829 " int f() { return 42; }\n" 12830 "};", 12831 MergeInlineOnly); 12832 verifyFormat("struct C\n" 12833 "// comment\n" 12834 "/* comment */\n" 12835 "// comment\n" 12836 "{\n" 12837 " int f() { return 42; }\n" 12838 "};", 12839 MergeInlineOnly); 12840 verifyFormat("/* comment */ struct C\n" 12841 "{\n" 12842 " int f() { return 42; }\n" 12843 "};", 12844 MergeInlineOnly); 12845 } 12846 12847 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12848 FormatStyle MergeInlineOnly = getLLVMStyle(); 12849 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12850 FormatStyle::SFS_InlineOnly; 12851 verifyFormat("class C {\n" 12852 " int f() { return 42; }\n" 12853 "};", 12854 MergeInlineOnly); 12855 verifyFormat("int f() {\n" 12856 " return 42;\n" 12857 "}", 12858 MergeInlineOnly); 12859 12860 // SFS_InlineOnly does not imply SFS_Empty 12861 verifyFormat("class C {\n" 12862 " int f() {}\n" 12863 "};", 12864 MergeInlineOnly); 12865 verifyFormat("int f() {\n" 12866 "}", 12867 MergeInlineOnly); 12868 12869 // Also verify behavior when BraceWrapping.AfterFunction = true 12870 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12871 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12872 verifyFormat("class C {\n" 12873 " int f() { return 42; }\n" 12874 "};", 12875 MergeInlineOnly); 12876 verifyFormat("int f()\n" 12877 "{\n" 12878 " return 42;\n" 12879 "}", 12880 MergeInlineOnly); 12881 12882 // SFS_InlineOnly does not imply SFS_Empty 12883 verifyFormat("int f()\n" 12884 "{\n" 12885 "}", 12886 MergeInlineOnly); 12887 verifyFormat("class C {\n" 12888 " int f() {}\n" 12889 "};", 12890 MergeInlineOnly); 12891 } 12892 12893 TEST_F(FormatTest, SplitEmptyFunction) { 12894 FormatStyle Style = getLLVMStyleWithColumns(40); 12895 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12896 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12897 Style.BraceWrapping.AfterFunction = true; 12898 Style.BraceWrapping.SplitEmptyFunction = false; 12899 12900 verifyFormat("int f()\n" 12901 "{}", 12902 Style); 12903 verifyFormat("int f()\n" 12904 "{\n" 12905 " return 42;\n" 12906 "}", 12907 Style); 12908 verifyFormat("int f()\n" 12909 "{\n" 12910 " // some comment\n" 12911 "}", 12912 Style); 12913 12914 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12915 verifyFormat("int f() {}", Style); 12916 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12917 "{}", 12918 Style); 12919 verifyFormat("int f()\n" 12920 "{\n" 12921 " return 0;\n" 12922 "}", 12923 Style); 12924 12925 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12926 verifyFormat("class Foo {\n" 12927 " int f() {}\n" 12928 "};\n", 12929 Style); 12930 verifyFormat("class Foo {\n" 12931 " int f() { return 0; }\n" 12932 "};\n", 12933 Style); 12934 verifyFormat("class Foo {\n" 12935 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12936 " {}\n" 12937 "};\n", 12938 Style); 12939 verifyFormat("class Foo {\n" 12940 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12941 " {\n" 12942 " return 0;\n" 12943 " }\n" 12944 "};\n", 12945 Style); 12946 12947 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12948 verifyFormat("int f() {}", Style); 12949 verifyFormat("int f() { return 0; }", Style); 12950 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12951 "{}", 12952 Style); 12953 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12954 "{\n" 12955 " return 0;\n" 12956 "}", 12957 Style); 12958 } 12959 12960 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12961 FormatStyle Style = getLLVMStyleWithColumns(40); 12962 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12963 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12964 Style.BraceWrapping.AfterFunction = true; 12965 Style.BraceWrapping.SplitEmptyFunction = true; 12966 Style.BraceWrapping.SplitEmptyRecord = false; 12967 12968 verifyFormat("class C {};", Style); 12969 verifyFormat("struct C {};", Style); 12970 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12971 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12972 "{\n" 12973 "}", 12974 Style); 12975 verifyFormat("class C {\n" 12976 " C()\n" 12977 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12978 " bbbbbbbbbbbbbbbbbbb()\n" 12979 " {\n" 12980 " }\n" 12981 " void\n" 12982 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12983 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12984 " {\n" 12985 " }\n" 12986 "};", 12987 Style); 12988 } 12989 12990 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12991 FormatStyle Style = getLLVMStyle(); 12992 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12993 verifyFormat("#ifdef A\n" 12994 "int f() {}\n" 12995 "#else\n" 12996 "int g() {}\n" 12997 "#endif", 12998 Style); 12999 } 13000 13001 TEST_F(FormatTest, SplitEmptyClass) { 13002 FormatStyle Style = getLLVMStyle(); 13003 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13004 Style.BraceWrapping.AfterClass = true; 13005 Style.BraceWrapping.SplitEmptyRecord = false; 13006 13007 verifyFormat("class Foo\n" 13008 "{};", 13009 Style); 13010 verifyFormat("/* something */ class Foo\n" 13011 "{};", 13012 Style); 13013 verifyFormat("template <typename X> class Foo\n" 13014 "{};", 13015 Style); 13016 verifyFormat("class Foo\n" 13017 "{\n" 13018 " Foo();\n" 13019 "};", 13020 Style); 13021 verifyFormat("typedef class Foo\n" 13022 "{\n" 13023 "} Foo_t;", 13024 Style); 13025 13026 Style.BraceWrapping.SplitEmptyRecord = true; 13027 Style.BraceWrapping.AfterStruct = true; 13028 verifyFormat("class rep\n" 13029 "{\n" 13030 "};", 13031 Style); 13032 verifyFormat("struct rep\n" 13033 "{\n" 13034 "};", 13035 Style); 13036 verifyFormat("template <typename T> class rep\n" 13037 "{\n" 13038 "};", 13039 Style); 13040 verifyFormat("template <typename T> struct rep\n" 13041 "{\n" 13042 "};", 13043 Style); 13044 verifyFormat("class rep\n" 13045 "{\n" 13046 " int x;\n" 13047 "};", 13048 Style); 13049 verifyFormat("struct rep\n" 13050 "{\n" 13051 " int x;\n" 13052 "};", 13053 Style); 13054 verifyFormat("template <typename T> class rep\n" 13055 "{\n" 13056 " int x;\n" 13057 "};", 13058 Style); 13059 verifyFormat("template <typename T> struct rep\n" 13060 "{\n" 13061 " int x;\n" 13062 "};", 13063 Style); 13064 verifyFormat("template <typename T> class rep // Foo\n" 13065 "{\n" 13066 " int x;\n" 13067 "};", 13068 Style); 13069 verifyFormat("template <typename T> struct rep // Bar\n" 13070 "{\n" 13071 " int x;\n" 13072 "};", 13073 Style); 13074 13075 verifyFormat("template <typename T> class rep<T>\n" 13076 "{\n" 13077 " int x;\n" 13078 "};", 13079 Style); 13080 13081 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13082 "{\n" 13083 " int x;\n" 13084 "};", 13085 Style); 13086 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13087 "{\n" 13088 "};", 13089 Style); 13090 13091 verifyFormat("#include \"stdint.h\"\n" 13092 "namespace rep {}", 13093 Style); 13094 verifyFormat("#include <stdint.h>\n" 13095 "namespace rep {}", 13096 Style); 13097 verifyFormat("#include <stdint.h>\n" 13098 "namespace rep {}", 13099 "#include <stdint.h>\n" 13100 "namespace rep {\n" 13101 "\n" 13102 "\n" 13103 "}", 13104 Style); 13105 } 13106 13107 TEST_F(FormatTest, SplitEmptyStruct) { 13108 FormatStyle Style = getLLVMStyle(); 13109 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13110 Style.BraceWrapping.AfterStruct = true; 13111 Style.BraceWrapping.SplitEmptyRecord = false; 13112 13113 verifyFormat("struct Foo\n" 13114 "{};", 13115 Style); 13116 verifyFormat("/* something */ struct Foo\n" 13117 "{};", 13118 Style); 13119 verifyFormat("template <typename X> struct Foo\n" 13120 "{};", 13121 Style); 13122 verifyFormat("struct Foo\n" 13123 "{\n" 13124 " Foo();\n" 13125 "};", 13126 Style); 13127 verifyFormat("typedef struct Foo\n" 13128 "{\n" 13129 "} Foo_t;", 13130 Style); 13131 // typedef struct Bar {} Bar_t; 13132 } 13133 13134 TEST_F(FormatTest, SplitEmptyUnion) { 13135 FormatStyle Style = getLLVMStyle(); 13136 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13137 Style.BraceWrapping.AfterUnion = true; 13138 Style.BraceWrapping.SplitEmptyRecord = false; 13139 13140 verifyFormat("union Foo\n" 13141 "{};", 13142 Style); 13143 verifyFormat("/* something */ union Foo\n" 13144 "{};", 13145 Style); 13146 verifyFormat("union Foo\n" 13147 "{\n" 13148 " A,\n" 13149 "};", 13150 Style); 13151 verifyFormat("typedef union Foo\n" 13152 "{\n" 13153 "} Foo_t;", 13154 Style); 13155 } 13156 13157 TEST_F(FormatTest, SplitEmptyNamespace) { 13158 FormatStyle Style = getLLVMStyle(); 13159 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13160 Style.BraceWrapping.AfterNamespace = true; 13161 Style.BraceWrapping.SplitEmptyNamespace = false; 13162 13163 verifyFormat("namespace Foo\n" 13164 "{};", 13165 Style); 13166 verifyFormat("/* something */ namespace Foo\n" 13167 "{};", 13168 Style); 13169 verifyFormat("inline namespace Foo\n" 13170 "{};", 13171 Style); 13172 verifyFormat("/* something */ inline namespace Foo\n" 13173 "{};", 13174 Style); 13175 verifyFormat("export namespace Foo\n" 13176 "{};", 13177 Style); 13178 verifyFormat("namespace Foo\n" 13179 "{\n" 13180 "void Bar();\n" 13181 "};", 13182 Style); 13183 } 13184 13185 TEST_F(FormatTest, NeverMergeShortRecords) { 13186 FormatStyle Style = getLLVMStyle(); 13187 13188 verifyFormat("class Foo {\n" 13189 " Foo();\n" 13190 "};", 13191 Style); 13192 verifyFormat("typedef class Foo {\n" 13193 " Foo();\n" 13194 "} Foo_t;", 13195 Style); 13196 verifyFormat("struct Foo {\n" 13197 " Foo();\n" 13198 "};", 13199 Style); 13200 verifyFormat("typedef struct Foo {\n" 13201 " Foo();\n" 13202 "} Foo_t;", 13203 Style); 13204 verifyFormat("union Foo {\n" 13205 " A,\n" 13206 "};", 13207 Style); 13208 verifyFormat("typedef union Foo {\n" 13209 " A,\n" 13210 "} Foo_t;", 13211 Style); 13212 verifyFormat("namespace Foo {\n" 13213 "void Bar();\n" 13214 "};", 13215 Style); 13216 13217 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13218 Style.BraceWrapping.AfterClass = true; 13219 Style.BraceWrapping.AfterStruct = true; 13220 Style.BraceWrapping.AfterUnion = true; 13221 Style.BraceWrapping.AfterNamespace = true; 13222 verifyFormat("class Foo\n" 13223 "{\n" 13224 " Foo();\n" 13225 "};", 13226 Style); 13227 verifyFormat("typedef class Foo\n" 13228 "{\n" 13229 " Foo();\n" 13230 "} Foo_t;", 13231 Style); 13232 verifyFormat("struct Foo\n" 13233 "{\n" 13234 " Foo();\n" 13235 "};", 13236 Style); 13237 verifyFormat("typedef struct Foo\n" 13238 "{\n" 13239 " Foo();\n" 13240 "} Foo_t;", 13241 Style); 13242 verifyFormat("union Foo\n" 13243 "{\n" 13244 " A,\n" 13245 "};", 13246 Style); 13247 verifyFormat("typedef union Foo\n" 13248 "{\n" 13249 " A,\n" 13250 "} Foo_t;", 13251 Style); 13252 verifyFormat("namespace Foo\n" 13253 "{\n" 13254 "void Bar();\n" 13255 "};", 13256 Style); 13257 } 13258 13259 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13260 // Elaborate type variable declarations. 13261 verifyFormat("struct foo a = {bar};\nint n;"); 13262 verifyFormat("class foo a = {bar};\nint n;"); 13263 verifyFormat("union foo a = {bar};\nint n;"); 13264 13265 // Elaborate types inside function definitions. 13266 verifyFormat("struct foo f() {}\nint n;"); 13267 verifyFormat("class foo f() {}\nint n;"); 13268 verifyFormat("union foo f() {}\nint n;"); 13269 13270 // Templates. 13271 verifyFormat("template <class X> void f() {}\nint n;"); 13272 verifyFormat("template <struct X> void f() {}\nint n;"); 13273 verifyFormat("template <union X> void f() {}\nint n;"); 13274 13275 // Actual definitions... 13276 verifyFormat("struct {\n} n;"); 13277 verifyFormat( 13278 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13279 verifyFormat("union Z {\n int n;\n} x;"); 13280 verifyFormat("class MACRO Z {\n} n;"); 13281 verifyFormat("class MACRO(X) Z {\n} n;"); 13282 verifyFormat("class __attribute__(X) Z {\n} n;"); 13283 verifyFormat("class __declspec(X) Z {\n} n;"); 13284 verifyFormat("class A##B##C {\n} n;"); 13285 verifyFormat("class alignas(16) Z {\n} n;"); 13286 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13287 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13288 13289 // Redefinition from nested context: 13290 verifyFormat("class A::B::C {\n} n;"); 13291 13292 // Template definitions. 13293 verifyFormat( 13294 "template <typename F>\n" 13295 "Matcher(const Matcher<F> &Other,\n" 13296 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13297 " !is_same<F, T>::value>::type * = 0)\n" 13298 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13299 13300 // FIXME: This is still incorrectly handled at the formatter side. 13301 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13302 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13303 13304 // FIXME: 13305 // This now gets parsed incorrectly as class definition. 13306 // verifyFormat("class A<int> f() {\n}\nint n;"); 13307 13308 // Elaborate types where incorrectly parsing the structural element would 13309 // break the indent. 13310 verifyFormat("if (true)\n" 13311 " class X x;\n" 13312 "else\n" 13313 " f();\n"); 13314 13315 // This is simply incomplete. Formatting is not important, but must not crash. 13316 verifyFormat("class A:"); 13317 } 13318 13319 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13320 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13321 format("#error Leave all white!!!!! space* alone!\n")); 13322 EXPECT_EQ( 13323 "#warning Leave all white!!!!! space* alone!\n", 13324 format("#warning Leave all white!!!!! space* alone!\n")); 13325 EXPECT_EQ("#error 1", format(" # error 1")); 13326 EXPECT_EQ("#warning 1", format(" # warning 1")); 13327 } 13328 13329 TEST_F(FormatTest, FormatHashIfExpressions) { 13330 verifyFormat("#if AAAA && BBBB"); 13331 verifyFormat("#if (AAAA && BBBB)"); 13332 verifyFormat("#elif (AAAA && BBBB)"); 13333 // FIXME: Come up with a better indentation for #elif. 13334 verifyFormat( 13335 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13336 " defined(BBBBBBBB)\n" 13337 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13338 " defined(BBBBBBBB)\n" 13339 "#endif", 13340 getLLVMStyleWithColumns(65)); 13341 } 13342 13343 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13344 FormatStyle AllowsMergedIf = getGoogleStyle(); 13345 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13346 FormatStyle::SIS_WithoutElse; 13347 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13348 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13349 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13350 EXPECT_EQ("if (true) return 42;", 13351 format("if (true)\nreturn 42;", AllowsMergedIf)); 13352 FormatStyle ShortMergedIf = AllowsMergedIf; 13353 ShortMergedIf.ColumnLimit = 25; 13354 verifyFormat("#define A \\\n" 13355 " if (true) return 42;", 13356 ShortMergedIf); 13357 verifyFormat("#define A \\\n" 13358 " f(); \\\n" 13359 " if (true)\n" 13360 "#define B", 13361 ShortMergedIf); 13362 verifyFormat("#define A \\\n" 13363 " f(); \\\n" 13364 " if (true)\n" 13365 "g();", 13366 ShortMergedIf); 13367 verifyFormat("{\n" 13368 "#ifdef A\n" 13369 " // Comment\n" 13370 " if (true) continue;\n" 13371 "#endif\n" 13372 " // Comment\n" 13373 " if (true) continue;\n" 13374 "}", 13375 ShortMergedIf); 13376 ShortMergedIf.ColumnLimit = 33; 13377 verifyFormat("#define A \\\n" 13378 " if constexpr (true) return 42;", 13379 ShortMergedIf); 13380 verifyFormat("#define A \\\n" 13381 " if CONSTEXPR (true) return 42;", 13382 ShortMergedIf); 13383 ShortMergedIf.ColumnLimit = 29; 13384 verifyFormat("#define A \\\n" 13385 " if (aaaaaaaaaa) return 1; \\\n" 13386 " return 2;", 13387 ShortMergedIf); 13388 ShortMergedIf.ColumnLimit = 28; 13389 verifyFormat("#define A \\\n" 13390 " if (aaaaaaaaaa) \\\n" 13391 " return 1; \\\n" 13392 " return 2;", 13393 ShortMergedIf); 13394 verifyFormat("#define A \\\n" 13395 " if constexpr (aaaaaaa) \\\n" 13396 " return 1; \\\n" 13397 " return 2;", 13398 ShortMergedIf); 13399 verifyFormat("#define A \\\n" 13400 " if CONSTEXPR (aaaaaaa) \\\n" 13401 " return 1; \\\n" 13402 " return 2;", 13403 ShortMergedIf); 13404 13405 verifyFormat("//\n" 13406 "#define a \\\n" 13407 " if \\\n" 13408 " 0", 13409 getChromiumStyle(FormatStyle::LK_Cpp)); 13410 } 13411 13412 TEST_F(FormatTest, FormatStarDependingOnContext) { 13413 verifyFormat("void f(int *a);"); 13414 verifyFormat("void f() { f(fint * b); }"); 13415 verifyFormat("class A {\n void f(int *a);\n};"); 13416 verifyFormat("class A {\n int *a;\n};"); 13417 verifyFormat("namespace a {\n" 13418 "namespace b {\n" 13419 "class A {\n" 13420 " void f() {}\n" 13421 " int *a;\n" 13422 "};\n" 13423 "} // namespace b\n" 13424 "} // namespace a"); 13425 } 13426 13427 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13428 verifyFormat("while"); 13429 verifyFormat("operator"); 13430 } 13431 13432 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13433 // This code would be painfully slow to format if we didn't skip it. 13434 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 13435 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13436 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13437 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13438 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13439 "A(1, 1)\n" 13440 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13441 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13442 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13443 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13444 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13445 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13446 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13447 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13448 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13449 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13450 // Deeply nested part is untouched, rest is formatted. 13451 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13452 format(std::string("int i;\n") + Code + "int j;\n", 13453 getLLVMStyle(), SC_ExpectIncomplete)); 13454 } 13455 13456 //===----------------------------------------------------------------------===// 13457 // Objective-C tests. 13458 //===----------------------------------------------------------------------===// 13459 13460 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13461 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13462 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13463 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13464 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13465 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13466 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13467 format("-(NSInteger)Method3:(id)anObject;")); 13468 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13469 format("-(NSInteger)Method4:(id)anObject;")); 13470 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13471 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13472 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13473 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13474 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13475 "forAllCells:(BOOL)flag;", 13476 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13477 "forAllCells:(BOOL)flag;")); 13478 13479 // Very long objectiveC method declaration. 13480 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13481 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13482 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13483 " inRange:(NSRange)range\n" 13484 " outRange:(NSRange)out_range\n" 13485 " outRange1:(NSRange)out_range1\n" 13486 " outRange2:(NSRange)out_range2\n" 13487 " outRange3:(NSRange)out_range3\n" 13488 " outRange4:(NSRange)out_range4\n" 13489 " outRange5:(NSRange)out_range5\n" 13490 " outRange6:(NSRange)out_range6\n" 13491 " outRange7:(NSRange)out_range7\n" 13492 " outRange8:(NSRange)out_range8\n" 13493 " outRange9:(NSRange)out_range9;"); 13494 13495 // When the function name has to be wrapped. 13496 FormatStyle Style = getLLVMStyle(); 13497 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13498 // and always indents instead. 13499 Style.IndentWrappedFunctionNames = false; 13500 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13501 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13502 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13503 "}", 13504 Style); 13505 Style.IndentWrappedFunctionNames = true; 13506 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13507 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13508 " anotherName:(NSString)dddddddddddddd {\n" 13509 "}", 13510 Style); 13511 13512 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13513 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13514 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13515 // protocol lists (but not for template classes): 13516 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13517 13518 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13519 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13520 13521 // If there's no return type (very rare in practice!), LLVM and Google style 13522 // agree. 13523 verifyFormat("- foo;"); 13524 verifyFormat("- foo:(int)f;"); 13525 verifyGoogleFormat("- foo:(int)foo;"); 13526 } 13527 13528 TEST_F(FormatTest, BreaksStringLiterals) { 13529 EXPECT_EQ("\"some text \"\n" 13530 "\"other\";", 13531 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13532 EXPECT_EQ("\"some text \"\n" 13533 "\"other\";", 13534 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13535 EXPECT_EQ( 13536 "#define A \\\n" 13537 " \"some \" \\\n" 13538 " \"text \" \\\n" 13539 " \"other\";", 13540 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13541 EXPECT_EQ( 13542 "#define A \\\n" 13543 " \"so \" \\\n" 13544 " \"text \" \\\n" 13545 " \"other\";", 13546 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13547 13548 EXPECT_EQ("\"some text\"", 13549 format("\"some text\"", getLLVMStyleWithColumns(1))); 13550 EXPECT_EQ("\"some text\"", 13551 format("\"some text\"", getLLVMStyleWithColumns(11))); 13552 EXPECT_EQ("\"some \"\n" 13553 "\"text\"", 13554 format("\"some text\"", getLLVMStyleWithColumns(10))); 13555 EXPECT_EQ("\"some \"\n" 13556 "\"text\"", 13557 format("\"some text\"", getLLVMStyleWithColumns(7))); 13558 EXPECT_EQ("\"some\"\n" 13559 "\" tex\"\n" 13560 "\"t\"", 13561 format("\"some text\"", getLLVMStyleWithColumns(6))); 13562 EXPECT_EQ("\"some\"\n" 13563 "\" tex\"\n" 13564 "\" and\"", 13565 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13566 EXPECT_EQ("\"some\"\n" 13567 "\"/tex\"\n" 13568 "\"/and\"", 13569 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13570 13571 EXPECT_EQ("variable =\n" 13572 " \"long string \"\n" 13573 " \"literal\";", 13574 format("variable = \"long string literal\";", 13575 getLLVMStyleWithColumns(20))); 13576 13577 EXPECT_EQ("variable = f(\n" 13578 " \"long string \"\n" 13579 " \"literal\",\n" 13580 " short,\n" 13581 " loooooooooooooooooooong);", 13582 format("variable = f(\"long string literal\", short, " 13583 "loooooooooooooooooooong);", 13584 getLLVMStyleWithColumns(20))); 13585 13586 EXPECT_EQ( 13587 "f(g(\"long string \"\n" 13588 " \"literal\"),\n" 13589 " b);", 13590 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13591 EXPECT_EQ("f(g(\"long string \"\n" 13592 " \"literal\",\n" 13593 " a),\n" 13594 " b);", 13595 format("f(g(\"long string literal\", a), b);", 13596 getLLVMStyleWithColumns(20))); 13597 EXPECT_EQ( 13598 "f(\"one two\".split(\n" 13599 " variable));", 13600 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13601 EXPECT_EQ("f(\"one two three four five six \"\n" 13602 " \"seven\".split(\n" 13603 " really_looooong_variable));", 13604 format("f(\"one two three four five six seven\"." 13605 "split(really_looooong_variable));", 13606 getLLVMStyleWithColumns(33))); 13607 13608 EXPECT_EQ("f(\"some \"\n" 13609 " \"text\",\n" 13610 " other);", 13611 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13612 13613 // Only break as a last resort. 13614 verifyFormat( 13615 "aaaaaaaaaaaaaaaaaaaa(\n" 13616 " aaaaaaaaaaaaaaaaaaaa,\n" 13617 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13618 13619 EXPECT_EQ("\"splitmea\"\n" 13620 "\"trandomp\"\n" 13621 "\"oint\"", 13622 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13623 13624 EXPECT_EQ("\"split/\"\n" 13625 "\"pathat/\"\n" 13626 "\"slashes\"", 13627 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13628 13629 EXPECT_EQ("\"split/\"\n" 13630 "\"pathat/\"\n" 13631 "\"slashes\"", 13632 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13633 EXPECT_EQ("\"split at \"\n" 13634 "\"spaces/at/\"\n" 13635 "\"slashes.at.any$\"\n" 13636 "\"non-alphanumeric%\"\n" 13637 "\"1111111111characte\"\n" 13638 "\"rs\"", 13639 format("\"split at " 13640 "spaces/at/" 13641 "slashes.at." 13642 "any$non-" 13643 "alphanumeric%" 13644 "1111111111characte" 13645 "rs\"", 13646 getLLVMStyleWithColumns(20))); 13647 13648 // Verify that splitting the strings understands 13649 // Style::AlwaysBreakBeforeMultilineStrings. 13650 EXPECT_EQ("aaaaaaaaaaaa(\n" 13651 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13652 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13653 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13654 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13655 "aaaaaaaaaaaaaaaaaaaaaa\");", 13656 getGoogleStyle())); 13657 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13658 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13659 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13660 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13661 "aaaaaaaaaaaaaaaaaaaaaa\";", 13662 getGoogleStyle())); 13663 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13664 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13665 format("llvm::outs() << " 13666 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13667 "aaaaaaaaaaaaaaaaaaa\";")); 13668 EXPECT_EQ("ffff(\n" 13669 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13670 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13671 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13672 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13673 getGoogleStyle())); 13674 13675 FormatStyle Style = getLLVMStyleWithColumns(12); 13676 Style.BreakStringLiterals = false; 13677 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13678 13679 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13680 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13681 EXPECT_EQ("#define A \\\n" 13682 " \"some \" \\\n" 13683 " \"text \" \\\n" 13684 " \"other\";", 13685 format("#define A \"some text other\";", AlignLeft)); 13686 } 13687 13688 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13689 EXPECT_EQ("C a = \"some more \"\n" 13690 " \"text\";", 13691 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13692 } 13693 13694 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13695 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13696 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13697 EXPECT_EQ("int i = a(b());", 13698 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13699 } 13700 13701 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13702 EXPECT_EQ( 13703 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13704 "(\n" 13705 " \"x\t\");", 13706 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13707 "aaaaaaa(" 13708 "\"x\t\");")); 13709 } 13710 13711 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13712 EXPECT_EQ( 13713 "u8\"utf8 string \"\n" 13714 "u8\"literal\";", 13715 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13716 EXPECT_EQ( 13717 "u\"utf16 string \"\n" 13718 "u\"literal\";", 13719 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13720 EXPECT_EQ( 13721 "U\"utf32 string \"\n" 13722 "U\"literal\";", 13723 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13724 EXPECT_EQ("L\"wide string \"\n" 13725 "L\"literal\";", 13726 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13727 EXPECT_EQ("@\"NSString \"\n" 13728 "@\"literal\";", 13729 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13730 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13731 13732 // This input makes clang-format try to split the incomplete unicode escape 13733 // sequence, which used to lead to a crasher. 13734 verifyNoCrash( 13735 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13736 getLLVMStyleWithColumns(60)); 13737 } 13738 13739 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13740 FormatStyle Style = getGoogleStyleWithColumns(15); 13741 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13742 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13743 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13744 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13745 EXPECT_EQ("u8R\"x(raw literal)x\";", 13746 format("u8R\"x(raw literal)x\";", Style)); 13747 } 13748 13749 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13750 FormatStyle Style = getLLVMStyleWithColumns(20); 13751 EXPECT_EQ( 13752 "_T(\"aaaaaaaaaaaaaa\")\n" 13753 "_T(\"aaaaaaaaaaaaaa\")\n" 13754 "_T(\"aaaaaaaaaaaa\")", 13755 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13756 EXPECT_EQ("f(x,\n" 13757 " _T(\"aaaaaaaaaaaa\")\n" 13758 " _T(\"aaa\"),\n" 13759 " z);", 13760 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13761 13762 // FIXME: Handle embedded spaces in one iteration. 13763 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13764 // "_T(\"aaaaaaaaaaaaa\")\n" 13765 // "_T(\"aaaaaaaaaaaaa\")\n" 13766 // "_T(\"a\")", 13767 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13768 // getLLVMStyleWithColumns(20))); 13769 EXPECT_EQ( 13770 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13771 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13772 EXPECT_EQ("f(\n" 13773 "#if !TEST\n" 13774 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13775 "#endif\n" 13776 ");", 13777 format("f(\n" 13778 "#if !TEST\n" 13779 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13780 "#endif\n" 13781 ");")); 13782 EXPECT_EQ("f(\n" 13783 "\n" 13784 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13785 format("f(\n" 13786 "\n" 13787 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13788 // Regression test for accessing tokens past the end of a vector in the 13789 // TokenLexer. 13790 verifyNoCrash(R"(_T( 13791 " 13792 ) 13793 )"); 13794 } 13795 13796 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13797 // In a function call with two operands, the second can be broken with no line 13798 // break before it. 13799 EXPECT_EQ( 13800 "func(a, \"long long \"\n" 13801 " \"long long\");", 13802 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13803 // In a function call with three operands, the second must be broken with a 13804 // line break before it. 13805 EXPECT_EQ("func(a,\n" 13806 " \"long long long \"\n" 13807 " \"long\",\n" 13808 " c);", 13809 format("func(a, \"long long long long\", c);", 13810 getLLVMStyleWithColumns(24))); 13811 // In a function call with three operands, the third must be broken with a 13812 // line break before it. 13813 EXPECT_EQ("func(a, b,\n" 13814 " \"long long long \"\n" 13815 " \"long\");", 13816 format("func(a, b, \"long long long long\");", 13817 getLLVMStyleWithColumns(24))); 13818 // In a function call with three operands, both the second and the third must 13819 // be broken with a line break before them. 13820 EXPECT_EQ("func(a,\n" 13821 " \"long long long \"\n" 13822 " \"long\",\n" 13823 " \"long long long \"\n" 13824 " \"long\");", 13825 format("func(a, \"long long long long\", \"long long long long\");", 13826 getLLVMStyleWithColumns(24))); 13827 // In a chain of << with two operands, the second can be broken with no line 13828 // break before it. 13829 EXPECT_EQ("a << \"line line \"\n" 13830 " \"line\";", 13831 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13832 // In a chain of << with three operands, the second can be broken with no line 13833 // break before it. 13834 EXPECT_EQ( 13835 "abcde << \"line \"\n" 13836 " \"line line\"\n" 13837 " << c;", 13838 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13839 // In a chain of << with three operands, the third must be broken with a line 13840 // break before it. 13841 EXPECT_EQ( 13842 "a << b\n" 13843 " << \"line line \"\n" 13844 " \"line\";", 13845 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13846 // In a chain of << with three operands, the second can be broken with no line 13847 // break before it and the third must be broken with a line break before it. 13848 EXPECT_EQ("abcd << \"line line \"\n" 13849 " \"line\"\n" 13850 " << \"line line \"\n" 13851 " \"line\";", 13852 format("abcd << \"line line line\" << \"line line line\";", 13853 getLLVMStyleWithColumns(20))); 13854 // In a chain of binary operators with two operands, the second can be broken 13855 // with no line break before it. 13856 EXPECT_EQ( 13857 "abcd + \"line line \"\n" 13858 " \"line line\";", 13859 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13860 // In a chain of binary operators with three operands, the second must be 13861 // broken with a line break before it. 13862 EXPECT_EQ("abcd +\n" 13863 " \"line line \"\n" 13864 " \"line line\" +\n" 13865 " e;", 13866 format("abcd + \"line line line line\" + e;", 13867 getLLVMStyleWithColumns(20))); 13868 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13869 // the first must be broken with a line break before it. 13870 FormatStyle Style = getLLVMStyleWithColumns(25); 13871 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13872 EXPECT_EQ("someFunction(\n" 13873 " \"long long long \"\n" 13874 " \"long\",\n" 13875 " a);", 13876 format("someFunction(\"long long long long\", a);", Style)); 13877 } 13878 13879 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13880 EXPECT_EQ( 13881 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13882 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13883 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13884 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13885 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13886 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13887 } 13888 13889 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13890 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13891 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13892 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13893 "multiline raw string literal xxxxxxxxxxxxxx\n" 13894 ")x\",\n" 13895 " a),\n" 13896 " b);", 13897 format("fffffffffff(g(R\"x(\n" 13898 "multiline raw string literal xxxxxxxxxxxxxx\n" 13899 ")x\", a), b);", 13900 getGoogleStyleWithColumns(20))); 13901 EXPECT_EQ("fffffffffff(\n" 13902 " g(R\"x(qqq\n" 13903 "multiline raw string literal xxxxxxxxxxxxxx\n" 13904 ")x\",\n" 13905 " a),\n" 13906 " b);", 13907 format("fffffffffff(g(R\"x(qqq\n" 13908 "multiline raw string literal xxxxxxxxxxxxxx\n" 13909 ")x\", a), b);", 13910 getGoogleStyleWithColumns(20))); 13911 13912 EXPECT_EQ("fffffffffff(R\"x(\n" 13913 "multiline raw string literal xxxxxxxxxxxxxx\n" 13914 ")x\");", 13915 format("fffffffffff(R\"x(\n" 13916 "multiline raw string literal xxxxxxxxxxxxxx\n" 13917 ")x\");", 13918 getGoogleStyleWithColumns(20))); 13919 EXPECT_EQ("fffffffffff(R\"x(\n" 13920 "multiline raw string literal xxxxxxxxxxxxxx\n" 13921 ")x\" + bbbbbb);", 13922 format("fffffffffff(R\"x(\n" 13923 "multiline raw string literal xxxxxxxxxxxxxx\n" 13924 ")x\" + bbbbbb);", 13925 getGoogleStyleWithColumns(20))); 13926 EXPECT_EQ("fffffffffff(\n" 13927 " R\"x(\n" 13928 "multiline raw string literal xxxxxxxxxxxxxx\n" 13929 ")x\" +\n" 13930 " bbbbbb);", 13931 format("fffffffffff(\n" 13932 " R\"x(\n" 13933 "multiline raw string literal xxxxxxxxxxxxxx\n" 13934 ")x\" + bbbbbb);", 13935 getGoogleStyleWithColumns(20))); 13936 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13937 format("fffffffffff(\n" 13938 " R\"(single line raw string)\" + bbbbbb);")); 13939 } 13940 13941 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13942 verifyFormat("string a = \"unterminated;"); 13943 EXPECT_EQ("function(\"unterminated,\n" 13944 " OtherParameter);", 13945 format("function( \"unterminated,\n" 13946 " OtherParameter);")); 13947 } 13948 13949 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13950 FormatStyle Style = getLLVMStyle(); 13951 Style.Standard = FormatStyle::LS_Cpp03; 13952 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13953 format("#define x(_a) printf(\"foo\"_a);", Style)); 13954 } 13955 13956 TEST_F(FormatTest, CppLexVersion) { 13957 FormatStyle Style = getLLVMStyle(); 13958 // Formatting of x * y differs if x is a type. 13959 verifyFormat("void foo() { MACRO(a * b); }", Style); 13960 verifyFormat("void foo() { MACRO(int *b); }", Style); 13961 13962 // LLVM style uses latest lexer. 13963 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13964 Style.Standard = FormatStyle::LS_Cpp17; 13965 // But in c++17, char8_t isn't a keyword. 13966 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13967 } 13968 13969 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13970 13971 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13972 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13973 " \"ddeeefff\");", 13974 format("someFunction(\"aaabbbcccdddeeefff\");", 13975 getLLVMStyleWithColumns(25))); 13976 EXPECT_EQ("someFunction1234567890(\n" 13977 " \"aaabbbcccdddeeefff\");", 13978 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13979 getLLVMStyleWithColumns(26))); 13980 EXPECT_EQ("someFunction1234567890(\n" 13981 " \"aaabbbcccdddeeeff\"\n" 13982 " \"f\");", 13983 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13984 getLLVMStyleWithColumns(25))); 13985 EXPECT_EQ("someFunction1234567890(\n" 13986 " \"aaabbbcccdddeeeff\"\n" 13987 " \"f\");", 13988 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13989 getLLVMStyleWithColumns(24))); 13990 EXPECT_EQ("someFunction(\n" 13991 " \"aaabbbcc ddde \"\n" 13992 " \"efff\");", 13993 format("someFunction(\"aaabbbcc ddde efff\");", 13994 getLLVMStyleWithColumns(25))); 13995 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13996 " \"ddeeefff\");", 13997 format("someFunction(\"aaabbbccc ddeeefff\");", 13998 getLLVMStyleWithColumns(25))); 13999 EXPECT_EQ("someFunction1234567890(\n" 14000 " \"aaabb \"\n" 14001 " \"cccdddeeefff\");", 14002 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 14003 getLLVMStyleWithColumns(25))); 14004 EXPECT_EQ("#define A \\\n" 14005 " string s = \\\n" 14006 " \"123456789\" \\\n" 14007 " \"0\"; \\\n" 14008 " int i;", 14009 format("#define A string s = \"1234567890\"; int i;", 14010 getLLVMStyleWithColumns(20))); 14011 EXPECT_EQ("someFunction(\n" 14012 " \"aaabbbcc \"\n" 14013 " \"dddeeefff\");", 14014 format("someFunction(\"aaabbbcc dddeeefff\");", 14015 getLLVMStyleWithColumns(25))); 14016 } 14017 14018 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 14019 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 14020 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 14021 EXPECT_EQ("\"test\"\n" 14022 "\"\\n\"", 14023 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 14024 EXPECT_EQ("\"tes\\\\\"\n" 14025 "\"n\"", 14026 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 14027 EXPECT_EQ("\"\\\\\\\\\"\n" 14028 "\"\\n\"", 14029 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 14030 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 14031 EXPECT_EQ("\"\\uff01\"\n" 14032 "\"test\"", 14033 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14034 EXPECT_EQ("\"\\Uff01ff02\"", 14035 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14036 EXPECT_EQ("\"\\x000000000001\"\n" 14037 "\"next\"", 14038 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14039 EXPECT_EQ("\"\\x000000000001next\"", 14040 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14041 EXPECT_EQ("\"\\x000000000001\"", 14042 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14043 EXPECT_EQ("\"test\"\n" 14044 "\"\\000000\"\n" 14045 "\"000001\"", 14046 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14047 EXPECT_EQ("\"test\\000\"\n" 14048 "\"00000000\"\n" 14049 "\"1\"", 14050 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14051 } 14052 14053 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14054 verifyFormat("void f() {\n" 14055 " return g() {}\n" 14056 " void h() {}"); 14057 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14058 "g();\n" 14059 "}"); 14060 } 14061 14062 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14063 verifyFormat( 14064 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14065 } 14066 14067 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14068 verifyFormat("class X {\n" 14069 " void f() {\n" 14070 " }\n" 14071 "};", 14072 getLLVMStyleWithColumns(12)); 14073 } 14074 14075 TEST_F(FormatTest, ConfigurableIndentWidth) { 14076 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14077 EightIndent.IndentWidth = 8; 14078 EightIndent.ContinuationIndentWidth = 8; 14079 verifyFormat("void f() {\n" 14080 " someFunction();\n" 14081 " if (true) {\n" 14082 " f();\n" 14083 " }\n" 14084 "}", 14085 EightIndent); 14086 verifyFormat("class X {\n" 14087 " void f() {\n" 14088 " }\n" 14089 "};", 14090 EightIndent); 14091 verifyFormat("int x[] = {\n" 14092 " call(),\n" 14093 " call()};", 14094 EightIndent); 14095 } 14096 14097 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14098 verifyFormat("double\n" 14099 "f();", 14100 getLLVMStyleWithColumns(8)); 14101 } 14102 14103 TEST_F(FormatTest, ConfigurableUseOfTab) { 14104 FormatStyle Tab = getLLVMStyleWithColumns(42); 14105 Tab.IndentWidth = 8; 14106 Tab.UseTab = FormatStyle::UT_Always; 14107 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14108 14109 EXPECT_EQ("if (aaaaaaaa && // q\n" 14110 " bb)\t\t// w\n" 14111 "\t;", 14112 format("if (aaaaaaaa &&// q\n" 14113 "bb)// w\n" 14114 ";", 14115 Tab)); 14116 EXPECT_EQ("if (aaa && bbb) // w\n" 14117 "\t;", 14118 format("if(aaa&&bbb)// w\n" 14119 ";", 14120 Tab)); 14121 14122 verifyFormat("class X {\n" 14123 "\tvoid f() {\n" 14124 "\t\tsomeFunction(parameter1,\n" 14125 "\t\t\t parameter2);\n" 14126 "\t}\n" 14127 "};", 14128 Tab); 14129 verifyFormat("#define A \\\n" 14130 "\tvoid f() { \\\n" 14131 "\t\tsomeFunction( \\\n" 14132 "\t\t parameter1, \\\n" 14133 "\t\t parameter2); \\\n" 14134 "\t}", 14135 Tab); 14136 verifyFormat("int a;\t // x\n" 14137 "int bbbbbbbb; // x\n", 14138 Tab); 14139 14140 Tab.TabWidth = 4; 14141 Tab.IndentWidth = 8; 14142 verifyFormat("class TabWidth4Indent8 {\n" 14143 "\t\tvoid f() {\n" 14144 "\t\t\t\tsomeFunction(parameter1,\n" 14145 "\t\t\t\t\t\t\t parameter2);\n" 14146 "\t\t}\n" 14147 "};", 14148 Tab); 14149 14150 Tab.TabWidth = 4; 14151 Tab.IndentWidth = 4; 14152 verifyFormat("class TabWidth4Indent4 {\n" 14153 "\tvoid f() {\n" 14154 "\t\tsomeFunction(parameter1,\n" 14155 "\t\t\t\t\t parameter2);\n" 14156 "\t}\n" 14157 "};", 14158 Tab); 14159 14160 Tab.TabWidth = 8; 14161 Tab.IndentWidth = 4; 14162 verifyFormat("class TabWidth8Indent4 {\n" 14163 " void f() {\n" 14164 "\tsomeFunction(parameter1,\n" 14165 "\t\t parameter2);\n" 14166 " }\n" 14167 "};", 14168 Tab); 14169 14170 Tab.TabWidth = 8; 14171 Tab.IndentWidth = 8; 14172 EXPECT_EQ("/*\n" 14173 "\t a\t\tcomment\n" 14174 "\t in multiple lines\n" 14175 " */", 14176 format(" /*\t \t \n" 14177 " \t \t a\t\tcomment\t \t\n" 14178 " \t \t in multiple lines\t\n" 14179 " \t */", 14180 Tab)); 14181 14182 Tab.UseTab = FormatStyle::UT_ForIndentation; 14183 verifyFormat("{\n" 14184 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14185 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14186 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14187 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14188 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14189 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14190 "};", 14191 Tab); 14192 verifyFormat("enum AA {\n" 14193 "\ta1, // Force multiple lines\n" 14194 "\ta2,\n" 14195 "\ta3\n" 14196 "};", 14197 Tab); 14198 EXPECT_EQ("if (aaaaaaaa && // q\n" 14199 " bb) // w\n" 14200 "\t;", 14201 format("if (aaaaaaaa &&// q\n" 14202 "bb)// w\n" 14203 ";", 14204 Tab)); 14205 verifyFormat("class X {\n" 14206 "\tvoid f() {\n" 14207 "\t\tsomeFunction(parameter1,\n" 14208 "\t\t parameter2);\n" 14209 "\t}\n" 14210 "};", 14211 Tab); 14212 verifyFormat("{\n" 14213 "\tQ(\n" 14214 "\t {\n" 14215 "\t\t int a;\n" 14216 "\t\t someFunction(aaaaaaaa,\n" 14217 "\t\t bbbbbbb);\n" 14218 "\t },\n" 14219 "\t p);\n" 14220 "}", 14221 Tab); 14222 EXPECT_EQ("{\n" 14223 "\t/* aaaa\n" 14224 "\t bbbb */\n" 14225 "}", 14226 format("{\n" 14227 "/* aaaa\n" 14228 " bbbb */\n" 14229 "}", 14230 Tab)); 14231 EXPECT_EQ("{\n" 14232 "\t/*\n" 14233 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14234 "\t bbbbbbbbbbbbb\n" 14235 "\t*/\n" 14236 "}", 14237 format("{\n" 14238 "/*\n" 14239 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14240 "*/\n" 14241 "}", 14242 Tab)); 14243 EXPECT_EQ("{\n" 14244 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14245 "\t// bbbbbbbbbbbbb\n" 14246 "}", 14247 format("{\n" 14248 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14249 "}", 14250 Tab)); 14251 EXPECT_EQ("{\n" 14252 "\t/*\n" 14253 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14254 "\t bbbbbbbbbbbbb\n" 14255 "\t*/\n" 14256 "}", 14257 format("{\n" 14258 "\t/*\n" 14259 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14260 "\t*/\n" 14261 "}", 14262 Tab)); 14263 EXPECT_EQ("{\n" 14264 "\t/*\n" 14265 "\n" 14266 "\t*/\n" 14267 "}", 14268 format("{\n" 14269 "\t/*\n" 14270 "\n" 14271 "\t*/\n" 14272 "}", 14273 Tab)); 14274 EXPECT_EQ("{\n" 14275 "\t/*\n" 14276 " asdf\n" 14277 "\t*/\n" 14278 "}", 14279 format("{\n" 14280 "\t/*\n" 14281 " asdf\n" 14282 "\t*/\n" 14283 "}", 14284 Tab)); 14285 14286 verifyFormat("void f() {\n" 14287 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14288 "\t : bbbbbbbbbbbbbbbbbb\n" 14289 "}", 14290 Tab); 14291 FormatStyle TabNoBreak = Tab; 14292 TabNoBreak.BreakBeforeTernaryOperators = false; 14293 verifyFormat("void f() {\n" 14294 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14295 "\t bbbbbbbbbbbbbbbbbb\n" 14296 "}", 14297 TabNoBreak); 14298 verifyFormat("void f() {\n" 14299 "\treturn true ?\n" 14300 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14301 "\t bbbbbbbbbbbbbbbbbbbb\n" 14302 "}", 14303 TabNoBreak); 14304 14305 Tab.UseTab = FormatStyle::UT_Never; 14306 EXPECT_EQ("/*\n" 14307 " a\t\tcomment\n" 14308 " in multiple lines\n" 14309 " */", 14310 format(" /*\t \t \n" 14311 " \t \t a\t\tcomment\t \t\n" 14312 " \t \t in multiple lines\t\n" 14313 " \t */", 14314 Tab)); 14315 EXPECT_EQ("/* some\n" 14316 " comment */", 14317 format(" \t \t /* some\n" 14318 " \t \t comment */", 14319 Tab)); 14320 EXPECT_EQ("int a; /* some\n" 14321 " comment */", 14322 format(" \t \t int a; /* some\n" 14323 " \t \t comment */", 14324 Tab)); 14325 14326 EXPECT_EQ("int a; /* some\n" 14327 "comment */", 14328 format(" \t \t int\ta; /* some\n" 14329 " \t \t comment */", 14330 Tab)); 14331 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14332 " comment */", 14333 format(" \t \t f(\"\t\t\"); /* some\n" 14334 " \t \t comment */", 14335 Tab)); 14336 EXPECT_EQ("{\n" 14337 " /*\n" 14338 " * Comment\n" 14339 " */\n" 14340 " int i;\n" 14341 "}", 14342 format("{\n" 14343 "\t/*\n" 14344 "\t * Comment\n" 14345 "\t */\n" 14346 "\t int i;\n" 14347 "}", 14348 Tab)); 14349 14350 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14351 Tab.TabWidth = 8; 14352 Tab.IndentWidth = 8; 14353 EXPECT_EQ("if (aaaaaaaa && // q\n" 14354 " bb) // w\n" 14355 "\t;", 14356 format("if (aaaaaaaa &&// q\n" 14357 "bb)// w\n" 14358 ";", 14359 Tab)); 14360 EXPECT_EQ("if (aaa && bbb) // w\n" 14361 "\t;", 14362 format("if(aaa&&bbb)// w\n" 14363 ";", 14364 Tab)); 14365 verifyFormat("class X {\n" 14366 "\tvoid f() {\n" 14367 "\t\tsomeFunction(parameter1,\n" 14368 "\t\t\t parameter2);\n" 14369 "\t}\n" 14370 "};", 14371 Tab); 14372 verifyFormat("#define A \\\n" 14373 "\tvoid f() { \\\n" 14374 "\t\tsomeFunction( \\\n" 14375 "\t\t parameter1, \\\n" 14376 "\t\t parameter2); \\\n" 14377 "\t}", 14378 Tab); 14379 Tab.TabWidth = 4; 14380 Tab.IndentWidth = 8; 14381 verifyFormat("class TabWidth4Indent8 {\n" 14382 "\t\tvoid f() {\n" 14383 "\t\t\t\tsomeFunction(parameter1,\n" 14384 "\t\t\t\t\t\t\t parameter2);\n" 14385 "\t\t}\n" 14386 "};", 14387 Tab); 14388 Tab.TabWidth = 4; 14389 Tab.IndentWidth = 4; 14390 verifyFormat("class TabWidth4Indent4 {\n" 14391 "\tvoid f() {\n" 14392 "\t\tsomeFunction(parameter1,\n" 14393 "\t\t\t\t\t parameter2);\n" 14394 "\t}\n" 14395 "};", 14396 Tab); 14397 Tab.TabWidth = 8; 14398 Tab.IndentWidth = 4; 14399 verifyFormat("class TabWidth8Indent4 {\n" 14400 " void f() {\n" 14401 "\tsomeFunction(parameter1,\n" 14402 "\t\t parameter2);\n" 14403 " }\n" 14404 "};", 14405 Tab); 14406 Tab.TabWidth = 8; 14407 Tab.IndentWidth = 8; 14408 EXPECT_EQ("/*\n" 14409 "\t a\t\tcomment\n" 14410 "\t in multiple lines\n" 14411 " */", 14412 format(" /*\t \t \n" 14413 " \t \t a\t\tcomment\t \t\n" 14414 " \t \t in multiple lines\t\n" 14415 " \t */", 14416 Tab)); 14417 verifyFormat("{\n" 14418 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14419 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14420 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14421 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14422 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14423 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14424 "};", 14425 Tab); 14426 verifyFormat("enum AA {\n" 14427 "\ta1, // Force multiple lines\n" 14428 "\ta2,\n" 14429 "\ta3\n" 14430 "};", 14431 Tab); 14432 EXPECT_EQ("if (aaaaaaaa && // q\n" 14433 " bb) // w\n" 14434 "\t;", 14435 format("if (aaaaaaaa &&// q\n" 14436 "bb)// w\n" 14437 ";", 14438 Tab)); 14439 verifyFormat("class X {\n" 14440 "\tvoid f() {\n" 14441 "\t\tsomeFunction(parameter1,\n" 14442 "\t\t\t parameter2);\n" 14443 "\t}\n" 14444 "};", 14445 Tab); 14446 verifyFormat("{\n" 14447 "\tQ(\n" 14448 "\t {\n" 14449 "\t\t int a;\n" 14450 "\t\t someFunction(aaaaaaaa,\n" 14451 "\t\t\t\t bbbbbbb);\n" 14452 "\t },\n" 14453 "\t p);\n" 14454 "}", 14455 Tab); 14456 EXPECT_EQ("{\n" 14457 "\t/* aaaa\n" 14458 "\t bbbb */\n" 14459 "}", 14460 format("{\n" 14461 "/* aaaa\n" 14462 " bbbb */\n" 14463 "}", 14464 Tab)); 14465 EXPECT_EQ("{\n" 14466 "\t/*\n" 14467 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14468 "\t bbbbbbbbbbbbb\n" 14469 "\t*/\n" 14470 "}", 14471 format("{\n" 14472 "/*\n" 14473 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14474 "*/\n" 14475 "}", 14476 Tab)); 14477 EXPECT_EQ("{\n" 14478 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14479 "\t// bbbbbbbbbbbbb\n" 14480 "}", 14481 format("{\n" 14482 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14483 "}", 14484 Tab)); 14485 EXPECT_EQ("{\n" 14486 "\t/*\n" 14487 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14488 "\t bbbbbbbbbbbbb\n" 14489 "\t*/\n" 14490 "}", 14491 format("{\n" 14492 "\t/*\n" 14493 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14494 "\t*/\n" 14495 "}", 14496 Tab)); 14497 EXPECT_EQ("{\n" 14498 "\t/*\n" 14499 "\n" 14500 "\t*/\n" 14501 "}", 14502 format("{\n" 14503 "\t/*\n" 14504 "\n" 14505 "\t*/\n" 14506 "}", 14507 Tab)); 14508 EXPECT_EQ("{\n" 14509 "\t/*\n" 14510 " asdf\n" 14511 "\t*/\n" 14512 "}", 14513 format("{\n" 14514 "\t/*\n" 14515 " asdf\n" 14516 "\t*/\n" 14517 "}", 14518 Tab)); 14519 EXPECT_EQ("/* some\n" 14520 " comment */", 14521 format(" \t \t /* some\n" 14522 " \t \t comment */", 14523 Tab)); 14524 EXPECT_EQ("int a; /* some\n" 14525 " comment */", 14526 format(" \t \t int a; /* some\n" 14527 " \t \t comment */", 14528 Tab)); 14529 EXPECT_EQ("int a; /* some\n" 14530 "comment */", 14531 format(" \t \t int\ta; /* some\n" 14532 " \t \t comment */", 14533 Tab)); 14534 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14535 " comment */", 14536 format(" \t \t f(\"\t\t\"); /* some\n" 14537 " \t \t comment */", 14538 Tab)); 14539 EXPECT_EQ("{\n" 14540 "\t/*\n" 14541 "\t * Comment\n" 14542 "\t */\n" 14543 "\tint i;\n" 14544 "}", 14545 format("{\n" 14546 "\t/*\n" 14547 "\t * Comment\n" 14548 "\t */\n" 14549 "\t int i;\n" 14550 "}", 14551 Tab)); 14552 Tab.TabWidth = 2; 14553 Tab.IndentWidth = 2; 14554 EXPECT_EQ("{\n" 14555 "\t/* aaaa\n" 14556 "\t\t bbbb */\n" 14557 "}", 14558 format("{\n" 14559 "/* aaaa\n" 14560 "\t bbbb */\n" 14561 "}", 14562 Tab)); 14563 EXPECT_EQ("{\n" 14564 "\t/*\n" 14565 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14566 "\t\tbbbbbbbbbbbbb\n" 14567 "\t*/\n" 14568 "}", 14569 format("{\n" 14570 "/*\n" 14571 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14572 "*/\n" 14573 "}", 14574 Tab)); 14575 Tab.AlignConsecutiveAssignments.Enabled = true; 14576 Tab.AlignConsecutiveDeclarations.Enabled = true; 14577 Tab.TabWidth = 4; 14578 Tab.IndentWidth = 4; 14579 verifyFormat("class Assign {\n" 14580 "\tvoid f() {\n" 14581 "\t\tint x = 123;\n" 14582 "\t\tint random = 4;\n" 14583 "\t\tstd::string alphabet =\n" 14584 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14585 "\t}\n" 14586 "};", 14587 Tab); 14588 14589 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14590 Tab.TabWidth = 8; 14591 Tab.IndentWidth = 8; 14592 EXPECT_EQ("if (aaaaaaaa && // q\n" 14593 " bb) // w\n" 14594 "\t;", 14595 format("if (aaaaaaaa &&// q\n" 14596 "bb)// w\n" 14597 ";", 14598 Tab)); 14599 EXPECT_EQ("if (aaa && bbb) // w\n" 14600 "\t;", 14601 format("if(aaa&&bbb)// w\n" 14602 ";", 14603 Tab)); 14604 verifyFormat("class X {\n" 14605 "\tvoid f() {\n" 14606 "\t\tsomeFunction(parameter1,\n" 14607 "\t\t parameter2);\n" 14608 "\t}\n" 14609 "};", 14610 Tab); 14611 verifyFormat("#define A \\\n" 14612 "\tvoid f() { \\\n" 14613 "\t\tsomeFunction( \\\n" 14614 "\t\t parameter1, \\\n" 14615 "\t\t parameter2); \\\n" 14616 "\t}", 14617 Tab); 14618 Tab.TabWidth = 4; 14619 Tab.IndentWidth = 8; 14620 verifyFormat("class TabWidth4Indent8 {\n" 14621 "\t\tvoid f() {\n" 14622 "\t\t\t\tsomeFunction(parameter1,\n" 14623 "\t\t\t\t parameter2);\n" 14624 "\t\t}\n" 14625 "};", 14626 Tab); 14627 Tab.TabWidth = 4; 14628 Tab.IndentWidth = 4; 14629 verifyFormat("class TabWidth4Indent4 {\n" 14630 "\tvoid f() {\n" 14631 "\t\tsomeFunction(parameter1,\n" 14632 "\t\t parameter2);\n" 14633 "\t}\n" 14634 "};", 14635 Tab); 14636 Tab.TabWidth = 8; 14637 Tab.IndentWidth = 4; 14638 verifyFormat("class TabWidth8Indent4 {\n" 14639 " void f() {\n" 14640 "\tsomeFunction(parameter1,\n" 14641 "\t parameter2);\n" 14642 " }\n" 14643 "};", 14644 Tab); 14645 Tab.TabWidth = 8; 14646 Tab.IndentWidth = 8; 14647 EXPECT_EQ("/*\n" 14648 " a\t\tcomment\n" 14649 " in multiple lines\n" 14650 " */", 14651 format(" /*\t \t \n" 14652 " \t \t a\t\tcomment\t \t\n" 14653 " \t \t in multiple lines\t\n" 14654 " \t */", 14655 Tab)); 14656 verifyFormat("{\n" 14657 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14658 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14659 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14660 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14661 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14662 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14663 "};", 14664 Tab); 14665 verifyFormat("enum AA {\n" 14666 "\ta1, // Force multiple lines\n" 14667 "\ta2,\n" 14668 "\ta3\n" 14669 "};", 14670 Tab); 14671 EXPECT_EQ("if (aaaaaaaa && // q\n" 14672 " bb) // w\n" 14673 "\t;", 14674 format("if (aaaaaaaa &&// q\n" 14675 "bb)// w\n" 14676 ";", 14677 Tab)); 14678 verifyFormat("class X {\n" 14679 "\tvoid f() {\n" 14680 "\t\tsomeFunction(parameter1,\n" 14681 "\t\t parameter2);\n" 14682 "\t}\n" 14683 "};", 14684 Tab); 14685 verifyFormat("{\n" 14686 "\tQ(\n" 14687 "\t {\n" 14688 "\t\t int a;\n" 14689 "\t\t someFunction(aaaaaaaa,\n" 14690 "\t\t bbbbbbb);\n" 14691 "\t },\n" 14692 "\t p);\n" 14693 "}", 14694 Tab); 14695 EXPECT_EQ("{\n" 14696 "\t/* aaaa\n" 14697 "\t bbbb */\n" 14698 "}", 14699 format("{\n" 14700 "/* aaaa\n" 14701 " bbbb */\n" 14702 "}", 14703 Tab)); 14704 EXPECT_EQ("{\n" 14705 "\t/*\n" 14706 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14707 "\t bbbbbbbbbbbbb\n" 14708 "\t*/\n" 14709 "}", 14710 format("{\n" 14711 "/*\n" 14712 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14713 "*/\n" 14714 "}", 14715 Tab)); 14716 EXPECT_EQ("{\n" 14717 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14718 "\t// bbbbbbbbbbbbb\n" 14719 "}", 14720 format("{\n" 14721 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14722 "}", 14723 Tab)); 14724 EXPECT_EQ("{\n" 14725 "\t/*\n" 14726 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14727 "\t bbbbbbbbbbbbb\n" 14728 "\t*/\n" 14729 "}", 14730 format("{\n" 14731 "\t/*\n" 14732 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14733 "\t*/\n" 14734 "}", 14735 Tab)); 14736 EXPECT_EQ("{\n" 14737 "\t/*\n" 14738 "\n" 14739 "\t*/\n" 14740 "}", 14741 format("{\n" 14742 "\t/*\n" 14743 "\n" 14744 "\t*/\n" 14745 "}", 14746 Tab)); 14747 EXPECT_EQ("{\n" 14748 "\t/*\n" 14749 " asdf\n" 14750 "\t*/\n" 14751 "}", 14752 format("{\n" 14753 "\t/*\n" 14754 " asdf\n" 14755 "\t*/\n" 14756 "}", 14757 Tab)); 14758 EXPECT_EQ("/* some\n" 14759 " comment */", 14760 format(" \t \t /* some\n" 14761 " \t \t comment */", 14762 Tab)); 14763 EXPECT_EQ("int a; /* some\n" 14764 " comment */", 14765 format(" \t \t int a; /* some\n" 14766 " \t \t comment */", 14767 Tab)); 14768 EXPECT_EQ("int a; /* some\n" 14769 "comment */", 14770 format(" \t \t int\ta; /* some\n" 14771 " \t \t comment */", 14772 Tab)); 14773 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14774 " comment */", 14775 format(" \t \t f(\"\t\t\"); /* some\n" 14776 " \t \t comment */", 14777 Tab)); 14778 EXPECT_EQ("{\n" 14779 "\t/*\n" 14780 "\t * Comment\n" 14781 "\t */\n" 14782 "\tint i;\n" 14783 "}", 14784 format("{\n" 14785 "\t/*\n" 14786 "\t * Comment\n" 14787 "\t */\n" 14788 "\t int i;\n" 14789 "}", 14790 Tab)); 14791 Tab.TabWidth = 2; 14792 Tab.IndentWidth = 2; 14793 EXPECT_EQ("{\n" 14794 "\t/* aaaa\n" 14795 "\t bbbb */\n" 14796 "}", 14797 format("{\n" 14798 "/* aaaa\n" 14799 " bbbb */\n" 14800 "}", 14801 Tab)); 14802 EXPECT_EQ("{\n" 14803 "\t/*\n" 14804 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14805 "\t bbbbbbbbbbbbb\n" 14806 "\t*/\n" 14807 "}", 14808 format("{\n" 14809 "/*\n" 14810 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14811 "*/\n" 14812 "}", 14813 Tab)); 14814 Tab.AlignConsecutiveAssignments.Enabled = true; 14815 Tab.AlignConsecutiveDeclarations.Enabled = true; 14816 Tab.TabWidth = 4; 14817 Tab.IndentWidth = 4; 14818 verifyFormat("class Assign {\n" 14819 "\tvoid f() {\n" 14820 "\t\tint x = 123;\n" 14821 "\t\tint random = 4;\n" 14822 "\t\tstd::string alphabet =\n" 14823 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14824 "\t}\n" 14825 "};", 14826 Tab); 14827 Tab.AlignOperands = FormatStyle::OAS_Align; 14828 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14829 " cccccccccccccccccccc;", 14830 Tab); 14831 // no alignment 14832 verifyFormat("int aaaaaaaaaa =\n" 14833 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14834 Tab); 14835 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14836 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14837 " : 333333333333333;", 14838 Tab); 14839 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14840 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14841 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14842 " + cccccccccccccccccccc;", 14843 Tab); 14844 } 14845 14846 TEST_F(FormatTest, ZeroTabWidth) { 14847 FormatStyle Tab = getLLVMStyleWithColumns(42); 14848 Tab.IndentWidth = 8; 14849 Tab.UseTab = FormatStyle::UT_Never; 14850 Tab.TabWidth = 0; 14851 EXPECT_EQ("void a(){\n" 14852 " // line starts with '\t'\n" 14853 "};", 14854 format("void a(){\n" 14855 "\t// line starts with '\t'\n" 14856 "};", 14857 Tab)); 14858 14859 EXPECT_EQ("void a(){\n" 14860 " // line starts with '\t'\n" 14861 "};", 14862 format("void a(){\n" 14863 "\t\t// line starts with '\t'\n" 14864 "};", 14865 Tab)); 14866 14867 Tab.UseTab = FormatStyle::UT_ForIndentation; 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_ForContinuationAndIndentation; 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_AlignWithSpaces; 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_Always; 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 14936 TEST_F(FormatTest, CalculatesOriginalColumn) { 14937 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14938 "q\"; /* some\n" 14939 " comment */", 14940 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14941 "q\"; /* some\n" 14942 " comment */", 14943 getLLVMStyle())); 14944 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14945 "/* some\n" 14946 " comment */", 14947 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14948 " /* some\n" 14949 " comment */", 14950 getLLVMStyle())); 14951 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14952 "qqq\n" 14953 "/* some\n" 14954 " comment */", 14955 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14956 "qqq\n" 14957 " /* some\n" 14958 " comment */", 14959 getLLVMStyle())); 14960 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14961 "wwww; /* some\n" 14962 " comment */", 14963 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14964 "wwww; /* some\n" 14965 " comment */", 14966 getLLVMStyle())); 14967 } 14968 14969 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14970 FormatStyle NoSpace = getLLVMStyle(); 14971 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14972 14973 verifyFormat("while(true)\n" 14974 " continue;", 14975 NoSpace); 14976 verifyFormat("for(;;)\n" 14977 " continue;", 14978 NoSpace); 14979 verifyFormat("if(true)\n" 14980 " f();\n" 14981 "else if(true)\n" 14982 " f();", 14983 NoSpace); 14984 verifyFormat("do {\n" 14985 " do_something();\n" 14986 "} while(something());", 14987 NoSpace); 14988 verifyFormat("switch(x) {\n" 14989 "default:\n" 14990 " break;\n" 14991 "}", 14992 NoSpace); 14993 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14994 verifyFormat("size_t x = sizeof(x);", NoSpace); 14995 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14996 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14997 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14998 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14999 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 15000 verifyFormat("alignas(128) char a[128];", NoSpace); 15001 verifyFormat("size_t x = alignof(MyType);", NoSpace); 15002 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 15003 verifyFormat("int f() throw(Deprecated);", NoSpace); 15004 verifyFormat("typedef void (*cb)(int);", NoSpace); 15005 verifyFormat("T A::operator()();", NoSpace); 15006 verifyFormat("X A::operator++(T);", NoSpace); 15007 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 15008 15009 FormatStyle Space = getLLVMStyle(); 15010 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 15011 15012 verifyFormat("int f ();", Space); 15013 verifyFormat("void f (int a, T b) {\n" 15014 " while (true)\n" 15015 " continue;\n" 15016 "}", 15017 Space); 15018 verifyFormat("if (true)\n" 15019 " f ();\n" 15020 "else if (true)\n" 15021 " f ();", 15022 Space); 15023 verifyFormat("do {\n" 15024 " do_something ();\n" 15025 "} while (something ());", 15026 Space); 15027 verifyFormat("switch (x) {\n" 15028 "default:\n" 15029 " break;\n" 15030 "}", 15031 Space); 15032 verifyFormat("A::A () : a (1) {}", Space); 15033 verifyFormat("void f () __attribute__ ((asdf));", Space); 15034 verifyFormat("*(&a + 1);\n" 15035 "&((&a)[1]);\n" 15036 "a[(b + c) * d];\n" 15037 "(((a + 1) * 2) + 3) * 4;", 15038 Space); 15039 verifyFormat("#define A(x) x", Space); 15040 verifyFormat("#define A (x) x", Space); 15041 verifyFormat("#if defined(x)\n" 15042 "#endif", 15043 Space); 15044 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15045 verifyFormat("size_t x = sizeof (x);", Space); 15046 verifyFormat("auto f (int x) -> decltype (x);", Space); 15047 verifyFormat("auto f (int x) -> typeof (x);", Space); 15048 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15049 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15050 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15051 verifyFormat("alignas (128) char a[128];", Space); 15052 verifyFormat("size_t x = alignof (MyType);", Space); 15053 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15054 verifyFormat("int f () throw (Deprecated);", Space); 15055 verifyFormat("typedef void (*cb) (int);", Space); 15056 // FIXME these tests regressed behaviour. 15057 // verifyFormat("T A::operator() ();", Space); 15058 // verifyFormat("X A::operator++ (T);", Space); 15059 verifyFormat("auto lambda = [] () { return 0; };", Space); 15060 verifyFormat("int x = int (y);", Space); 15061 15062 FormatStyle SomeSpace = getLLVMStyle(); 15063 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15064 15065 verifyFormat("[]() -> float {}", SomeSpace); 15066 verifyFormat("[] (auto foo) {}", SomeSpace); 15067 verifyFormat("[foo]() -> int {}", SomeSpace); 15068 verifyFormat("int f();", SomeSpace); 15069 verifyFormat("void f (int a, T b) {\n" 15070 " while (true)\n" 15071 " continue;\n" 15072 "}", 15073 SomeSpace); 15074 verifyFormat("if (true)\n" 15075 " f();\n" 15076 "else if (true)\n" 15077 " f();", 15078 SomeSpace); 15079 verifyFormat("do {\n" 15080 " do_something();\n" 15081 "} while (something());", 15082 SomeSpace); 15083 verifyFormat("switch (x) {\n" 15084 "default:\n" 15085 " break;\n" 15086 "}", 15087 SomeSpace); 15088 verifyFormat("A::A() : a (1) {}", SomeSpace); 15089 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15090 verifyFormat("*(&a + 1);\n" 15091 "&((&a)[1]);\n" 15092 "a[(b + c) * d];\n" 15093 "(((a + 1) * 2) + 3) * 4;", 15094 SomeSpace); 15095 verifyFormat("#define A(x) x", SomeSpace); 15096 verifyFormat("#define A (x) x", SomeSpace); 15097 verifyFormat("#if defined(x)\n" 15098 "#endif", 15099 SomeSpace); 15100 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15101 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15102 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15103 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15104 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15105 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15106 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15107 verifyFormat("alignas (128) char a[128];", SomeSpace); 15108 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15109 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15110 SomeSpace); 15111 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15112 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15113 verifyFormat("T A::operator()();", SomeSpace); 15114 // FIXME these tests regressed behaviour. 15115 // verifyFormat("X A::operator++ (T);", SomeSpace); 15116 verifyFormat("int x = int (y);", SomeSpace); 15117 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15118 15119 FormatStyle SpaceControlStatements = getLLVMStyle(); 15120 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15121 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15122 15123 verifyFormat("while (true)\n" 15124 " continue;", 15125 SpaceControlStatements); 15126 verifyFormat("if (true)\n" 15127 " f();\n" 15128 "else if (true)\n" 15129 " f();", 15130 SpaceControlStatements); 15131 verifyFormat("for (;;) {\n" 15132 " do_something();\n" 15133 "}", 15134 SpaceControlStatements); 15135 verifyFormat("do {\n" 15136 " do_something();\n" 15137 "} while (something());", 15138 SpaceControlStatements); 15139 verifyFormat("switch (x) {\n" 15140 "default:\n" 15141 " break;\n" 15142 "}", 15143 SpaceControlStatements); 15144 15145 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15146 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15147 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15148 15149 verifyFormat("int f ();", SpaceFuncDecl); 15150 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15151 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15152 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15153 verifyFormat("#define A(x) x", SpaceFuncDecl); 15154 verifyFormat("#define A (x) x", SpaceFuncDecl); 15155 verifyFormat("#if defined(x)\n" 15156 "#endif", 15157 SpaceFuncDecl); 15158 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15159 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15160 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15161 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15162 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15163 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15164 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15165 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15166 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15167 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15168 SpaceFuncDecl); 15169 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15170 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15171 // FIXME these tests regressed behaviour. 15172 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15173 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15174 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15175 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15176 verifyFormat("int x = int(y);", SpaceFuncDecl); 15177 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15178 SpaceFuncDecl); 15179 15180 FormatStyle SpaceFuncDef = getLLVMStyle(); 15181 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15182 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15183 15184 verifyFormat("int f();", SpaceFuncDef); 15185 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15186 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15187 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15188 verifyFormat("#define A(x) x", SpaceFuncDef); 15189 verifyFormat("#define A (x) x", SpaceFuncDef); 15190 verifyFormat("#if defined(x)\n" 15191 "#endif", 15192 SpaceFuncDef); 15193 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15194 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15195 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15196 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15197 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15198 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15199 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15200 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15201 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15202 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15203 SpaceFuncDef); 15204 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15205 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15206 verifyFormat("T A::operator()();", SpaceFuncDef); 15207 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15208 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15209 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15210 verifyFormat("int x = int(y);", SpaceFuncDef); 15211 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15212 SpaceFuncDef); 15213 15214 FormatStyle SpaceIfMacros = getLLVMStyle(); 15215 SpaceIfMacros.IfMacros.clear(); 15216 SpaceIfMacros.IfMacros.push_back("MYIF"); 15217 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15218 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15219 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15220 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15221 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15222 15223 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15224 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15225 FormatStyle::SBS_Never); 15226 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15227 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15228 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15229 verifyFormat("for (;;) {\n" 15230 "}", 15231 SpaceForeachMacros); 15232 verifyFormat("foreach (Item *item, itemlist) {\n" 15233 "}", 15234 SpaceForeachMacros); 15235 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15236 "}", 15237 SpaceForeachMacros); 15238 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15239 "}", 15240 SpaceForeachMacros); 15241 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15242 15243 FormatStyle SomeSpace2 = getLLVMStyle(); 15244 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15245 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15246 verifyFormat("[]() -> float {}", SomeSpace2); 15247 verifyFormat("[] (auto foo) {}", SomeSpace2); 15248 verifyFormat("[foo]() -> int {}", SomeSpace2); 15249 verifyFormat("int f();", SomeSpace2); 15250 verifyFormat("void f (int a, T b) {\n" 15251 " while (true)\n" 15252 " continue;\n" 15253 "}", 15254 SomeSpace2); 15255 verifyFormat("if (true)\n" 15256 " f();\n" 15257 "else if (true)\n" 15258 " f();", 15259 SomeSpace2); 15260 verifyFormat("do {\n" 15261 " do_something();\n" 15262 "} while (something());", 15263 SomeSpace2); 15264 verifyFormat("switch (x) {\n" 15265 "default:\n" 15266 " break;\n" 15267 "}", 15268 SomeSpace2); 15269 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15270 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15271 verifyFormat("*(&a + 1);\n" 15272 "&((&a)[1]);\n" 15273 "a[(b + c) * d];\n" 15274 "(((a + 1) * 2) + 3) * 4;", 15275 SomeSpace2); 15276 verifyFormat("#define A(x) x", SomeSpace2); 15277 verifyFormat("#define A (x) x", SomeSpace2); 15278 verifyFormat("#if defined(x)\n" 15279 "#endif", 15280 SomeSpace2); 15281 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15282 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15283 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15284 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15285 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15286 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15287 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15288 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15289 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15290 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15291 SomeSpace2); 15292 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15293 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15294 verifyFormat("T A::operator()();", SomeSpace2); 15295 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15296 verifyFormat("int x = int (y);", SomeSpace2); 15297 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15298 15299 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15300 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15301 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15302 .AfterOverloadedOperator = true; 15303 15304 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15305 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15306 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15307 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15308 15309 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15310 .AfterOverloadedOperator = false; 15311 15312 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15313 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15314 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15315 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15316 15317 auto SpaceAfterRequires = getLLVMStyle(); 15318 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15319 EXPECT_FALSE( 15320 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15321 EXPECT_FALSE( 15322 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15323 verifyFormat("void f(auto x)\n" 15324 " requires requires(int i) { x + i; }\n" 15325 "{}", 15326 SpaceAfterRequires); 15327 verifyFormat("void f(auto x)\n" 15328 " requires(requires(int i) { x + i; })\n" 15329 "{}", 15330 SpaceAfterRequires); 15331 verifyFormat("if (requires(int i) { x + i; })\n" 15332 " return;", 15333 SpaceAfterRequires); 15334 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15335 verifyFormat("template <typename T>\n" 15336 " requires(Foo<T>)\n" 15337 "class Bar;", 15338 SpaceAfterRequires); 15339 15340 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15341 verifyFormat("void f(auto x)\n" 15342 " requires requires(int i) { x + i; }\n" 15343 "{}", 15344 SpaceAfterRequires); 15345 verifyFormat("void f(auto x)\n" 15346 " requires (requires(int i) { x + i; })\n" 15347 "{}", 15348 SpaceAfterRequires); 15349 verifyFormat("if (requires(int i) { x + i; })\n" 15350 " return;", 15351 SpaceAfterRequires); 15352 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15353 verifyFormat("template <typename T>\n" 15354 " requires (Foo<T>)\n" 15355 "class Bar;", 15356 SpaceAfterRequires); 15357 15358 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15359 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15360 verifyFormat("void f(auto x)\n" 15361 " requires requires (int i) { x + i; }\n" 15362 "{}", 15363 SpaceAfterRequires); 15364 verifyFormat("void f(auto x)\n" 15365 " requires(requires (int i) { x + i; })\n" 15366 "{}", 15367 SpaceAfterRequires); 15368 verifyFormat("if (requires (int i) { x + i; })\n" 15369 " return;", 15370 SpaceAfterRequires); 15371 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15372 verifyFormat("template <typename T>\n" 15373 " requires(Foo<T>)\n" 15374 "class Bar;", 15375 SpaceAfterRequires); 15376 15377 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15378 verifyFormat("void f(auto x)\n" 15379 " requires requires (int i) { x + i; }\n" 15380 "{}", 15381 SpaceAfterRequires); 15382 verifyFormat("void f(auto x)\n" 15383 " requires (requires (int i) { x + i; })\n" 15384 "{}", 15385 SpaceAfterRequires); 15386 verifyFormat("if (requires (int i) { x + i; })\n" 15387 " return;", 15388 SpaceAfterRequires); 15389 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15390 verifyFormat("template <typename T>\n" 15391 " requires (Foo<T>)\n" 15392 "class Bar;", 15393 SpaceAfterRequires); 15394 } 15395 15396 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15397 FormatStyle Spaces = getLLVMStyle(); 15398 Spaces.SpaceAfterLogicalNot = true; 15399 15400 verifyFormat("bool x = ! y", Spaces); 15401 verifyFormat("if (! isFailure())", Spaces); 15402 verifyFormat("if (! (a && b))", Spaces); 15403 verifyFormat("\"Error!\"", Spaces); 15404 verifyFormat("! ! x", Spaces); 15405 } 15406 15407 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15408 FormatStyle Spaces = getLLVMStyle(); 15409 15410 Spaces.SpacesInParentheses = true; 15411 verifyFormat("do_something( ::globalVar );", Spaces); 15412 verifyFormat("call( x, y, z );", Spaces); 15413 verifyFormat("call();", Spaces); 15414 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15415 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15416 Spaces); 15417 verifyFormat("while ( (bool)1 )\n" 15418 " continue;", 15419 Spaces); 15420 verifyFormat("for ( ;; )\n" 15421 " continue;", 15422 Spaces); 15423 verifyFormat("if ( true )\n" 15424 " f();\n" 15425 "else if ( true )\n" 15426 " f();", 15427 Spaces); 15428 verifyFormat("do {\n" 15429 " do_something( (int)i );\n" 15430 "} while ( something() );", 15431 Spaces); 15432 verifyFormat("switch ( x ) {\n" 15433 "default:\n" 15434 " break;\n" 15435 "}", 15436 Spaces); 15437 15438 Spaces.SpacesInParentheses = false; 15439 Spaces.SpacesInCStyleCastParentheses = true; 15440 verifyFormat("Type *A = ( Type * )P;", Spaces); 15441 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15442 verifyFormat("x = ( int32 )y;", Spaces); 15443 verifyFormat("int a = ( int )(2.0f);", Spaces); 15444 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15445 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15446 verifyFormat("#define x (( int )-1)", Spaces); 15447 15448 // Run the first set of tests again with: 15449 Spaces.SpacesInParentheses = false; 15450 Spaces.SpaceInEmptyParentheses = true; 15451 Spaces.SpacesInCStyleCastParentheses = true; 15452 verifyFormat("call(x, y, z);", Spaces); 15453 verifyFormat("call( );", Spaces); 15454 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15455 verifyFormat("while (( bool )1)\n" 15456 " continue;", 15457 Spaces); 15458 verifyFormat("for (;;)\n" 15459 " continue;", 15460 Spaces); 15461 verifyFormat("if (true)\n" 15462 " f( );\n" 15463 "else if (true)\n" 15464 " f( );", 15465 Spaces); 15466 verifyFormat("do {\n" 15467 " do_something(( int )i);\n" 15468 "} while (something( ));", 15469 Spaces); 15470 verifyFormat("switch (x) {\n" 15471 "default:\n" 15472 " break;\n" 15473 "}", 15474 Spaces); 15475 15476 // Run the first set of tests again with: 15477 Spaces.SpaceAfterCStyleCast = true; 15478 verifyFormat("call(x, y, z);", Spaces); 15479 verifyFormat("call( );", Spaces); 15480 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15481 verifyFormat("while (( bool ) 1)\n" 15482 " continue;", 15483 Spaces); 15484 verifyFormat("for (;;)\n" 15485 " continue;", 15486 Spaces); 15487 verifyFormat("if (true)\n" 15488 " f( );\n" 15489 "else if (true)\n" 15490 " f( );", 15491 Spaces); 15492 verifyFormat("do {\n" 15493 " do_something(( int ) i);\n" 15494 "} while (something( ));", 15495 Spaces); 15496 verifyFormat("switch (x) {\n" 15497 "default:\n" 15498 " break;\n" 15499 "}", 15500 Spaces); 15501 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15502 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15503 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15504 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15505 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15506 15507 // Run subset of tests again with: 15508 Spaces.SpacesInCStyleCastParentheses = false; 15509 Spaces.SpaceAfterCStyleCast = true; 15510 verifyFormat("while ((bool) 1)\n" 15511 " continue;", 15512 Spaces); 15513 verifyFormat("do {\n" 15514 " do_something((int) i);\n" 15515 "} while (something( ));", 15516 Spaces); 15517 15518 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15519 verifyFormat("size_t idx = (size_t) a;", Spaces); 15520 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15521 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15522 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15523 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15524 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15525 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15526 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15527 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15528 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15529 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15530 Spaces.ColumnLimit = 80; 15531 Spaces.IndentWidth = 4; 15532 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15533 verifyFormat("void foo( ) {\n" 15534 " size_t foo = (*(function))(\n" 15535 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15536 "BarrrrrrrrrrrrLong,\n" 15537 " FoooooooooLooooong);\n" 15538 "}", 15539 Spaces); 15540 Spaces.SpaceAfterCStyleCast = false; 15541 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15542 verifyFormat("size_t idx = (size_t)a;", Spaces); 15543 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15544 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15545 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15546 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15547 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15548 15549 verifyFormat("void foo( ) {\n" 15550 " size_t foo = (*(function))(\n" 15551 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15552 "BarrrrrrrrrrrrLong,\n" 15553 " FoooooooooLooooong);\n" 15554 "}", 15555 Spaces); 15556 } 15557 15558 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15559 verifyFormat("int a[5];"); 15560 verifyFormat("a[3] += 42;"); 15561 15562 FormatStyle Spaces = getLLVMStyle(); 15563 Spaces.SpacesInSquareBrackets = true; 15564 // Not lambdas. 15565 verifyFormat("int a[ 5 ];", Spaces); 15566 verifyFormat("a[ 3 ] += 42;", Spaces); 15567 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15568 verifyFormat("double &operator[](int i) { return 0; }\n" 15569 "int i;", 15570 Spaces); 15571 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15572 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15573 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15574 // Lambdas. 15575 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15576 verifyFormat("return [ i, args... ] {};", Spaces); 15577 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15578 verifyFormat("int foo = [ = ]() {};", Spaces); 15579 verifyFormat("int foo = [ & ]() {};", Spaces); 15580 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15581 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15582 } 15583 15584 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15585 FormatStyle NoSpaceStyle = getLLVMStyle(); 15586 verifyFormat("int a[5];", NoSpaceStyle); 15587 verifyFormat("a[3] += 42;", NoSpaceStyle); 15588 15589 verifyFormat("int a[1];", NoSpaceStyle); 15590 verifyFormat("int 1 [a];", NoSpaceStyle); 15591 verifyFormat("int a[1][2];", NoSpaceStyle); 15592 verifyFormat("a[7] = 5;", NoSpaceStyle); 15593 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15594 verifyFormat("f([] {})", NoSpaceStyle); 15595 15596 FormatStyle Space = getLLVMStyle(); 15597 Space.SpaceBeforeSquareBrackets = true; 15598 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15599 verifyFormat("return [i, args...] {};", Space); 15600 15601 verifyFormat("int a [5];", Space); 15602 verifyFormat("a [3] += 42;", Space); 15603 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15604 verifyFormat("double &operator[](int i) { return 0; }\n" 15605 "int i;", 15606 Space); 15607 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15608 verifyFormat("int i = a [a][a]->f();", Space); 15609 verifyFormat("int i = (*b) [a]->f();", Space); 15610 15611 verifyFormat("int a [1];", Space); 15612 verifyFormat("int 1 [a];", Space); 15613 verifyFormat("int a [1][2];", Space); 15614 verifyFormat("a [7] = 5;", Space); 15615 verifyFormat("int a = (f()) [23];", Space); 15616 verifyFormat("f([] {})", Space); 15617 } 15618 15619 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15620 verifyFormat("int a = 5;"); 15621 verifyFormat("a += 42;"); 15622 verifyFormat("a or_eq 8;"); 15623 15624 FormatStyle Spaces = getLLVMStyle(); 15625 Spaces.SpaceBeforeAssignmentOperators = false; 15626 verifyFormat("int a= 5;", Spaces); 15627 verifyFormat("a+= 42;", Spaces); 15628 verifyFormat("a or_eq 8;", Spaces); 15629 } 15630 15631 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15632 verifyFormat("class Foo : public Bar {};"); 15633 verifyFormat("Foo::Foo() : foo(1) {}"); 15634 verifyFormat("for (auto a : b) {\n}"); 15635 verifyFormat("int x = a ? b : c;"); 15636 verifyFormat("{\n" 15637 "label0:\n" 15638 " int x = 0;\n" 15639 "}"); 15640 verifyFormat("switch (x) {\n" 15641 "case 1:\n" 15642 "default:\n" 15643 "}"); 15644 verifyFormat("switch (allBraces) {\n" 15645 "case 1: {\n" 15646 " break;\n" 15647 "}\n" 15648 "case 2: {\n" 15649 " [[fallthrough]];\n" 15650 "}\n" 15651 "default: {\n" 15652 " break;\n" 15653 "}\n" 15654 "}"); 15655 15656 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15657 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15658 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15659 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15660 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15661 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15662 verifyFormat("{\n" 15663 "label1:\n" 15664 " int x = 0;\n" 15665 "}", 15666 CtorInitializerStyle); 15667 verifyFormat("switch (x) {\n" 15668 "case 1:\n" 15669 "default:\n" 15670 "}", 15671 CtorInitializerStyle); 15672 verifyFormat("switch (allBraces) {\n" 15673 "case 1: {\n" 15674 " break;\n" 15675 "}\n" 15676 "case 2: {\n" 15677 " [[fallthrough]];\n" 15678 "}\n" 15679 "default: {\n" 15680 " break;\n" 15681 "}\n" 15682 "}", 15683 CtorInitializerStyle); 15684 CtorInitializerStyle.BreakConstructorInitializers = 15685 FormatStyle::BCIS_AfterColon; 15686 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15687 " aaaaaaaaaaaaaaaa(1),\n" 15688 " bbbbbbbbbbbbbbbb(2) {}", 15689 CtorInitializerStyle); 15690 CtorInitializerStyle.BreakConstructorInitializers = 15691 FormatStyle::BCIS_BeforeComma; 15692 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15693 " : aaaaaaaaaaaaaaaa(1)\n" 15694 " , bbbbbbbbbbbbbbbb(2) {}", 15695 CtorInitializerStyle); 15696 CtorInitializerStyle.BreakConstructorInitializers = 15697 FormatStyle::BCIS_BeforeColon; 15698 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15699 " : aaaaaaaaaaaaaaaa(1),\n" 15700 " bbbbbbbbbbbbbbbb(2) {}", 15701 CtorInitializerStyle); 15702 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15703 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15704 ": aaaaaaaaaaaaaaaa(1),\n" 15705 " bbbbbbbbbbbbbbbb(2) {}", 15706 CtorInitializerStyle); 15707 15708 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15709 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15710 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15711 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15712 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15713 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15714 verifyFormat("{\n" 15715 "label2:\n" 15716 " int x = 0;\n" 15717 "}", 15718 InheritanceStyle); 15719 verifyFormat("switch (x) {\n" 15720 "case 1:\n" 15721 "default:\n" 15722 "}", 15723 InheritanceStyle); 15724 verifyFormat("switch (allBraces) {\n" 15725 "case 1: {\n" 15726 " break;\n" 15727 "}\n" 15728 "case 2: {\n" 15729 " [[fallthrough]];\n" 15730 "}\n" 15731 "default: {\n" 15732 " break;\n" 15733 "}\n" 15734 "}", 15735 InheritanceStyle); 15736 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15737 verifyFormat("class Foooooooooooooooooooooo\n" 15738 " : public aaaaaaaaaaaaaaaaaa,\n" 15739 " public bbbbbbbbbbbbbbbbbb {\n" 15740 "}", 15741 InheritanceStyle); 15742 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15743 verifyFormat("class Foooooooooooooooooooooo:\n" 15744 " public aaaaaaaaaaaaaaaaaa,\n" 15745 " public bbbbbbbbbbbbbbbbbb {\n" 15746 "}", 15747 InheritanceStyle); 15748 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15749 verifyFormat("class Foooooooooooooooooooooo\n" 15750 " : public aaaaaaaaaaaaaaaaaa\n" 15751 " , public bbbbbbbbbbbbbbbbbb {\n" 15752 "}", 15753 InheritanceStyle); 15754 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15755 verifyFormat("class Foooooooooooooooooooooo\n" 15756 " : public aaaaaaaaaaaaaaaaaa,\n" 15757 " public bbbbbbbbbbbbbbbbbb {\n" 15758 "}", 15759 InheritanceStyle); 15760 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15761 verifyFormat("class Foooooooooooooooooooooo\n" 15762 ": public aaaaaaaaaaaaaaaaaa,\n" 15763 " public bbbbbbbbbbbbbbbbbb {}", 15764 InheritanceStyle); 15765 15766 FormatStyle ForLoopStyle = getLLVMStyle(); 15767 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15768 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15769 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15770 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15771 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15772 verifyFormat("{\n" 15773 "label2:\n" 15774 " int x = 0;\n" 15775 "}", 15776 ForLoopStyle); 15777 verifyFormat("switch (x) {\n" 15778 "case 1:\n" 15779 "default:\n" 15780 "}", 15781 ForLoopStyle); 15782 verifyFormat("switch (allBraces) {\n" 15783 "case 1: {\n" 15784 " break;\n" 15785 "}\n" 15786 "case 2: {\n" 15787 " [[fallthrough]];\n" 15788 "}\n" 15789 "default: {\n" 15790 " break;\n" 15791 "}\n" 15792 "}", 15793 ForLoopStyle); 15794 15795 FormatStyle CaseStyle = getLLVMStyle(); 15796 CaseStyle.SpaceBeforeCaseColon = true; 15797 verifyFormat("class Foo : public Bar {};", CaseStyle); 15798 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15799 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15800 verifyFormat("int x = a ? b : c;", CaseStyle); 15801 verifyFormat("switch (x) {\n" 15802 "case 1 :\n" 15803 "default :\n" 15804 "}", 15805 CaseStyle); 15806 verifyFormat("switch (allBraces) {\n" 15807 "case 1 : {\n" 15808 " break;\n" 15809 "}\n" 15810 "case 2 : {\n" 15811 " [[fallthrough]];\n" 15812 "}\n" 15813 "default : {\n" 15814 " break;\n" 15815 "}\n" 15816 "}", 15817 CaseStyle); 15818 15819 FormatStyle NoSpaceStyle = getLLVMStyle(); 15820 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15821 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15822 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15823 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15824 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15825 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15826 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15827 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15828 verifyFormat("{\n" 15829 "label3:\n" 15830 " int x = 0;\n" 15831 "}", 15832 NoSpaceStyle); 15833 verifyFormat("switch (x) {\n" 15834 "case 1:\n" 15835 "default:\n" 15836 "}", 15837 NoSpaceStyle); 15838 verifyFormat("switch (allBraces) {\n" 15839 "case 1: {\n" 15840 " break;\n" 15841 "}\n" 15842 "case 2: {\n" 15843 " [[fallthrough]];\n" 15844 "}\n" 15845 "default: {\n" 15846 " break;\n" 15847 "}\n" 15848 "}", 15849 NoSpaceStyle); 15850 15851 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15852 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15853 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15854 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15855 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15856 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15857 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15858 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15859 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15860 verifyFormat("{\n" 15861 "label3:\n" 15862 " int x = 0;\n" 15863 "}", 15864 InvertedSpaceStyle); 15865 verifyFormat("switch (x) {\n" 15866 "case 1 :\n" 15867 "case 2 : {\n" 15868 " break;\n" 15869 "}\n" 15870 "default :\n" 15871 " break;\n" 15872 "}", 15873 InvertedSpaceStyle); 15874 verifyFormat("switch (allBraces) {\n" 15875 "case 1 : {\n" 15876 " break;\n" 15877 "}\n" 15878 "case 2 : {\n" 15879 " [[fallthrough]];\n" 15880 "}\n" 15881 "default : {\n" 15882 " break;\n" 15883 "}\n" 15884 "}", 15885 InvertedSpaceStyle); 15886 } 15887 15888 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15889 FormatStyle Style = getLLVMStyle(); 15890 15891 Style.PointerAlignment = FormatStyle::PAS_Left; 15892 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15893 verifyFormat("void* const* x = NULL;", Style); 15894 15895 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15896 do { \ 15897 Style.PointerAlignment = FormatStyle::Pointers; \ 15898 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15899 verifyFormat(Code, Style); \ 15900 } while (false) 15901 15902 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15903 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15904 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15905 15906 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15907 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15908 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15909 15910 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15911 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15912 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15913 15914 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15915 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15916 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15917 15918 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15919 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15920 SAPQ_Default); 15921 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15922 SAPQ_Default); 15923 15924 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15925 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15926 SAPQ_Before); 15927 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15928 SAPQ_Before); 15929 15930 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15931 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15932 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15933 SAPQ_After); 15934 15935 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15936 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15937 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15938 15939 #undef verifyQualifierSpaces 15940 15941 FormatStyle Spaces = getLLVMStyle(); 15942 Spaces.AttributeMacros.push_back("qualified"); 15943 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15944 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15945 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15946 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15947 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15948 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15949 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15950 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15951 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15952 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15953 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15954 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15955 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15956 15957 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15958 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15959 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15960 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15961 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15962 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15963 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15964 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15965 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15966 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15967 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15968 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15969 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15970 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15971 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15972 15973 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15974 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15975 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15976 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15977 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15978 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15979 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15980 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15981 } 15982 15983 TEST_F(FormatTest, AlignConsecutiveMacros) { 15984 FormatStyle Style = getLLVMStyle(); 15985 Style.AlignConsecutiveAssignments.Enabled = true; 15986 Style.AlignConsecutiveDeclarations.Enabled = true; 15987 15988 verifyFormat("#define a 3\n" 15989 "#define bbbb 4\n" 15990 "#define ccc (5)", 15991 Style); 15992 15993 verifyFormat("#define f(x) (x * x)\n" 15994 "#define fff(x, y, z) (x * y + z)\n" 15995 "#define ffff(x, y) (x - y)", 15996 Style); 15997 15998 verifyFormat("#define foo(x, y) (x + y)\n" 15999 "#define bar (5, 6)(2 + 2)", 16000 Style); 16001 16002 verifyFormat("#define a 3\n" 16003 "#define bbbb 4\n" 16004 "#define ccc (5)\n" 16005 "#define f(x) (x * x)\n" 16006 "#define fff(x, y, z) (x * y + z)\n" 16007 "#define ffff(x, y) (x - y)", 16008 Style); 16009 16010 Style.AlignConsecutiveMacros.Enabled = true; 16011 verifyFormat("#define a 3\n" 16012 "#define bbbb 4\n" 16013 "#define ccc (5)", 16014 Style); 16015 16016 verifyFormat("#define f(x) (x * x)\n" 16017 "#define fff(x, y, z) (x * y + z)\n" 16018 "#define ffff(x, y) (x - y)", 16019 Style); 16020 16021 verifyFormat("#define foo(x, y) (x + y)\n" 16022 "#define bar (5, 6)(2 + 2)", 16023 Style); 16024 16025 verifyFormat("#define a 3\n" 16026 "#define bbbb 4\n" 16027 "#define ccc (5)\n" 16028 "#define f(x) (x * x)\n" 16029 "#define fff(x, y, z) (x * y + z)\n" 16030 "#define ffff(x, y) (x - y)", 16031 Style); 16032 16033 verifyFormat("#define a 5\n" 16034 "#define foo(x, y) (x + y)\n" 16035 "#define CCC (6)\n" 16036 "auto lambda = []() {\n" 16037 " auto ii = 0;\n" 16038 " float j = 0;\n" 16039 " return 0;\n" 16040 "};\n" 16041 "int i = 0;\n" 16042 "float i2 = 0;\n" 16043 "auto v = type{\n" 16044 " i = 1, //\n" 16045 " (i = 2), //\n" 16046 " i = 3 //\n" 16047 "};", 16048 Style); 16049 16050 Style.AlignConsecutiveMacros.Enabled = false; 16051 Style.ColumnLimit = 20; 16052 16053 verifyFormat("#define a \\\n" 16054 " \"aabbbbbbbbbbbb\"\n" 16055 "#define D \\\n" 16056 " \"aabbbbbbbbbbbb\" \\\n" 16057 " \"ccddeeeeeeeee\"\n" 16058 "#define B \\\n" 16059 " \"QQQQQQQQQQQQQ\" \\\n" 16060 " \"FFFFFFFFFFFFF\" \\\n" 16061 " \"LLLLLLLL\"\n", 16062 Style); 16063 16064 Style.AlignConsecutiveMacros.Enabled = true; 16065 verifyFormat("#define a \\\n" 16066 " \"aabbbbbbbbbbbb\"\n" 16067 "#define D \\\n" 16068 " \"aabbbbbbbbbbbb\" \\\n" 16069 " \"ccddeeeeeeeee\"\n" 16070 "#define B \\\n" 16071 " \"QQQQQQQQQQQQQ\" \\\n" 16072 " \"FFFFFFFFFFFFF\" \\\n" 16073 " \"LLLLLLLL\"\n", 16074 Style); 16075 16076 // Test across comments 16077 Style.MaxEmptyLinesToKeep = 10; 16078 Style.ReflowComments = false; 16079 Style.AlignConsecutiveMacros.AcrossComments = true; 16080 EXPECT_EQ("#define a 3\n" 16081 "// line comment\n" 16082 "#define bbbb 4\n" 16083 "#define ccc (5)", 16084 format("#define a 3\n" 16085 "// line comment\n" 16086 "#define bbbb 4\n" 16087 "#define ccc (5)", 16088 Style)); 16089 16090 EXPECT_EQ("#define a 3\n" 16091 "/* block comment */\n" 16092 "#define bbbb 4\n" 16093 "#define ccc (5)", 16094 format("#define a 3\n" 16095 "/* block comment */\n" 16096 "#define bbbb 4\n" 16097 "#define ccc (5)", 16098 Style)); 16099 16100 EXPECT_EQ("#define a 3\n" 16101 "/* multi-line *\n" 16102 " * block comment */\n" 16103 "#define bbbb 4\n" 16104 "#define ccc (5)", 16105 format("#define a 3\n" 16106 "/* multi-line *\n" 16107 " * block comment */\n" 16108 "#define bbbb 4\n" 16109 "#define ccc (5)", 16110 Style)); 16111 16112 EXPECT_EQ("#define a 3\n" 16113 "// multi-line line comment\n" 16114 "//\n" 16115 "#define bbbb 4\n" 16116 "#define ccc (5)", 16117 format("#define a 3\n" 16118 "// multi-line line comment\n" 16119 "//\n" 16120 "#define bbbb 4\n" 16121 "#define ccc (5)", 16122 Style)); 16123 16124 EXPECT_EQ("#define a 3\n" 16125 "// empty lines still break.\n" 16126 "\n" 16127 "#define bbbb 4\n" 16128 "#define ccc (5)", 16129 format("#define a 3\n" 16130 "// empty lines still break.\n" 16131 "\n" 16132 "#define bbbb 4\n" 16133 "#define ccc (5)", 16134 Style)); 16135 16136 // Test across empty lines 16137 Style.AlignConsecutiveMacros.AcrossComments = false; 16138 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16139 EXPECT_EQ("#define a 3\n" 16140 "\n" 16141 "#define bbbb 4\n" 16142 "#define ccc (5)", 16143 format("#define a 3\n" 16144 "\n" 16145 "#define bbbb 4\n" 16146 "#define ccc (5)", 16147 Style)); 16148 16149 EXPECT_EQ("#define a 3\n" 16150 "\n" 16151 "\n" 16152 "\n" 16153 "#define bbbb 4\n" 16154 "#define ccc (5)", 16155 format("#define a 3\n" 16156 "\n" 16157 "\n" 16158 "\n" 16159 "#define bbbb 4\n" 16160 "#define ccc (5)", 16161 Style)); 16162 16163 EXPECT_EQ("#define a 3\n" 16164 "// comments should break alignment\n" 16165 "//\n" 16166 "#define bbbb 4\n" 16167 "#define ccc (5)", 16168 format("#define a 3\n" 16169 "// comments should break alignment\n" 16170 "//\n" 16171 "#define bbbb 4\n" 16172 "#define ccc (5)", 16173 Style)); 16174 16175 // Test across empty lines and comments 16176 Style.AlignConsecutiveMacros.AcrossComments = true; 16177 verifyFormat("#define a 3\n" 16178 "\n" 16179 "// line comment\n" 16180 "#define bbbb 4\n" 16181 "#define ccc (5)", 16182 Style); 16183 16184 EXPECT_EQ("#define a 3\n" 16185 "\n" 16186 "\n" 16187 "/* multi-line *\n" 16188 " * block comment */\n" 16189 "\n" 16190 "\n" 16191 "#define bbbb 4\n" 16192 "#define ccc (5)", 16193 format("#define a 3\n" 16194 "\n" 16195 "\n" 16196 "/* multi-line *\n" 16197 " * block comment */\n" 16198 "\n" 16199 "\n" 16200 "#define bbbb 4\n" 16201 "#define ccc (5)", 16202 Style)); 16203 16204 EXPECT_EQ("#define a 3\n" 16205 "\n" 16206 "\n" 16207 "/* multi-line *\n" 16208 " * block comment */\n" 16209 "\n" 16210 "\n" 16211 "#define bbbb 4\n" 16212 "#define ccc (5)", 16213 format("#define a 3\n" 16214 "\n" 16215 "\n" 16216 "/* multi-line *\n" 16217 " * block comment */\n" 16218 "\n" 16219 "\n" 16220 "#define bbbb 4\n" 16221 "#define ccc (5)", 16222 Style)); 16223 } 16224 16225 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16226 FormatStyle Alignment = getLLVMStyle(); 16227 Alignment.AlignConsecutiveMacros.Enabled = true; 16228 Alignment.AlignConsecutiveAssignments.Enabled = true; 16229 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16230 16231 Alignment.MaxEmptyLinesToKeep = 10; 16232 /* Test alignment across empty lines */ 16233 EXPECT_EQ("int a = 5;\n" 16234 "\n" 16235 "int oneTwoThree = 123;", 16236 format("int a = 5;\n" 16237 "\n" 16238 "int oneTwoThree= 123;", 16239 Alignment)); 16240 EXPECT_EQ("int a = 5;\n" 16241 "int one = 1;\n" 16242 "\n" 16243 "int oneTwoThree = 123;", 16244 format("int a = 5;\n" 16245 "int one = 1;\n" 16246 "\n" 16247 "int oneTwoThree = 123;", 16248 Alignment)); 16249 EXPECT_EQ("int a = 5;\n" 16250 "int one = 1;\n" 16251 "\n" 16252 "int oneTwoThree = 123;\n" 16253 "int oneTwo = 12;", 16254 format("int a = 5;\n" 16255 "int one = 1;\n" 16256 "\n" 16257 "int oneTwoThree = 123;\n" 16258 "int oneTwo = 12;", 16259 Alignment)); 16260 16261 /* Test across comments */ 16262 EXPECT_EQ("int a = 5;\n" 16263 "/* block comment */\n" 16264 "int oneTwoThree = 123;", 16265 format("int a = 5;\n" 16266 "/* block comment */\n" 16267 "int oneTwoThree=123;", 16268 Alignment)); 16269 16270 EXPECT_EQ("int a = 5;\n" 16271 "// line comment\n" 16272 "int oneTwoThree = 123;", 16273 format("int a = 5;\n" 16274 "// line comment\n" 16275 "int oneTwoThree=123;", 16276 Alignment)); 16277 16278 /* Test across comments and newlines */ 16279 EXPECT_EQ("int a = 5;\n" 16280 "\n" 16281 "/* block comment */\n" 16282 "int oneTwoThree = 123;", 16283 format("int a = 5;\n" 16284 "\n" 16285 "/* block comment */\n" 16286 "int oneTwoThree=123;", 16287 Alignment)); 16288 16289 EXPECT_EQ("int a = 5;\n" 16290 "\n" 16291 "// line comment\n" 16292 "int oneTwoThree = 123;", 16293 format("int a = 5;\n" 16294 "\n" 16295 "// line comment\n" 16296 "int oneTwoThree=123;", 16297 Alignment)); 16298 } 16299 16300 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16301 FormatStyle Alignment = getLLVMStyle(); 16302 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16303 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16304 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16305 16306 Alignment.MaxEmptyLinesToKeep = 10; 16307 /* Test alignment across empty lines */ 16308 EXPECT_EQ("int a = 5;\n" 16309 "\n" 16310 "float const oneTwoThree = 123;", 16311 format("int a = 5;\n" 16312 "\n" 16313 "float const oneTwoThree = 123;", 16314 Alignment)); 16315 EXPECT_EQ("int a = 5;\n" 16316 "float const one = 1;\n" 16317 "\n" 16318 "int oneTwoThree = 123;", 16319 format("int a = 5;\n" 16320 "float const one = 1;\n" 16321 "\n" 16322 "int oneTwoThree = 123;", 16323 Alignment)); 16324 16325 /* Test across comments */ 16326 EXPECT_EQ("float const a = 5;\n" 16327 "/* block comment */\n" 16328 "int oneTwoThree = 123;", 16329 format("float const a = 5;\n" 16330 "/* block comment */\n" 16331 "int oneTwoThree=123;", 16332 Alignment)); 16333 16334 EXPECT_EQ("float const a = 5;\n" 16335 "// line comment\n" 16336 "int oneTwoThree = 123;", 16337 format("float const a = 5;\n" 16338 "// line comment\n" 16339 "int oneTwoThree=123;", 16340 Alignment)); 16341 16342 /* Test across comments and newlines */ 16343 EXPECT_EQ("float const a = 5;\n" 16344 "\n" 16345 "/* block comment */\n" 16346 "int oneTwoThree = 123;", 16347 format("float const a = 5;\n" 16348 "\n" 16349 "/* block comment */\n" 16350 "int oneTwoThree=123;", 16351 Alignment)); 16352 16353 EXPECT_EQ("float const a = 5;\n" 16354 "\n" 16355 "// line comment\n" 16356 "int oneTwoThree = 123;", 16357 format("float const a = 5;\n" 16358 "\n" 16359 "// line comment\n" 16360 "int oneTwoThree=123;", 16361 Alignment)); 16362 } 16363 16364 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16365 FormatStyle Alignment = getLLVMStyle(); 16366 Alignment.AlignConsecutiveBitFields.Enabled = true; 16367 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16368 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16369 16370 Alignment.MaxEmptyLinesToKeep = 10; 16371 /* Test alignment across empty lines */ 16372 EXPECT_EQ("int a : 5;\n" 16373 "\n" 16374 "int longbitfield : 6;", 16375 format("int a : 5;\n" 16376 "\n" 16377 "int longbitfield : 6;", 16378 Alignment)); 16379 EXPECT_EQ("int a : 5;\n" 16380 "int one : 1;\n" 16381 "\n" 16382 "int longbitfield : 6;", 16383 format("int a : 5;\n" 16384 "int one : 1;\n" 16385 "\n" 16386 "int longbitfield : 6;", 16387 Alignment)); 16388 16389 /* Test across comments */ 16390 EXPECT_EQ("int a : 5;\n" 16391 "/* block comment */\n" 16392 "int longbitfield : 6;", 16393 format("int a : 5;\n" 16394 "/* block comment */\n" 16395 "int longbitfield : 6;", 16396 Alignment)); 16397 EXPECT_EQ("int a : 5;\n" 16398 "int one : 1;\n" 16399 "// line comment\n" 16400 "int longbitfield : 6;", 16401 format("int a : 5;\n" 16402 "int one : 1;\n" 16403 "// line comment\n" 16404 "int longbitfield : 6;", 16405 Alignment)); 16406 16407 /* Test across comments and newlines */ 16408 EXPECT_EQ("int a : 5;\n" 16409 "/* block comment */\n" 16410 "\n" 16411 "int longbitfield : 6;", 16412 format("int a : 5;\n" 16413 "/* block comment */\n" 16414 "\n" 16415 "int longbitfield : 6;", 16416 Alignment)); 16417 EXPECT_EQ("int a : 5;\n" 16418 "int one : 1;\n" 16419 "\n" 16420 "// line comment\n" 16421 "\n" 16422 "int longbitfield : 6;", 16423 format("int a : 5;\n" 16424 "int one : 1;\n" 16425 "\n" 16426 "// line comment \n" 16427 "\n" 16428 "int longbitfield : 6;", 16429 Alignment)); 16430 } 16431 16432 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16433 FormatStyle Alignment = getLLVMStyle(); 16434 Alignment.AlignConsecutiveMacros.Enabled = true; 16435 Alignment.AlignConsecutiveAssignments.Enabled = true; 16436 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16437 16438 Alignment.MaxEmptyLinesToKeep = 10; 16439 /* Test alignment across empty lines */ 16440 EXPECT_EQ("int a = 5;\n" 16441 "\n" 16442 "int oneTwoThree = 123;", 16443 format("int a = 5;\n" 16444 "\n" 16445 "int oneTwoThree= 123;", 16446 Alignment)); 16447 EXPECT_EQ("int a = 5;\n" 16448 "int one = 1;\n" 16449 "\n" 16450 "int oneTwoThree = 123;", 16451 format("int a = 5;\n" 16452 "int one = 1;\n" 16453 "\n" 16454 "int oneTwoThree = 123;", 16455 Alignment)); 16456 16457 /* Test across comments */ 16458 EXPECT_EQ("int a = 5;\n" 16459 "/* block comment */\n" 16460 "int oneTwoThree = 123;", 16461 format("int a = 5;\n" 16462 "/* block comment */\n" 16463 "int oneTwoThree=123;", 16464 Alignment)); 16465 16466 EXPECT_EQ("int a = 5;\n" 16467 "// line comment\n" 16468 "int oneTwoThree = 123;", 16469 format("int a = 5;\n" 16470 "// line comment\n" 16471 "int oneTwoThree=123;", 16472 Alignment)); 16473 16474 EXPECT_EQ("int a = 5;\n" 16475 "/*\n" 16476 " * multi-line block comment\n" 16477 " */\n" 16478 "int oneTwoThree = 123;", 16479 format("int a = 5;\n" 16480 "/*\n" 16481 " * multi-line block comment\n" 16482 " */\n" 16483 "int oneTwoThree=123;", 16484 Alignment)); 16485 16486 EXPECT_EQ("int a = 5;\n" 16487 "//\n" 16488 "// multi-line line comment\n" 16489 "//\n" 16490 "int oneTwoThree = 123;", 16491 format("int a = 5;\n" 16492 "//\n" 16493 "// multi-line line comment\n" 16494 "//\n" 16495 "int oneTwoThree=123;", 16496 Alignment)); 16497 16498 /* Test across comments and newlines */ 16499 EXPECT_EQ("int a = 5;\n" 16500 "\n" 16501 "/* block comment */\n" 16502 "int oneTwoThree = 123;", 16503 format("int a = 5;\n" 16504 "\n" 16505 "/* block comment */\n" 16506 "int oneTwoThree=123;", 16507 Alignment)); 16508 16509 EXPECT_EQ("int a = 5;\n" 16510 "\n" 16511 "// line comment\n" 16512 "int oneTwoThree = 123;", 16513 format("int a = 5;\n" 16514 "\n" 16515 "// line comment\n" 16516 "int oneTwoThree=123;", 16517 Alignment)); 16518 } 16519 16520 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16521 FormatStyle Alignment = getLLVMStyle(); 16522 Alignment.AlignConsecutiveMacros.Enabled = true; 16523 Alignment.AlignConsecutiveAssignments.Enabled = true; 16524 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16525 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16526 verifyFormat("int a = 5;\n" 16527 "int oneTwoThree = 123;", 16528 Alignment); 16529 verifyFormat("int a = method();\n" 16530 "int oneTwoThree = 133;", 16531 Alignment); 16532 verifyFormat("a &= 5;\n" 16533 "bcd *= 5;\n" 16534 "ghtyf += 5;\n" 16535 "dvfvdb -= 5;\n" 16536 "a /= 5;\n" 16537 "vdsvsv %= 5;\n" 16538 "sfdbddfbdfbb ^= 5;\n" 16539 "dvsdsv |= 5;\n" 16540 "int dsvvdvsdvvv = 123;", 16541 Alignment); 16542 verifyFormat("int i = 1, j = 10;\n" 16543 "something = 2000;", 16544 Alignment); 16545 verifyFormat("something = 2000;\n" 16546 "int i = 1, j = 10;\n", 16547 Alignment); 16548 verifyFormat("something = 2000;\n" 16549 "another = 911;\n" 16550 "int i = 1, j = 10;\n" 16551 "oneMore = 1;\n" 16552 "i = 2;", 16553 Alignment); 16554 verifyFormat("int a = 5;\n" 16555 "int one = 1;\n" 16556 "method();\n" 16557 "int oneTwoThree = 123;\n" 16558 "int oneTwo = 12;", 16559 Alignment); 16560 verifyFormat("int oneTwoThree = 123;\n" 16561 "int oneTwo = 12;\n" 16562 "method();\n", 16563 Alignment); 16564 verifyFormat("int oneTwoThree = 123; // comment\n" 16565 "int oneTwo = 12; // comment", 16566 Alignment); 16567 16568 // Bug 25167 16569 /* Uncomment when fixed 16570 verifyFormat("#if A\n" 16571 "#else\n" 16572 "int aaaaaaaa = 12;\n" 16573 "#endif\n" 16574 "#if B\n" 16575 "#else\n" 16576 "int a = 12;\n" 16577 "#endif\n", 16578 Alignment); 16579 verifyFormat("enum foo {\n" 16580 "#if A\n" 16581 "#else\n" 16582 " aaaaaaaa = 12;\n" 16583 "#endif\n" 16584 "#if B\n" 16585 "#else\n" 16586 " a = 12;\n" 16587 "#endif\n" 16588 "};\n", 16589 Alignment); 16590 */ 16591 16592 Alignment.MaxEmptyLinesToKeep = 10; 16593 /* Test alignment across empty lines */ 16594 EXPECT_EQ("int a = 5;\n" 16595 "\n" 16596 "int oneTwoThree = 123;", 16597 format("int a = 5;\n" 16598 "\n" 16599 "int oneTwoThree= 123;", 16600 Alignment)); 16601 EXPECT_EQ("int a = 5;\n" 16602 "int one = 1;\n" 16603 "\n" 16604 "int oneTwoThree = 123;", 16605 format("int a = 5;\n" 16606 "int one = 1;\n" 16607 "\n" 16608 "int oneTwoThree = 123;", 16609 Alignment)); 16610 EXPECT_EQ("int a = 5;\n" 16611 "int one = 1;\n" 16612 "\n" 16613 "int oneTwoThree = 123;\n" 16614 "int oneTwo = 12;", 16615 format("int a = 5;\n" 16616 "int one = 1;\n" 16617 "\n" 16618 "int oneTwoThree = 123;\n" 16619 "int oneTwo = 12;", 16620 Alignment)); 16621 16622 /* Test across comments */ 16623 EXPECT_EQ("int a = 5;\n" 16624 "/* block comment */\n" 16625 "int oneTwoThree = 123;", 16626 format("int a = 5;\n" 16627 "/* block comment */\n" 16628 "int oneTwoThree=123;", 16629 Alignment)); 16630 16631 EXPECT_EQ("int a = 5;\n" 16632 "// line comment\n" 16633 "int oneTwoThree = 123;", 16634 format("int a = 5;\n" 16635 "// line comment\n" 16636 "int oneTwoThree=123;", 16637 Alignment)); 16638 16639 /* Test across comments and newlines */ 16640 EXPECT_EQ("int a = 5;\n" 16641 "\n" 16642 "/* block comment */\n" 16643 "int oneTwoThree = 123;", 16644 format("int a = 5;\n" 16645 "\n" 16646 "/* block comment */\n" 16647 "int oneTwoThree=123;", 16648 Alignment)); 16649 16650 EXPECT_EQ("int a = 5;\n" 16651 "\n" 16652 "// line comment\n" 16653 "int oneTwoThree = 123;", 16654 format("int a = 5;\n" 16655 "\n" 16656 "// line comment\n" 16657 "int oneTwoThree=123;", 16658 Alignment)); 16659 16660 EXPECT_EQ("int a = 5;\n" 16661 "//\n" 16662 "// multi-line line comment\n" 16663 "//\n" 16664 "int oneTwoThree = 123;", 16665 format("int a = 5;\n" 16666 "//\n" 16667 "// multi-line line comment\n" 16668 "//\n" 16669 "int oneTwoThree=123;", 16670 Alignment)); 16671 16672 EXPECT_EQ("int a = 5;\n" 16673 "/*\n" 16674 " * multi-line block comment\n" 16675 " */\n" 16676 "int oneTwoThree = 123;", 16677 format("int a = 5;\n" 16678 "/*\n" 16679 " * multi-line block comment\n" 16680 " */\n" 16681 "int oneTwoThree=123;", 16682 Alignment)); 16683 16684 EXPECT_EQ("int a = 5;\n" 16685 "\n" 16686 "/* block comment */\n" 16687 "\n" 16688 "\n" 16689 "\n" 16690 "int oneTwoThree = 123;", 16691 format("int a = 5;\n" 16692 "\n" 16693 "/* block comment */\n" 16694 "\n" 16695 "\n" 16696 "\n" 16697 "int oneTwoThree=123;", 16698 Alignment)); 16699 16700 EXPECT_EQ("int a = 5;\n" 16701 "\n" 16702 "// line comment\n" 16703 "\n" 16704 "\n" 16705 "\n" 16706 "int oneTwoThree = 123;", 16707 format("int a = 5;\n" 16708 "\n" 16709 "// line comment\n" 16710 "\n" 16711 "\n" 16712 "\n" 16713 "int oneTwoThree=123;", 16714 Alignment)); 16715 16716 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16717 verifyFormat("#define A \\\n" 16718 " int aaaa = 12; \\\n" 16719 " int b = 23; \\\n" 16720 " int ccc = 234; \\\n" 16721 " int dddddddddd = 2345;", 16722 Alignment); 16723 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16724 verifyFormat("#define A \\\n" 16725 " int aaaa = 12; \\\n" 16726 " int b = 23; \\\n" 16727 " int ccc = 234; \\\n" 16728 " int dddddddddd = 2345;", 16729 Alignment); 16730 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16731 verifyFormat("#define A " 16732 " \\\n" 16733 " int aaaa = 12; " 16734 " \\\n" 16735 " int b = 23; " 16736 " \\\n" 16737 " int ccc = 234; " 16738 " \\\n" 16739 " int dddddddddd = 2345;", 16740 Alignment); 16741 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16742 "k = 4, int l = 5,\n" 16743 " int m = 6) {\n" 16744 " int j = 10;\n" 16745 " otherThing = 1;\n" 16746 "}", 16747 Alignment); 16748 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16749 " int i = 1;\n" 16750 " int j = 2;\n" 16751 " int big = 10000;\n" 16752 "}", 16753 Alignment); 16754 verifyFormat("class C {\n" 16755 "public:\n" 16756 " int i = 1;\n" 16757 " virtual void f() = 0;\n" 16758 "};", 16759 Alignment); 16760 verifyFormat("int i = 1;\n" 16761 "if (SomeType t = getSomething()) {\n" 16762 "}\n" 16763 "int j = 2;\n" 16764 "int big = 10000;", 16765 Alignment); 16766 verifyFormat("int j = 7;\n" 16767 "for (int k = 0; k < N; ++k) {\n" 16768 "}\n" 16769 "int j = 2;\n" 16770 "int big = 10000;\n" 16771 "}", 16772 Alignment); 16773 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16774 verifyFormat("int i = 1;\n" 16775 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16776 " = someLooooooooooooooooongFunction();\n" 16777 "int j = 2;", 16778 Alignment); 16779 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16780 verifyFormat("int i = 1;\n" 16781 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16782 " someLooooooooooooooooongFunction();\n" 16783 "int j = 2;", 16784 Alignment); 16785 16786 verifyFormat("auto lambda = []() {\n" 16787 " auto i = 0;\n" 16788 " return 0;\n" 16789 "};\n" 16790 "int i = 0;\n" 16791 "auto v = type{\n" 16792 " i = 1, //\n" 16793 " (i = 2), //\n" 16794 " i = 3 //\n" 16795 "};", 16796 Alignment); 16797 16798 verifyFormat( 16799 "int i = 1;\n" 16800 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16801 " loooooooooooooooooooooongParameterB);\n" 16802 "int j = 2;", 16803 Alignment); 16804 16805 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16806 " typename B = very_long_type_name_1,\n" 16807 " typename T_2 = very_long_type_name_2>\n" 16808 "auto foo() {}\n", 16809 Alignment); 16810 verifyFormat("int a, b = 1;\n" 16811 "int c = 2;\n" 16812 "int dd = 3;\n", 16813 Alignment); 16814 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16815 "float b[1][] = {{3.f}};\n", 16816 Alignment); 16817 verifyFormat("for (int i = 0; i < 1; i++)\n" 16818 " int x = 1;\n", 16819 Alignment); 16820 verifyFormat("for (i = 0; i < 1; i++)\n" 16821 " x = 1;\n" 16822 "y = 1;\n", 16823 Alignment); 16824 16825 Alignment.ReflowComments = true; 16826 Alignment.ColumnLimit = 50; 16827 EXPECT_EQ("int x = 0;\n" 16828 "int yy = 1; /// specificlennospace\n" 16829 "int zzz = 2;\n", 16830 format("int x = 0;\n" 16831 "int yy = 1; ///specificlennospace\n" 16832 "int zzz = 2;\n", 16833 Alignment)); 16834 } 16835 16836 TEST_F(FormatTest, AlignCompoundAssignments) { 16837 FormatStyle Alignment = getLLVMStyle(); 16838 Alignment.AlignConsecutiveAssignments.Enabled = true; 16839 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 16840 Alignment.AlignConsecutiveAssignments.PadOperators = false; 16841 verifyFormat("sfdbddfbdfbb = 5;\n" 16842 "dvsdsv = 5;\n" 16843 "int dsvvdvsdvvv = 123;", 16844 Alignment); 16845 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16846 "dvsdsv |= 5;\n" 16847 "int dsvvdvsdvvv = 123;", 16848 Alignment); 16849 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16850 "dvsdsv <<= 5;\n" 16851 "int dsvvdvsdvvv = 123;", 16852 Alignment); 16853 // Test that `<=` is not treated as a compound assignment. 16854 verifyFormat("aa &= 5;\n" 16855 "b <= 10;\n" 16856 "c = 15;", 16857 Alignment); 16858 Alignment.AlignConsecutiveAssignments.PadOperators = true; 16859 verifyFormat("sfdbddfbdfbb = 5;\n" 16860 "dvsdsv = 5;\n" 16861 "int dsvvdvsdvvv = 123;", 16862 Alignment); 16863 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16864 "dvsdsv |= 5;\n" 16865 "int dsvvdvsdvvv = 123;", 16866 Alignment); 16867 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16868 "dvsdsv <<= 5;\n" 16869 "int dsvvdvsdvvv = 123;", 16870 Alignment); 16871 EXPECT_EQ("a += 5;\n" 16872 "one = 1;\n" 16873 "\n" 16874 "oneTwoThree = 123;\n", 16875 format("a += 5;\n" 16876 "one = 1;\n" 16877 "\n" 16878 "oneTwoThree = 123;\n", 16879 Alignment)); 16880 EXPECT_EQ("a += 5;\n" 16881 "one = 1;\n" 16882 "//\n" 16883 "oneTwoThree = 123;\n", 16884 format("a += 5;\n" 16885 "one = 1;\n" 16886 "//\n" 16887 "oneTwoThree = 123;\n", 16888 Alignment)); 16889 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16890 EXPECT_EQ("a += 5;\n" 16891 "one = 1;\n" 16892 "\n" 16893 "oneTwoThree = 123;\n", 16894 format("a += 5;\n" 16895 "one = 1;\n" 16896 "\n" 16897 "oneTwoThree = 123;\n", 16898 Alignment)); 16899 EXPECT_EQ("a += 5;\n" 16900 "one = 1;\n" 16901 "//\n" 16902 "oneTwoThree = 123;\n", 16903 format("a += 5;\n" 16904 "one = 1;\n" 16905 "//\n" 16906 "oneTwoThree = 123;\n", 16907 Alignment)); 16908 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 16909 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16910 EXPECT_EQ("a += 5;\n" 16911 "one = 1;\n" 16912 "\n" 16913 "oneTwoThree = 123;\n", 16914 format("a += 5;\n" 16915 "one = 1;\n" 16916 "\n" 16917 "oneTwoThree = 123;\n", 16918 Alignment)); 16919 EXPECT_EQ("a += 5;\n" 16920 "one = 1;\n" 16921 "//\n" 16922 "oneTwoThree = 123;\n", 16923 format("a += 5;\n" 16924 "one = 1;\n" 16925 "//\n" 16926 "oneTwoThree = 123;\n", 16927 Alignment)); 16928 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16929 EXPECT_EQ("a += 5;\n" 16930 "one >>= 1;\n" 16931 "\n" 16932 "oneTwoThree = 123;\n", 16933 format("a += 5;\n" 16934 "one >>= 1;\n" 16935 "\n" 16936 "oneTwoThree = 123;\n", 16937 Alignment)); 16938 EXPECT_EQ("a += 5;\n" 16939 "one = 1;\n" 16940 "//\n" 16941 "oneTwoThree <<= 123;\n", 16942 format("a += 5;\n" 16943 "one = 1;\n" 16944 "//\n" 16945 "oneTwoThree <<= 123;\n", 16946 Alignment)); 16947 } 16948 16949 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16950 FormatStyle Alignment = getLLVMStyle(); 16951 Alignment.AlignConsecutiveMacros.Enabled = true; 16952 verifyFormat("int a = 5;\n" 16953 "int oneTwoThree = 123;", 16954 Alignment); 16955 verifyFormat("int a = 5;\n" 16956 "int oneTwoThree = 123;", 16957 Alignment); 16958 16959 Alignment.AlignConsecutiveAssignments.Enabled = true; 16960 verifyFormat("int a = 5;\n" 16961 "int oneTwoThree = 123;", 16962 Alignment); 16963 verifyFormat("int a = method();\n" 16964 "int oneTwoThree = 133;", 16965 Alignment); 16966 verifyFormat("aa <= 5;\n" 16967 "a &= 5;\n" 16968 "bcd *= 5;\n" 16969 "ghtyf += 5;\n" 16970 "dvfvdb -= 5;\n" 16971 "a /= 5;\n" 16972 "vdsvsv %= 5;\n" 16973 "sfdbddfbdfbb ^= 5;\n" 16974 "dvsdsv |= 5;\n" 16975 "int dsvvdvsdvvv = 123;", 16976 Alignment); 16977 verifyFormat("int i = 1, j = 10;\n" 16978 "something = 2000;", 16979 Alignment); 16980 verifyFormat("something = 2000;\n" 16981 "int i = 1, j = 10;\n", 16982 Alignment); 16983 verifyFormat("something = 2000;\n" 16984 "another = 911;\n" 16985 "int i = 1, j = 10;\n" 16986 "oneMore = 1;\n" 16987 "i = 2;", 16988 Alignment); 16989 verifyFormat("int a = 5;\n" 16990 "int one = 1;\n" 16991 "method();\n" 16992 "int oneTwoThree = 123;\n" 16993 "int oneTwo = 12;", 16994 Alignment); 16995 verifyFormat("int oneTwoThree = 123;\n" 16996 "int oneTwo = 12;\n" 16997 "method();\n", 16998 Alignment); 16999 verifyFormat("int oneTwoThree = 123; // comment\n" 17000 "int oneTwo = 12; // comment", 17001 Alignment); 17002 verifyFormat("int f() = default;\n" 17003 "int &operator() = default;\n" 17004 "int &operator=() {", 17005 Alignment); 17006 verifyFormat("int f() = delete;\n" 17007 "int &operator() = delete;\n" 17008 "int &operator=() {", 17009 Alignment); 17010 verifyFormat("int f() = default; // comment\n" 17011 "int &operator() = default; // comment\n" 17012 "int &operator=() {", 17013 Alignment); 17014 verifyFormat("int f() = default;\n" 17015 "int &operator() = default;\n" 17016 "int &operator==() {", 17017 Alignment); 17018 verifyFormat("int f() = default;\n" 17019 "int &operator() = default;\n" 17020 "int &operator<=() {", 17021 Alignment); 17022 verifyFormat("int f() = default;\n" 17023 "int &operator() = default;\n" 17024 "int &operator!=() {", 17025 Alignment); 17026 verifyFormat("int f() = default;\n" 17027 "int &operator() = default;\n" 17028 "int &operator=();", 17029 Alignment); 17030 verifyFormat("int f() = delete;\n" 17031 "int &operator() = delete;\n" 17032 "int &operator=();", 17033 Alignment); 17034 verifyFormat("/* long long padding */ int f() = default;\n" 17035 "int &operator() = default;\n" 17036 "int &operator/**/ =();", 17037 Alignment); 17038 // https://llvm.org/PR33697 17039 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17040 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17041 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17042 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17043 " void f() = delete;\n" 17044 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17045 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17046 "};\n", 17047 AlignmentWithPenalty); 17048 17049 // Bug 25167 17050 /* Uncomment when fixed 17051 verifyFormat("#if A\n" 17052 "#else\n" 17053 "int aaaaaaaa = 12;\n" 17054 "#endif\n" 17055 "#if B\n" 17056 "#else\n" 17057 "int a = 12;\n" 17058 "#endif\n", 17059 Alignment); 17060 verifyFormat("enum foo {\n" 17061 "#if A\n" 17062 "#else\n" 17063 " aaaaaaaa = 12;\n" 17064 "#endif\n" 17065 "#if B\n" 17066 "#else\n" 17067 " a = 12;\n" 17068 "#endif\n" 17069 "};\n", 17070 Alignment); 17071 */ 17072 17073 EXPECT_EQ("int a = 5;\n" 17074 "\n" 17075 "int oneTwoThree = 123;", 17076 format("int a = 5;\n" 17077 "\n" 17078 "int oneTwoThree= 123;", 17079 Alignment)); 17080 EXPECT_EQ("int a = 5;\n" 17081 "int one = 1;\n" 17082 "\n" 17083 "int oneTwoThree = 123;", 17084 format("int a = 5;\n" 17085 "int one = 1;\n" 17086 "\n" 17087 "int oneTwoThree = 123;", 17088 Alignment)); 17089 EXPECT_EQ("int a = 5;\n" 17090 "int one = 1;\n" 17091 "\n" 17092 "int oneTwoThree = 123;\n" 17093 "int oneTwo = 12;", 17094 format("int a = 5;\n" 17095 "int one = 1;\n" 17096 "\n" 17097 "int oneTwoThree = 123;\n" 17098 "int oneTwo = 12;", 17099 Alignment)); 17100 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17101 verifyFormat("#define A \\\n" 17102 " int aaaa = 12; \\\n" 17103 " int b = 23; \\\n" 17104 " int ccc = 234; \\\n" 17105 " int dddddddddd = 2345;", 17106 Alignment); 17107 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17108 verifyFormat("#define A \\\n" 17109 " int aaaa = 12; \\\n" 17110 " int b = 23; \\\n" 17111 " int ccc = 234; \\\n" 17112 " int dddddddddd = 2345;", 17113 Alignment); 17114 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17115 verifyFormat("#define A " 17116 " \\\n" 17117 " int aaaa = 12; " 17118 " \\\n" 17119 " int b = 23; " 17120 " \\\n" 17121 " int ccc = 234; " 17122 " \\\n" 17123 " int dddddddddd = 2345;", 17124 Alignment); 17125 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17126 "k = 4, int l = 5,\n" 17127 " int m = 6) {\n" 17128 " int j = 10;\n" 17129 " otherThing = 1;\n" 17130 "}", 17131 Alignment); 17132 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17133 " int i = 1;\n" 17134 " int j = 2;\n" 17135 " int big = 10000;\n" 17136 "}", 17137 Alignment); 17138 verifyFormat("class C {\n" 17139 "public:\n" 17140 " int i = 1;\n" 17141 " virtual void f() = 0;\n" 17142 "};", 17143 Alignment); 17144 verifyFormat("int i = 1;\n" 17145 "if (SomeType t = getSomething()) {\n" 17146 "}\n" 17147 "int j = 2;\n" 17148 "int big = 10000;", 17149 Alignment); 17150 verifyFormat("int j = 7;\n" 17151 "for (int k = 0; k < N; ++k) {\n" 17152 "}\n" 17153 "int j = 2;\n" 17154 "int big = 10000;\n" 17155 "}", 17156 Alignment); 17157 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17158 verifyFormat("int i = 1;\n" 17159 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17160 " = someLooooooooooooooooongFunction();\n" 17161 "int j = 2;", 17162 Alignment); 17163 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17164 verifyFormat("int i = 1;\n" 17165 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17166 " someLooooooooooooooooongFunction();\n" 17167 "int j = 2;", 17168 Alignment); 17169 17170 verifyFormat("auto lambda = []() {\n" 17171 " auto i = 0;\n" 17172 " return 0;\n" 17173 "};\n" 17174 "int i = 0;\n" 17175 "auto v = type{\n" 17176 " i = 1, //\n" 17177 " (i = 2), //\n" 17178 " i = 3 //\n" 17179 "};", 17180 Alignment); 17181 17182 verifyFormat( 17183 "int i = 1;\n" 17184 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17185 " loooooooooooooooooooooongParameterB);\n" 17186 "int j = 2;", 17187 Alignment); 17188 17189 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17190 " typename B = very_long_type_name_1,\n" 17191 " typename T_2 = very_long_type_name_2>\n" 17192 "auto foo() {}\n", 17193 Alignment); 17194 verifyFormat("int a, b = 1;\n" 17195 "int c = 2;\n" 17196 "int dd = 3;\n", 17197 Alignment); 17198 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17199 "float b[1][] = {{3.f}};\n", 17200 Alignment); 17201 verifyFormat("for (int i = 0; i < 1; i++)\n" 17202 " int x = 1;\n", 17203 Alignment); 17204 verifyFormat("for (i = 0; i < 1; i++)\n" 17205 " x = 1;\n" 17206 "y = 1;\n", 17207 Alignment); 17208 17209 EXPECT_EQ(Alignment.ReflowComments, true); 17210 Alignment.ColumnLimit = 50; 17211 EXPECT_EQ("int x = 0;\n" 17212 "int yy = 1; /// specificlennospace\n" 17213 "int zzz = 2;\n", 17214 format("int x = 0;\n" 17215 "int yy = 1; ///specificlennospace\n" 17216 "int zzz = 2;\n", 17217 Alignment)); 17218 17219 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17220 "auto b = [] {\n" 17221 " f();\n" 17222 " return;\n" 17223 "};", 17224 Alignment); 17225 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17226 "auto b = g([] {\n" 17227 " f();\n" 17228 " return;\n" 17229 "});", 17230 Alignment); 17231 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17232 "auto b = g(param, [] {\n" 17233 " f();\n" 17234 " return;\n" 17235 "});", 17236 Alignment); 17237 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17238 "auto b = [] {\n" 17239 " if (condition) {\n" 17240 " return;\n" 17241 " }\n" 17242 "};", 17243 Alignment); 17244 17245 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17246 " ccc ? aaaaa : bbbbb,\n" 17247 " dddddddddddddddddddddddddd);", 17248 Alignment); 17249 // FIXME: https://llvm.org/PR53497 17250 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17251 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17252 // " ccc ? aaaaa : bbbbb,\n" 17253 // " dddddddddddddddddddddddddd);", 17254 // Alignment); 17255 } 17256 17257 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17258 FormatStyle Alignment = getLLVMStyle(); 17259 Alignment.AlignConsecutiveBitFields.Enabled = true; 17260 verifyFormat("int const a : 5;\n" 17261 "int oneTwoThree : 23;", 17262 Alignment); 17263 17264 // Initializers are allowed starting with c++2a 17265 verifyFormat("int const a : 5 = 1;\n" 17266 "int oneTwoThree : 23 = 0;", 17267 Alignment); 17268 17269 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17270 verifyFormat("int const a : 5;\n" 17271 "int oneTwoThree : 23;", 17272 Alignment); 17273 17274 verifyFormat("int const a : 5; // comment\n" 17275 "int oneTwoThree : 23; // comment", 17276 Alignment); 17277 17278 verifyFormat("int const a : 5 = 1;\n" 17279 "int oneTwoThree : 23 = 0;", 17280 Alignment); 17281 17282 Alignment.AlignConsecutiveAssignments.Enabled = true; 17283 verifyFormat("int const a : 5 = 1;\n" 17284 "int oneTwoThree : 23 = 0;", 17285 Alignment); 17286 verifyFormat("int const a : 5 = {1};\n" 17287 "int oneTwoThree : 23 = 0;", 17288 Alignment); 17289 17290 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17291 verifyFormat("int const a :5;\n" 17292 "int oneTwoThree:23;", 17293 Alignment); 17294 17295 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17296 verifyFormat("int const a :5;\n" 17297 "int oneTwoThree :23;", 17298 Alignment); 17299 17300 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17301 verifyFormat("int const a : 5;\n" 17302 "int oneTwoThree: 23;", 17303 Alignment); 17304 17305 // Known limitations: ':' is only recognized as a bitfield colon when 17306 // followed by a number. 17307 /* 17308 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17309 "int a : 5;", 17310 Alignment); 17311 */ 17312 } 17313 17314 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17315 FormatStyle Alignment = getLLVMStyle(); 17316 Alignment.AlignConsecutiveMacros.Enabled = true; 17317 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17318 verifyFormat("float const a = 5;\n" 17319 "int oneTwoThree = 123;", 17320 Alignment); 17321 verifyFormat("int a = 5;\n" 17322 "float const oneTwoThree = 123;", 17323 Alignment); 17324 17325 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17326 verifyFormat("float const a = 5;\n" 17327 "int oneTwoThree = 123;", 17328 Alignment); 17329 verifyFormat("int a = method();\n" 17330 "float const oneTwoThree = 133;", 17331 Alignment); 17332 verifyFormat("int i = 1, j = 10;\n" 17333 "something = 2000;", 17334 Alignment); 17335 verifyFormat("something = 2000;\n" 17336 "int i = 1, j = 10;\n", 17337 Alignment); 17338 verifyFormat("float something = 2000;\n" 17339 "double another = 911;\n" 17340 "int i = 1, j = 10;\n" 17341 "const int *oneMore = 1;\n" 17342 "unsigned i = 2;", 17343 Alignment); 17344 verifyFormat("float a = 5;\n" 17345 "int one = 1;\n" 17346 "method();\n" 17347 "const double oneTwoThree = 123;\n" 17348 "const unsigned int oneTwo = 12;", 17349 Alignment); 17350 verifyFormat("int oneTwoThree{0}; // comment\n" 17351 "unsigned oneTwo; // comment", 17352 Alignment); 17353 verifyFormat("unsigned int *a;\n" 17354 "int *b;\n" 17355 "unsigned int Const *c;\n" 17356 "unsigned int const *d;\n" 17357 "unsigned int Const &e;\n" 17358 "unsigned int const &f;", 17359 Alignment); 17360 verifyFormat("Const unsigned int *c;\n" 17361 "const unsigned int *d;\n" 17362 "Const unsigned int &e;\n" 17363 "const unsigned int &f;\n" 17364 "const unsigned g;\n" 17365 "Const unsigned h;", 17366 Alignment); 17367 EXPECT_EQ("float const a = 5;\n" 17368 "\n" 17369 "int oneTwoThree = 123;", 17370 format("float const a = 5;\n" 17371 "\n" 17372 "int oneTwoThree= 123;", 17373 Alignment)); 17374 EXPECT_EQ("float a = 5;\n" 17375 "int one = 1;\n" 17376 "\n" 17377 "unsigned oneTwoThree = 123;", 17378 format("float a = 5;\n" 17379 "int one = 1;\n" 17380 "\n" 17381 "unsigned oneTwoThree = 123;", 17382 Alignment)); 17383 EXPECT_EQ("float a = 5;\n" 17384 "int one = 1;\n" 17385 "\n" 17386 "unsigned oneTwoThree = 123;\n" 17387 "int oneTwo = 12;", 17388 format("float a = 5;\n" 17389 "int one = 1;\n" 17390 "\n" 17391 "unsigned oneTwoThree = 123;\n" 17392 "int oneTwo = 12;", 17393 Alignment)); 17394 // Function prototype alignment 17395 verifyFormat("int a();\n" 17396 "double b();", 17397 Alignment); 17398 verifyFormat("int a(int x);\n" 17399 "double b();", 17400 Alignment); 17401 unsigned OldColumnLimit = Alignment.ColumnLimit; 17402 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17403 // otherwise the function parameters will be re-flowed onto a single line. 17404 Alignment.ColumnLimit = 0; 17405 EXPECT_EQ("int a(int x,\n" 17406 " float y);\n" 17407 "double b(int x,\n" 17408 " double y);", 17409 format("int a(int x,\n" 17410 " float y);\n" 17411 "double b(int x,\n" 17412 " double y);", 17413 Alignment)); 17414 // This ensures that function parameters of function declarations are 17415 // correctly indented when their owning functions are indented. 17416 // The failure case here is for 'double y' to not be indented enough. 17417 EXPECT_EQ("double a(int x);\n" 17418 "int b(int y,\n" 17419 " double z);", 17420 format("double a(int x);\n" 17421 "int b(int y,\n" 17422 " double z);", 17423 Alignment)); 17424 // Set ColumnLimit low so that we induce wrapping immediately after 17425 // the function name and opening paren. 17426 Alignment.ColumnLimit = 13; 17427 verifyFormat("int function(\n" 17428 " int x,\n" 17429 " bool y);", 17430 Alignment); 17431 Alignment.ColumnLimit = OldColumnLimit; 17432 // Ensure function pointers don't screw up recursive alignment 17433 verifyFormat("int a(int x, void (*fp)(int y));\n" 17434 "double b();", 17435 Alignment); 17436 Alignment.AlignConsecutiveAssignments.Enabled = true; 17437 // Ensure recursive alignment is broken by function braces, so that the 17438 // "a = 1" does not align with subsequent assignments inside the function 17439 // body. 17440 verifyFormat("int func(int a = 1) {\n" 17441 " int b = 2;\n" 17442 " int cc = 3;\n" 17443 "}", 17444 Alignment); 17445 verifyFormat("float something = 2000;\n" 17446 "double another = 911;\n" 17447 "int i = 1, j = 10;\n" 17448 "const int *oneMore = 1;\n" 17449 "unsigned i = 2;", 17450 Alignment); 17451 verifyFormat("int oneTwoThree = {0}; // comment\n" 17452 "unsigned oneTwo = 0; // comment", 17453 Alignment); 17454 // Make sure that scope is correctly tracked, in the absence of braces 17455 verifyFormat("for (int i = 0; i < n; i++)\n" 17456 " j = i;\n" 17457 "double x = 1;\n", 17458 Alignment); 17459 verifyFormat("if (int i = 0)\n" 17460 " j = i;\n" 17461 "double x = 1;\n", 17462 Alignment); 17463 // Ensure operator[] and operator() are comprehended 17464 verifyFormat("struct test {\n" 17465 " long long int foo();\n" 17466 " int operator[](int a);\n" 17467 " double bar();\n" 17468 "};\n", 17469 Alignment); 17470 verifyFormat("struct test {\n" 17471 " long long int foo();\n" 17472 " int operator()(int a);\n" 17473 " double bar();\n" 17474 "};\n", 17475 Alignment); 17476 // http://llvm.org/PR52914 17477 verifyFormat("char *a[] = {\"a\", // comment\n" 17478 " \"bb\"};\n" 17479 "int bbbbbbb = 0;", 17480 Alignment); 17481 17482 // PAS_Right 17483 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17484 " int const i = 1;\n" 17485 " int *j = 2;\n" 17486 " int big = 10000;\n" 17487 "\n" 17488 " unsigned oneTwoThree = 123;\n" 17489 " int oneTwo = 12;\n" 17490 " method();\n" 17491 " float k = 2;\n" 17492 " int ll = 10000;\n" 17493 "}", 17494 format("void SomeFunction(int parameter= 0) {\n" 17495 " int const i= 1;\n" 17496 " int *j=2;\n" 17497 " int big = 10000;\n" 17498 "\n" 17499 "unsigned oneTwoThree =123;\n" 17500 "int oneTwo = 12;\n" 17501 " method();\n" 17502 "float k= 2;\n" 17503 "int ll=10000;\n" 17504 "}", 17505 Alignment)); 17506 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17507 " int const i = 1;\n" 17508 " int **j = 2, ***k;\n" 17509 " int &k = i;\n" 17510 " int &&l = i + j;\n" 17511 " int big = 10000;\n" 17512 "\n" 17513 " unsigned oneTwoThree = 123;\n" 17514 " int oneTwo = 12;\n" 17515 " method();\n" 17516 " float k = 2;\n" 17517 " int ll = 10000;\n" 17518 "}", 17519 format("void SomeFunction(int parameter= 0) {\n" 17520 " int const i= 1;\n" 17521 " int **j=2,***k;\n" 17522 "int &k=i;\n" 17523 "int &&l=i+j;\n" 17524 " int big = 10000;\n" 17525 "\n" 17526 "unsigned oneTwoThree =123;\n" 17527 "int oneTwo = 12;\n" 17528 " method();\n" 17529 "float k= 2;\n" 17530 "int ll=10000;\n" 17531 "}", 17532 Alignment)); 17533 // variables are aligned at their name, pointers are at the right most 17534 // position 17535 verifyFormat("int *a;\n" 17536 "int **b;\n" 17537 "int ***c;\n" 17538 "int foobar;\n", 17539 Alignment); 17540 17541 // PAS_Left 17542 FormatStyle AlignmentLeft = Alignment; 17543 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17544 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17545 " int const i = 1;\n" 17546 " int* j = 2;\n" 17547 " int big = 10000;\n" 17548 "\n" 17549 " unsigned oneTwoThree = 123;\n" 17550 " int oneTwo = 12;\n" 17551 " method();\n" 17552 " float k = 2;\n" 17553 " int ll = 10000;\n" 17554 "}", 17555 format("void SomeFunction(int parameter= 0) {\n" 17556 " int const i= 1;\n" 17557 " int *j=2;\n" 17558 " int big = 10000;\n" 17559 "\n" 17560 "unsigned oneTwoThree =123;\n" 17561 "int oneTwo = 12;\n" 17562 " method();\n" 17563 "float k= 2;\n" 17564 "int ll=10000;\n" 17565 "}", 17566 AlignmentLeft)); 17567 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17568 " int const i = 1;\n" 17569 " int** j = 2;\n" 17570 " int& k = i;\n" 17571 " int&& l = i + j;\n" 17572 " int big = 10000;\n" 17573 "\n" 17574 " unsigned oneTwoThree = 123;\n" 17575 " int oneTwo = 12;\n" 17576 " method();\n" 17577 " float k = 2;\n" 17578 " int ll = 10000;\n" 17579 "}", 17580 format("void SomeFunction(int parameter= 0) {\n" 17581 " int const i= 1;\n" 17582 " int **j=2;\n" 17583 "int &k=i;\n" 17584 "int &&l=i+j;\n" 17585 " int big = 10000;\n" 17586 "\n" 17587 "unsigned oneTwoThree =123;\n" 17588 "int oneTwo = 12;\n" 17589 " method();\n" 17590 "float k= 2;\n" 17591 "int ll=10000;\n" 17592 "}", 17593 AlignmentLeft)); 17594 // variables are aligned at their name, pointers are at the left most position 17595 verifyFormat("int* a;\n" 17596 "int** b;\n" 17597 "int*** c;\n" 17598 "int foobar;\n", 17599 AlignmentLeft); 17600 17601 // PAS_Middle 17602 FormatStyle AlignmentMiddle = Alignment; 17603 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17604 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17605 " int const i = 1;\n" 17606 " int * j = 2;\n" 17607 " int big = 10000;\n" 17608 "\n" 17609 " unsigned oneTwoThree = 123;\n" 17610 " int oneTwo = 12;\n" 17611 " method();\n" 17612 " float k = 2;\n" 17613 " int ll = 10000;\n" 17614 "}", 17615 format("void SomeFunction(int parameter= 0) {\n" 17616 " int const i= 1;\n" 17617 " int *j=2;\n" 17618 " int big = 10000;\n" 17619 "\n" 17620 "unsigned oneTwoThree =123;\n" 17621 "int oneTwo = 12;\n" 17622 " method();\n" 17623 "float k= 2;\n" 17624 "int ll=10000;\n" 17625 "}", 17626 AlignmentMiddle)); 17627 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17628 " int const i = 1;\n" 17629 " int ** j = 2, ***k;\n" 17630 " int & k = i;\n" 17631 " int && l = i + j;\n" 17632 " int big = 10000;\n" 17633 "\n" 17634 " unsigned oneTwoThree = 123;\n" 17635 " int oneTwo = 12;\n" 17636 " method();\n" 17637 " float k = 2;\n" 17638 " int ll = 10000;\n" 17639 "}", 17640 format("void SomeFunction(int parameter= 0) {\n" 17641 " int const i= 1;\n" 17642 " int **j=2,***k;\n" 17643 "int &k=i;\n" 17644 "int &&l=i+j;\n" 17645 " int big = 10000;\n" 17646 "\n" 17647 "unsigned oneTwoThree =123;\n" 17648 "int oneTwo = 12;\n" 17649 " method();\n" 17650 "float k= 2;\n" 17651 "int ll=10000;\n" 17652 "}", 17653 AlignmentMiddle)); 17654 // variables are aligned at their name, pointers are in the middle 17655 verifyFormat("int * a;\n" 17656 "int * b;\n" 17657 "int *** c;\n" 17658 "int foobar;\n", 17659 AlignmentMiddle); 17660 17661 Alignment.AlignConsecutiveAssignments.Enabled = false; 17662 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17663 verifyFormat("#define A \\\n" 17664 " int aaaa = 12; \\\n" 17665 " float b = 23; \\\n" 17666 " const int ccc = 234; \\\n" 17667 " unsigned dddddddddd = 2345;", 17668 Alignment); 17669 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17670 verifyFormat("#define A \\\n" 17671 " int aaaa = 12; \\\n" 17672 " float b = 23; \\\n" 17673 " const int ccc = 234; \\\n" 17674 " unsigned dddddddddd = 2345;", 17675 Alignment); 17676 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17677 Alignment.ColumnLimit = 30; 17678 verifyFormat("#define A \\\n" 17679 " int aaaa = 12; \\\n" 17680 " float b = 23; \\\n" 17681 " const int ccc = 234; \\\n" 17682 " int dddddddddd = 2345;", 17683 Alignment); 17684 Alignment.ColumnLimit = 80; 17685 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17686 "k = 4, int l = 5,\n" 17687 " int m = 6) {\n" 17688 " const int j = 10;\n" 17689 " otherThing = 1;\n" 17690 "}", 17691 Alignment); 17692 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17693 " int const i = 1;\n" 17694 " int *j = 2;\n" 17695 " int big = 10000;\n" 17696 "}", 17697 Alignment); 17698 verifyFormat("class C {\n" 17699 "public:\n" 17700 " int i = 1;\n" 17701 " virtual void f() = 0;\n" 17702 "};", 17703 Alignment); 17704 verifyFormat("float i = 1;\n" 17705 "if (SomeType t = getSomething()) {\n" 17706 "}\n" 17707 "const unsigned j = 2;\n" 17708 "int big = 10000;", 17709 Alignment); 17710 verifyFormat("float j = 7;\n" 17711 "for (int k = 0; k < N; ++k) {\n" 17712 "}\n" 17713 "unsigned j = 2;\n" 17714 "int big = 10000;\n" 17715 "}", 17716 Alignment); 17717 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17718 verifyFormat("float i = 1;\n" 17719 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17720 " = someLooooooooooooooooongFunction();\n" 17721 "int j = 2;", 17722 Alignment); 17723 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17724 verifyFormat("int i = 1;\n" 17725 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17726 " someLooooooooooooooooongFunction();\n" 17727 "int j = 2;", 17728 Alignment); 17729 17730 Alignment.AlignConsecutiveAssignments.Enabled = true; 17731 verifyFormat("auto lambda = []() {\n" 17732 " auto ii = 0;\n" 17733 " float j = 0;\n" 17734 " return 0;\n" 17735 "};\n" 17736 "int i = 0;\n" 17737 "float i2 = 0;\n" 17738 "auto v = type{\n" 17739 " i = 1, //\n" 17740 " (i = 2), //\n" 17741 " i = 3 //\n" 17742 "};", 17743 Alignment); 17744 Alignment.AlignConsecutiveAssignments.Enabled = false; 17745 17746 verifyFormat( 17747 "int i = 1;\n" 17748 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17749 " loooooooooooooooooooooongParameterB);\n" 17750 "int j = 2;", 17751 Alignment); 17752 17753 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17754 // We expect declarations and assignments to align, as long as it doesn't 17755 // exceed the column limit, starting a new alignment sequence whenever it 17756 // happens. 17757 Alignment.AlignConsecutiveAssignments.Enabled = true; 17758 Alignment.ColumnLimit = 30; 17759 verifyFormat("float ii = 1;\n" 17760 "unsigned j = 2;\n" 17761 "int someVerylongVariable = 1;\n" 17762 "AnotherLongType ll = 123456;\n" 17763 "VeryVeryLongType k = 2;\n" 17764 "int myvar = 1;", 17765 Alignment); 17766 Alignment.ColumnLimit = 80; 17767 Alignment.AlignConsecutiveAssignments.Enabled = false; 17768 17769 verifyFormat( 17770 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17771 " typename LongType, typename B>\n" 17772 "auto foo() {}\n", 17773 Alignment); 17774 verifyFormat("float a, b = 1;\n" 17775 "int c = 2;\n" 17776 "int dd = 3;\n", 17777 Alignment); 17778 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17779 "float b[1][] = {{3.f}};\n", 17780 Alignment); 17781 Alignment.AlignConsecutiveAssignments.Enabled = true; 17782 verifyFormat("float a, b = 1;\n" 17783 "int c = 2;\n" 17784 "int dd = 3;\n", 17785 Alignment); 17786 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17787 "float b[1][] = {{3.f}};\n", 17788 Alignment); 17789 Alignment.AlignConsecutiveAssignments.Enabled = false; 17790 17791 Alignment.ColumnLimit = 30; 17792 Alignment.BinPackParameters = false; 17793 verifyFormat("void foo(float a,\n" 17794 " float b,\n" 17795 " int c,\n" 17796 " uint32_t *d) {\n" 17797 " int *e = 0;\n" 17798 " float f = 0;\n" 17799 " double g = 0;\n" 17800 "}\n" 17801 "void bar(ino_t a,\n" 17802 " int b,\n" 17803 " uint32_t *c,\n" 17804 " bool d) {}\n", 17805 Alignment); 17806 Alignment.BinPackParameters = true; 17807 Alignment.ColumnLimit = 80; 17808 17809 // Bug 33507 17810 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17811 verifyFormat( 17812 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17813 " static const Version verVs2017;\n" 17814 " return true;\n" 17815 "});\n", 17816 Alignment); 17817 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17818 17819 // See llvm.org/PR35641 17820 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17821 verifyFormat("int func() { //\n" 17822 " int b;\n" 17823 " unsigned c;\n" 17824 "}", 17825 Alignment); 17826 17827 // See PR37175 17828 FormatStyle Style = getMozillaStyle(); 17829 Style.AlignConsecutiveDeclarations.Enabled = true; 17830 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17831 "foo(int a);", 17832 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17833 17834 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17835 verifyFormat("unsigned int* a;\n" 17836 "int* b;\n" 17837 "unsigned int Const* c;\n" 17838 "unsigned int const* d;\n" 17839 "unsigned int Const& e;\n" 17840 "unsigned int const& f;", 17841 Alignment); 17842 verifyFormat("Const unsigned int* c;\n" 17843 "const unsigned int* d;\n" 17844 "Const unsigned int& e;\n" 17845 "const unsigned int& f;\n" 17846 "const unsigned g;\n" 17847 "Const unsigned h;", 17848 Alignment); 17849 17850 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17851 verifyFormat("unsigned int * a;\n" 17852 "int * b;\n" 17853 "unsigned int Const * c;\n" 17854 "unsigned int const * d;\n" 17855 "unsigned int Const & e;\n" 17856 "unsigned int const & f;", 17857 Alignment); 17858 verifyFormat("Const unsigned int * c;\n" 17859 "const unsigned int * d;\n" 17860 "Const unsigned int & e;\n" 17861 "const unsigned int & f;\n" 17862 "const unsigned g;\n" 17863 "Const unsigned h;", 17864 Alignment); 17865 17866 // See PR46529 17867 FormatStyle BracedAlign = getLLVMStyle(); 17868 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 17869 verifyFormat("const auto result{[]() {\n" 17870 " const auto something = 1;\n" 17871 " return 2;\n" 17872 "}};", 17873 BracedAlign); 17874 verifyFormat("int foo{[]() {\n" 17875 " int bar{0};\n" 17876 " return 0;\n" 17877 "}()};", 17878 BracedAlign); 17879 BracedAlign.Cpp11BracedListStyle = false; 17880 verifyFormat("const auto result{ []() {\n" 17881 " const auto something = 1;\n" 17882 " return 2;\n" 17883 "} };", 17884 BracedAlign); 17885 verifyFormat("int foo{ []() {\n" 17886 " int bar{ 0 };\n" 17887 " return 0;\n" 17888 "}() };", 17889 BracedAlign); 17890 } 17891 17892 TEST_F(FormatTest, AlignWithLineBreaks) { 17893 auto Style = getLLVMStyleWithColumns(120); 17894 17895 EXPECT_EQ(Style.AlignConsecutiveAssignments, 17896 FormatStyle::AlignConsecutiveStyle( 17897 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 17898 /*AcrossComments=*/false, /*AlignCompound=*/false, 17899 /*PadOperators=*/true})); 17900 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 17901 FormatStyle::AlignConsecutiveStyle({})); 17902 verifyFormat("void foo() {\n" 17903 " int myVar = 5;\n" 17904 " double x = 3.14;\n" 17905 " auto str = \"Hello \"\n" 17906 " \"World\";\n" 17907 " auto s = \"Hello \"\n" 17908 " \"Again\";\n" 17909 "}", 17910 Style); 17911 17912 // clang-format off 17913 verifyFormat("void foo() {\n" 17914 " const int capacityBefore = Entries.capacity();\n" 17915 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17916 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17917 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17918 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17919 "}", 17920 Style); 17921 // clang-format on 17922 17923 Style.AlignConsecutiveAssignments.Enabled = true; 17924 verifyFormat("void foo() {\n" 17925 " int myVar = 5;\n" 17926 " double x = 3.14;\n" 17927 " auto str = \"Hello \"\n" 17928 " \"World\";\n" 17929 " auto s = \"Hello \"\n" 17930 " \"Again\";\n" 17931 "}", 17932 Style); 17933 17934 // clang-format off 17935 verifyFormat("void foo() {\n" 17936 " const int capacityBefore = Entries.capacity();\n" 17937 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17938 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17939 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17940 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17941 "}", 17942 Style); 17943 // clang-format on 17944 17945 Style.AlignConsecutiveAssignments.Enabled = false; 17946 Style.AlignConsecutiveDeclarations.Enabled = true; 17947 verifyFormat("void foo() {\n" 17948 " int myVar = 5;\n" 17949 " double x = 3.14;\n" 17950 " auto str = \"Hello \"\n" 17951 " \"World\";\n" 17952 " auto s = \"Hello \"\n" 17953 " \"Again\";\n" 17954 "}", 17955 Style); 17956 17957 // clang-format off 17958 verifyFormat("void foo() {\n" 17959 " const int capacityBefore = Entries.capacity();\n" 17960 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17961 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17962 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17963 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17964 "}", 17965 Style); 17966 // clang-format on 17967 17968 Style.AlignConsecutiveAssignments.Enabled = true; 17969 Style.AlignConsecutiveDeclarations.Enabled = true; 17970 17971 verifyFormat("void foo() {\n" 17972 " int myVar = 5;\n" 17973 " double x = 3.14;\n" 17974 " auto str = \"Hello \"\n" 17975 " \"World\";\n" 17976 " auto s = \"Hello \"\n" 17977 " \"Again\";\n" 17978 "}", 17979 Style); 17980 17981 // clang-format off 17982 verifyFormat("void foo() {\n" 17983 " const int capacityBefore = Entries.capacity();\n" 17984 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17985 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17986 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17987 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17988 "}", 17989 Style); 17990 // clang-format on 17991 17992 Style = getLLVMStyleWithColumns(120); 17993 Style.AlignConsecutiveAssignments.Enabled = true; 17994 Style.ContinuationIndentWidth = 4; 17995 Style.IndentWidth = 4; 17996 17997 // clang-format off 17998 verifyFormat("void SomeFunc() {\n" 17999 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18000 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18001 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18002 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18003 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18004 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18005 "}", 18006 Style); 18007 // clang-format on 18008 18009 Style.BinPackArguments = false; 18010 18011 // clang-format off 18012 verifyFormat("void SomeFunc() {\n" 18013 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 18014 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18015 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 18016 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18017 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 18018 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18019 "}", 18020 Style); 18021 // clang-format on 18022 } 18023 18024 TEST_F(FormatTest, AlignWithInitializerPeriods) { 18025 auto Style = getLLVMStyleWithColumns(60); 18026 18027 verifyFormat("void foo1(void) {\n" 18028 " BYTE p[1] = 1;\n" 18029 " A B = {.one_foooooooooooooooo = 2,\n" 18030 " .two_fooooooooooooo = 3,\n" 18031 " .three_fooooooooooooo = 4};\n" 18032 " BYTE payload = 2;\n" 18033 "}", 18034 Style); 18035 18036 Style.AlignConsecutiveAssignments.Enabled = true; 18037 Style.AlignConsecutiveDeclarations.Enabled = false; 18038 verifyFormat("void foo2(void) {\n" 18039 " BYTE p[1] = 1;\n" 18040 " A B = {.one_foooooooooooooooo = 2,\n" 18041 " .two_fooooooooooooo = 3,\n" 18042 " .three_fooooooooooooo = 4};\n" 18043 " BYTE payload = 2;\n" 18044 "}", 18045 Style); 18046 18047 Style.AlignConsecutiveAssignments.Enabled = false; 18048 Style.AlignConsecutiveDeclarations.Enabled = true; 18049 verifyFormat("void foo3(void) {\n" 18050 " BYTE p[1] = 1;\n" 18051 " A B = {.one_foooooooooooooooo = 2,\n" 18052 " .two_fooooooooooooo = 3,\n" 18053 " .three_fooooooooooooo = 4};\n" 18054 " BYTE payload = 2;\n" 18055 "}", 18056 Style); 18057 18058 Style.AlignConsecutiveAssignments.Enabled = true; 18059 Style.AlignConsecutiveDeclarations.Enabled = true; 18060 verifyFormat("void foo4(void) {\n" 18061 " BYTE p[1] = 1;\n" 18062 " A B = {.one_foooooooooooooooo = 2,\n" 18063 " .two_fooooooooooooo = 3,\n" 18064 " .three_fooooooooooooo = 4};\n" 18065 " BYTE payload = 2;\n" 18066 "}", 18067 Style); 18068 } 18069 18070 TEST_F(FormatTest, LinuxBraceBreaking) { 18071 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18072 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18073 verifyFormat("namespace a\n" 18074 "{\n" 18075 "class A\n" 18076 "{\n" 18077 " void f()\n" 18078 " {\n" 18079 " if (true) {\n" 18080 " a();\n" 18081 " b();\n" 18082 " } else {\n" 18083 " a();\n" 18084 " }\n" 18085 " }\n" 18086 " void g() { return; }\n" 18087 "};\n" 18088 "struct B {\n" 18089 " int x;\n" 18090 "};\n" 18091 "} // namespace a\n", 18092 LinuxBraceStyle); 18093 verifyFormat("enum X {\n" 18094 " Y = 0,\n" 18095 "}\n", 18096 LinuxBraceStyle); 18097 verifyFormat("struct S {\n" 18098 " int Type;\n" 18099 " union {\n" 18100 " int x;\n" 18101 " double y;\n" 18102 " } Value;\n" 18103 " class C\n" 18104 " {\n" 18105 " MyFavoriteType Value;\n" 18106 " } Class;\n" 18107 "}\n", 18108 LinuxBraceStyle); 18109 } 18110 18111 TEST_F(FormatTest, MozillaBraceBreaking) { 18112 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18113 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18114 MozillaBraceStyle.FixNamespaceComments = false; 18115 verifyFormat("namespace a {\n" 18116 "class A\n" 18117 "{\n" 18118 " void f()\n" 18119 " {\n" 18120 " if (true) {\n" 18121 " a();\n" 18122 " b();\n" 18123 " }\n" 18124 " }\n" 18125 " void g() { return; }\n" 18126 "};\n" 18127 "enum E\n" 18128 "{\n" 18129 " A,\n" 18130 " // foo\n" 18131 " B,\n" 18132 " C\n" 18133 "};\n" 18134 "struct B\n" 18135 "{\n" 18136 " int x;\n" 18137 "};\n" 18138 "}\n", 18139 MozillaBraceStyle); 18140 verifyFormat("struct S\n" 18141 "{\n" 18142 " int Type;\n" 18143 " union\n" 18144 " {\n" 18145 " int x;\n" 18146 " double y;\n" 18147 " } Value;\n" 18148 " class C\n" 18149 " {\n" 18150 " MyFavoriteType Value;\n" 18151 " } Class;\n" 18152 "}\n", 18153 MozillaBraceStyle); 18154 } 18155 18156 TEST_F(FormatTest, StroustrupBraceBreaking) { 18157 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18158 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18159 verifyFormat("namespace a {\n" 18160 "class A {\n" 18161 " void f()\n" 18162 " {\n" 18163 " if (true) {\n" 18164 " a();\n" 18165 " b();\n" 18166 " }\n" 18167 " }\n" 18168 " void g() { return; }\n" 18169 "};\n" 18170 "struct B {\n" 18171 " int x;\n" 18172 "};\n" 18173 "} // namespace a\n", 18174 StroustrupBraceStyle); 18175 18176 verifyFormat("void foo()\n" 18177 "{\n" 18178 " if (a) {\n" 18179 " a();\n" 18180 " }\n" 18181 " else {\n" 18182 " b();\n" 18183 " }\n" 18184 "}\n", 18185 StroustrupBraceStyle); 18186 18187 verifyFormat("#ifdef _DEBUG\n" 18188 "int foo(int i = 0)\n" 18189 "#else\n" 18190 "int foo(int i = 5)\n" 18191 "#endif\n" 18192 "{\n" 18193 " return i;\n" 18194 "}", 18195 StroustrupBraceStyle); 18196 18197 verifyFormat("void foo() {}\n" 18198 "void bar()\n" 18199 "#ifdef _DEBUG\n" 18200 "{\n" 18201 " foo();\n" 18202 "}\n" 18203 "#else\n" 18204 "{\n" 18205 "}\n" 18206 "#endif", 18207 StroustrupBraceStyle); 18208 18209 verifyFormat("void foobar() { int i = 5; }\n" 18210 "#ifdef _DEBUG\n" 18211 "void bar() {}\n" 18212 "#else\n" 18213 "void bar() { foobar(); }\n" 18214 "#endif", 18215 StroustrupBraceStyle); 18216 } 18217 18218 TEST_F(FormatTest, AllmanBraceBreaking) { 18219 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18220 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18221 18222 EXPECT_EQ("namespace a\n" 18223 "{\n" 18224 "void f();\n" 18225 "void g();\n" 18226 "} // namespace a\n", 18227 format("namespace a\n" 18228 "{\n" 18229 "void f();\n" 18230 "void g();\n" 18231 "}\n", 18232 AllmanBraceStyle)); 18233 18234 verifyFormat("namespace a\n" 18235 "{\n" 18236 "class A\n" 18237 "{\n" 18238 " void f()\n" 18239 " {\n" 18240 " if (true)\n" 18241 " {\n" 18242 " a();\n" 18243 " b();\n" 18244 " }\n" 18245 " }\n" 18246 " void g() { return; }\n" 18247 "};\n" 18248 "struct B\n" 18249 "{\n" 18250 " int x;\n" 18251 "};\n" 18252 "union C\n" 18253 "{\n" 18254 "};\n" 18255 "} // namespace a", 18256 AllmanBraceStyle); 18257 18258 verifyFormat("void f()\n" 18259 "{\n" 18260 " if (true)\n" 18261 " {\n" 18262 " a();\n" 18263 " }\n" 18264 " else if (false)\n" 18265 " {\n" 18266 " b();\n" 18267 " }\n" 18268 " else\n" 18269 " {\n" 18270 " c();\n" 18271 " }\n" 18272 "}\n", 18273 AllmanBraceStyle); 18274 18275 verifyFormat("void f()\n" 18276 "{\n" 18277 " for (int i = 0; i < 10; ++i)\n" 18278 " {\n" 18279 " a();\n" 18280 " }\n" 18281 " while (false)\n" 18282 " {\n" 18283 " b();\n" 18284 " }\n" 18285 " do\n" 18286 " {\n" 18287 " c();\n" 18288 " } while (false)\n" 18289 "}\n", 18290 AllmanBraceStyle); 18291 18292 verifyFormat("void f(int a)\n" 18293 "{\n" 18294 " switch (a)\n" 18295 " {\n" 18296 " case 0:\n" 18297 " break;\n" 18298 " case 1:\n" 18299 " {\n" 18300 " break;\n" 18301 " }\n" 18302 " case 2:\n" 18303 " {\n" 18304 " }\n" 18305 " break;\n" 18306 " default:\n" 18307 " break;\n" 18308 " }\n" 18309 "}\n", 18310 AllmanBraceStyle); 18311 18312 verifyFormat("enum X\n" 18313 "{\n" 18314 " Y = 0,\n" 18315 "}\n", 18316 AllmanBraceStyle); 18317 verifyFormat("enum X\n" 18318 "{\n" 18319 " Y = 0\n" 18320 "}\n", 18321 AllmanBraceStyle); 18322 18323 verifyFormat("@interface BSApplicationController ()\n" 18324 "{\n" 18325 "@private\n" 18326 " id _extraIvar;\n" 18327 "}\n" 18328 "@end\n", 18329 AllmanBraceStyle); 18330 18331 verifyFormat("#ifdef _DEBUG\n" 18332 "int foo(int i = 0)\n" 18333 "#else\n" 18334 "int foo(int i = 5)\n" 18335 "#endif\n" 18336 "{\n" 18337 " return i;\n" 18338 "}", 18339 AllmanBraceStyle); 18340 18341 verifyFormat("void foo() {}\n" 18342 "void bar()\n" 18343 "#ifdef _DEBUG\n" 18344 "{\n" 18345 " foo();\n" 18346 "}\n" 18347 "#else\n" 18348 "{\n" 18349 "}\n" 18350 "#endif", 18351 AllmanBraceStyle); 18352 18353 verifyFormat("void foobar() { int i = 5; }\n" 18354 "#ifdef _DEBUG\n" 18355 "void bar() {}\n" 18356 "#else\n" 18357 "void bar() { foobar(); }\n" 18358 "#endif", 18359 AllmanBraceStyle); 18360 18361 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18362 FormatStyle::SLS_All); 18363 18364 verifyFormat("[](int i) { return i + 2; };\n" 18365 "[](int i, int j)\n" 18366 "{\n" 18367 " auto x = i + j;\n" 18368 " auto y = i * j;\n" 18369 " return x ^ y;\n" 18370 "};\n" 18371 "void foo()\n" 18372 "{\n" 18373 " auto shortLambda = [](int i) { return i + 2; };\n" 18374 " auto longLambda = [](int i, int j)\n" 18375 " {\n" 18376 " auto x = i + j;\n" 18377 " auto y = i * j;\n" 18378 " return x ^ y;\n" 18379 " };\n" 18380 "}", 18381 AllmanBraceStyle); 18382 18383 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18384 18385 verifyFormat("[](int i)\n" 18386 "{\n" 18387 " return i + 2;\n" 18388 "};\n" 18389 "[](int i, int j)\n" 18390 "{\n" 18391 " auto x = i + j;\n" 18392 " auto y = i * j;\n" 18393 " return x ^ y;\n" 18394 "};\n" 18395 "void foo()\n" 18396 "{\n" 18397 " auto shortLambda = [](int i)\n" 18398 " {\n" 18399 " return i + 2;\n" 18400 " };\n" 18401 " auto longLambda = [](int i, int j)\n" 18402 " {\n" 18403 " auto x = i + j;\n" 18404 " auto y = i * j;\n" 18405 " return x ^ y;\n" 18406 " };\n" 18407 "}", 18408 AllmanBraceStyle); 18409 18410 // Reset 18411 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18412 18413 // This shouldn't affect ObjC blocks.. 18414 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18415 " // ...\n" 18416 " int i;\n" 18417 "}];", 18418 AllmanBraceStyle); 18419 verifyFormat("void (^block)(void) = ^{\n" 18420 " // ...\n" 18421 " int i;\n" 18422 "};", 18423 AllmanBraceStyle); 18424 // .. or dict literals. 18425 verifyFormat("void f()\n" 18426 "{\n" 18427 " // ...\n" 18428 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18429 "}", 18430 AllmanBraceStyle); 18431 verifyFormat("void f()\n" 18432 "{\n" 18433 " // ...\n" 18434 " [object someMethod:@{a : @\"b\"}];\n" 18435 "}", 18436 AllmanBraceStyle); 18437 verifyFormat("int f()\n" 18438 "{ // comment\n" 18439 " return 42;\n" 18440 "}", 18441 AllmanBraceStyle); 18442 18443 AllmanBraceStyle.ColumnLimit = 19; 18444 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18445 AllmanBraceStyle.ColumnLimit = 18; 18446 verifyFormat("void f()\n" 18447 "{\n" 18448 " int i;\n" 18449 "}", 18450 AllmanBraceStyle); 18451 AllmanBraceStyle.ColumnLimit = 80; 18452 18453 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18454 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18455 FormatStyle::SIS_WithoutElse; 18456 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18457 verifyFormat("void f(bool b)\n" 18458 "{\n" 18459 " if (b)\n" 18460 " {\n" 18461 " return;\n" 18462 " }\n" 18463 "}\n", 18464 BreakBeforeBraceShortIfs); 18465 verifyFormat("void f(bool b)\n" 18466 "{\n" 18467 " if constexpr (b)\n" 18468 " {\n" 18469 " return;\n" 18470 " }\n" 18471 "}\n", 18472 BreakBeforeBraceShortIfs); 18473 verifyFormat("void f(bool b)\n" 18474 "{\n" 18475 " if CONSTEXPR (b)\n" 18476 " {\n" 18477 " return;\n" 18478 " }\n" 18479 "}\n", 18480 BreakBeforeBraceShortIfs); 18481 verifyFormat("void f(bool b)\n" 18482 "{\n" 18483 " if (b) return;\n" 18484 "}\n", 18485 BreakBeforeBraceShortIfs); 18486 verifyFormat("void f(bool b)\n" 18487 "{\n" 18488 " if constexpr (b) return;\n" 18489 "}\n", 18490 BreakBeforeBraceShortIfs); 18491 verifyFormat("void f(bool b)\n" 18492 "{\n" 18493 " if CONSTEXPR (b) return;\n" 18494 "}\n", 18495 BreakBeforeBraceShortIfs); 18496 verifyFormat("void f(bool b)\n" 18497 "{\n" 18498 " while (b)\n" 18499 " {\n" 18500 " return;\n" 18501 " }\n" 18502 "}\n", 18503 BreakBeforeBraceShortIfs); 18504 } 18505 18506 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18507 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18508 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18509 18510 // Make a few changes to the style for testing purposes 18511 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18512 FormatStyle::SFS_Empty; 18513 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18514 18515 // FIXME: this test case can't decide whether there should be a blank line 18516 // after the ~D() line or not. It adds one if one doesn't exist in the test 18517 // and it removes the line if one exists. 18518 /* 18519 verifyFormat("class A;\n" 18520 "namespace B\n" 18521 " {\n" 18522 "class C;\n" 18523 "// Comment\n" 18524 "class D\n" 18525 " {\n" 18526 "public:\n" 18527 " D();\n" 18528 " ~D() {}\n" 18529 "private:\n" 18530 " enum E\n" 18531 " {\n" 18532 " F\n" 18533 " }\n" 18534 " };\n" 18535 " } // namespace B\n", 18536 WhitesmithsBraceStyle); 18537 */ 18538 18539 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18540 verifyFormat("namespace a\n" 18541 " {\n" 18542 "class A\n" 18543 " {\n" 18544 " void f()\n" 18545 " {\n" 18546 " if (true)\n" 18547 " {\n" 18548 " a();\n" 18549 " b();\n" 18550 " }\n" 18551 " }\n" 18552 " void g()\n" 18553 " {\n" 18554 " return;\n" 18555 " }\n" 18556 " };\n" 18557 "struct B\n" 18558 " {\n" 18559 " int x;\n" 18560 " };\n" 18561 " } // namespace a", 18562 WhitesmithsBraceStyle); 18563 18564 verifyFormat("namespace a\n" 18565 " {\n" 18566 "namespace b\n" 18567 " {\n" 18568 "class A\n" 18569 " {\n" 18570 " void f()\n" 18571 " {\n" 18572 " if (true)\n" 18573 " {\n" 18574 " a();\n" 18575 " b();\n" 18576 " }\n" 18577 " }\n" 18578 " void g()\n" 18579 " {\n" 18580 " return;\n" 18581 " }\n" 18582 " };\n" 18583 "struct B\n" 18584 " {\n" 18585 " int x;\n" 18586 " };\n" 18587 " } // namespace b\n" 18588 " } // namespace a", 18589 WhitesmithsBraceStyle); 18590 18591 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18592 verifyFormat("namespace a\n" 18593 " {\n" 18594 "namespace b\n" 18595 " {\n" 18596 " class A\n" 18597 " {\n" 18598 " void f()\n" 18599 " {\n" 18600 " if (true)\n" 18601 " {\n" 18602 " a();\n" 18603 " b();\n" 18604 " }\n" 18605 " }\n" 18606 " void g()\n" 18607 " {\n" 18608 " return;\n" 18609 " }\n" 18610 " };\n" 18611 " struct B\n" 18612 " {\n" 18613 " int x;\n" 18614 " };\n" 18615 " } // namespace b\n" 18616 " } // namespace a", 18617 WhitesmithsBraceStyle); 18618 18619 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18620 verifyFormat("namespace a\n" 18621 " {\n" 18622 " namespace b\n" 18623 " {\n" 18624 " class A\n" 18625 " {\n" 18626 " void f()\n" 18627 " {\n" 18628 " if (true)\n" 18629 " {\n" 18630 " a();\n" 18631 " b();\n" 18632 " }\n" 18633 " }\n" 18634 " void g()\n" 18635 " {\n" 18636 " return;\n" 18637 " }\n" 18638 " };\n" 18639 " struct B\n" 18640 " {\n" 18641 " int x;\n" 18642 " };\n" 18643 " } // namespace b\n" 18644 " } // namespace a", 18645 WhitesmithsBraceStyle); 18646 18647 verifyFormat("void f()\n" 18648 " {\n" 18649 " if (true)\n" 18650 " {\n" 18651 " a();\n" 18652 " }\n" 18653 " else if (false)\n" 18654 " {\n" 18655 " b();\n" 18656 " }\n" 18657 " else\n" 18658 " {\n" 18659 " c();\n" 18660 " }\n" 18661 " }\n", 18662 WhitesmithsBraceStyle); 18663 18664 verifyFormat("void f()\n" 18665 " {\n" 18666 " for (int i = 0; i < 10; ++i)\n" 18667 " {\n" 18668 " a();\n" 18669 " }\n" 18670 " while (false)\n" 18671 " {\n" 18672 " b();\n" 18673 " }\n" 18674 " do\n" 18675 " {\n" 18676 " c();\n" 18677 " } while (false)\n" 18678 " }\n", 18679 WhitesmithsBraceStyle); 18680 18681 WhitesmithsBraceStyle.IndentCaseLabels = true; 18682 verifyFormat("void switchTest1(int a)\n" 18683 " {\n" 18684 " switch (a)\n" 18685 " {\n" 18686 " case 2:\n" 18687 " {\n" 18688 " }\n" 18689 " break;\n" 18690 " }\n" 18691 " }\n", 18692 WhitesmithsBraceStyle); 18693 18694 verifyFormat("void switchTest2(int a)\n" 18695 " {\n" 18696 " switch (a)\n" 18697 " {\n" 18698 " case 0:\n" 18699 " break;\n" 18700 " case 1:\n" 18701 " {\n" 18702 " break;\n" 18703 " }\n" 18704 " case 2:\n" 18705 " {\n" 18706 " }\n" 18707 " break;\n" 18708 " default:\n" 18709 " break;\n" 18710 " }\n" 18711 " }\n", 18712 WhitesmithsBraceStyle); 18713 18714 verifyFormat("void switchTest3(int a)\n" 18715 " {\n" 18716 " switch (a)\n" 18717 " {\n" 18718 " case 0:\n" 18719 " {\n" 18720 " foo(x);\n" 18721 " }\n" 18722 " break;\n" 18723 " default:\n" 18724 " {\n" 18725 " foo(1);\n" 18726 " }\n" 18727 " break;\n" 18728 " }\n" 18729 " }\n", 18730 WhitesmithsBraceStyle); 18731 18732 WhitesmithsBraceStyle.IndentCaseLabels = false; 18733 18734 verifyFormat("void switchTest4(int a)\n" 18735 " {\n" 18736 " switch (a)\n" 18737 " {\n" 18738 " case 2:\n" 18739 " {\n" 18740 " }\n" 18741 " break;\n" 18742 " }\n" 18743 " }\n", 18744 WhitesmithsBraceStyle); 18745 18746 verifyFormat("void switchTest5(int a)\n" 18747 " {\n" 18748 " switch (a)\n" 18749 " {\n" 18750 " case 0:\n" 18751 " break;\n" 18752 " case 1:\n" 18753 " {\n" 18754 " foo();\n" 18755 " break;\n" 18756 " }\n" 18757 " case 2:\n" 18758 " {\n" 18759 " }\n" 18760 " break;\n" 18761 " default:\n" 18762 " break;\n" 18763 " }\n" 18764 " }\n", 18765 WhitesmithsBraceStyle); 18766 18767 verifyFormat("void switchTest6(int a)\n" 18768 " {\n" 18769 " switch (a)\n" 18770 " {\n" 18771 " case 0:\n" 18772 " {\n" 18773 " foo(x);\n" 18774 " }\n" 18775 " break;\n" 18776 " default:\n" 18777 " {\n" 18778 " foo(1);\n" 18779 " }\n" 18780 " break;\n" 18781 " }\n" 18782 " }\n", 18783 WhitesmithsBraceStyle); 18784 18785 verifyFormat("enum X\n" 18786 " {\n" 18787 " Y = 0, // testing\n" 18788 " }\n", 18789 WhitesmithsBraceStyle); 18790 18791 verifyFormat("enum X\n" 18792 " {\n" 18793 " Y = 0\n" 18794 " }\n", 18795 WhitesmithsBraceStyle); 18796 verifyFormat("enum X\n" 18797 " {\n" 18798 " Y = 0,\n" 18799 " Z = 1\n" 18800 " };\n", 18801 WhitesmithsBraceStyle); 18802 18803 verifyFormat("@interface BSApplicationController ()\n" 18804 " {\n" 18805 "@private\n" 18806 " id _extraIvar;\n" 18807 " }\n" 18808 "@end\n", 18809 WhitesmithsBraceStyle); 18810 18811 verifyFormat("#ifdef _DEBUG\n" 18812 "int foo(int i = 0)\n" 18813 "#else\n" 18814 "int foo(int i = 5)\n" 18815 "#endif\n" 18816 " {\n" 18817 " return i;\n" 18818 " }", 18819 WhitesmithsBraceStyle); 18820 18821 verifyFormat("void foo() {}\n" 18822 "void bar()\n" 18823 "#ifdef _DEBUG\n" 18824 " {\n" 18825 " foo();\n" 18826 " }\n" 18827 "#else\n" 18828 " {\n" 18829 " }\n" 18830 "#endif", 18831 WhitesmithsBraceStyle); 18832 18833 verifyFormat("void foobar()\n" 18834 " {\n" 18835 " int i = 5;\n" 18836 " }\n" 18837 "#ifdef _DEBUG\n" 18838 "void bar()\n" 18839 " {\n" 18840 " }\n" 18841 "#else\n" 18842 "void bar()\n" 18843 " {\n" 18844 " foobar();\n" 18845 " }\n" 18846 "#endif", 18847 WhitesmithsBraceStyle); 18848 18849 // This shouldn't affect ObjC blocks.. 18850 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18851 " // ...\n" 18852 " int i;\n" 18853 "}];", 18854 WhitesmithsBraceStyle); 18855 verifyFormat("void (^block)(void) = ^{\n" 18856 " // ...\n" 18857 " int i;\n" 18858 "};", 18859 WhitesmithsBraceStyle); 18860 // .. or dict literals. 18861 verifyFormat("void f()\n" 18862 " {\n" 18863 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18864 " }", 18865 WhitesmithsBraceStyle); 18866 18867 verifyFormat("int f()\n" 18868 " { // comment\n" 18869 " return 42;\n" 18870 " }", 18871 WhitesmithsBraceStyle); 18872 18873 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18874 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18875 FormatStyle::SIS_OnlyFirstIf; 18876 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18877 verifyFormat("void f(bool b)\n" 18878 " {\n" 18879 " if (b)\n" 18880 " {\n" 18881 " return;\n" 18882 " }\n" 18883 " }\n", 18884 BreakBeforeBraceShortIfs); 18885 verifyFormat("void f(bool b)\n" 18886 " {\n" 18887 " if (b) return;\n" 18888 " }\n", 18889 BreakBeforeBraceShortIfs); 18890 verifyFormat("void f(bool b)\n" 18891 " {\n" 18892 " while (b)\n" 18893 " {\n" 18894 " return;\n" 18895 " }\n" 18896 " }\n", 18897 BreakBeforeBraceShortIfs); 18898 } 18899 18900 TEST_F(FormatTest, GNUBraceBreaking) { 18901 FormatStyle GNUBraceStyle = getLLVMStyle(); 18902 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18903 verifyFormat("namespace a\n" 18904 "{\n" 18905 "class A\n" 18906 "{\n" 18907 " void f()\n" 18908 " {\n" 18909 " int a;\n" 18910 " {\n" 18911 " int b;\n" 18912 " }\n" 18913 " if (true)\n" 18914 " {\n" 18915 " a();\n" 18916 " b();\n" 18917 " }\n" 18918 " }\n" 18919 " void g() { return; }\n" 18920 "}\n" 18921 "} // namespace a", 18922 GNUBraceStyle); 18923 18924 verifyFormat("void f()\n" 18925 "{\n" 18926 " if (true)\n" 18927 " {\n" 18928 " a();\n" 18929 " }\n" 18930 " else if (false)\n" 18931 " {\n" 18932 " b();\n" 18933 " }\n" 18934 " else\n" 18935 " {\n" 18936 " c();\n" 18937 " }\n" 18938 "}\n", 18939 GNUBraceStyle); 18940 18941 verifyFormat("void f()\n" 18942 "{\n" 18943 " for (int i = 0; i < 10; ++i)\n" 18944 " {\n" 18945 " a();\n" 18946 " }\n" 18947 " while (false)\n" 18948 " {\n" 18949 " b();\n" 18950 " }\n" 18951 " do\n" 18952 " {\n" 18953 " c();\n" 18954 " }\n" 18955 " while (false);\n" 18956 "}\n", 18957 GNUBraceStyle); 18958 18959 verifyFormat("void f(int a)\n" 18960 "{\n" 18961 " switch (a)\n" 18962 " {\n" 18963 " case 0:\n" 18964 " break;\n" 18965 " case 1:\n" 18966 " {\n" 18967 " break;\n" 18968 " }\n" 18969 " case 2:\n" 18970 " {\n" 18971 " }\n" 18972 " break;\n" 18973 " default:\n" 18974 " break;\n" 18975 " }\n" 18976 "}\n", 18977 GNUBraceStyle); 18978 18979 verifyFormat("enum X\n" 18980 "{\n" 18981 " Y = 0,\n" 18982 "}\n", 18983 GNUBraceStyle); 18984 18985 verifyFormat("@interface BSApplicationController ()\n" 18986 "{\n" 18987 "@private\n" 18988 " id _extraIvar;\n" 18989 "}\n" 18990 "@end\n", 18991 GNUBraceStyle); 18992 18993 verifyFormat("#ifdef _DEBUG\n" 18994 "int foo(int i = 0)\n" 18995 "#else\n" 18996 "int foo(int i = 5)\n" 18997 "#endif\n" 18998 "{\n" 18999 " return i;\n" 19000 "}", 19001 GNUBraceStyle); 19002 19003 verifyFormat("void foo() {}\n" 19004 "void bar()\n" 19005 "#ifdef _DEBUG\n" 19006 "{\n" 19007 " foo();\n" 19008 "}\n" 19009 "#else\n" 19010 "{\n" 19011 "}\n" 19012 "#endif", 19013 GNUBraceStyle); 19014 19015 verifyFormat("void foobar() { int i = 5; }\n" 19016 "#ifdef _DEBUG\n" 19017 "void bar() {}\n" 19018 "#else\n" 19019 "void bar() { foobar(); }\n" 19020 "#endif", 19021 GNUBraceStyle); 19022 } 19023 19024 TEST_F(FormatTest, WebKitBraceBreaking) { 19025 FormatStyle WebKitBraceStyle = getLLVMStyle(); 19026 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 19027 WebKitBraceStyle.FixNamespaceComments = false; 19028 verifyFormat("namespace a {\n" 19029 "class A {\n" 19030 " void f()\n" 19031 " {\n" 19032 " if (true) {\n" 19033 " a();\n" 19034 " b();\n" 19035 " }\n" 19036 " }\n" 19037 " void g() { return; }\n" 19038 "};\n" 19039 "enum E {\n" 19040 " A,\n" 19041 " // foo\n" 19042 " B,\n" 19043 " C\n" 19044 "};\n" 19045 "struct B {\n" 19046 " int x;\n" 19047 "};\n" 19048 "}\n", 19049 WebKitBraceStyle); 19050 verifyFormat("struct S {\n" 19051 " int Type;\n" 19052 " union {\n" 19053 " int x;\n" 19054 " double y;\n" 19055 " } Value;\n" 19056 " class C {\n" 19057 " MyFavoriteType Value;\n" 19058 " } Class;\n" 19059 "};\n", 19060 WebKitBraceStyle); 19061 } 19062 19063 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19064 verifyFormat("void f() {\n" 19065 " try {\n" 19066 " } catch (const Exception &e) {\n" 19067 " }\n" 19068 "}\n", 19069 getLLVMStyle()); 19070 } 19071 19072 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19073 auto Style = getLLVMStyle(); 19074 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19075 Style.AlignConsecutiveAssignments.Enabled = true; 19076 Style.AlignConsecutiveDeclarations.Enabled = true; 19077 verifyFormat("struct test demo[] = {\n" 19078 " {56, 23, \"hello\"},\n" 19079 " {-1, 93463, \"world\"},\n" 19080 " { 7, 5, \"!!\"}\n" 19081 "};\n", 19082 Style); 19083 19084 verifyFormat("struct test demo[] = {\n" 19085 " {56, 23, \"hello\"}, // first line\n" 19086 " {-1, 93463, \"world\"}, // second line\n" 19087 " { 7, 5, \"!!\"} // third line\n" 19088 "};\n", 19089 Style); 19090 19091 verifyFormat("struct test demo[4] = {\n" 19092 " { 56, 23, 21, \"oh\"}, // first line\n" 19093 " { -1, 93463, 22, \"my\"}, // second line\n" 19094 " { 7, 5, 1, \"goodness\"} // third line\n" 19095 " {234, 5, 1, \"gracious\"} // fourth line\n" 19096 "};\n", 19097 Style); 19098 19099 verifyFormat("struct test demo[3] = {\n" 19100 " {56, 23, \"hello\"},\n" 19101 " {-1, 93463, \"world\"},\n" 19102 " { 7, 5, \"!!\"}\n" 19103 "};\n", 19104 Style); 19105 19106 verifyFormat("struct test demo[3] = {\n" 19107 " {int{56}, 23, \"hello\"},\n" 19108 " {int{-1}, 93463, \"world\"},\n" 19109 " { int{7}, 5, \"!!\"}\n" 19110 "};\n", 19111 Style); 19112 19113 verifyFormat("struct test demo[] = {\n" 19114 " {56, 23, \"hello\"},\n" 19115 " {-1, 93463, \"world\"},\n" 19116 " { 7, 5, \"!!\"},\n" 19117 "};\n", 19118 Style); 19119 19120 verifyFormat("test demo[] = {\n" 19121 " {56, 23, \"hello\"},\n" 19122 " {-1, 93463, \"world\"},\n" 19123 " { 7, 5, \"!!\"},\n" 19124 "};\n", 19125 Style); 19126 19127 verifyFormat("demo = std::array<struct test, 3>{\n" 19128 " test{56, 23, \"hello\"},\n" 19129 " test{-1, 93463, \"world\"},\n" 19130 " test{ 7, 5, \"!!\"},\n" 19131 "};\n", 19132 Style); 19133 19134 verifyFormat("test demo[] = {\n" 19135 " {56, 23, \"hello\"},\n" 19136 "#if X\n" 19137 " {-1, 93463, \"world\"},\n" 19138 "#endif\n" 19139 " { 7, 5, \"!!\"}\n" 19140 "};\n", 19141 Style); 19142 19143 verifyFormat( 19144 "test demo[] = {\n" 19145 " { 7, 23,\n" 19146 " \"hello world i am a very long line that really, in any\"\n" 19147 " \"just world, ought to be split over multiple lines\"},\n" 19148 " {-1, 93463, \"world\"},\n" 19149 " {56, 5, \"!!\"}\n" 19150 "};\n", 19151 Style); 19152 19153 verifyFormat("return GradForUnaryCwise(g, {\n" 19154 " {{\"sign\"}, \"Sign\", " 19155 " {\"x\", \"dy\"}},\n" 19156 " { {\"dx\"}, \"Mul\", {\"dy\"" 19157 ", \"sign\"}},\n" 19158 "});\n", 19159 Style); 19160 19161 Style.ColumnLimit = 0; 19162 EXPECT_EQ( 19163 "test demo[] = {\n" 19164 " {56, 23, \"hello world i am a very long line that really, " 19165 "in any just world, ought to be split over multiple lines\"},\n" 19166 " {-1, 93463, " 19167 " \"world\"},\n" 19168 " { 7, 5, " 19169 " \"!!\"},\n" 19170 "};", 19171 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19172 "that really, in any just world, ought to be split over multiple " 19173 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19174 Style)); 19175 19176 Style.ColumnLimit = 80; 19177 verifyFormat("test demo[] = {\n" 19178 " {56, 23, /* a comment */ \"hello\"},\n" 19179 " {-1, 93463, \"world\"},\n" 19180 " { 7, 5, \"!!\"}\n" 19181 "};\n", 19182 Style); 19183 19184 verifyFormat("test demo[] = {\n" 19185 " {56, 23, \"hello\"},\n" 19186 " {-1, 93463, \"world\" /* comment here */},\n" 19187 " { 7, 5, \"!!\"}\n" 19188 "};\n", 19189 Style); 19190 19191 verifyFormat("test demo[] = {\n" 19192 " {56, /* a comment */ 23, \"hello\"},\n" 19193 " {-1, 93463, \"world\"},\n" 19194 " { 7, 5, \"!!\"}\n" 19195 "};\n", 19196 Style); 19197 19198 Style.ColumnLimit = 20; 19199 EXPECT_EQ( 19200 "demo = std::array<\n" 19201 " struct test, 3>{\n" 19202 " test{\n" 19203 " 56, 23,\n" 19204 " \"hello \"\n" 19205 " \"world i \"\n" 19206 " \"am a very \"\n" 19207 " \"long line \"\n" 19208 " \"that \"\n" 19209 " \"really, \"\n" 19210 " \"in any \"\n" 19211 " \"just \"\n" 19212 " \"world, \"\n" 19213 " \"ought to \"\n" 19214 " \"be split \"\n" 19215 " \"over \"\n" 19216 " \"multiple \"\n" 19217 " \"lines\"},\n" 19218 " test{-1, 93463,\n" 19219 " \"world\"},\n" 19220 " test{ 7, 5,\n" 19221 " \"!!\" },\n" 19222 "};", 19223 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19224 "i am a very long line that really, in any just world, ought " 19225 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19226 "test{7, 5, \"!!\"},};", 19227 Style)); 19228 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19229 Style = getLLVMStyleWithColumns(50); 19230 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19231 verifyFormat("static A x = {\n" 19232 " {{init1, init2, init3, init4},\n" 19233 " {init1, init2, init3, init4}}\n" 19234 "};", 19235 Style); 19236 // TODO: Fix the indentations below when this option is fully functional. 19237 verifyFormat("int a[][] = {\n" 19238 " {\n" 19239 " {0, 2}, //\n" 19240 " {1, 2} //\n" 19241 " }\n" 19242 "};", 19243 Style); 19244 Style.ColumnLimit = 100; 19245 EXPECT_EQ( 19246 "test demo[] = {\n" 19247 " {56, 23,\n" 19248 " \"hello world i am a very long line that really, in any just world" 19249 ", ought to be split over \"\n" 19250 " \"multiple lines\" },\n" 19251 " {-1, 93463, \"world\"},\n" 19252 " { 7, 5, \"!!\"},\n" 19253 "};", 19254 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19255 "that really, in any just world, ought to be split over multiple " 19256 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19257 Style)); 19258 19259 Style = getLLVMStyleWithColumns(50); 19260 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19261 verifyFormat("struct test demo[] = {\n" 19262 " {56, 23, \"hello\"},\n" 19263 " {-1, 93463, \"world\"},\n" 19264 " { 7, 5, \"!!\"}\n" 19265 "};\n" 19266 "static A x = {\n" 19267 " {{init1, init2, init3, init4},\n" 19268 " {init1, init2, init3, init4}}\n" 19269 "};", 19270 Style); 19271 Style.ColumnLimit = 100; 19272 Style.AlignConsecutiveAssignments.AcrossComments = true; 19273 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19274 verifyFormat("struct test demo[] = {\n" 19275 " {56, 23, \"hello\"},\n" 19276 " {-1, 93463, \"world\"},\n" 19277 " { 7, 5, \"!!\"}\n" 19278 "};\n" 19279 "struct test demo[4] = {\n" 19280 " { 56, 23, 21, \"oh\"}, // first line\n" 19281 " { -1, 93463, 22, \"my\"}, // second line\n" 19282 " { 7, 5, 1, \"goodness\"} // third line\n" 19283 " {234, 5, 1, \"gracious\"} // fourth line\n" 19284 "};\n", 19285 Style); 19286 EXPECT_EQ( 19287 "test demo[] = {\n" 19288 " {56,\n" 19289 " \"hello world i am a very long line that really, in any just world" 19290 ", ought to be split over \"\n" 19291 " \"multiple lines\", 23},\n" 19292 " {-1, \"world\", 93463},\n" 19293 " { 7, \"!!\", 5},\n" 19294 "};", 19295 format("test demo[] = {{56, \"hello world i am a very long line " 19296 "that really, in any just world, ought to be split over multiple " 19297 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19298 Style)); 19299 } 19300 19301 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19302 auto Style = getLLVMStyle(); 19303 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19304 /* FIXME: This case gets misformatted. 19305 verifyFormat("auto foo = Items{\n" 19306 " Section{0, bar(), },\n" 19307 " Section{1, boo() }\n" 19308 "};\n", 19309 Style); 19310 */ 19311 verifyFormat("auto foo = Items{\n" 19312 " Section{\n" 19313 " 0, bar(),\n" 19314 " }\n" 19315 "};\n", 19316 Style); 19317 verifyFormat("struct test demo[] = {\n" 19318 " {56, 23, \"hello\"},\n" 19319 " {-1, 93463, \"world\"},\n" 19320 " {7, 5, \"!!\" }\n" 19321 "};\n", 19322 Style); 19323 verifyFormat("struct test demo[] = {\n" 19324 " {56, 23, \"hello\"}, // first line\n" 19325 " {-1, 93463, \"world\"}, // second line\n" 19326 " {7, 5, \"!!\" } // third line\n" 19327 "};\n", 19328 Style); 19329 verifyFormat("struct test demo[4] = {\n" 19330 " {56, 23, 21, \"oh\" }, // first line\n" 19331 " {-1, 93463, 22, \"my\" }, // second line\n" 19332 " {7, 5, 1, \"goodness\"} // third line\n" 19333 " {234, 5, 1, \"gracious\"} // fourth line\n" 19334 "};\n", 19335 Style); 19336 verifyFormat("struct test demo[3] = {\n" 19337 " {56, 23, \"hello\"},\n" 19338 " {-1, 93463, \"world\"},\n" 19339 " {7, 5, \"!!\" }\n" 19340 "};\n", 19341 Style); 19342 19343 verifyFormat("struct test demo[3] = {\n" 19344 " {int{56}, 23, \"hello\"},\n" 19345 " {int{-1}, 93463, \"world\"},\n" 19346 " {int{7}, 5, \"!!\" }\n" 19347 "};\n", 19348 Style); 19349 verifyFormat("struct test demo[] = {\n" 19350 " {56, 23, \"hello\"},\n" 19351 " {-1, 93463, \"world\"},\n" 19352 " {7, 5, \"!!\" },\n" 19353 "};\n", 19354 Style); 19355 verifyFormat("test demo[] = {\n" 19356 " {56, 23, \"hello\"},\n" 19357 " {-1, 93463, \"world\"},\n" 19358 " {7, 5, \"!!\" },\n" 19359 "};\n", 19360 Style); 19361 verifyFormat("demo = std::array<struct test, 3>{\n" 19362 " test{56, 23, \"hello\"},\n" 19363 " test{-1, 93463, \"world\"},\n" 19364 " test{7, 5, \"!!\" },\n" 19365 "};\n", 19366 Style); 19367 verifyFormat("test demo[] = {\n" 19368 " {56, 23, \"hello\"},\n" 19369 "#if X\n" 19370 " {-1, 93463, \"world\"},\n" 19371 "#endif\n" 19372 " {7, 5, \"!!\" }\n" 19373 "};\n", 19374 Style); 19375 verifyFormat( 19376 "test demo[] = {\n" 19377 " {7, 23,\n" 19378 " \"hello world i am a very long line that really, in any\"\n" 19379 " \"just world, ought to be split over multiple lines\"},\n" 19380 " {-1, 93463, \"world\" },\n" 19381 " {56, 5, \"!!\" }\n" 19382 "};\n", 19383 Style); 19384 19385 verifyFormat("return GradForUnaryCwise(g, {\n" 19386 " {{\"sign\"}, \"Sign\", {\"x\", " 19387 "\"dy\"} },\n" 19388 " {{\"dx\"}, \"Mul\", " 19389 "{\"dy\", \"sign\"}},\n" 19390 "});\n", 19391 Style); 19392 19393 Style.ColumnLimit = 0; 19394 EXPECT_EQ( 19395 "test demo[] = {\n" 19396 " {56, 23, \"hello world i am a very long line that really, in any " 19397 "just world, ought to be split over multiple lines\"},\n" 19398 " {-1, 93463, \"world\" " 19399 " },\n" 19400 " {7, 5, \"!!\" " 19401 " },\n" 19402 "};", 19403 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19404 "that really, in any just world, ought to be split over multiple " 19405 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19406 Style)); 19407 19408 Style.ColumnLimit = 80; 19409 verifyFormat("test demo[] = {\n" 19410 " {56, 23, /* a comment */ \"hello\"},\n" 19411 " {-1, 93463, \"world\" },\n" 19412 " {7, 5, \"!!\" }\n" 19413 "};\n", 19414 Style); 19415 19416 verifyFormat("test demo[] = {\n" 19417 " {56, 23, \"hello\" },\n" 19418 " {-1, 93463, \"world\" /* comment here */},\n" 19419 " {7, 5, \"!!\" }\n" 19420 "};\n", 19421 Style); 19422 19423 verifyFormat("test demo[] = {\n" 19424 " {56, /* a comment */ 23, \"hello\"},\n" 19425 " {-1, 93463, \"world\"},\n" 19426 " {7, 5, \"!!\" }\n" 19427 "};\n", 19428 Style); 19429 19430 Style.ColumnLimit = 20; 19431 EXPECT_EQ( 19432 "demo = std::array<\n" 19433 " struct test, 3>{\n" 19434 " test{\n" 19435 " 56, 23,\n" 19436 " \"hello \"\n" 19437 " \"world i \"\n" 19438 " \"am a very \"\n" 19439 " \"long line \"\n" 19440 " \"that \"\n" 19441 " \"really, \"\n" 19442 " \"in any \"\n" 19443 " \"just \"\n" 19444 " \"world, \"\n" 19445 " \"ought to \"\n" 19446 " \"be split \"\n" 19447 " \"over \"\n" 19448 " \"multiple \"\n" 19449 " \"lines\"},\n" 19450 " test{-1, 93463,\n" 19451 " \"world\"},\n" 19452 " test{7, 5,\n" 19453 " \"!!\" },\n" 19454 "};", 19455 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19456 "i am a very long line that really, in any just world, ought " 19457 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19458 "test{7, 5, \"!!\"},};", 19459 Style)); 19460 19461 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19462 Style = getLLVMStyleWithColumns(50); 19463 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19464 verifyFormat("static A x = {\n" 19465 " {{init1, init2, init3, init4},\n" 19466 " {init1, init2, init3, init4}}\n" 19467 "};", 19468 Style); 19469 Style.ColumnLimit = 100; 19470 EXPECT_EQ( 19471 "test demo[] = {\n" 19472 " {56, 23,\n" 19473 " \"hello world i am a very long line that really, in any just world" 19474 ", ought to be split over \"\n" 19475 " \"multiple lines\" },\n" 19476 " {-1, 93463, \"world\"},\n" 19477 " {7, 5, \"!!\" },\n" 19478 "};", 19479 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19480 "that really, in any just world, ought to be split over multiple " 19481 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19482 Style)); 19483 } 19484 19485 TEST_F(FormatTest, UnderstandsPragmas) { 19486 verifyFormat("#pragma omp reduction(| : var)"); 19487 verifyFormat("#pragma omp reduction(+ : var)"); 19488 19489 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19490 "(including parentheses).", 19491 format("#pragma mark Any non-hyphenated or hyphenated string " 19492 "(including parentheses).")); 19493 } 19494 19495 TEST_F(FormatTest, UnderstandPragmaOption) { 19496 verifyFormat("#pragma option -C -A"); 19497 19498 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19499 } 19500 19501 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19502 FormatStyle Style = getLLVMStyleWithColumns(20); 19503 19504 // See PR41213 19505 EXPECT_EQ("/*\n" 19506 " *\t9012345\n" 19507 " * /8901\n" 19508 " */", 19509 format("/*\n" 19510 " *\t9012345 /8901\n" 19511 " */", 19512 Style)); 19513 EXPECT_EQ("/*\n" 19514 " *345678\n" 19515 " *\t/8901\n" 19516 " */", 19517 format("/*\n" 19518 " *345678\t/8901\n" 19519 " */", 19520 Style)); 19521 19522 verifyFormat("int a; // the\n" 19523 " // comment", 19524 Style); 19525 EXPECT_EQ("int a; /* first line\n" 19526 " * second\n" 19527 " * line third\n" 19528 " * line\n" 19529 " */", 19530 format("int a; /* first line\n" 19531 " * second\n" 19532 " * line third\n" 19533 " * line\n" 19534 " */", 19535 Style)); 19536 EXPECT_EQ("int a; // first line\n" 19537 " // second\n" 19538 " // line third\n" 19539 " // line", 19540 format("int a; // first line\n" 19541 " // second line\n" 19542 " // third line", 19543 Style)); 19544 19545 Style.PenaltyExcessCharacter = 90; 19546 verifyFormat("int a; // the comment", Style); 19547 EXPECT_EQ("int a; // the comment\n" 19548 " // aaa", 19549 format("int a; // the comment aaa", Style)); 19550 EXPECT_EQ("int a; /* first line\n" 19551 " * second line\n" 19552 " * third line\n" 19553 " */", 19554 format("int a; /* first line\n" 19555 " * second line\n" 19556 " * third line\n" 19557 " */", 19558 Style)); 19559 EXPECT_EQ("int a; // first line\n" 19560 " // second line\n" 19561 " // third line", 19562 format("int a; // first line\n" 19563 " // second line\n" 19564 " // third line", 19565 Style)); 19566 // FIXME: Investigate why this is not getting the same layout as the test 19567 // above. 19568 EXPECT_EQ("int a; /* first line\n" 19569 " * second line\n" 19570 " * third line\n" 19571 " */", 19572 format("int a; /* first line second line third line" 19573 "\n*/", 19574 Style)); 19575 19576 EXPECT_EQ("// foo bar baz bazfoo\n" 19577 "// foo bar foo bar\n", 19578 format("// foo bar baz bazfoo\n" 19579 "// foo bar foo bar\n", 19580 Style)); 19581 EXPECT_EQ("// foo bar baz bazfoo\n" 19582 "// foo bar foo bar\n", 19583 format("// foo bar baz bazfoo\n" 19584 "// foo bar foo bar\n", 19585 Style)); 19586 19587 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19588 // next one. 19589 EXPECT_EQ("// foo bar baz bazfoo\n" 19590 "// bar foo bar\n", 19591 format("// foo bar baz bazfoo bar\n" 19592 "// foo bar\n", 19593 Style)); 19594 19595 EXPECT_EQ("// foo bar baz bazfoo\n" 19596 "// foo bar baz bazfoo\n" 19597 "// bar foo bar\n", 19598 format("// foo bar baz bazfoo\n" 19599 "// foo bar baz bazfoo bar\n" 19600 "// foo bar\n", 19601 Style)); 19602 19603 EXPECT_EQ("// foo bar baz bazfoo\n" 19604 "// foo bar baz bazfoo\n" 19605 "// bar foo bar\n", 19606 format("// foo bar baz bazfoo\n" 19607 "// foo bar baz bazfoo bar\n" 19608 "// foo bar\n", 19609 Style)); 19610 19611 // Make sure we do not keep protruding characters if strict mode reflow is 19612 // cheaper than keeping protruding characters. 19613 Style.ColumnLimit = 21; 19614 EXPECT_EQ( 19615 "// foo foo foo foo\n" 19616 "// foo foo foo foo\n" 19617 "// foo foo foo foo\n", 19618 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19619 19620 EXPECT_EQ("int a = /* long block\n" 19621 " comment */\n" 19622 " 42;", 19623 format("int a = /* long block comment */ 42;", Style)); 19624 } 19625 19626 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19627 FormatStyle Style = getLLVMStyle(); 19628 Style.ColumnLimit = 8; 19629 Style.PenaltyExcessCharacter = 15; 19630 verifyFormat("int foo(\n" 19631 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19632 Style); 19633 Style.PenaltyBreakOpenParenthesis = 200; 19634 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19635 format("int foo(\n" 19636 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19637 Style)); 19638 } 19639 19640 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19641 FormatStyle Style = getLLVMStyle(); 19642 Style.ColumnLimit = 5; 19643 Style.PenaltyExcessCharacter = 150; 19644 verifyFormat("foo((\n" 19645 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19646 19647 Style); 19648 Style.PenaltyBreakOpenParenthesis = 100000; 19649 EXPECT_EQ("foo((int)\n" 19650 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19651 format("foo((\n" 19652 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19653 Style)); 19654 } 19655 19656 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19657 FormatStyle Style = getLLVMStyle(); 19658 Style.ColumnLimit = 4; 19659 Style.PenaltyExcessCharacter = 100; 19660 verifyFormat("for (\n" 19661 " int iiiiiiiiiiiiiiiii =\n" 19662 " 0;\n" 19663 " iiiiiiiiiiiiiiiii <\n" 19664 " 2;\n" 19665 " iiiiiiiiiiiiiiiii++) {\n" 19666 "}", 19667 19668 Style); 19669 Style.PenaltyBreakOpenParenthesis = 1250; 19670 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19671 " 0;\n" 19672 " iiiiiiiiiiiiiiiii <\n" 19673 " 2;\n" 19674 " iiiiiiiiiiiiiiiii++) {\n" 19675 "}", 19676 format("for (\n" 19677 " int iiiiiiiiiiiiiiiii =\n" 19678 " 0;\n" 19679 " iiiiiiiiiiiiiiiii <\n" 19680 " 2;\n" 19681 " iiiiiiiiiiiiiiiii++) {\n" 19682 "}", 19683 Style)); 19684 } 19685 19686 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19687 for (size_t i = 1; i < Styles.size(); ++i) \ 19688 EXPECT_EQ(Styles[0], Styles[i]) \ 19689 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19690 19691 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19692 SmallVector<FormatStyle, 3> Styles; 19693 Styles.resize(3); 19694 19695 Styles[0] = getLLVMStyle(); 19696 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19697 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19698 EXPECT_ALL_STYLES_EQUAL(Styles); 19699 19700 Styles[0] = getGoogleStyle(); 19701 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19702 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19703 EXPECT_ALL_STYLES_EQUAL(Styles); 19704 19705 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19706 EXPECT_TRUE( 19707 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19708 EXPECT_TRUE( 19709 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19710 EXPECT_ALL_STYLES_EQUAL(Styles); 19711 19712 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19713 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19714 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19715 EXPECT_ALL_STYLES_EQUAL(Styles); 19716 19717 Styles[0] = getMozillaStyle(); 19718 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19719 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19720 EXPECT_ALL_STYLES_EQUAL(Styles); 19721 19722 Styles[0] = getWebKitStyle(); 19723 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19724 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19725 EXPECT_ALL_STYLES_EQUAL(Styles); 19726 19727 Styles[0] = getGNUStyle(); 19728 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19729 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19730 EXPECT_ALL_STYLES_EQUAL(Styles); 19731 19732 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19733 } 19734 19735 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19736 SmallVector<FormatStyle, 8> Styles; 19737 Styles.resize(2); 19738 19739 Styles[0] = getGoogleStyle(); 19740 Styles[1] = getLLVMStyle(); 19741 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19742 EXPECT_ALL_STYLES_EQUAL(Styles); 19743 19744 Styles.resize(5); 19745 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19746 Styles[1] = getLLVMStyle(); 19747 Styles[1].Language = FormatStyle::LK_JavaScript; 19748 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19749 19750 Styles[2] = getLLVMStyle(); 19751 Styles[2].Language = FormatStyle::LK_JavaScript; 19752 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19753 "BasedOnStyle: Google", 19754 &Styles[2]) 19755 .value()); 19756 19757 Styles[3] = getLLVMStyle(); 19758 Styles[3].Language = FormatStyle::LK_JavaScript; 19759 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19760 "Language: JavaScript", 19761 &Styles[3]) 19762 .value()); 19763 19764 Styles[4] = getLLVMStyle(); 19765 Styles[4].Language = FormatStyle::LK_JavaScript; 19766 EXPECT_EQ(0, parseConfiguration("---\n" 19767 "BasedOnStyle: LLVM\n" 19768 "IndentWidth: 123\n" 19769 "---\n" 19770 "BasedOnStyle: Google\n" 19771 "Language: JavaScript", 19772 &Styles[4]) 19773 .value()); 19774 EXPECT_ALL_STYLES_EQUAL(Styles); 19775 } 19776 19777 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19778 Style.FIELD = false; \ 19779 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19780 EXPECT_TRUE(Style.FIELD); \ 19781 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19782 EXPECT_FALSE(Style.FIELD); 19783 19784 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19785 19786 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19787 Style.STRUCT.FIELD = false; \ 19788 EXPECT_EQ(0, \ 19789 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19790 .value()); \ 19791 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19792 EXPECT_EQ(0, \ 19793 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19794 .value()); \ 19795 EXPECT_FALSE(Style.STRUCT.FIELD); 19796 19797 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19798 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19799 19800 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19801 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19802 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19803 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19804 19805 TEST_F(FormatTest, ParsesConfigurationBools) { 19806 FormatStyle Style = {}; 19807 Style.Language = FormatStyle::LK_Cpp; 19808 CHECK_PARSE_BOOL(AlignTrailingComments); 19809 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19810 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19811 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19812 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19813 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19814 CHECK_PARSE_BOOL(BinPackArguments); 19815 CHECK_PARSE_BOOL(BinPackParameters); 19816 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19817 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19818 CHECK_PARSE_BOOL(BreakStringLiterals); 19819 CHECK_PARSE_BOOL(CompactNamespaces); 19820 CHECK_PARSE_BOOL(DeriveLineEnding); 19821 CHECK_PARSE_BOOL(DerivePointerAlignment); 19822 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19823 CHECK_PARSE_BOOL(DisableFormat); 19824 CHECK_PARSE_BOOL(IndentAccessModifiers); 19825 CHECK_PARSE_BOOL(IndentCaseLabels); 19826 CHECK_PARSE_BOOL(IndentCaseBlocks); 19827 CHECK_PARSE_BOOL(IndentGotoLabels); 19828 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19829 CHECK_PARSE_BOOL(IndentRequiresClause); 19830 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19831 CHECK_PARSE_BOOL(InsertBraces); 19832 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19833 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19834 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19835 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19836 CHECK_PARSE_BOOL(ReflowComments); 19837 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19838 CHECK_PARSE_BOOL(SortUsingDeclarations); 19839 CHECK_PARSE_BOOL(SpacesInParentheses); 19840 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19841 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19842 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19843 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19844 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19845 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19846 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19847 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19848 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19849 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19850 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19851 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19852 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19853 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19854 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19855 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19856 CHECK_PARSE_BOOL(UseCRLF); 19857 19858 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19859 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19860 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19861 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19862 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19863 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19864 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19865 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19866 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19867 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19868 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19869 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19870 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19871 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19872 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19873 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19874 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19875 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19876 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19877 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19878 AfterFunctionDeclarationName); 19879 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19880 AfterFunctionDefinitionName); 19881 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19882 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19883 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19884 } 19885 19886 #undef CHECK_PARSE_BOOL 19887 19888 TEST_F(FormatTest, ParsesConfiguration) { 19889 FormatStyle Style = {}; 19890 Style.Language = FormatStyle::LK_Cpp; 19891 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19892 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19893 ConstructorInitializerIndentWidth, 1234u); 19894 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19895 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19896 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19897 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19898 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19899 PenaltyBreakBeforeFirstCallParameter, 1234u); 19900 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19901 PenaltyBreakTemplateDeclaration, 1234u); 19902 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19903 1234u); 19904 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19905 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19906 PenaltyReturnTypeOnItsOwnLine, 1234u); 19907 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19908 SpacesBeforeTrailingComments, 1234u); 19909 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19910 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19911 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19912 19913 Style.QualifierAlignment = FormatStyle::QAS_Right; 19914 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19915 FormatStyle::QAS_Leave); 19916 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19917 FormatStyle::QAS_Right); 19918 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19919 FormatStyle::QAS_Left); 19920 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19921 FormatStyle::QAS_Custom); 19922 19923 Style.QualifierOrder.clear(); 19924 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19925 std::vector<std::string>({"const", "volatile", "type"})); 19926 Style.QualifierOrder.clear(); 19927 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19928 std::vector<std::string>({"const", "type"})); 19929 Style.QualifierOrder.clear(); 19930 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19931 std::vector<std::string>({"volatile", "type"})); 19932 19933 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 19934 do { \ 19935 Style.FIELD.Enabled = true; \ 19936 CHECK_PARSE(#FIELD ": None", FIELD, \ 19937 FormatStyle::AlignConsecutiveStyle( \ 19938 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19939 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19940 /*PadOperators=*/true})); \ 19941 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 19942 FormatStyle::AlignConsecutiveStyle( \ 19943 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19944 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19945 /*PadOperators=*/true})); \ 19946 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 19947 FormatStyle::AlignConsecutiveStyle( \ 19948 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19949 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19950 /*PadOperators=*/true})); \ 19951 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 19952 FormatStyle::AlignConsecutiveStyle( \ 19953 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19954 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 19955 /*PadOperators=*/true})); \ 19956 /* For backwards compability, false / true should still parse */ \ 19957 CHECK_PARSE(#FIELD ": false", FIELD, \ 19958 FormatStyle::AlignConsecutiveStyle( \ 19959 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19960 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19961 /*PadOperators=*/true})); \ 19962 CHECK_PARSE(#FIELD ": true", FIELD, \ 19963 FormatStyle::AlignConsecutiveStyle( \ 19964 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19965 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19966 /*PadOperators=*/true})); \ 19967 \ 19968 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 19969 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 19970 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 19971 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 19972 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 19973 } while (false) 19974 19975 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 19976 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 19977 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 19978 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 19979 19980 #undef CHECK_ALIGN_CONSECUTIVE 19981 19982 Style.PointerAlignment = FormatStyle::PAS_Middle; 19983 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19984 FormatStyle::PAS_Left); 19985 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19986 FormatStyle::PAS_Right); 19987 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19988 FormatStyle::PAS_Middle); 19989 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19990 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19991 FormatStyle::RAS_Pointer); 19992 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19993 FormatStyle::RAS_Left); 19994 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19995 FormatStyle::RAS_Right); 19996 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19997 FormatStyle::RAS_Middle); 19998 // For backward compatibility: 19999 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 20000 FormatStyle::PAS_Left); 20001 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 20002 FormatStyle::PAS_Right); 20003 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 20004 FormatStyle::PAS_Middle); 20005 20006 Style.Standard = FormatStyle::LS_Auto; 20007 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 20008 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 20009 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 20010 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 20011 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 20012 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 20013 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 20014 // Legacy aliases: 20015 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 20016 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 20017 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 20018 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 20019 20020 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 20021 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 20022 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 20023 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 20024 FormatStyle::BOS_None); 20025 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 20026 FormatStyle::BOS_All); 20027 // For backward compatibility: 20028 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 20029 FormatStyle::BOS_None); 20030 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 20031 FormatStyle::BOS_All); 20032 20033 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20034 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20035 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20036 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20037 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20038 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20039 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20040 // For backward compatibility: 20041 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20042 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20043 20044 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20045 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20046 FormatStyle::BILS_AfterComma); 20047 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20048 FormatStyle::BILS_BeforeComma); 20049 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20050 FormatStyle::BILS_AfterColon); 20051 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20052 FormatStyle::BILS_BeforeColon); 20053 // For backward compatibility: 20054 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20055 FormatStyle::BILS_BeforeComma); 20056 20057 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20058 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20059 FormatStyle::PCIS_Never); 20060 CHECK_PARSE("PackConstructorInitializers: BinPack", 20061 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20062 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20063 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20064 CHECK_PARSE("PackConstructorInitializers: NextLine", 20065 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20066 // For backward compatibility: 20067 CHECK_PARSE("BasedOnStyle: Google\n" 20068 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20069 "AllowAllConstructorInitializersOnNextLine: false", 20070 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20071 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20072 CHECK_PARSE("BasedOnStyle: Google\n" 20073 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20074 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20075 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20076 "AllowAllConstructorInitializersOnNextLine: true", 20077 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20078 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20079 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20080 "AllowAllConstructorInitializersOnNextLine: false", 20081 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20082 20083 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20084 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20085 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20086 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20087 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20088 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20089 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20090 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20091 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20092 20093 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20094 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20095 FormatStyle::BAS_Align); 20096 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20097 FormatStyle::BAS_DontAlign); 20098 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20099 FormatStyle::BAS_AlwaysBreak); 20100 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20101 FormatStyle::BAS_BlockIndent); 20102 // For backward compatibility: 20103 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20104 FormatStyle::BAS_DontAlign); 20105 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20106 FormatStyle::BAS_Align); 20107 20108 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20109 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20110 FormatStyle::ENAS_DontAlign); 20111 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20112 FormatStyle::ENAS_Left); 20113 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20114 FormatStyle::ENAS_Right); 20115 // For backward compatibility: 20116 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20117 FormatStyle::ENAS_Left); 20118 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20119 FormatStyle::ENAS_Right); 20120 20121 Style.AlignOperands = FormatStyle::OAS_Align; 20122 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20123 FormatStyle::OAS_DontAlign); 20124 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20125 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20126 FormatStyle::OAS_AlignAfterOperator); 20127 // For backward compatibility: 20128 CHECK_PARSE("AlignOperands: false", AlignOperands, 20129 FormatStyle::OAS_DontAlign); 20130 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20131 20132 Style.UseTab = FormatStyle::UT_ForIndentation; 20133 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20134 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20135 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20136 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20137 FormatStyle::UT_ForContinuationAndIndentation); 20138 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20139 FormatStyle::UT_AlignWithSpaces); 20140 // For backward compatibility: 20141 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20142 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20143 20144 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20145 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20146 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20147 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20148 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20149 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20150 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20151 // For backward compatibility: 20152 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20153 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20154 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20155 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20156 20157 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20158 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20159 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20160 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20161 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20162 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20163 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20164 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20165 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20166 // For backward compatibility: 20167 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20168 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20169 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20170 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20171 20172 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20173 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20174 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20175 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20176 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20177 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20178 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20179 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20180 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20181 20182 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20183 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20184 FormatStyle::SBPO_Never); 20185 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20186 FormatStyle::SBPO_Always); 20187 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20188 FormatStyle::SBPO_ControlStatements); 20189 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20190 SpaceBeforeParens, 20191 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20192 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20193 FormatStyle::SBPO_NonEmptyParentheses); 20194 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20195 FormatStyle::SBPO_Custom); 20196 // For backward compatibility: 20197 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20198 FormatStyle::SBPO_Never); 20199 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20200 FormatStyle::SBPO_ControlStatements); 20201 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20202 SpaceBeforeParens, 20203 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20204 20205 Style.ColumnLimit = 123; 20206 FormatStyle BaseStyle = getLLVMStyle(); 20207 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20208 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20209 20210 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20211 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20212 FormatStyle::BS_Attach); 20213 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20214 FormatStyle::BS_Linux); 20215 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20216 FormatStyle::BS_Mozilla); 20217 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20218 FormatStyle::BS_Stroustrup); 20219 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20220 FormatStyle::BS_Allman); 20221 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20222 FormatStyle::BS_Whitesmiths); 20223 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20224 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20225 FormatStyle::BS_WebKit); 20226 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20227 FormatStyle::BS_Custom); 20228 20229 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20230 CHECK_PARSE("BraceWrapping:\n" 20231 " AfterControlStatement: MultiLine", 20232 BraceWrapping.AfterControlStatement, 20233 FormatStyle::BWACS_MultiLine); 20234 CHECK_PARSE("BraceWrapping:\n" 20235 " AfterControlStatement: Always", 20236 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20237 CHECK_PARSE("BraceWrapping:\n" 20238 " AfterControlStatement: Never", 20239 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20240 // For backward compatibility: 20241 CHECK_PARSE("BraceWrapping:\n" 20242 " AfterControlStatement: true", 20243 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20244 CHECK_PARSE("BraceWrapping:\n" 20245 " AfterControlStatement: false", 20246 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20247 20248 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20249 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20250 FormatStyle::RTBS_None); 20251 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20252 FormatStyle::RTBS_All); 20253 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20254 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20255 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20256 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20257 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20258 AlwaysBreakAfterReturnType, 20259 FormatStyle::RTBS_TopLevelDefinitions); 20260 20261 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20262 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20263 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20264 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20265 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20266 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20267 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20268 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20269 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20270 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20271 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20272 20273 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20274 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20275 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20276 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20277 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20278 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20279 AlwaysBreakAfterDefinitionReturnType, 20280 FormatStyle::DRTBS_TopLevel); 20281 20282 Style.NamespaceIndentation = FormatStyle::NI_All; 20283 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20284 FormatStyle::NI_None); 20285 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20286 FormatStyle::NI_Inner); 20287 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20288 FormatStyle::NI_All); 20289 20290 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20291 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20292 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20293 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20294 AllowShortIfStatementsOnASingleLine, 20295 FormatStyle::SIS_WithoutElse); 20296 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20297 AllowShortIfStatementsOnASingleLine, 20298 FormatStyle::SIS_OnlyFirstIf); 20299 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20300 AllowShortIfStatementsOnASingleLine, 20301 FormatStyle::SIS_AllIfsAndElse); 20302 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20303 AllowShortIfStatementsOnASingleLine, 20304 FormatStyle::SIS_OnlyFirstIf); 20305 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20306 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20307 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20308 AllowShortIfStatementsOnASingleLine, 20309 FormatStyle::SIS_WithoutElse); 20310 20311 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20312 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20313 FormatStyle::IEBS_AfterExternBlock); 20314 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20315 FormatStyle::IEBS_Indent); 20316 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20317 FormatStyle::IEBS_NoIndent); 20318 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20319 FormatStyle::IEBS_Indent); 20320 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20321 FormatStyle::IEBS_NoIndent); 20322 20323 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20324 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20325 FormatStyle::BFCS_Both); 20326 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20327 FormatStyle::BFCS_None); 20328 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20329 FormatStyle::BFCS_Before); 20330 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20331 FormatStyle::BFCS_After); 20332 20333 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20334 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20335 FormatStyle::SJSIO_After); 20336 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20337 FormatStyle::SJSIO_Before); 20338 20339 // FIXME: This is required because parsing a configuration simply overwrites 20340 // the first N elements of the list instead of resetting it. 20341 Style.ForEachMacros.clear(); 20342 std::vector<std::string> BoostForeach; 20343 BoostForeach.push_back("BOOST_FOREACH"); 20344 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20345 std::vector<std::string> BoostAndQForeach; 20346 BoostAndQForeach.push_back("BOOST_FOREACH"); 20347 BoostAndQForeach.push_back("Q_FOREACH"); 20348 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20349 BoostAndQForeach); 20350 20351 Style.IfMacros.clear(); 20352 std::vector<std::string> CustomIfs; 20353 CustomIfs.push_back("MYIF"); 20354 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20355 20356 Style.AttributeMacros.clear(); 20357 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20358 std::vector<std::string>{"__capability"}); 20359 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20360 std::vector<std::string>({"attr1", "attr2"})); 20361 20362 Style.StatementAttributeLikeMacros.clear(); 20363 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20364 StatementAttributeLikeMacros, 20365 std::vector<std::string>({"emit", "Q_EMIT"})); 20366 20367 Style.StatementMacros.clear(); 20368 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20369 std::vector<std::string>{"QUNUSED"}); 20370 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20371 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20372 20373 Style.NamespaceMacros.clear(); 20374 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20375 std::vector<std::string>{"TESTSUITE"}); 20376 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20377 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20378 20379 Style.WhitespaceSensitiveMacros.clear(); 20380 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20381 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20382 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20383 WhitespaceSensitiveMacros, 20384 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20385 Style.WhitespaceSensitiveMacros.clear(); 20386 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20387 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20388 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20389 WhitespaceSensitiveMacros, 20390 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20391 20392 Style.IncludeStyle.IncludeCategories.clear(); 20393 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20394 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20395 CHECK_PARSE("IncludeCategories:\n" 20396 " - Regex: abc/.*\n" 20397 " Priority: 2\n" 20398 " - Regex: .*\n" 20399 " Priority: 1\n" 20400 " CaseSensitive: true\n", 20401 IncludeStyle.IncludeCategories, ExpectedCategories); 20402 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20403 "abc$"); 20404 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20405 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20406 20407 Style.SortIncludes = FormatStyle::SI_Never; 20408 CHECK_PARSE("SortIncludes: true", SortIncludes, 20409 FormatStyle::SI_CaseSensitive); 20410 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20411 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20412 FormatStyle::SI_CaseInsensitive); 20413 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20414 FormatStyle::SI_CaseSensitive); 20415 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20416 20417 Style.RawStringFormats.clear(); 20418 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20419 { 20420 FormatStyle::LK_TextProto, 20421 {"pb", "proto"}, 20422 {"PARSE_TEXT_PROTO"}, 20423 /*CanonicalDelimiter=*/"", 20424 "llvm", 20425 }, 20426 { 20427 FormatStyle::LK_Cpp, 20428 {"cc", "cpp"}, 20429 {"C_CODEBLOCK", "CPPEVAL"}, 20430 /*CanonicalDelimiter=*/"cc", 20431 /*BasedOnStyle=*/"", 20432 }, 20433 }; 20434 20435 CHECK_PARSE("RawStringFormats:\n" 20436 " - Language: TextProto\n" 20437 " Delimiters:\n" 20438 " - 'pb'\n" 20439 " - 'proto'\n" 20440 " EnclosingFunctions:\n" 20441 " - 'PARSE_TEXT_PROTO'\n" 20442 " BasedOnStyle: llvm\n" 20443 " - Language: Cpp\n" 20444 " Delimiters:\n" 20445 " - 'cc'\n" 20446 " - 'cpp'\n" 20447 " EnclosingFunctions:\n" 20448 " - 'C_CODEBLOCK'\n" 20449 " - 'CPPEVAL'\n" 20450 " CanonicalDelimiter: 'cc'", 20451 RawStringFormats, ExpectedRawStringFormats); 20452 20453 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20454 " Minimum: 0\n" 20455 " Maximum: 0", 20456 SpacesInLineCommentPrefix.Minimum, 0u); 20457 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20458 Style.SpacesInLineCommentPrefix.Minimum = 1; 20459 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20460 " Minimum: 2", 20461 SpacesInLineCommentPrefix.Minimum, 0u); 20462 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20463 " Maximum: -1", 20464 SpacesInLineCommentPrefix.Maximum, -1u); 20465 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20466 " Minimum: 2", 20467 SpacesInLineCommentPrefix.Minimum, 2u); 20468 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20469 " Maximum: 1", 20470 SpacesInLineCommentPrefix.Maximum, 1u); 20471 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20472 20473 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20474 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20475 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20476 FormatStyle::SIAS_Always); 20477 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20478 // For backward compatibility: 20479 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20480 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20481 20482 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20483 FormatStyle::RCPS_WithPreceding); 20484 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20485 FormatStyle::RCPS_WithFollowing); 20486 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20487 FormatStyle::RCPS_SingleLine); 20488 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20489 FormatStyle::RCPS_OwnLine); 20490 20491 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20492 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20493 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20494 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20495 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20496 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20497 // For backward compatibility: 20498 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20499 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20500 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20501 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20502 } 20503 20504 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20505 FormatStyle Style = {}; 20506 Style.Language = FormatStyle::LK_Cpp; 20507 CHECK_PARSE("Language: Cpp\n" 20508 "IndentWidth: 12", 20509 IndentWidth, 12u); 20510 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20511 "IndentWidth: 34", 20512 &Style), 20513 ParseError::Unsuitable); 20514 FormatStyle BinPackedTCS = {}; 20515 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20516 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20517 "InsertTrailingCommas: Wrapped", 20518 &BinPackedTCS), 20519 ParseError::BinPackTrailingCommaConflict); 20520 EXPECT_EQ(12u, Style.IndentWidth); 20521 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20522 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20523 20524 Style.Language = FormatStyle::LK_JavaScript; 20525 CHECK_PARSE("Language: JavaScript\n" 20526 "IndentWidth: 12", 20527 IndentWidth, 12u); 20528 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20529 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20530 "IndentWidth: 34", 20531 &Style), 20532 ParseError::Unsuitable); 20533 EXPECT_EQ(23u, Style.IndentWidth); 20534 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20535 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20536 20537 CHECK_PARSE("BasedOnStyle: LLVM\n" 20538 "IndentWidth: 67", 20539 IndentWidth, 67u); 20540 20541 CHECK_PARSE("---\n" 20542 "Language: JavaScript\n" 20543 "IndentWidth: 12\n" 20544 "---\n" 20545 "Language: Cpp\n" 20546 "IndentWidth: 34\n" 20547 "...\n", 20548 IndentWidth, 12u); 20549 20550 Style.Language = FormatStyle::LK_Cpp; 20551 CHECK_PARSE("---\n" 20552 "Language: JavaScript\n" 20553 "IndentWidth: 12\n" 20554 "---\n" 20555 "Language: Cpp\n" 20556 "IndentWidth: 34\n" 20557 "...\n", 20558 IndentWidth, 34u); 20559 CHECK_PARSE("---\n" 20560 "IndentWidth: 78\n" 20561 "---\n" 20562 "Language: JavaScript\n" 20563 "IndentWidth: 56\n" 20564 "...\n", 20565 IndentWidth, 78u); 20566 20567 Style.ColumnLimit = 123; 20568 Style.IndentWidth = 234; 20569 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20570 Style.TabWidth = 345; 20571 EXPECT_FALSE(parseConfiguration("---\n" 20572 "IndentWidth: 456\n" 20573 "BreakBeforeBraces: Allman\n" 20574 "---\n" 20575 "Language: JavaScript\n" 20576 "IndentWidth: 111\n" 20577 "TabWidth: 111\n" 20578 "---\n" 20579 "Language: Cpp\n" 20580 "BreakBeforeBraces: Stroustrup\n" 20581 "TabWidth: 789\n" 20582 "...\n", 20583 &Style)); 20584 EXPECT_EQ(123u, Style.ColumnLimit); 20585 EXPECT_EQ(456u, Style.IndentWidth); 20586 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20587 EXPECT_EQ(789u, Style.TabWidth); 20588 20589 EXPECT_EQ(parseConfiguration("---\n" 20590 "Language: JavaScript\n" 20591 "IndentWidth: 56\n" 20592 "---\n" 20593 "IndentWidth: 78\n" 20594 "...\n", 20595 &Style), 20596 ParseError::Error); 20597 EXPECT_EQ(parseConfiguration("---\n" 20598 "Language: JavaScript\n" 20599 "IndentWidth: 56\n" 20600 "---\n" 20601 "Language: JavaScript\n" 20602 "IndentWidth: 78\n" 20603 "...\n", 20604 &Style), 20605 ParseError::Error); 20606 20607 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20608 } 20609 20610 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20611 FormatStyle Style = {}; 20612 Style.Language = FormatStyle::LK_JavaScript; 20613 Style.BreakBeforeTernaryOperators = true; 20614 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20615 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20616 20617 Style.BreakBeforeTernaryOperators = true; 20618 EXPECT_EQ(0, parseConfiguration("---\n" 20619 "BasedOnStyle: Google\n" 20620 "---\n" 20621 "Language: JavaScript\n" 20622 "IndentWidth: 76\n" 20623 "...\n", 20624 &Style) 20625 .value()); 20626 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20627 EXPECT_EQ(76u, Style.IndentWidth); 20628 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20629 } 20630 20631 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20632 FormatStyle Style = getLLVMStyle(); 20633 std::string YAML = configurationAsText(Style); 20634 FormatStyle ParsedStyle = {}; 20635 ParsedStyle.Language = FormatStyle::LK_Cpp; 20636 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20637 EXPECT_EQ(Style, ParsedStyle); 20638 } 20639 20640 TEST_F(FormatTest, WorksFor8bitEncodings) { 20641 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20642 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20643 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20644 "\"\xef\xee\xf0\xf3...\"", 20645 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20646 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20647 "\xef\xee\xf0\xf3...\"", 20648 getLLVMStyleWithColumns(12))); 20649 } 20650 20651 TEST_F(FormatTest, HandlesUTF8BOM) { 20652 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20653 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20654 format("\xef\xbb\xbf#include <iostream>")); 20655 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20656 format("\xef\xbb\xbf\n#include <iostream>")); 20657 } 20658 20659 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20660 #if !defined(_MSC_VER) 20661 20662 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20663 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20664 getLLVMStyleWithColumns(35)); 20665 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20666 getLLVMStyleWithColumns(31)); 20667 verifyFormat("// Однажды в студёную зимнюю пору...", 20668 getLLVMStyleWithColumns(36)); 20669 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20670 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20671 getLLVMStyleWithColumns(39)); 20672 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20673 getLLVMStyleWithColumns(35)); 20674 } 20675 20676 TEST_F(FormatTest, SplitsUTF8Strings) { 20677 // Non-printable characters' width is currently considered to be the length in 20678 // bytes in UTF8. The characters can be displayed in very different manner 20679 // (zero-width, single width with a substitution glyph, expanded to their code 20680 // (e.g. "<8d>"), so there's no single correct way to handle them. 20681 EXPECT_EQ("\"aaaaÄ\"\n" 20682 "\"\xc2\x8d\";", 20683 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20684 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20685 "\"\xc2\x8d\";", 20686 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20687 EXPECT_EQ("\"Однажды, в \"\n" 20688 "\"студёную \"\n" 20689 "\"зимнюю \"\n" 20690 "\"пору,\"", 20691 format("\"Однажды, в студёную зимнюю пору,\"", 20692 getLLVMStyleWithColumns(13))); 20693 EXPECT_EQ( 20694 "\"一 二 三 \"\n" 20695 "\"四 五六 \"\n" 20696 "\"七 八 九 \"\n" 20697 "\"十\"", 20698 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20699 EXPECT_EQ("\"一\t\"\n" 20700 "\"二 \t\"\n" 20701 "\"三 四 \"\n" 20702 "\"五\t\"\n" 20703 "\"六 \t\"\n" 20704 "\"七 \"\n" 20705 "\"八九十\tqq\"", 20706 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20707 getLLVMStyleWithColumns(11))); 20708 20709 // UTF8 character in an escape sequence. 20710 EXPECT_EQ("\"aaaaaa\"\n" 20711 "\"\\\xC2\x8D\"", 20712 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20713 } 20714 20715 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20716 EXPECT_EQ("const char *sssss =\n" 20717 " \"一二三四五六七八\\\n" 20718 " 九 十\";", 20719 format("const char *sssss = \"一二三四五六七八\\\n" 20720 " 九 十\";", 20721 getLLVMStyleWithColumns(30))); 20722 } 20723 20724 TEST_F(FormatTest, SplitsUTF8LineComments) { 20725 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20726 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20727 EXPECT_EQ("// Я из лесу\n" 20728 "// вышел; был\n" 20729 "// сильный\n" 20730 "// мороз.", 20731 format("// Я из лесу вышел; был сильный мороз.", 20732 getLLVMStyleWithColumns(13))); 20733 EXPECT_EQ("// 一二三\n" 20734 "// 四五六七\n" 20735 "// 八 九\n" 20736 "// 十", 20737 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20738 } 20739 20740 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20741 EXPECT_EQ("/* Гляжу,\n" 20742 " * поднимается\n" 20743 " * медленно в\n" 20744 " * гору\n" 20745 " * Лошадка,\n" 20746 " * везущая\n" 20747 " * хворосту\n" 20748 " * воз. */", 20749 format("/* Гляжу, поднимается медленно в гору\n" 20750 " * Лошадка, везущая хворосту воз. */", 20751 getLLVMStyleWithColumns(13))); 20752 EXPECT_EQ( 20753 "/* 一二三\n" 20754 " * 四五六七\n" 20755 " * 八 九\n" 20756 " * 十 */", 20757 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20758 EXPECT_EQ("/* \n" 20759 " * \n" 20760 " * - */", 20761 format("/* - */", getLLVMStyleWithColumns(12))); 20762 } 20763 20764 #endif // _MSC_VER 20765 20766 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20767 FormatStyle Style = getLLVMStyle(); 20768 20769 Style.ConstructorInitializerIndentWidth = 4; 20770 verifyFormat( 20771 "SomeClass::Constructor()\n" 20772 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20773 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20774 Style); 20775 20776 Style.ConstructorInitializerIndentWidth = 2; 20777 verifyFormat( 20778 "SomeClass::Constructor()\n" 20779 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20780 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20781 Style); 20782 20783 Style.ConstructorInitializerIndentWidth = 0; 20784 verifyFormat( 20785 "SomeClass::Constructor()\n" 20786 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20787 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20788 Style); 20789 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20790 verifyFormat( 20791 "SomeLongTemplateVariableName<\n" 20792 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20793 Style); 20794 verifyFormat("bool smaller = 1 < " 20795 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20796 " " 20797 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20798 Style); 20799 20800 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20801 verifyFormat("SomeClass::Constructor() :\n" 20802 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20803 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20804 Style); 20805 } 20806 20807 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20808 FormatStyle Style = getLLVMStyle(); 20809 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20810 Style.ConstructorInitializerIndentWidth = 4; 20811 verifyFormat("SomeClass::Constructor()\n" 20812 " : a(a)\n" 20813 " , b(b)\n" 20814 " , c(c) {}", 20815 Style); 20816 verifyFormat("SomeClass::Constructor()\n" 20817 " : a(a) {}", 20818 Style); 20819 20820 Style.ColumnLimit = 0; 20821 verifyFormat("SomeClass::Constructor()\n" 20822 " : a(a) {}", 20823 Style); 20824 verifyFormat("SomeClass::Constructor() noexcept\n" 20825 " : a(a) {}", 20826 Style); 20827 verifyFormat("SomeClass::Constructor()\n" 20828 " : a(a)\n" 20829 " , b(b)\n" 20830 " , c(c) {}", 20831 Style); 20832 verifyFormat("SomeClass::Constructor()\n" 20833 " : a(a) {\n" 20834 " foo();\n" 20835 " bar();\n" 20836 "}", 20837 Style); 20838 20839 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20840 verifyFormat("SomeClass::Constructor()\n" 20841 " : a(a)\n" 20842 " , b(b)\n" 20843 " , c(c) {\n}", 20844 Style); 20845 verifyFormat("SomeClass::Constructor()\n" 20846 " : a(a) {\n}", 20847 Style); 20848 20849 Style.ColumnLimit = 80; 20850 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20851 Style.ConstructorInitializerIndentWidth = 2; 20852 verifyFormat("SomeClass::Constructor()\n" 20853 " : a(a)\n" 20854 " , b(b)\n" 20855 " , c(c) {}", 20856 Style); 20857 20858 Style.ConstructorInitializerIndentWidth = 0; 20859 verifyFormat("SomeClass::Constructor()\n" 20860 ": a(a)\n" 20861 ", b(b)\n" 20862 ", c(c) {}", 20863 Style); 20864 20865 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20866 Style.ConstructorInitializerIndentWidth = 4; 20867 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20868 verifyFormat( 20869 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20870 Style); 20871 verifyFormat( 20872 "SomeClass::Constructor()\n" 20873 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20874 Style); 20875 Style.ConstructorInitializerIndentWidth = 4; 20876 Style.ColumnLimit = 60; 20877 verifyFormat("SomeClass::Constructor()\n" 20878 " : aaaaaaaa(aaaaaaaa)\n" 20879 " , aaaaaaaa(aaaaaaaa)\n" 20880 " , aaaaaaaa(aaaaaaaa) {}", 20881 Style); 20882 } 20883 20884 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20885 FormatStyle Style = getLLVMStyle(); 20886 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20887 Style.ConstructorInitializerIndentWidth = 4; 20888 verifyFormat("SomeClass::Constructor()\n" 20889 " : a{a}\n" 20890 " , b{b} {}", 20891 Style); 20892 verifyFormat("SomeClass::Constructor()\n" 20893 " : a{a}\n" 20894 "#if CONDITION\n" 20895 " , b{b}\n" 20896 "#endif\n" 20897 "{\n}", 20898 Style); 20899 Style.ConstructorInitializerIndentWidth = 2; 20900 verifyFormat("SomeClass::Constructor()\n" 20901 "#if CONDITION\n" 20902 " : a{a}\n" 20903 "#endif\n" 20904 " , b{b}\n" 20905 " , c{c} {\n}", 20906 Style); 20907 Style.ConstructorInitializerIndentWidth = 0; 20908 verifyFormat("SomeClass::Constructor()\n" 20909 ": a{a}\n" 20910 "#ifdef CONDITION\n" 20911 ", b{b}\n" 20912 "#else\n" 20913 ", c{c}\n" 20914 "#endif\n" 20915 ", d{d} {\n}", 20916 Style); 20917 Style.ConstructorInitializerIndentWidth = 4; 20918 verifyFormat("SomeClass::Constructor()\n" 20919 " : a{a}\n" 20920 "#if WINDOWS\n" 20921 "#if DEBUG\n" 20922 " , b{0}\n" 20923 "#else\n" 20924 " , b{1}\n" 20925 "#endif\n" 20926 "#else\n" 20927 "#if DEBUG\n" 20928 " , b{2}\n" 20929 "#else\n" 20930 " , b{3}\n" 20931 "#endif\n" 20932 "#endif\n" 20933 "{\n}", 20934 Style); 20935 verifyFormat("SomeClass::Constructor()\n" 20936 " : a{a}\n" 20937 "#if WINDOWS\n" 20938 " , b{0}\n" 20939 "#if DEBUG\n" 20940 " , c{0}\n" 20941 "#else\n" 20942 " , c{1}\n" 20943 "#endif\n" 20944 "#else\n" 20945 "#if DEBUG\n" 20946 " , c{2}\n" 20947 "#else\n" 20948 " , c{3}\n" 20949 "#endif\n" 20950 " , b{1}\n" 20951 "#endif\n" 20952 "{\n}", 20953 Style); 20954 } 20955 20956 TEST_F(FormatTest, Destructors) { 20957 verifyFormat("void F(int &i) { i.~int(); }"); 20958 verifyFormat("void F(int &i) { i->~int(); }"); 20959 } 20960 20961 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20962 FormatStyle Style = getWebKitStyle(); 20963 20964 // Don't indent in outer namespaces. 20965 verifyFormat("namespace outer {\n" 20966 "int i;\n" 20967 "namespace inner {\n" 20968 " int i;\n" 20969 "} // namespace inner\n" 20970 "} // namespace outer\n" 20971 "namespace other_outer {\n" 20972 "int i;\n" 20973 "}", 20974 Style); 20975 20976 // Don't indent case labels. 20977 verifyFormat("switch (variable) {\n" 20978 "case 1:\n" 20979 "case 2:\n" 20980 " doSomething();\n" 20981 " break;\n" 20982 "default:\n" 20983 " ++variable;\n" 20984 "}", 20985 Style); 20986 20987 // Wrap before binary operators. 20988 EXPECT_EQ("void f()\n" 20989 "{\n" 20990 " if (aaaaaaaaaaaaaaaa\n" 20991 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20992 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20993 " return;\n" 20994 "}", 20995 format("void f() {\n" 20996 "if (aaaaaaaaaaaaaaaa\n" 20997 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20998 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20999 "return;\n" 21000 "}", 21001 Style)); 21002 21003 // Allow functions on a single line. 21004 verifyFormat("void f() { return; }", Style); 21005 21006 // Allow empty blocks on a single line and insert a space in empty blocks. 21007 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 21008 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 21009 // However, don't merge non-empty short loops. 21010 EXPECT_EQ("while (true) {\n" 21011 " continue;\n" 21012 "}", 21013 format("while (true) { continue; }", Style)); 21014 21015 // Constructor initializers are formatted one per line with the "," on the 21016 // new line. 21017 verifyFormat("Constructor()\n" 21018 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 21019 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 21020 " aaaaaaaaaaaaaa)\n" 21021 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 21022 "{\n" 21023 "}", 21024 Style); 21025 verifyFormat("SomeClass::Constructor()\n" 21026 " : a(a)\n" 21027 "{\n" 21028 "}", 21029 Style); 21030 EXPECT_EQ("SomeClass::Constructor()\n" 21031 " : a(a)\n" 21032 "{\n" 21033 "}", 21034 format("SomeClass::Constructor():a(a){}", Style)); 21035 verifyFormat("SomeClass::Constructor()\n" 21036 " : a(a)\n" 21037 " , b(b)\n" 21038 " , c(c)\n" 21039 "{\n" 21040 "}", 21041 Style); 21042 verifyFormat("SomeClass::Constructor()\n" 21043 " : a(a)\n" 21044 "{\n" 21045 " foo();\n" 21046 " bar();\n" 21047 "}", 21048 Style); 21049 21050 // Access specifiers should be aligned left. 21051 verifyFormat("class C {\n" 21052 "public:\n" 21053 " int i;\n" 21054 "};", 21055 Style); 21056 21057 // Do not align comments. 21058 verifyFormat("int a; // Do not\n" 21059 "double b; // align comments.", 21060 Style); 21061 21062 // Do not align operands. 21063 EXPECT_EQ("ASSERT(aaaa\n" 21064 " || bbbb);", 21065 format("ASSERT ( aaaa\n||bbbb);", Style)); 21066 21067 // Accept input's line breaks. 21068 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21069 " || bbbbbbbbbbbbbbb) {\n" 21070 " i++;\n" 21071 "}", 21072 format("if (aaaaaaaaaaaaaaa\n" 21073 "|| bbbbbbbbbbbbbbb) { i++; }", 21074 Style)); 21075 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21076 " i++;\n" 21077 "}", 21078 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21079 21080 // Don't automatically break all macro definitions (llvm.org/PR17842). 21081 verifyFormat("#define aNumber 10", Style); 21082 // However, generally keep the line breaks that the user authored. 21083 EXPECT_EQ("#define aNumber \\\n" 21084 " 10", 21085 format("#define aNumber \\\n" 21086 " 10", 21087 Style)); 21088 21089 // Keep empty and one-element array literals on a single line. 21090 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21091 " copyItems:YES];", 21092 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21093 "copyItems:YES];", 21094 Style)); 21095 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21096 " copyItems:YES];", 21097 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21098 " copyItems:YES];", 21099 Style)); 21100 // FIXME: This does not seem right, there should be more indentation before 21101 // the array literal's entries. Nested blocks have the same problem. 21102 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21103 " @\"a\",\n" 21104 " @\"a\"\n" 21105 "]\n" 21106 " copyItems:YES];", 21107 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21108 " @\"a\",\n" 21109 " @\"a\"\n" 21110 " ]\n" 21111 " copyItems:YES];", 21112 Style)); 21113 EXPECT_EQ( 21114 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21115 " copyItems:YES];", 21116 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21117 " copyItems:YES];", 21118 Style)); 21119 21120 verifyFormat("[self.a b:c c:d];", Style); 21121 EXPECT_EQ("[self.a b:c\n" 21122 " c:d];", 21123 format("[self.a b:c\n" 21124 "c:d];", 21125 Style)); 21126 } 21127 21128 TEST_F(FormatTest, FormatsLambdas) { 21129 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21130 verifyFormat( 21131 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21132 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21133 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21134 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21135 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21136 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21137 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21138 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21139 verifyFormat("int x = f(*+[] {});"); 21140 verifyFormat("void f() {\n" 21141 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21142 "}\n"); 21143 verifyFormat("void f() {\n" 21144 " other(x.begin(), //\n" 21145 " x.end(), //\n" 21146 " [&](int, int) { return 1; });\n" 21147 "}\n"); 21148 verifyFormat("void f() {\n" 21149 " other.other.other.other.other(\n" 21150 " x.begin(), x.end(),\n" 21151 " [something, rather](int, int, int, int, int, int, int) { " 21152 "return 1; });\n" 21153 "}\n"); 21154 verifyFormat( 21155 "void f() {\n" 21156 " other.other.other.other.other(\n" 21157 " x.begin(), x.end(),\n" 21158 " [something, rather](int, int, int, int, int, int, int) {\n" 21159 " //\n" 21160 " });\n" 21161 "}\n"); 21162 verifyFormat("SomeFunction([]() { // A cool function...\n" 21163 " return 43;\n" 21164 "});"); 21165 EXPECT_EQ("SomeFunction([]() {\n" 21166 "#define A a\n" 21167 " return 43;\n" 21168 "});", 21169 format("SomeFunction([](){\n" 21170 "#define A a\n" 21171 "return 43;\n" 21172 "});")); 21173 verifyFormat("void f() {\n" 21174 " SomeFunction([](decltype(x), A *a) {});\n" 21175 " SomeFunction([](typeof(x), A *a) {});\n" 21176 " SomeFunction([](_Atomic(x), A *a) {});\n" 21177 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21178 "}"); 21179 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21180 " [](const aaaaaaaaaa &a) { return a; });"); 21181 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21182 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21183 "});"); 21184 verifyFormat("Constructor()\n" 21185 " : Field([] { // comment\n" 21186 " int i;\n" 21187 " }) {}"); 21188 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21189 " return some_parameter.size();\n" 21190 "};"); 21191 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21192 " [](const string &s) { return s; };"); 21193 verifyFormat("int i = aaaaaa ? 1 //\n" 21194 " : [] {\n" 21195 " return 2; //\n" 21196 " }();"); 21197 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21198 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21199 " return x == 2; // force break\n" 21200 " });"); 21201 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21202 " [=](int iiiiiiiiiiii) {\n" 21203 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21204 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21205 " });", 21206 getLLVMStyleWithColumns(60)); 21207 21208 verifyFormat("SomeFunction({[&] {\n" 21209 " // comment\n" 21210 " },\n" 21211 " [&] {\n" 21212 " // comment\n" 21213 " }});"); 21214 verifyFormat("SomeFunction({[&] {\n" 21215 " // comment\n" 21216 "}});"); 21217 verifyFormat( 21218 "virtual aaaaaaaaaaaaaaaa(\n" 21219 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21220 " aaaaa aaaaaaaaa);"); 21221 21222 // Lambdas with return types. 21223 verifyFormat("int c = []() -> int { return 2; }();\n"); 21224 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21225 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21226 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21227 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21228 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21229 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21230 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21231 verifyFormat("[a, a]() -> a<1> {};"); 21232 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21233 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21234 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21235 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21236 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21237 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21238 verifyFormat("[]() -> foo<!5> { return {}; };"); 21239 verifyFormat("[]() -> foo<~5> { return {}; };"); 21240 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21241 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21242 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21243 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21244 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21245 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21246 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21247 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21248 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21249 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21250 verifyFormat("namespace bar {\n" 21251 "// broken:\n" 21252 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21253 "} // namespace bar"); 21254 verifyFormat("namespace bar {\n" 21255 "// broken:\n" 21256 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21257 "} // namespace bar"); 21258 verifyFormat("namespace bar {\n" 21259 "// broken:\n" 21260 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21261 "} // namespace bar"); 21262 verifyFormat("namespace bar {\n" 21263 "// broken:\n" 21264 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21265 "} // namespace bar"); 21266 verifyFormat("namespace bar {\n" 21267 "// broken:\n" 21268 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21269 "} // namespace bar"); 21270 verifyFormat("namespace bar {\n" 21271 "// broken:\n" 21272 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21273 "} // namespace bar"); 21274 verifyFormat("namespace bar {\n" 21275 "// broken:\n" 21276 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21277 "} // namespace bar"); 21278 verifyFormat("namespace bar {\n" 21279 "// broken:\n" 21280 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21281 "} // namespace bar"); 21282 verifyFormat("namespace bar {\n" 21283 "// broken:\n" 21284 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21285 "} // namespace bar"); 21286 verifyFormat("namespace bar {\n" 21287 "// broken:\n" 21288 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21289 "} // namespace bar"); 21290 verifyFormat("namespace bar {\n" 21291 "// broken:\n" 21292 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21293 "} // namespace bar"); 21294 verifyFormat("namespace bar {\n" 21295 "// broken:\n" 21296 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21297 "} // namespace bar"); 21298 verifyFormat("namespace bar {\n" 21299 "// broken:\n" 21300 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21301 "} // namespace bar"); 21302 verifyFormat("namespace bar {\n" 21303 "// broken:\n" 21304 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21305 "} // namespace bar"); 21306 verifyFormat("namespace bar {\n" 21307 "// broken:\n" 21308 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21309 "} // namespace bar"); 21310 verifyFormat("namespace bar {\n" 21311 "// broken:\n" 21312 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21313 "} // namespace bar"); 21314 verifyFormat("namespace bar {\n" 21315 "// broken:\n" 21316 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21317 "} // namespace bar"); 21318 verifyFormat("namespace bar {\n" 21319 "// broken:\n" 21320 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21321 "} // namespace bar"); 21322 verifyFormat("[]() -> a<1> {};"); 21323 verifyFormat("[]() -> a<1> { ; };"); 21324 verifyFormat("[]() -> a<1> { ; }();"); 21325 verifyFormat("[a, a]() -> a<true> {};"); 21326 verifyFormat("[]() -> a<true> {};"); 21327 verifyFormat("[]() -> a<true> { ; };"); 21328 verifyFormat("[]() -> a<true> { ; }();"); 21329 verifyFormat("[a, a]() -> a<false> {};"); 21330 verifyFormat("[]() -> a<false> {};"); 21331 verifyFormat("[]() -> a<false> { ; };"); 21332 verifyFormat("[]() -> a<false> { ; }();"); 21333 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21334 verifyFormat("namespace bar {\n" 21335 "auto foo{[]() -> foo<false> { ; }};\n" 21336 "} // namespace bar"); 21337 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21338 " int j) -> int {\n" 21339 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21340 "};"); 21341 verifyFormat( 21342 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21343 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21344 " return aaaaaaaaaaaaaaaaa;\n" 21345 " });", 21346 getLLVMStyleWithColumns(70)); 21347 verifyFormat("[]() //\n" 21348 " -> int {\n" 21349 " return 1; //\n" 21350 "};"); 21351 verifyFormat("[]() -> Void<T...> {};"); 21352 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21353 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21354 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21355 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21356 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21357 verifyFormat("return int{[x = x]() { return x; }()};"); 21358 21359 // Lambdas with explicit template argument lists. 21360 verifyFormat( 21361 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21362 verifyFormat("auto L = []<class T>(T) {\n" 21363 " {\n" 21364 " f();\n" 21365 " g();\n" 21366 " }\n" 21367 "};\n"); 21368 verifyFormat("auto L = []<class... T>(T...) {\n" 21369 " {\n" 21370 " f();\n" 21371 " g();\n" 21372 " }\n" 21373 "};\n"); 21374 verifyFormat("auto L = []<typename... T>(T...) {\n" 21375 " {\n" 21376 " f();\n" 21377 " g();\n" 21378 " }\n" 21379 "};\n"); 21380 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21381 " {\n" 21382 " f();\n" 21383 " g();\n" 21384 " }\n" 21385 "};\n"); 21386 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21387 " {\n" 21388 " f();\n" 21389 " g();\n" 21390 " }\n" 21391 "};\n"); 21392 21393 // Multiple lambdas in the same parentheses change indentation rules. These 21394 // lambdas are forced to start on new lines. 21395 verifyFormat("SomeFunction(\n" 21396 " []() {\n" 21397 " //\n" 21398 " },\n" 21399 " []() {\n" 21400 " //\n" 21401 " });"); 21402 21403 // A lambda passed as arg0 is always pushed to the next line. 21404 verifyFormat("SomeFunction(\n" 21405 " [this] {\n" 21406 " //\n" 21407 " },\n" 21408 " 1);\n"); 21409 21410 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21411 // the arg0 case above. 21412 auto Style = getGoogleStyle(); 21413 Style.BinPackArguments = false; 21414 verifyFormat("SomeFunction(\n" 21415 " a,\n" 21416 " [this] {\n" 21417 " //\n" 21418 " },\n" 21419 " b);\n", 21420 Style); 21421 verifyFormat("SomeFunction(\n" 21422 " a,\n" 21423 " [this] {\n" 21424 " //\n" 21425 " },\n" 21426 " b);\n"); 21427 21428 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21429 // the BinPackArguments value (as long as the code is wide enough). 21430 verifyFormat( 21431 "something->SomeFunction(\n" 21432 " a,\n" 21433 " [this] {\n" 21434 " " 21435 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21436 " },\n" 21437 " b);\n"); 21438 21439 // A multi-line lambda is pulled up as long as the introducer fits on the 21440 // previous line and there are no further args. 21441 verifyFormat("function(1, [this, that] {\n" 21442 " //\n" 21443 "});\n"); 21444 verifyFormat("function([this, that] {\n" 21445 " //\n" 21446 "});\n"); 21447 // FIXME: this format is not ideal and we should consider forcing the first 21448 // arg onto its own line. 21449 verifyFormat("function(a, b, c, //\n" 21450 " d, [this, that] {\n" 21451 " //\n" 21452 " });\n"); 21453 21454 // Multiple lambdas are treated correctly even when there is a short arg0. 21455 verifyFormat("SomeFunction(\n" 21456 " 1,\n" 21457 " [this] {\n" 21458 " //\n" 21459 " },\n" 21460 " [this] {\n" 21461 " //\n" 21462 " },\n" 21463 " 1);\n"); 21464 21465 // More complex introducers. 21466 verifyFormat("return [i, args...] {};"); 21467 21468 // Not lambdas. 21469 verifyFormat("constexpr char hello[]{\"hello\"};"); 21470 verifyFormat("double &operator[](int i) { return 0; }\n" 21471 "int i;"); 21472 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21473 verifyFormat("int i = a[a][a]->f();"); 21474 verifyFormat("int i = (*b)[a]->f();"); 21475 21476 // Other corner cases. 21477 verifyFormat("void f() {\n" 21478 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21479 " );\n" 21480 "}"); 21481 21482 // Lambdas created through weird macros. 21483 verifyFormat("void f() {\n" 21484 " MACRO((const AA &a) { return 1; });\n" 21485 " MACRO((AA &a) { return 1; });\n" 21486 "}"); 21487 21488 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21489 " doo_dah();\n" 21490 " doo_dah();\n" 21491 " })) {\n" 21492 "}"); 21493 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21494 " doo_dah();\n" 21495 " doo_dah();\n" 21496 " })) {\n" 21497 "}"); 21498 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21499 " doo_dah();\n" 21500 " doo_dah();\n" 21501 " })) {\n" 21502 "}"); 21503 verifyFormat("auto lambda = []() {\n" 21504 " int a = 2\n" 21505 "#if A\n" 21506 " + 2\n" 21507 "#endif\n" 21508 " ;\n" 21509 "};"); 21510 21511 // Lambdas with complex multiline introducers. 21512 verifyFormat( 21513 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21514 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21515 " -> ::std::unordered_set<\n" 21516 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21517 " //\n" 21518 " });"); 21519 21520 FormatStyle DoNotMerge = getLLVMStyle(); 21521 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21522 verifyFormat("auto c = []() {\n" 21523 " return b;\n" 21524 "};", 21525 "auto c = []() { return b; };", DoNotMerge); 21526 verifyFormat("auto c = []() {\n" 21527 "};", 21528 " auto c = []() {};", DoNotMerge); 21529 21530 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21531 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21532 verifyFormat("auto c = []() {\n" 21533 " return b;\n" 21534 "};", 21535 "auto c = []() {\n" 21536 " return b;\n" 21537 " };", 21538 MergeEmptyOnly); 21539 verifyFormat("auto c = []() {};", 21540 "auto c = []() {\n" 21541 "};", 21542 MergeEmptyOnly); 21543 21544 FormatStyle MergeInline = getLLVMStyle(); 21545 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21546 verifyFormat("auto c = []() {\n" 21547 " return b;\n" 21548 "};", 21549 "auto c = []() { return b; };", MergeInline); 21550 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21551 MergeInline); 21552 verifyFormat("function([]() { return b; }, a)", 21553 "function([]() { return b; }, a)", MergeInline); 21554 verifyFormat("function(a, []() { return b; })", 21555 "function(a, []() { return b; })", MergeInline); 21556 21557 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21558 // AllowShortLambdasOnASingleLine 21559 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21560 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21561 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21562 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21563 FormatStyle::ShortLambdaStyle::SLS_None; 21564 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21565 " []()\n" 21566 " {\n" 21567 " return 17;\n" 21568 " });", 21569 LLVMWithBeforeLambdaBody); 21570 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21571 " []()\n" 21572 " {\n" 21573 " });", 21574 LLVMWithBeforeLambdaBody); 21575 verifyFormat("auto fct_SLS_None = []()\n" 21576 "{\n" 21577 " return 17;\n" 21578 "};", 21579 LLVMWithBeforeLambdaBody); 21580 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21581 " []()\n" 21582 " {\n" 21583 " return Call(\n" 21584 " []()\n" 21585 " {\n" 21586 " return 17;\n" 21587 " });\n" 21588 " });", 21589 LLVMWithBeforeLambdaBody); 21590 verifyFormat("void Fct() {\n" 21591 " return {[]()\n" 21592 " {\n" 21593 " return 17;\n" 21594 " }};\n" 21595 "}", 21596 LLVMWithBeforeLambdaBody); 21597 21598 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21599 FormatStyle::ShortLambdaStyle::SLS_Empty; 21600 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21601 " []()\n" 21602 " {\n" 21603 " return 17;\n" 21604 " });", 21605 LLVMWithBeforeLambdaBody); 21606 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21607 LLVMWithBeforeLambdaBody); 21608 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21609 "ongFunctionName_SLS_Empty(\n" 21610 " []() {});", 21611 LLVMWithBeforeLambdaBody); 21612 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21613 " []()\n" 21614 " {\n" 21615 " return 17;\n" 21616 " });", 21617 LLVMWithBeforeLambdaBody); 21618 verifyFormat("auto fct_SLS_Empty = []()\n" 21619 "{\n" 21620 " return 17;\n" 21621 "};", 21622 LLVMWithBeforeLambdaBody); 21623 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21624 " []()\n" 21625 " {\n" 21626 " return Call([]() {});\n" 21627 " });", 21628 LLVMWithBeforeLambdaBody); 21629 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21630 " []()\n" 21631 " {\n" 21632 " return Call([]() {});\n" 21633 " });", 21634 LLVMWithBeforeLambdaBody); 21635 verifyFormat( 21636 "FctWithLongLineInLambda_SLS_Empty(\n" 21637 " []()\n" 21638 " {\n" 21639 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21640 " AndShouldNotBeConsiderAsInline,\n" 21641 " LambdaBodyMustBeBreak);\n" 21642 " });", 21643 LLVMWithBeforeLambdaBody); 21644 21645 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21646 FormatStyle::ShortLambdaStyle::SLS_Inline; 21647 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21648 LLVMWithBeforeLambdaBody); 21649 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21650 LLVMWithBeforeLambdaBody); 21651 verifyFormat("auto fct_SLS_Inline = []()\n" 21652 "{\n" 21653 " return 17;\n" 21654 "};", 21655 LLVMWithBeforeLambdaBody); 21656 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21657 "17; }); });", 21658 LLVMWithBeforeLambdaBody); 21659 verifyFormat( 21660 "FctWithLongLineInLambda_SLS_Inline(\n" 21661 " []()\n" 21662 " {\n" 21663 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21664 " AndShouldNotBeConsiderAsInline,\n" 21665 " LambdaBodyMustBeBreak);\n" 21666 " });", 21667 LLVMWithBeforeLambdaBody); 21668 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21669 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21670 " []() { return 17; });", 21671 LLVMWithBeforeLambdaBody); 21672 verifyFormat( 21673 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21674 LLVMWithBeforeLambdaBody); 21675 21676 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21677 FormatStyle::ShortLambdaStyle::SLS_All; 21678 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21679 LLVMWithBeforeLambdaBody); 21680 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21681 LLVMWithBeforeLambdaBody); 21682 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21683 LLVMWithBeforeLambdaBody); 21684 verifyFormat("FctWithOneParam_SLS_All(\n" 21685 " []()\n" 21686 " {\n" 21687 " // A cool function...\n" 21688 " return 43;\n" 21689 " });", 21690 LLVMWithBeforeLambdaBody); 21691 verifyFormat("FctWithMultipleParams_SLS_All(" 21692 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21693 " []() { return 17; });", 21694 LLVMWithBeforeLambdaBody); 21695 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21696 LLVMWithBeforeLambdaBody); 21697 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21698 LLVMWithBeforeLambdaBody); 21699 verifyFormat( 21700 "FctWithLongLineInLambda_SLS_All(\n" 21701 " []()\n" 21702 " {\n" 21703 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21704 " AndShouldNotBeConsiderAsInline,\n" 21705 " LambdaBodyMustBeBreak);\n" 21706 " });", 21707 LLVMWithBeforeLambdaBody); 21708 verifyFormat( 21709 "auto fct_SLS_All = []()\n" 21710 "{\n" 21711 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21712 " AndShouldNotBeConsiderAsInline,\n" 21713 " LambdaBodyMustBeBreak);\n" 21714 "};", 21715 LLVMWithBeforeLambdaBody); 21716 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21717 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21718 LLVMWithBeforeLambdaBody); 21719 verifyFormat( 21720 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21721 " FirstParam,\n" 21722 " SecondParam,\n" 21723 " ThirdParam,\n" 21724 " FourthParam);", 21725 LLVMWithBeforeLambdaBody); 21726 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21727 " []() { return " 21728 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21729 " FirstParam,\n" 21730 " SecondParam,\n" 21731 " ThirdParam,\n" 21732 " FourthParam);", 21733 LLVMWithBeforeLambdaBody); 21734 verifyFormat( 21735 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21736 " SecondParam,\n" 21737 " ThirdParam,\n" 21738 " FourthParam,\n" 21739 " []() { return SomeValueNotSoLong; });", 21740 LLVMWithBeforeLambdaBody); 21741 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21742 " []()\n" 21743 " {\n" 21744 " return " 21745 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21746 "eConsiderAsInline;\n" 21747 " });", 21748 LLVMWithBeforeLambdaBody); 21749 verifyFormat( 21750 "FctWithLongLineInLambda_SLS_All(\n" 21751 " []()\n" 21752 " {\n" 21753 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21754 " AndShouldNotBeConsiderAsInline,\n" 21755 " LambdaBodyMustBeBreak);\n" 21756 " });", 21757 LLVMWithBeforeLambdaBody); 21758 verifyFormat("FctWithTwoParams_SLS_All(\n" 21759 " []()\n" 21760 " {\n" 21761 " // A cool function...\n" 21762 " return 43;\n" 21763 " },\n" 21764 " 87);", 21765 LLVMWithBeforeLambdaBody); 21766 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21767 LLVMWithBeforeLambdaBody); 21768 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21769 LLVMWithBeforeLambdaBody); 21770 verifyFormat( 21771 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21772 LLVMWithBeforeLambdaBody); 21773 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21774 "}); }, x);", 21775 LLVMWithBeforeLambdaBody); 21776 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21777 " []()\n" 21778 " {\n" 21779 " // A cool function...\n" 21780 " return Call([]() { return 17; });\n" 21781 " });", 21782 LLVMWithBeforeLambdaBody); 21783 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21784 " []()\n" 21785 " {\n" 21786 " return Call(\n" 21787 " []()\n" 21788 " {\n" 21789 " // A cool function...\n" 21790 " return 17;\n" 21791 " });\n" 21792 " });", 21793 LLVMWithBeforeLambdaBody); 21794 21795 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21796 FormatStyle::ShortLambdaStyle::SLS_None; 21797 21798 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21799 "{\n" 21800 " return MyAssignment::SelectFromList(this);\n" 21801 "};\n", 21802 LLVMWithBeforeLambdaBody); 21803 21804 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21805 "{\n" 21806 " return MyAssignment::SelectFromList(this);\n" 21807 "};\n", 21808 LLVMWithBeforeLambdaBody); 21809 21810 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21811 "{\n" 21812 " return MyAssignment::SelectFromList(this);\n" 21813 "};\n", 21814 LLVMWithBeforeLambdaBody); 21815 21816 verifyFormat("namespace test {\n" 21817 "class Test {\n" 21818 "public:\n" 21819 " Test() = default;\n" 21820 "};\n" 21821 "} // namespace test", 21822 LLVMWithBeforeLambdaBody); 21823 21824 // Lambdas with different indentation styles. 21825 Style = getLLVMStyleWithColumns(100); 21826 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21827 " return promise.then(\n" 21828 " [this, &someVariable, someObject = " 21829 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21830 " return someObject.startAsyncAction().then(\n" 21831 " [this, &someVariable](AsyncActionResult result) " 21832 "mutable { result.processMore(); });\n" 21833 " });\n" 21834 "}\n", 21835 format("SomeResult doSomething(SomeObject promise) {\n" 21836 " return promise.then([this, &someVariable, someObject = " 21837 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21838 " return someObject.startAsyncAction().then([this, " 21839 "&someVariable](AsyncActionResult result) mutable {\n" 21840 " result.processMore();\n" 21841 " });\n" 21842 " });\n" 21843 "}\n", 21844 Style)); 21845 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21846 verifyFormat("test() {\n" 21847 " ([]() -> {\n" 21848 " int b = 32;\n" 21849 " return 3;\n" 21850 " }).foo();\n" 21851 "}", 21852 Style); 21853 verifyFormat("test() {\n" 21854 " []() -> {\n" 21855 " int b = 32;\n" 21856 " return 3;\n" 21857 " }\n" 21858 "}", 21859 Style); 21860 verifyFormat("std::sort(v.begin(), v.end(),\n" 21861 " [](const auto &someLongArgumentName, const auto " 21862 "&someOtherLongArgumentName) {\n" 21863 " return someLongArgumentName.someMemberVariable < " 21864 "someOtherLongArgumentName.someMemberVariable;\n" 21865 "});", 21866 Style); 21867 verifyFormat("test() {\n" 21868 " (\n" 21869 " []() -> {\n" 21870 " int b = 32;\n" 21871 " return 3;\n" 21872 " },\n" 21873 " foo, bar)\n" 21874 " .foo();\n" 21875 "}", 21876 Style); 21877 verifyFormat("test() {\n" 21878 " ([]() -> {\n" 21879 " int b = 32;\n" 21880 " return 3;\n" 21881 " })\n" 21882 " .foo()\n" 21883 " .bar();\n" 21884 "}", 21885 Style); 21886 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21887 " return promise.then(\n" 21888 " [this, &someVariable, someObject = " 21889 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21890 " return someObject.startAsyncAction().then(\n" 21891 " [this, &someVariable](AsyncActionResult result) mutable { " 21892 "result.processMore(); });\n" 21893 " });\n" 21894 "}\n", 21895 format("SomeResult doSomething(SomeObject promise) {\n" 21896 " return promise.then([this, &someVariable, someObject = " 21897 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21898 " return someObject.startAsyncAction().then([this, " 21899 "&someVariable](AsyncActionResult result) mutable {\n" 21900 " result.processMore();\n" 21901 " });\n" 21902 " });\n" 21903 "}\n", 21904 Style)); 21905 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21906 " return promise.then([this, &someVariable] {\n" 21907 " return someObject.startAsyncAction().then(\n" 21908 " [this, &someVariable](AsyncActionResult result) mutable { " 21909 "result.processMore(); });\n" 21910 " });\n" 21911 "}\n", 21912 format("SomeResult doSomething(SomeObject promise) {\n" 21913 " return promise.then([this, &someVariable] {\n" 21914 " return someObject.startAsyncAction().then([this, " 21915 "&someVariable](AsyncActionResult result) mutable {\n" 21916 " result.processMore();\n" 21917 " });\n" 21918 " });\n" 21919 "}\n", 21920 Style)); 21921 Style = getGoogleStyle(); 21922 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21923 EXPECT_EQ("#define A \\\n" 21924 " [] { \\\n" 21925 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21926 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21927 " }", 21928 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21929 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21930 Style)); 21931 // TODO: The current formatting has a minor issue that's not worth fixing 21932 // right now whereby the closing brace is indented relative to the signature 21933 // instead of being aligned. This only happens with macros. 21934 } 21935 21936 TEST_F(FormatTest, LambdaWithLineComments) { 21937 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21938 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21939 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21940 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21941 FormatStyle::ShortLambdaStyle::SLS_All; 21942 21943 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21944 verifyFormat("auto k = []() // comment\n" 21945 "{ return; }", 21946 LLVMWithBeforeLambdaBody); 21947 verifyFormat("auto k = []() /* comment */ { return; }", 21948 LLVMWithBeforeLambdaBody); 21949 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21950 LLVMWithBeforeLambdaBody); 21951 verifyFormat("auto k = []() // X\n" 21952 "{ return; }", 21953 LLVMWithBeforeLambdaBody); 21954 verifyFormat( 21955 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21956 "{ return; }", 21957 LLVMWithBeforeLambdaBody); 21958 21959 LLVMWithBeforeLambdaBody.ColumnLimit = 0; 21960 21961 verifyFormat("foo([]()\n" 21962 " {\n" 21963 " bar(); //\n" 21964 " return 1; // comment\n" 21965 " }());", 21966 "foo([]() {\n" 21967 " bar(); //\n" 21968 " return 1; // comment\n" 21969 "}());", 21970 LLVMWithBeforeLambdaBody); 21971 verifyFormat("foo(\n" 21972 " 1, MACRO {\n" 21973 " baz();\n" 21974 " bar(); // comment\n" 21975 " },\n" 21976 " []() {});", 21977 "foo(\n" 21978 " 1, MACRO { baz(); bar(); // comment\n" 21979 " }, []() {}\n" 21980 ");", 21981 LLVMWithBeforeLambdaBody); 21982 } 21983 21984 TEST_F(FormatTest, EmptyLinesInLambdas) { 21985 verifyFormat("auto lambda = []() {\n" 21986 " x(); //\n" 21987 "};", 21988 "auto lambda = []() {\n" 21989 "\n" 21990 " x(); //\n" 21991 "\n" 21992 "};"); 21993 } 21994 21995 TEST_F(FormatTest, FormatsBlocks) { 21996 FormatStyle ShortBlocks = getLLVMStyle(); 21997 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21998 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21999 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 22000 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 22001 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 22002 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 22003 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 22004 22005 verifyFormat("foo(^{ bar(); });", ShortBlocks); 22006 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 22007 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 22008 22009 verifyFormat("[operation setCompletionBlock:^{\n" 22010 " [self onOperationDone];\n" 22011 "}];"); 22012 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 22013 " [self onOperationDone];\n" 22014 "}]};"); 22015 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 22016 " f();\n" 22017 "}];"); 22018 verifyFormat("int a = [operation block:^int(int *i) {\n" 22019 " return 1;\n" 22020 "}];"); 22021 verifyFormat("[myObject doSomethingWith:arg1\n" 22022 " aaa:^int(int *a) {\n" 22023 " return 1;\n" 22024 " }\n" 22025 " bbb:f(a * bbbbbbbb)];"); 22026 22027 verifyFormat("[operation setCompletionBlock:^{\n" 22028 " [self.delegate newDataAvailable];\n" 22029 "}];", 22030 getLLVMStyleWithColumns(60)); 22031 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 22032 " NSString *path = [self sessionFilePath];\n" 22033 " if (path) {\n" 22034 " // ...\n" 22035 " }\n" 22036 "});"); 22037 verifyFormat("[[SessionService sharedService]\n" 22038 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22039 " if (window) {\n" 22040 " [self windowDidLoad:window];\n" 22041 " } else {\n" 22042 " [self errorLoadingWindow];\n" 22043 " }\n" 22044 " }];"); 22045 verifyFormat("void (^largeBlock)(void) = ^{\n" 22046 " // ...\n" 22047 "};\n", 22048 getLLVMStyleWithColumns(40)); 22049 verifyFormat("[[SessionService sharedService]\n" 22050 " loadWindowWithCompletionBlock: //\n" 22051 " ^(SessionWindow *window) {\n" 22052 " if (window) {\n" 22053 " [self windowDidLoad:window];\n" 22054 " } else {\n" 22055 " [self errorLoadingWindow];\n" 22056 " }\n" 22057 " }];", 22058 getLLVMStyleWithColumns(60)); 22059 verifyFormat("[myObject doSomethingWith:arg1\n" 22060 " firstBlock:^(Foo *a) {\n" 22061 " // ...\n" 22062 " int i;\n" 22063 " }\n" 22064 " secondBlock:^(Bar *b) {\n" 22065 " // ...\n" 22066 " int i;\n" 22067 " }\n" 22068 " thirdBlock:^Foo(Bar *b) {\n" 22069 " // ...\n" 22070 " int i;\n" 22071 " }];"); 22072 verifyFormat("[myObject doSomethingWith:arg1\n" 22073 " firstBlock:-1\n" 22074 " secondBlock:^(Bar *b) {\n" 22075 " // ...\n" 22076 " int i;\n" 22077 " }];"); 22078 22079 verifyFormat("f(^{\n" 22080 " @autoreleasepool {\n" 22081 " if (a) {\n" 22082 " g();\n" 22083 " }\n" 22084 " }\n" 22085 "});"); 22086 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22087 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22088 "};"); 22089 22090 FormatStyle FourIndent = getLLVMStyle(); 22091 FourIndent.ObjCBlockIndentWidth = 4; 22092 verifyFormat("[operation setCompletionBlock:^{\n" 22093 " [self onOperationDone];\n" 22094 "}];", 22095 FourIndent); 22096 } 22097 22098 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22099 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22100 22101 verifyFormat("[[SessionService sharedService] " 22102 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22103 " if (window) {\n" 22104 " [self windowDidLoad:window];\n" 22105 " } else {\n" 22106 " [self errorLoadingWindow];\n" 22107 " }\n" 22108 "}];", 22109 ZeroColumn); 22110 EXPECT_EQ("[[SessionService sharedService]\n" 22111 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22112 " if (window) {\n" 22113 " [self windowDidLoad:window];\n" 22114 " } else {\n" 22115 " [self errorLoadingWindow];\n" 22116 " }\n" 22117 " }];", 22118 format("[[SessionService sharedService]\n" 22119 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22120 " if (window) {\n" 22121 " [self windowDidLoad:window];\n" 22122 " } else {\n" 22123 " [self errorLoadingWindow];\n" 22124 " }\n" 22125 "}];", 22126 ZeroColumn)); 22127 verifyFormat("[myObject doSomethingWith:arg1\n" 22128 " firstBlock:^(Foo *a) {\n" 22129 " // ...\n" 22130 " int i;\n" 22131 " }\n" 22132 " secondBlock:^(Bar *b) {\n" 22133 " // ...\n" 22134 " int i;\n" 22135 " }\n" 22136 " thirdBlock:^Foo(Bar *b) {\n" 22137 " // ...\n" 22138 " int i;\n" 22139 " }];", 22140 ZeroColumn); 22141 verifyFormat("f(^{\n" 22142 " @autoreleasepool {\n" 22143 " if (a) {\n" 22144 " g();\n" 22145 " }\n" 22146 " }\n" 22147 "});", 22148 ZeroColumn); 22149 verifyFormat("void (^largeBlock)(void) = ^{\n" 22150 " // ...\n" 22151 "};", 22152 ZeroColumn); 22153 22154 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22155 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22156 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22157 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22158 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22159 " int i;\n" 22160 "};", 22161 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22162 } 22163 22164 TEST_F(FormatTest, SupportsCRLF) { 22165 EXPECT_EQ("int a;\r\n" 22166 "int b;\r\n" 22167 "int c;\r\n", 22168 format("int a;\r\n" 22169 " int b;\r\n" 22170 " int c;\r\n", 22171 getLLVMStyle())); 22172 EXPECT_EQ("int a;\r\n" 22173 "int b;\r\n" 22174 "int c;\r\n", 22175 format("int a;\r\n" 22176 " int b;\n" 22177 " int c;\r\n", 22178 getLLVMStyle())); 22179 EXPECT_EQ("int a;\n" 22180 "int b;\n" 22181 "int c;\n", 22182 format("int a;\r\n" 22183 " int b;\n" 22184 " int c;\n", 22185 getLLVMStyle())); 22186 EXPECT_EQ("\"aaaaaaa \"\r\n" 22187 "\"bbbbbbb\";\r\n", 22188 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22189 EXPECT_EQ("#define A \\\r\n" 22190 " b; \\\r\n" 22191 " c; \\\r\n" 22192 " d;\r\n", 22193 format("#define A \\\r\n" 22194 " b; \\\r\n" 22195 " c; d; \r\n", 22196 getGoogleStyle())); 22197 22198 EXPECT_EQ("/*\r\n" 22199 "multi line block comments\r\n" 22200 "should not introduce\r\n" 22201 "an extra carriage return\r\n" 22202 "*/\r\n", 22203 format("/*\r\n" 22204 "multi line block comments\r\n" 22205 "should not introduce\r\n" 22206 "an extra carriage return\r\n" 22207 "*/\r\n")); 22208 EXPECT_EQ("/*\r\n" 22209 "\r\n" 22210 "*/", 22211 format("/*\r\n" 22212 " \r\r\r\n" 22213 "*/")); 22214 22215 FormatStyle style = getLLVMStyle(); 22216 22217 style.DeriveLineEnding = true; 22218 style.UseCRLF = false; 22219 EXPECT_EQ("union FooBarBazQux {\n" 22220 " int foo;\n" 22221 " int bar;\n" 22222 " int baz;\n" 22223 "};", 22224 format("union FooBarBazQux {\r\n" 22225 " int foo;\n" 22226 " int bar;\r\n" 22227 " int baz;\n" 22228 "};", 22229 style)); 22230 style.UseCRLF = true; 22231 EXPECT_EQ("union FooBarBazQux {\r\n" 22232 " int foo;\r\n" 22233 " int bar;\r\n" 22234 " int baz;\r\n" 22235 "};", 22236 format("union FooBarBazQux {\r\n" 22237 " int foo;\n" 22238 " int bar;\r\n" 22239 " int baz;\n" 22240 "};", 22241 style)); 22242 22243 style.DeriveLineEnding = false; 22244 style.UseCRLF = false; 22245 EXPECT_EQ("union FooBarBazQux {\n" 22246 " int foo;\n" 22247 " int bar;\n" 22248 " int baz;\n" 22249 " int qux;\n" 22250 "};", 22251 format("union FooBarBazQux {\r\n" 22252 " int foo;\n" 22253 " int bar;\r\n" 22254 " int baz;\n" 22255 " int qux;\r\n" 22256 "};", 22257 style)); 22258 style.UseCRLF = true; 22259 EXPECT_EQ("union FooBarBazQux {\r\n" 22260 " int foo;\r\n" 22261 " int bar;\r\n" 22262 " int baz;\r\n" 22263 " int qux;\r\n" 22264 "};", 22265 format("union FooBarBazQux {\r\n" 22266 " int foo;\n" 22267 " int bar;\r\n" 22268 " int baz;\n" 22269 " int qux;\n" 22270 "};", 22271 style)); 22272 22273 style.DeriveLineEnding = true; 22274 style.UseCRLF = false; 22275 EXPECT_EQ("union FooBarBazQux {\r\n" 22276 " int foo;\r\n" 22277 " int bar;\r\n" 22278 " int baz;\r\n" 22279 " int qux;\r\n" 22280 "};", 22281 format("union FooBarBazQux {\r\n" 22282 " int foo;\n" 22283 " int bar;\r\n" 22284 " int baz;\n" 22285 " int qux;\r\n" 22286 "};", 22287 style)); 22288 style.UseCRLF = true; 22289 EXPECT_EQ("union FooBarBazQux {\n" 22290 " int foo;\n" 22291 " int bar;\n" 22292 " int baz;\n" 22293 " int qux;\n" 22294 "};", 22295 format("union FooBarBazQux {\r\n" 22296 " int foo;\n" 22297 " int bar;\r\n" 22298 " int baz;\n" 22299 " int qux;\n" 22300 "};", 22301 style)); 22302 } 22303 22304 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22305 verifyFormat("MY_CLASS(C) {\n" 22306 " int i;\n" 22307 " int j;\n" 22308 "};"); 22309 } 22310 22311 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22312 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22313 TwoIndent.ContinuationIndentWidth = 2; 22314 22315 EXPECT_EQ("int i =\n" 22316 " longFunction(\n" 22317 " arg);", 22318 format("int i = longFunction(arg);", TwoIndent)); 22319 22320 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22321 SixIndent.ContinuationIndentWidth = 6; 22322 22323 EXPECT_EQ("int i =\n" 22324 " longFunction(\n" 22325 " arg);", 22326 format("int i = longFunction(arg);", SixIndent)); 22327 } 22328 22329 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22330 FormatStyle Style = getLLVMStyle(); 22331 verifyFormat("int Foo::getter(\n" 22332 " //\n" 22333 ") const {\n" 22334 " return foo;\n" 22335 "}", 22336 Style); 22337 verifyFormat("void Foo::setter(\n" 22338 " //\n" 22339 ") {\n" 22340 " foo = 1;\n" 22341 "}", 22342 Style); 22343 } 22344 22345 TEST_F(FormatTest, SpacesInAngles) { 22346 FormatStyle Spaces = getLLVMStyle(); 22347 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22348 22349 verifyFormat("vector< ::std::string > x1;", Spaces); 22350 verifyFormat("Foo< int, Bar > x2;", Spaces); 22351 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22352 22353 verifyFormat("static_cast< int >(arg);", Spaces); 22354 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22355 verifyFormat("f< int, float >();", Spaces); 22356 verifyFormat("template <> g() {}", Spaces); 22357 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22358 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22359 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22360 Spaces); 22361 22362 Spaces.Standard = FormatStyle::LS_Cpp03; 22363 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22364 verifyFormat("A< A< int > >();", Spaces); 22365 22366 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22367 verifyFormat("A<A<int> >();", Spaces); 22368 22369 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22370 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22371 Spaces); 22372 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22373 Spaces); 22374 22375 verifyFormat("A<A<int> >();", Spaces); 22376 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22377 verifyFormat("A< A< int > >();", Spaces); 22378 22379 Spaces.Standard = FormatStyle::LS_Cpp11; 22380 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22381 verifyFormat("A< A< int > >();", Spaces); 22382 22383 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22384 verifyFormat("vector<::std::string> x4;", Spaces); 22385 verifyFormat("vector<int> x5;", Spaces); 22386 verifyFormat("Foo<int, Bar> x6;", Spaces); 22387 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22388 22389 verifyFormat("A<A<int>>();", Spaces); 22390 22391 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22392 verifyFormat("vector<::std::string> x4;", Spaces); 22393 verifyFormat("vector< ::std::string > x4;", Spaces); 22394 verifyFormat("vector<int> x5;", Spaces); 22395 verifyFormat("vector< int > x5;", Spaces); 22396 verifyFormat("Foo<int, Bar> x6;", Spaces); 22397 verifyFormat("Foo< int, Bar > x6;", Spaces); 22398 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22399 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22400 22401 verifyFormat("A<A<int>>();", Spaces); 22402 verifyFormat("A< A< int > >();", Spaces); 22403 verifyFormat("A<A<int > >();", Spaces); 22404 verifyFormat("A< A< int>>();", Spaces); 22405 22406 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22407 verifyFormat("// clang-format off\n" 22408 "foo<<<1, 1>>>();\n" 22409 "// clang-format on\n", 22410 Spaces); 22411 verifyFormat("// clang-format off\n" 22412 "foo< < <1, 1> > >();\n" 22413 "// clang-format on\n", 22414 Spaces); 22415 } 22416 22417 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22418 FormatStyle Style = getLLVMStyle(); 22419 Style.SpaceAfterTemplateKeyword = false; 22420 verifyFormat("template<int> void foo();", Style); 22421 } 22422 22423 TEST_F(FormatTest, TripleAngleBrackets) { 22424 verifyFormat("f<<<1, 1>>>();"); 22425 verifyFormat("f<<<1, 1, 1, s>>>();"); 22426 verifyFormat("f<<<a, b, c, d>>>();"); 22427 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22428 verifyFormat("f<param><<<1, 1>>>();"); 22429 verifyFormat("f<1><<<1, 1>>>();"); 22430 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22431 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22432 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22433 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22434 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22435 } 22436 22437 TEST_F(FormatTest, MergeLessLessAtEnd) { 22438 verifyFormat("<<"); 22439 EXPECT_EQ("< < <", format("\\\n<<<")); 22440 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22441 "aaallvm::outs() <<"); 22442 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22443 "aaaallvm::outs()\n <<"); 22444 } 22445 22446 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22447 std::string code = "#if A\n" 22448 "#if B\n" 22449 "a.\n" 22450 "#endif\n" 22451 " a = 1;\n" 22452 "#else\n" 22453 "#endif\n" 22454 "#if C\n" 22455 "#else\n" 22456 "#endif\n"; 22457 EXPECT_EQ(code, format(code)); 22458 } 22459 22460 TEST_F(FormatTest, HandleConflictMarkers) { 22461 // Git/SVN conflict markers. 22462 EXPECT_EQ("int a;\n" 22463 "void f() {\n" 22464 " callme(some(parameter1,\n" 22465 "<<<<<<< text by the vcs\n" 22466 " parameter2),\n" 22467 "||||||| text by the vcs\n" 22468 " parameter2),\n" 22469 " parameter3,\n" 22470 "======= text by the vcs\n" 22471 " parameter2, parameter3),\n" 22472 ">>>>>>> text by the vcs\n" 22473 " otherparameter);\n", 22474 format("int a;\n" 22475 "void f() {\n" 22476 " callme(some(parameter1,\n" 22477 "<<<<<<< text by the vcs\n" 22478 " parameter2),\n" 22479 "||||||| text by the vcs\n" 22480 " parameter2),\n" 22481 " parameter3,\n" 22482 "======= text by the vcs\n" 22483 " parameter2,\n" 22484 " parameter3),\n" 22485 ">>>>>>> text by the vcs\n" 22486 " otherparameter);\n")); 22487 22488 // Perforce markers. 22489 EXPECT_EQ("void f() {\n" 22490 " function(\n" 22491 ">>>> text by the vcs\n" 22492 " parameter,\n" 22493 "==== text by the vcs\n" 22494 " parameter,\n" 22495 "==== text by the vcs\n" 22496 " parameter,\n" 22497 "<<<< text by the vcs\n" 22498 " parameter);\n", 22499 format("void f() {\n" 22500 " function(\n" 22501 ">>>> text by the vcs\n" 22502 " parameter,\n" 22503 "==== text by the vcs\n" 22504 " parameter,\n" 22505 "==== text by the vcs\n" 22506 " parameter,\n" 22507 "<<<< text by the vcs\n" 22508 " parameter);\n")); 22509 22510 EXPECT_EQ("<<<<<<<\n" 22511 "|||||||\n" 22512 "=======\n" 22513 ">>>>>>>", 22514 format("<<<<<<<\n" 22515 "|||||||\n" 22516 "=======\n" 22517 ">>>>>>>")); 22518 22519 EXPECT_EQ("<<<<<<<\n" 22520 "|||||||\n" 22521 "int i;\n" 22522 "=======\n" 22523 ">>>>>>>", 22524 format("<<<<<<<\n" 22525 "|||||||\n" 22526 "int i;\n" 22527 "=======\n" 22528 ">>>>>>>")); 22529 22530 // FIXME: Handle parsing of macros around conflict markers correctly: 22531 EXPECT_EQ("#define Macro \\\n" 22532 "<<<<<<<\n" 22533 "Something \\\n" 22534 "|||||||\n" 22535 "Else \\\n" 22536 "=======\n" 22537 "Other \\\n" 22538 ">>>>>>>\n" 22539 " End int i;\n", 22540 format("#define Macro \\\n" 22541 "<<<<<<<\n" 22542 " Something \\\n" 22543 "|||||||\n" 22544 " Else \\\n" 22545 "=======\n" 22546 " Other \\\n" 22547 ">>>>>>>\n" 22548 " End\n" 22549 "int i;\n")); 22550 22551 verifyFormat(R"(==== 22552 #ifdef A 22553 a 22554 #else 22555 b 22556 #endif 22557 )"); 22558 } 22559 22560 TEST_F(FormatTest, DisableRegions) { 22561 EXPECT_EQ("int i;\n" 22562 "// clang-format off\n" 22563 " int j;\n" 22564 "// clang-format on\n" 22565 "int k;", 22566 format(" int i;\n" 22567 " // clang-format off\n" 22568 " int j;\n" 22569 " // clang-format on\n" 22570 " int k;")); 22571 EXPECT_EQ("int i;\n" 22572 "/* clang-format off */\n" 22573 " int j;\n" 22574 "/* clang-format on */\n" 22575 "int k;", 22576 format(" int i;\n" 22577 " /* clang-format off */\n" 22578 " int j;\n" 22579 " /* clang-format on */\n" 22580 " int k;")); 22581 22582 // Don't reflow comments within disabled regions. 22583 EXPECT_EQ("// clang-format off\n" 22584 "// long long long long long long line\n" 22585 "/* clang-format on */\n" 22586 "/* long long long\n" 22587 " * long long long\n" 22588 " * line */\n" 22589 "int i;\n" 22590 "/* clang-format off */\n" 22591 "/* long long long long long long line */\n", 22592 format("// clang-format off\n" 22593 "// long long long long long long line\n" 22594 "/* clang-format on */\n" 22595 "/* long long long long long long line */\n" 22596 "int i;\n" 22597 "/* clang-format off */\n" 22598 "/* long long long long long long line */\n", 22599 getLLVMStyleWithColumns(20))); 22600 } 22601 22602 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22603 format("? ) ="); 22604 verifyNoCrash("#define a\\\n /**/}"); 22605 } 22606 22607 TEST_F(FormatTest, FormatsTableGenCode) { 22608 FormatStyle Style = getLLVMStyle(); 22609 Style.Language = FormatStyle::LK_TableGen; 22610 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22611 } 22612 22613 TEST_F(FormatTest, ArrayOfTemplates) { 22614 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22615 format("auto a = new unique_ptr<int > [ 10];")); 22616 22617 FormatStyle Spaces = getLLVMStyle(); 22618 Spaces.SpacesInSquareBrackets = true; 22619 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22620 format("auto a = new unique_ptr<int > [10];", Spaces)); 22621 } 22622 22623 TEST_F(FormatTest, ArrayAsTemplateType) { 22624 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22625 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22626 22627 FormatStyle Spaces = getLLVMStyle(); 22628 Spaces.SpacesInSquareBrackets = true; 22629 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22630 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22631 } 22632 22633 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22634 22635 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22636 llvm::vfs::InMemoryFileSystem FS; 22637 auto Style1 = getStyle("file", "", "Google", "", &FS); 22638 ASSERT_TRUE((bool)Style1); 22639 ASSERT_EQ(*Style1, getGoogleStyle()); 22640 } 22641 22642 TEST(FormatStyle, GetStyleOfFile) { 22643 llvm::vfs::InMemoryFileSystem FS; 22644 // Test 1: format file in the same directory. 22645 ASSERT_TRUE( 22646 FS.addFile("/a/.clang-format", 0, 22647 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22648 ASSERT_TRUE( 22649 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22650 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22651 ASSERT_TRUE((bool)Style1); 22652 ASSERT_EQ(*Style1, getLLVMStyle()); 22653 22654 // Test 2.1: fallback to default. 22655 ASSERT_TRUE( 22656 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22657 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22658 ASSERT_TRUE((bool)Style2); 22659 ASSERT_EQ(*Style2, getMozillaStyle()); 22660 22661 // Test 2.2: no format on 'none' fallback style. 22662 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22663 ASSERT_TRUE((bool)Style2); 22664 ASSERT_EQ(*Style2, getNoStyle()); 22665 22666 // Test 2.3: format if config is found with no based style while fallback is 22667 // 'none'. 22668 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22669 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22670 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22671 ASSERT_TRUE((bool)Style2); 22672 ASSERT_EQ(*Style2, getLLVMStyle()); 22673 22674 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22675 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22676 ASSERT_TRUE((bool)Style2); 22677 ASSERT_EQ(*Style2, getLLVMStyle()); 22678 22679 // Test 3: format file in parent directory. 22680 ASSERT_TRUE( 22681 FS.addFile("/c/.clang-format", 0, 22682 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22683 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22684 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22685 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22686 ASSERT_TRUE((bool)Style3); 22687 ASSERT_EQ(*Style3, getGoogleStyle()); 22688 22689 // Test 4: error on invalid fallback style 22690 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22691 ASSERT_FALSE((bool)Style4); 22692 llvm::consumeError(Style4.takeError()); 22693 22694 // Test 5: error on invalid yaml on command line 22695 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22696 ASSERT_FALSE((bool)Style5); 22697 llvm::consumeError(Style5.takeError()); 22698 22699 // Test 6: error on invalid style 22700 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22701 ASSERT_FALSE((bool)Style6); 22702 llvm::consumeError(Style6.takeError()); 22703 22704 // Test 7: found config file, error on parsing it 22705 ASSERT_TRUE( 22706 FS.addFile("/d/.clang-format", 0, 22707 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22708 "InvalidKey: InvalidValue"))); 22709 ASSERT_TRUE( 22710 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22711 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22712 ASSERT_FALSE((bool)Style7a); 22713 llvm::consumeError(Style7a.takeError()); 22714 22715 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22716 ASSERT_TRUE((bool)Style7b); 22717 22718 // Test 8: inferred per-language defaults apply. 22719 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22720 ASSERT_TRUE((bool)StyleTd); 22721 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22722 22723 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22724 // fallback style. 22725 ASSERT_TRUE(FS.addFile( 22726 "/e/sub/.clang-format", 0, 22727 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22728 "ColumnLimit: 20"))); 22729 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22730 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22731 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22732 ASSERT_TRUE(static_cast<bool>(Style9)); 22733 ASSERT_EQ(*Style9, [] { 22734 auto Style = getNoStyle(); 22735 Style.ColumnLimit = 20; 22736 return Style; 22737 }()); 22738 22739 // Test 9.1.2: propagate more than one level with no parent file. 22740 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22741 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22742 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22743 llvm::MemoryBuffer::getMemBuffer( 22744 "BasedOnStyle: InheritParentConfig\n" 22745 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22746 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22747 22748 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22749 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22750 ASSERT_TRUE(static_cast<bool>(Style9)); 22751 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22752 auto Style = getNoStyle(); 22753 Style.ColumnLimit = 20; 22754 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22755 return Style; 22756 }()); 22757 22758 // Test 9.2: with LLVM fallback style 22759 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22760 ASSERT_TRUE(static_cast<bool>(Style9)); 22761 ASSERT_EQ(*Style9, [] { 22762 auto Style = getLLVMStyle(); 22763 Style.ColumnLimit = 20; 22764 return Style; 22765 }()); 22766 22767 // Test 9.3: with a parent file 22768 ASSERT_TRUE( 22769 FS.addFile("/e/.clang-format", 0, 22770 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22771 "UseTab: Always"))); 22772 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22773 ASSERT_TRUE(static_cast<bool>(Style9)); 22774 ASSERT_EQ(*Style9, [] { 22775 auto Style = getGoogleStyle(); 22776 Style.ColumnLimit = 20; 22777 Style.UseTab = FormatStyle::UT_Always; 22778 return Style; 22779 }()); 22780 22781 // Test 9.4: propagate more than one level with a parent file. 22782 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22783 auto Style = getGoogleStyle(); 22784 Style.ColumnLimit = 20; 22785 Style.UseTab = FormatStyle::UT_Always; 22786 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22787 return Style; 22788 }(); 22789 22790 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22791 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22792 ASSERT_TRUE(static_cast<bool>(Style9)); 22793 ASSERT_EQ(*Style9, SubSubStyle); 22794 22795 // Test 9.5: use InheritParentConfig as style name 22796 Style9 = 22797 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22798 ASSERT_TRUE(static_cast<bool>(Style9)); 22799 ASSERT_EQ(*Style9, SubSubStyle); 22800 22801 // Test 9.6: use command line style with inheritance 22802 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22803 "none", "", &FS); 22804 ASSERT_TRUE(static_cast<bool>(Style9)); 22805 ASSERT_EQ(*Style9, SubSubStyle); 22806 22807 // Test 9.7: use command line style with inheritance and own config 22808 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22809 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22810 "/e/sub/code.cpp", "none", "", &FS); 22811 ASSERT_TRUE(static_cast<bool>(Style9)); 22812 ASSERT_EQ(*Style9, SubSubStyle); 22813 22814 // Test 9.8: use inheritance from a file without BasedOnStyle 22815 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22816 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22817 ASSERT_TRUE( 22818 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22819 llvm::MemoryBuffer::getMemBuffer( 22820 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22821 // Make sure we do not use the fallback style 22822 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22823 ASSERT_TRUE(static_cast<bool>(Style9)); 22824 ASSERT_EQ(*Style9, [] { 22825 auto Style = getLLVMStyle(); 22826 Style.ColumnLimit = 123; 22827 return Style; 22828 }()); 22829 22830 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22831 ASSERT_TRUE(static_cast<bool>(Style9)); 22832 ASSERT_EQ(*Style9, [] { 22833 auto Style = getLLVMStyle(); 22834 Style.ColumnLimit = 123; 22835 Style.IndentWidth = 7; 22836 return Style; 22837 }()); 22838 22839 // Test 9.9: use inheritance from a specific config file. 22840 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22841 "none", "", &FS); 22842 ASSERT_TRUE(static_cast<bool>(Style9)); 22843 ASSERT_EQ(*Style9, SubSubStyle); 22844 } 22845 22846 TEST(FormatStyle, GetStyleOfSpecificFile) { 22847 llvm::vfs::InMemoryFileSystem FS; 22848 // Specify absolute path to a format file in a parent directory. 22849 ASSERT_TRUE( 22850 FS.addFile("/e/.clang-format", 0, 22851 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22852 ASSERT_TRUE( 22853 FS.addFile("/e/explicit.clang-format", 0, 22854 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22855 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22856 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22857 auto Style = getStyle("file:/e/explicit.clang-format", 22858 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22859 ASSERT_TRUE(static_cast<bool>(Style)); 22860 ASSERT_EQ(*Style, getGoogleStyle()); 22861 22862 // Specify relative path to a format file. 22863 ASSERT_TRUE( 22864 FS.addFile("../../e/explicit.clang-format", 0, 22865 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22866 Style = getStyle("file:../../e/explicit.clang-format", 22867 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22868 ASSERT_TRUE(static_cast<bool>(Style)); 22869 ASSERT_EQ(*Style, getGoogleStyle()); 22870 22871 // Specify path to a format file that does not exist. 22872 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22873 "LLVM", "", &FS); 22874 ASSERT_FALSE(static_cast<bool>(Style)); 22875 llvm::consumeError(Style.takeError()); 22876 22877 // Specify path to a file on the filesystem. 22878 SmallString<128> FormatFilePath; 22879 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22880 "FormatFileTest", "tpl", FormatFilePath); 22881 EXPECT_FALSE((bool)ECF); 22882 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22883 EXPECT_FALSE((bool)ECF); 22884 FormatFileTest << "BasedOnStyle: Google\n"; 22885 FormatFileTest.close(); 22886 22887 SmallString<128> TestFilePath; 22888 std::error_code ECT = 22889 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22890 EXPECT_FALSE((bool)ECT); 22891 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22892 CodeFileTest << "int i;\n"; 22893 CodeFileTest.close(); 22894 22895 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22896 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22897 22898 llvm::sys::fs::remove(FormatFilePath.c_str()); 22899 llvm::sys::fs::remove(TestFilePath.c_str()); 22900 ASSERT_TRUE(static_cast<bool>(Style)); 22901 ASSERT_EQ(*Style, getGoogleStyle()); 22902 } 22903 22904 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22905 // Column limit is 20. 22906 std::string Code = "Type *a =\n" 22907 " new Type();\n" 22908 "g(iiiii, 0, jjjjj,\n" 22909 " 0, kkkkk, 0, mm);\n" 22910 "int bad = format ;"; 22911 std::string Expected = "auto a = new Type();\n" 22912 "g(iiiii, nullptr,\n" 22913 " jjjjj, nullptr,\n" 22914 " kkkkk, nullptr,\n" 22915 " mm);\n" 22916 "int bad = format ;"; 22917 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22918 tooling::Replacements Replaces = toReplacements( 22919 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22920 "auto "), 22921 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22922 "nullptr"), 22923 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22924 "nullptr"), 22925 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22926 "nullptr")}); 22927 22928 FormatStyle Style = getLLVMStyle(); 22929 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22930 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22931 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22932 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22933 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22934 EXPECT_TRUE(static_cast<bool>(Result)); 22935 EXPECT_EQ(Expected, *Result); 22936 } 22937 22938 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22939 std::string Code = "#include \"a.h\"\n" 22940 "#include \"c.h\"\n" 22941 "\n" 22942 "int main() {\n" 22943 " return 0;\n" 22944 "}"; 22945 std::string Expected = "#include \"a.h\"\n" 22946 "#include \"b.h\"\n" 22947 "#include \"c.h\"\n" 22948 "\n" 22949 "int main() {\n" 22950 " return 0;\n" 22951 "}"; 22952 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22953 tooling::Replacements Replaces = toReplacements( 22954 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22955 "#include \"b.h\"\n")}); 22956 22957 FormatStyle Style = getLLVMStyle(); 22958 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22959 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22960 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22961 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22962 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22963 EXPECT_TRUE(static_cast<bool>(Result)); 22964 EXPECT_EQ(Expected, *Result); 22965 } 22966 22967 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22968 EXPECT_EQ("using std::cin;\n" 22969 "using std::cout;", 22970 format("using std::cout;\n" 22971 "using std::cin;", 22972 getGoogleStyle())); 22973 } 22974 22975 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22976 FormatStyle Style = getLLVMStyle(); 22977 Style.Standard = FormatStyle::LS_Cpp03; 22978 // cpp03 recognize this string as identifier u8 and literal character 'a' 22979 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22980 } 22981 22982 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22983 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22984 // all modes, including C++11, C++14 and C++17 22985 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22986 } 22987 22988 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22989 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22990 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22991 } 22992 22993 TEST_F(FormatTest, StructuredBindings) { 22994 // Structured bindings is a C++17 feature. 22995 // all modes, including C++11, C++14 and C++17 22996 verifyFormat("auto [a, b] = f();"); 22997 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22998 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22999 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 23000 EXPECT_EQ("auto const volatile [a, b] = f();", 23001 format("auto const volatile[a, b] = f();")); 23002 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 23003 EXPECT_EQ("auto &[a, b, c] = f();", 23004 format("auto &[ a , b,c ] = f();")); 23005 EXPECT_EQ("auto &&[a, b, c] = f();", 23006 format("auto &&[ a , b,c ] = f();")); 23007 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 23008 EXPECT_EQ("auto const volatile &&[a, b] = f();", 23009 format("auto const volatile &&[a, b] = f();")); 23010 EXPECT_EQ("auto const &&[a, b] = f();", 23011 format("auto const && [a, b] = f();")); 23012 EXPECT_EQ("const auto &[a, b] = f();", 23013 format("const auto & [a, b] = f();")); 23014 EXPECT_EQ("const auto volatile &&[a, b] = f();", 23015 format("const auto volatile &&[a, b] = f();")); 23016 EXPECT_EQ("volatile const auto &&[a, b] = f();", 23017 format("volatile const auto &&[a, b] = f();")); 23018 EXPECT_EQ("const auto &&[a, b] = f();", 23019 format("const auto && [a, b] = f();")); 23020 23021 // Make sure we don't mistake structured bindings for lambdas. 23022 FormatStyle PointerMiddle = getLLVMStyle(); 23023 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 23024 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 23025 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 23026 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 23027 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 23028 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 23029 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 23030 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 23031 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 23032 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 23033 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 23034 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 23035 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 23036 23037 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 23038 format("for (const auto && [a, b] : some_range) {\n}")); 23039 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 23040 format("for (const auto & [a, b] : some_range) {\n}")); 23041 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 23042 format("for (const auto[a, b] : some_range) {\n}")); 23043 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 23044 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 23045 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 23046 EXPECT_EQ("auto const &[x, y](expr);", 23047 format("auto const & [x,y] (expr);")); 23048 EXPECT_EQ("auto const &&[x, y](expr);", 23049 format("auto const && [x,y] (expr);")); 23050 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 23051 EXPECT_EQ("auto const &[x, y]{expr};", 23052 format("auto const & [x,y] {expr};")); 23053 EXPECT_EQ("auto const &&[x, y]{expr};", 23054 format("auto const && [x,y] {expr};")); 23055 23056 FormatStyle Spaces = getLLVMStyle(); 23057 Spaces.SpacesInSquareBrackets = true; 23058 verifyFormat("auto [ a, b ] = f();", Spaces); 23059 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23060 verifyFormat("auto &[ a, b ] = f();", Spaces); 23061 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23062 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23063 } 23064 23065 TEST_F(FormatTest, FileAndCode) { 23066 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23067 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23068 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23069 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23070 EXPECT_EQ(FormatStyle::LK_ObjC, 23071 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23072 EXPECT_EQ( 23073 FormatStyle::LK_ObjC, 23074 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23075 EXPECT_EQ(FormatStyle::LK_ObjC, 23076 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23077 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23078 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23079 EXPECT_EQ(FormatStyle::LK_ObjC, 23080 guessLanguage("foo", "@interface Foo\n@end\n")); 23081 EXPECT_EQ(FormatStyle::LK_ObjC, 23082 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23083 EXPECT_EQ( 23084 FormatStyle::LK_ObjC, 23085 guessLanguage("foo.h", 23086 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23087 EXPECT_EQ( 23088 FormatStyle::LK_Cpp, 23089 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23090 // Only one of the two preprocessor regions has ObjC-like code. 23091 EXPECT_EQ(FormatStyle::LK_ObjC, 23092 guessLanguage("foo.h", "#if A\n" 23093 "#define B() C\n" 23094 "#else\n" 23095 "#define B() [NSString a:@\"\"]\n" 23096 "#endif\n")); 23097 } 23098 23099 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23100 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23101 EXPECT_EQ(FormatStyle::LK_ObjC, 23102 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23103 EXPECT_EQ(FormatStyle::LK_Cpp, 23104 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23105 EXPECT_EQ( 23106 FormatStyle::LK_Cpp, 23107 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23108 EXPECT_EQ(FormatStyle::LK_ObjC, 23109 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23110 EXPECT_EQ(FormatStyle::LK_Cpp, 23111 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23112 EXPECT_EQ(FormatStyle::LK_ObjC, 23113 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23114 EXPECT_EQ(FormatStyle::LK_Cpp, 23115 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23116 EXPECT_EQ(FormatStyle::LK_Cpp, 23117 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23118 EXPECT_EQ(FormatStyle::LK_ObjC, 23119 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23120 EXPECT_EQ(FormatStyle::LK_Cpp, 23121 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23122 EXPECT_EQ( 23123 FormatStyle::LK_Cpp, 23124 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23125 EXPECT_EQ( 23126 FormatStyle::LK_Cpp, 23127 guessLanguage("foo.h", 23128 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23129 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23130 } 23131 23132 TEST_F(FormatTest, GuessLanguageWithCaret) { 23133 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23134 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23135 EXPECT_EQ(FormatStyle::LK_ObjC, 23136 guessLanguage("foo.h", "int(^)(char, float);")); 23137 EXPECT_EQ(FormatStyle::LK_ObjC, 23138 guessLanguage("foo.h", "int(^foo)(char, float);")); 23139 EXPECT_EQ(FormatStyle::LK_ObjC, 23140 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23141 EXPECT_EQ(FormatStyle::LK_ObjC, 23142 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23143 EXPECT_EQ( 23144 FormatStyle::LK_ObjC, 23145 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23146 } 23147 23148 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23149 EXPECT_EQ(FormatStyle::LK_Cpp, 23150 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23151 EXPECT_EQ(FormatStyle::LK_Cpp, 23152 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23153 EXPECT_EQ(FormatStyle::LK_Cpp, 23154 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23155 } 23156 23157 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23158 // ASM symbolic names are identifiers that must be surrounded by [] without 23159 // space in between: 23160 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23161 23162 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23163 verifyFormat(R"(// 23164 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23165 )"); 23166 23167 // A list of several ASM symbolic names. 23168 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23169 23170 // ASM symbolic names in inline ASM with inputs and outputs. 23171 verifyFormat(R"(// 23172 asm("cmoveq %1, %2, %[result]" 23173 : [result] "=r"(result) 23174 : "r"(test), "r"(new), "[result]"(old)); 23175 )"); 23176 23177 // ASM symbolic names in inline ASM with no outputs. 23178 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23179 } 23180 23181 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23182 EXPECT_EQ(FormatStyle::LK_Cpp, 23183 guessLanguage("foo.h", "void f() {\n" 23184 " asm (\"mov %[e], %[d]\"\n" 23185 " : [d] \"=rm\" (d)\n" 23186 " [e] \"rm\" (*e));\n" 23187 "}")); 23188 EXPECT_EQ(FormatStyle::LK_Cpp, 23189 guessLanguage("foo.h", "void f() {\n" 23190 " _asm (\"mov %[e], %[d]\"\n" 23191 " : [d] \"=rm\" (d)\n" 23192 " [e] \"rm\" (*e));\n" 23193 "}")); 23194 EXPECT_EQ(FormatStyle::LK_Cpp, 23195 guessLanguage("foo.h", "void f() {\n" 23196 " __asm (\"mov %[e], %[d]\"\n" 23197 " : [d] \"=rm\" (d)\n" 23198 " [e] \"rm\" (*e));\n" 23199 "}")); 23200 EXPECT_EQ(FormatStyle::LK_Cpp, 23201 guessLanguage("foo.h", "void f() {\n" 23202 " __asm__ (\"mov %[e], %[d]\"\n" 23203 " : [d] \"=rm\" (d)\n" 23204 " [e] \"rm\" (*e));\n" 23205 "}")); 23206 EXPECT_EQ(FormatStyle::LK_Cpp, 23207 guessLanguage("foo.h", "void f() {\n" 23208 " asm (\"mov %[e], %[d]\"\n" 23209 " : [d] \"=rm\" (d),\n" 23210 " [e] \"rm\" (*e));\n" 23211 "}")); 23212 EXPECT_EQ(FormatStyle::LK_Cpp, 23213 guessLanguage("foo.h", "void f() {\n" 23214 " asm volatile (\"mov %[e], %[d]\"\n" 23215 " : [d] \"=rm\" (d)\n" 23216 " [e] \"rm\" (*e));\n" 23217 "}")); 23218 } 23219 23220 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23221 EXPECT_EQ(FormatStyle::LK_Cpp, 23222 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23223 EXPECT_EQ(FormatStyle::LK_ObjC, 23224 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23225 EXPECT_EQ( 23226 FormatStyle::LK_Cpp, 23227 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23228 EXPECT_EQ( 23229 FormatStyle::LK_ObjC, 23230 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23231 } 23232 23233 TEST_F(FormatTest, TypenameMacros) { 23234 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23235 23236 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23237 FormatStyle Google = getGoogleStyleWithColumns(0); 23238 Google.TypenameMacros = TypenameMacros; 23239 verifyFormat("struct foo {\n" 23240 " int bar;\n" 23241 " TAILQ_ENTRY(a) bleh;\n" 23242 "};", 23243 Google); 23244 23245 FormatStyle Macros = getLLVMStyle(); 23246 Macros.TypenameMacros = TypenameMacros; 23247 23248 verifyFormat("STACK_OF(int) a;", Macros); 23249 verifyFormat("STACK_OF(int) *a;", Macros); 23250 verifyFormat("STACK_OF(int const *) *a;", Macros); 23251 verifyFormat("STACK_OF(int *const) *a;", Macros); 23252 verifyFormat("STACK_OF(int, string) a;", Macros); 23253 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23254 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23255 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23256 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23257 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23258 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23259 23260 Macros.PointerAlignment = FormatStyle::PAS_Left; 23261 verifyFormat("STACK_OF(int)* a;", Macros); 23262 verifyFormat("STACK_OF(int*)* a;", Macros); 23263 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23264 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23265 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23266 } 23267 23268 TEST_F(FormatTest, AtomicQualifier) { 23269 // Check that we treate _Atomic as a type and not a function call 23270 FormatStyle Google = getGoogleStyleWithColumns(0); 23271 verifyFormat("struct foo {\n" 23272 " int a1;\n" 23273 " _Atomic(a) a2;\n" 23274 " _Atomic(_Atomic(int) *const) a3;\n" 23275 "};", 23276 Google); 23277 verifyFormat("_Atomic(uint64_t) a;"); 23278 verifyFormat("_Atomic(uint64_t) *a;"); 23279 verifyFormat("_Atomic(uint64_t const *) *a;"); 23280 verifyFormat("_Atomic(uint64_t *const) *a;"); 23281 verifyFormat("_Atomic(const uint64_t *) *a;"); 23282 verifyFormat("_Atomic(uint64_t) a;"); 23283 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23284 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23285 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23286 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23287 23288 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23289 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23290 FormatStyle Style = getLLVMStyle(); 23291 Style.PointerAlignment = FormatStyle::PAS_Left; 23292 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23293 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23294 verifyFormat("_Atomic(int)* a;", Style); 23295 verifyFormat("_Atomic(int*)* a;", Style); 23296 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23297 23298 Style.SpacesInCStyleCastParentheses = true; 23299 Style.SpacesInParentheses = false; 23300 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23301 Style.SpacesInCStyleCastParentheses = false; 23302 Style.SpacesInParentheses = true; 23303 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23304 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23305 } 23306 23307 TEST_F(FormatTest, AmbersandInLamda) { 23308 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23309 FormatStyle AlignStyle = getLLVMStyle(); 23310 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23311 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23312 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23313 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23314 } 23315 23316 TEST_F(FormatTest, SpacesInConditionalStatement) { 23317 FormatStyle Spaces = getLLVMStyle(); 23318 Spaces.IfMacros.clear(); 23319 Spaces.IfMacros.push_back("MYIF"); 23320 Spaces.SpacesInConditionalStatement = true; 23321 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23322 verifyFormat("if ( !a )\n return;", Spaces); 23323 verifyFormat("if ( a )\n return;", Spaces); 23324 verifyFormat("if constexpr ( a )\n return;", Spaces); 23325 verifyFormat("MYIF ( a )\n return;", Spaces); 23326 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23327 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23328 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23329 verifyFormat("while ( a )\n return;", Spaces); 23330 verifyFormat("while ( (a && b) )\n return;", Spaces); 23331 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23332 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23333 // Check that space on the left of "::" is inserted as expected at beginning 23334 // of condition. 23335 verifyFormat("while ( ::func() )\n return;", Spaces); 23336 23337 // Check impact of ControlStatementsExceptControlMacros is honored. 23338 Spaces.SpaceBeforeParens = 23339 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23340 verifyFormat("MYIF( a )\n return;", Spaces); 23341 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23342 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23343 } 23344 23345 TEST_F(FormatTest, AlternativeOperators) { 23346 // Test case for ensuring alternate operators are not 23347 // combined with their right most neighbour. 23348 verifyFormat("int a and b;"); 23349 verifyFormat("int a and_eq b;"); 23350 verifyFormat("int a bitand b;"); 23351 verifyFormat("int a bitor b;"); 23352 verifyFormat("int a compl b;"); 23353 verifyFormat("int a not b;"); 23354 verifyFormat("int a not_eq b;"); 23355 verifyFormat("int a or b;"); 23356 verifyFormat("int a xor b;"); 23357 verifyFormat("int a xor_eq b;"); 23358 verifyFormat("return this not_eq bitand other;"); 23359 verifyFormat("bool operator not_eq(const X bitand other)"); 23360 23361 verifyFormat("int a and 5;"); 23362 verifyFormat("int a and_eq 5;"); 23363 verifyFormat("int a bitand 5;"); 23364 verifyFormat("int a bitor 5;"); 23365 verifyFormat("int a compl 5;"); 23366 verifyFormat("int a not 5;"); 23367 verifyFormat("int a not_eq 5;"); 23368 verifyFormat("int a or 5;"); 23369 verifyFormat("int a xor 5;"); 23370 verifyFormat("int a xor_eq 5;"); 23371 23372 verifyFormat("int a compl(5);"); 23373 verifyFormat("int a not(5);"); 23374 23375 /* FIXME handle alternate tokens 23376 * https://en.cppreference.com/w/cpp/language/operator_alternative 23377 // alternative tokens 23378 verifyFormat("compl foo();"); // ~foo(); 23379 verifyFormat("foo() <%%>;"); // foo(); 23380 verifyFormat("void foo() <%%>;"); // void foo(){} 23381 verifyFormat("int a <:1:>;"); // int a[1];[ 23382 verifyFormat("%:define ABC abc"); // #define ABC abc 23383 verifyFormat("%:%:"); // ## 23384 */ 23385 } 23386 23387 TEST_F(FormatTest, STLWhileNotDefineChed) { 23388 verifyFormat("#if defined(while)\n" 23389 "#define while EMIT WARNING C4005\n" 23390 "#endif // while"); 23391 } 23392 23393 TEST_F(FormatTest, OperatorSpacing) { 23394 FormatStyle Style = getLLVMStyle(); 23395 Style.PointerAlignment = FormatStyle::PAS_Right; 23396 verifyFormat("Foo::operator*();", Style); 23397 verifyFormat("Foo::operator void *();", Style); 23398 verifyFormat("Foo::operator void **();", Style); 23399 verifyFormat("Foo::operator void *&();", Style); 23400 verifyFormat("Foo::operator void *&&();", Style); 23401 verifyFormat("Foo::operator void const *();", Style); 23402 verifyFormat("Foo::operator void const **();", Style); 23403 verifyFormat("Foo::operator void const *&();", Style); 23404 verifyFormat("Foo::operator void const *&&();", Style); 23405 verifyFormat("Foo::operator()(void *);", Style); 23406 verifyFormat("Foo::operator*(void *);", Style); 23407 verifyFormat("Foo::operator*();", Style); 23408 verifyFormat("Foo::operator**();", Style); 23409 verifyFormat("Foo::operator&();", Style); 23410 verifyFormat("Foo::operator<int> *();", Style); 23411 verifyFormat("Foo::operator<Foo> *();", Style); 23412 verifyFormat("Foo::operator<int> **();", Style); 23413 verifyFormat("Foo::operator<Foo> **();", Style); 23414 verifyFormat("Foo::operator<int> &();", Style); 23415 verifyFormat("Foo::operator<Foo> &();", Style); 23416 verifyFormat("Foo::operator<int> &&();", Style); 23417 verifyFormat("Foo::operator<Foo> &&();", Style); 23418 verifyFormat("Foo::operator<int> *&();", Style); 23419 verifyFormat("Foo::operator<Foo> *&();", Style); 23420 verifyFormat("Foo::operator<int> *&&();", Style); 23421 verifyFormat("Foo::operator<Foo> *&&();", Style); 23422 verifyFormat("operator*(int (*)(), class Foo);", Style); 23423 23424 verifyFormat("Foo::operator&();", Style); 23425 verifyFormat("Foo::operator void &();", 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("operator&(int (&)(), class Foo);", Style); 23431 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23432 23433 verifyFormat("Foo::operator&&();", Style); 23434 verifyFormat("Foo::operator**();", Style); 23435 verifyFormat("Foo::operator void &&();", Style); 23436 verifyFormat("Foo::operator void const &&();", Style); 23437 verifyFormat("Foo::operator()(void &&);", Style); 23438 verifyFormat("Foo::operator&&(void &&);", Style); 23439 verifyFormat("Foo::operator&&();", Style); 23440 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23441 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23442 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23443 Style); 23444 verifyFormat("operator void **()", Style); 23445 verifyFormat("operator const FooRight<Object> &()", Style); 23446 verifyFormat("operator const FooRight<Object> *()", Style); 23447 verifyFormat("operator const FooRight<Object> **()", Style); 23448 verifyFormat("operator const FooRight<Object> *&()", Style); 23449 verifyFormat("operator const FooRight<Object> *&&()", Style); 23450 23451 Style.PointerAlignment = FormatStyle::PAS_Left; 23452 verifyFormat("Foo::operator*();", Style); 23453 verifyFormat("Foo::operator**();", Style); 23454 verifyFormat("Foo::operator void*();", Style); 23455 verifyFormat("Foo::operator void**();", Style); 23456 verifyFormat("Foo::operator void*&();", Style); 23457 verifyFormat("Foo::operator void*&&();", Style); 23458 verifyFormat("Foo::operator void const*();", Style); 23459 verifyFormat("Foo::operator void const**();", Style); 23460 verifyFormat("Foo::operator void const*&();", Style); 23461 verifyFormat("Foo::operator void const*&&();", Style); 23462 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23463 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23464 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23465 verifyFormat("Foo::operator()(void*);", Style); 23466 verifyFormat("Foo::operator*(void*);", Style); 23467 verifyFormat("Foo::operator*();", Style); 23468 verifyFormat("Foo::operator<int>*();", Style); 23469 verifyFormat("Foo::operator<Foo>*();", Style); 23470 verifyFormat("Foo::operator<int>**();", Style); 23471 verifyFormat("Foo::operator<Foo>**();", Style); 23472 verifyFormat("Foo::operator<Foo>*&();", Style); 23473 verifyFormat("Foo::operator<int>&();", Style); 23474 verifyFormat("Foo::operator<Foo>&();", Style); 23475 verifyFormat("Foo::operator<int>&&();", Style); 23476 verifyFormat("Foo::operator<Foo>&&();", Style); 23477 verifyFormat("Foo::operator<int>*&();", Style); 23478 verifyFormat("Foo::operator<Foo>*&();", Style); 23479 verifyFormat("operator*(int (*)(), class Foo);", Style); 23480 23481 verifyFormat("Foo::operator&();", Style); 23482 verifyFormat("Foo::operator void&();", 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("operator&(int (&)(), class Foo);", Style); 23491 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23492 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23493 23494 verifyFormat("Foo::operator&&();", Style); 23495 verifyFormat("Foo::operator void&&();", Style); 23496 verifyFormat("Foo::operator void const&&();", Style); 23497 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23498 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23499 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23500 verifyFormat("Foo::operator()(void&&);", Style); 23501 verifyFormat("Foo::operator&&(void&&);", Style); 23502 verifyFormat("Foo::operator&&();", Style); 23503 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23504 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23505 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23506 Style); 23507 verifyFormat("operator void**()", Style); 23508 verifyFormat("operator const FooLeft<Object>&()", Style); 23509 verifyFormat("operator const FooLeft<Object>*()", Style); 23510 verifyFormat("operator const FooLeft<Object>**()", Style); 23511 verifyFormat("operator const FooLeft<Object>*&()", Style); 23512 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23513 23514 // PR45107 23515 verifyFormat("operator Vector<String>&();", Style); 23516 verifyFormat("operator const Vector<String>&();", Style); 23517 verifyFormat("operator foo::Bar*();", Style); 23518 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23519 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23520 Style); 23521 23522 Style.PointerAlignment = FormatStyle::PAS_Middle; 23523 verifyFormat("Foo::operator*();", Style); 23524 verifyFormat("Foo::operator void *();", Style); 23525 verifyFormat("Foo::operator()(void *);", Style); 23526 verifyFormat("Foo::operator*(void *);", Style); 23527 verifyFormat("Foo::operator*();", Style); 23528 verifyFormat("operator*(int (*)(), class Foo);", Style); 23529 23530 verifyFormat("Foo::operator&();", Style); 23531 verifyFormat("Foo::operator void &();", Style); 23532 verifyFormat("Foo::operator void const &();", Style); 23533 verifyFormat("Foo::operator()(void &);", Style); 23534 verifyFormat("Foo::operator&(void &);", Style); 23535 verifyFormat("Foo::operator&();", Style); 23536 verifyFormat("operator&(int (&)(), class Foo);", Style); 23537 23538 verifyFormat("Foo::operator&&();", Style); 23539 verifyFormat("Foo::operator void &&();", Style); 23540 verifyFormat("Foo::operator void const &&();", Style); 23541 verifyFormat("Foo::operator()(void &&);", Style); 23542 verifyFormat("Foo::operator&&(void &&);", Style); 23543 verifyFormat("Foo::operator&&();", Style); 23544 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23545 } 23546 23547 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23548 FormatStyle Style = getLLVMStyle(); 23549 // PR46157 23550 verifyFormat("foo(operator+, -42);", Style); 23551 verifyFormat("foo(operator++, -42);", Style); 23552 verifyFormat("foo(operator--, -42);", Style); 23553 verifyFormat("foo(-42, operator--);", Style); 23554 verifyFormat("foo(-42, operator, );", Style); 23555 verifyFormat("foo(operator, , -42);", Style); 23556 } 23557 23558 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23559 FormatStyle Style = getLLVMStyle(); 23560 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23561 23562 // Don't use the helpers here, since 'mess up' will change the whitespace 23563 // and these are all whitespace sensitive by definition 23564 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23565 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23566 EXPECT_EQ( 23567 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23568 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23569 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23570 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23571 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23572 " Still=Intentional);", 23573 format("FOO(String-ized&Messy+But,: :\n" 23574 " Still=Intentional);", 23575 Style)); 23576 Style.AlignConsecutiveAssignments.Enabled = true; 23577 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23578 " Still=Intentional);", 23579 format("FOO(String-ized=&Messy+But,: :\n" 23580 " Still=Intentional);", 23581 Style)); 23582 23583 Style.ColumnLimit = 21; 23584 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23585 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23586 } 23587 23588 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23589 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23590 // test its interaction with line wrapping 23591 FormatStyle Style = getLLVMStyleWithColumns(80); 23592 verifyFormat("namespace {\n" 23593 "int i;\n" 23594 "int j;\n" 23595 "} // namespace", 23596 Style); 23597 23598 verifyFormat("namespace AAA {\n" 23599 "int i;\n" 23600 "int j;\n" 23601 "} // namespace AAA", 23602 Style); 23603 23604 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23605 "int i;\n" 23606 "int j;\n" 23607 "} // namespace Averyveryveryverylongnamespace", 23608 format("namespace Averyveryveryverylongnamespace {\n" 23609 "int i;\n" 23610 "int j;\n" 23611 "}", 23612 Style)); 23613 23614 EXPECT_EQ( 23615 "namespace " 23616 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23617 " went::mad::now {\n" 23618 "int i;\n" 23619 "int j;\n" 23620 "} // namespace\n" 23621 " // " 23622 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23623 "went::mad::now", 23624 format("namespace " 23625 "would::it::save::you::a::lot::of::time::if_::i::" 23626 "just::gave::up::and_::went::mad::now {\n" 23627 "int i;\n" 23628 "int j;\n" 23629 "}", 23630 Style)); 23631 23632 // This used to duplicate the comment again and again on subsequent runs 23633 EXPECT_EQ( 23634 "namespace " 23635 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23636 " went::mad::now {\n" 23637 "int i;\n" 23638 "int j;\n" 23639 "} // namespace\n" 23640 " // " 23641 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23642 "went::mad::now", 23643 format("namespace " 23644 "would::it::save::you::a::lot::of::time::if_::i::" 23645 "just::gave::up::and_::went::mad::now {\n" 23646 "int i;\n" 23647 "int j;\n" 23648 "} // namespace\n" 23649 " // " 23650 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23651 "and_::went::mad::now", 23652 Style)); 23653 } 23654 23655 TEST_F(FormatTest, LikelyUnlikely) { 23656 FormatStyle Style = getLLVMStyle(); 23657 23658 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23659 " return 29;\n" 23660 "}", 23661 Style); 23662 23663 verifyFormat("if (argc > 5) [[likely]] {\n" 23664 " return 29;\n" 23665 "}", 23666 Style); 23667 23668 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23669 " return 29;\n" 23670 "} else [[likely]] {\n" 23671 " return 42;\n" 23672 "}\n", 23673 Style); 23674 23675 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23676 " return 29;\n" 23677 "} else if (argc > 10) [[likely]] {\n" 23678 " return 99;\n" 23679 "} else {\n" 23680 " return 42;\n" 23681 "}\n", 23682 Style); 23683 23684 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23685 " return 29;\n" 23686 "}", 23687 Style); 23688 23689 verifyFormat("if (argc > 5) [[unlikely]]\n" 23690 " return 29;\n", 23691 Style); 23692 verifyFormat("if (argc > 5) [[likely]]\n" 23693 " return 29;\n", 23694 Style); 23695 23696 Style.AttributeMacros.push_back("UNLIKELY"); 23697 Style.AttributeMacros.push_back("LIKELY"); 23698 verifyFormat("if (argc > 5) UNLIKELY\n" 23699 " return 29;\n", 23700 Style); 23701 23702 verifyFormat("if (argc > 5) UNLIKELY {\n" 23703 " return 29;\n" 23704 "}", 23705 Style); 23706 verifyFormat("if (argc > 5) UNLIKELY {\n" 23707 " return 29;\n" 23708 "} else [[likely]] {\n" 23709 " return 42;\n" 23710 "}\n", 23711 Style); 23712 verifyFormat("if (argc > 5) UNLIKELY {\n" 23713 " return 29;\n" 23714 "} else LIKELY {\n" 23715 " return 42;\n" 23716 "}\n", 23717 Style); 23718 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23719 " return 29;\n" 23720 "} else LIKELY {\n" 23721 " return 42;\n" 23722 "}\n", 23723 Style); 23724 } 23725 23726 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23727 verifyFormat("Constructor()\n" 23728 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23729 " aaaa(aaaaaaaaaaaaaaaaaa, " 23730 "aaaaaaaaaaaaaaaaaat))"); 23731 verifyFormat("Constructor()\n" 23732 " : aaaaaaaaaaaaa(aaaaaa), " 23733 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23734 23735 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23736 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23737 verifyFormat("Constructor()\n" 23738 " : aaaaaa(aaaaaa),\n" 23739 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23740 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23741 StyleWithWhitespacePenalty); 23742 verifyFormat("Constructor()\n" 23743 " : aaaaaaaaaaaaa(aaaaaa), " 23744 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23745 StyleWithWhitespacePenalty); 23746 } 23747 23748 TEST_F(FormatTest, LLVMDefaultStyle) { 23749 FormatStyle Style = getLLVMStyle(); 23750 verifyFormat("extern \"C\" {\n" 23751 "int foo();\n" 23752 "}", 23753 Style); 23754 } 23755 TEST_F(FormatTest, GNUDefaultStyle) { 23756 FormatStyle Style = getGNUStyle(); 23757 verifyFormat("extern \"C\"\n" 23758 "{\n" 23759 " int foo ();\n" 23760 "}", 23761 Style); 23762 } 23763 TEST_F(FormatTest, MozillaDefaultStyle) { 23764 FormatStyle Style = getMozillaStyle(); 23765 verifyFormat("extern \"C\"\n" 23766 "{\n" 23767 " int foo();\n" 23768 "}", 23769 Style); 23770 } 23771 TEST_F(FormatTest, GoogleDefaultStyle) { 23772 FormatStyle Style = getGoogleStyle(); 23773 verifyFormat("extern \"C\" {\n" 23774 "int foo();\n" 23775 "}", 23776 Style); 23777 } 23778 TEST_F(FormatTest, ChromiumDefaultStyle) { 23779 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23780 verifyFormat("extern \"C\" {\n" 23781 "int foo();\n" 23782 "}", 23783 Style); 23784 } 23785 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23786 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23787 verifyFormat("extern \"C\"\n" 23788 "{\n" 23789 " int foo();\n" 23790 "}", 23791 Style); 23792 } 23793 TEST_F(FormatTest, WebKitDefaultStyle) { 23794 FormatStyle Style = getWebKitStyle(); 23795 verifyFormat("extern \"C\" {\n" 23796 "int foo();\n" 23797 "}", 23798 Style); 23799 } 23800 23801 TEST_F(FormatTest, Concepts) { 23802 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23803 FormatStyle::BBCDS_Always); 23804 verifyFormat("template <typename T>\n" 23805 "concept True = true;"); 23806 23807 verifyFormat("template <typename T>\n" 23808 "concept C = ((false || foo()) && C2<T>) ||\n" 23809 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23810 getLLVMStyleWithColumns(60)); 23811 23812 verifyFormat("template <typename T>\n" 23813 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23814 "sizeof(T) <= 8;"); 23815 23816 verifyFormat("template <typename T>\n" 23817 "concept DelayedCheck = true && requires(T t) {\n" 23818 " t.bar();\n" 23819 " t.baz();\n" 23820 " } && sizeof(T) <= 8;"); 23821 23822 verifyFormat("template <typename T>\n" 23823 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23824 " t.bar();\n" 23825 " t.baz();\n" 23826 " } && sizeof(T) <= 8;"); 23827 23828 verifyFormat("template <typename T>\n" 23829 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23830 "sizeof(T) <= 8;"); 23831 23832 verifyFormat("template <typename T>\n" 23833 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23834 "&& sizeof(T) <= 8;"); 23835 23836 verifyFormat( 23837 "template <typename T>\n" 23838 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23839 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23840 23841 verifyFormat("template <typename T>\n" 23842 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23843 "&& sizeof(T) <= 8;"); 23844 23845 verifyFormat( 23846 "template <typename T>\n" 23847 "concept DelayedCheck = (bool)(0) ||\n" 23848 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23849 23850 verifyFormat("template <typename T>\n" 23851 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23852 "&& sizeof(T) <= 8;"); 23853 23854 verifyFormat("template <typename T>\n" 23855 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23856 "sizeof(T) <= 8;"); 23857 23858 verifyFormat("template <typename T>\n" 23859 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23860 " requires(T t) {\n" 23861 " t.bar();\n" 23862 " t.baz();\n" 23863 " } && sizeof(T) <= 8 && !(4 < 3);", 23864 getLLVMStyleWithColumns(60)); 23865 23866 verifyFormat("template <typename T>\n" 23867 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23868 23869 verifyFormat("template <typename T>\n" 23870 "concept C = foo();"); 23871 23872 verifyFormat("template <typename T>\n" 23873 "concept C = foo(T());"); 23874 23875 verifyFormat("template <typename T>\n" 23876 "concept C = foo(T{});"); 23877 23878 verifyFormat("template <typename T>\n" 23879 "concept Size = V<sizeof(T)>::Value > 5;"); 23880 23881 verifyFormat("template <typename T>\n" 23882 "concept True = S<T>::Value;"); 23883 23884 verifyFormat( 23885 "template <typename T>\n" 23886 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23887 " sizeof(T) <= 8;"); 23888 23889 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23890 // the lambda l square. 23891 verifyFormat("template <typename T>\n" 23892 "concept C = [] -> bool { return true; }() && requires(T t) { " 23893 "t.bar(); } &&\n" 23894 " sizeof(T) <= 8;"); 23895 23896 verifyFormat( 23897 "template <typename T>\n" 23898 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23899 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23900 23901 verifyFormat("template <typename T>\n" 23902 "concept C = decltype([]() { return std::true_type{}; " 23903 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23904 getLLVMStyleWithColumns(120)); 23905 23906 verifyFormat("template <typename T>\n" 23907 "concept C = decltype([]() -> std::true_type { return {}; " 23908 "}())::value &&\n" 23909 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23910 23911 verifyFormat("template <typename T>\n" 23912 "concept C = true;\n" 23913 "Foo Bar;"); 23914 23915 verifyFormat("template <typename T>\n" 23916 "concept Hashable = requires(T a) {\n" 23917 " { std::hash<T>{}(a) } -> " 23918 "std::convertible_to<std::size_t>;\n" 23919 " };"); 23920 23921 verifyFormat( 23922 "template <typename T>\n" 23923 "concept EqualityComparable = requires(T a, T b) {\n" 23924 " { a == b } -> std::same_as<bool>;\n" 23925 " };"); 23926 23927 verifyFormat( 23928 "template <typename T>\n" 23929 "concept EqualityComparable = requires(T a, T b) {\n" 23930 " { a == b } -> std::same_as<bool>;\n" 23931 " { a != b } -> std::same_as<bool>;\n" 23932 " };"); 23933 23934 verifyFormat("template <typename T>\n" 23935 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23936 " { a == b };\n" 23937 " { a != b };\n" 23938 " };"); 23939 23940 verifyFormat("template <typename T>\n" 23941 "concept HasSizeT = requires { typename T::size_t; };"); 23942 23943 verifyFormat("template <typename T>\n" 23944 "concept Semiregular =\n" 23945 " DefaultConstructible<T> && CopyConstructible<T> && " 23946 "CopyAssignable<T> &&\n" 23947 " requires(T a, std::size_t n) {\n" 23948 " requires Same<T *, decltype(&a)>;\n" 23949 " { a.~T() } noexcept;\n" 23950 " requires Same<T *, decltype(new T)>;\n" 23951 " requires Same<T *, decltype(new T[n])>;\n" 23952 " { delete new T; };\n" 23953 " { delete new T[n]; };\n" 23954 " };"); 23955 23956 verifyFormat("template <typename T>\n" 23957 "concept Semiregular =\n" 23958 " requires(T a, std::size_t n) {\n" 23959 " requires Same<T *, decltype(&a)>;\n" 23960 " { a.~T() } noexcept;\n" 23961 " requires Same<T *, decltype(new T)>;\n" 23962 " requires Same<T *, decltype(new T[n])>;\n" 23963 " { delete new T; };\n" 23964 " { delete new T[n]; };\n" 23965 " { new T } -> std::same_as<T *>;\n" 23966 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23967 "CopyAssignable<T>;"); 23968 23969 verifyFormat( 23970 "template <typename T>\n" 23971 "concept Semiregular =\n" 23972 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23973 " requires Same<T *, decltype(&a)>;\n" 23974 " { a.~T() } noexcept;\n" 23975 " requires Same<T *, decltype(new T)>;\n" 23976 " requires Same<T *, decltype(new " 23977 "T[n])>;\n" 23978 " { delete new T; };\n" 23979 " { delete new T[n]; };\n" 23980 " } && CopyConstructible<T> && " 23981 "CopyAssignable<T>;"); 23982 23983 verifyFormat("template <typename T>\n" 23984 "concept Two = requires(T t) {\n" 23985 " { t.foo() } -> std::same_as<Bar>;\n" 23986 " } && requires(T &&t) {\n" 23987 " { t.foo() } -> std::same_as<Bar &&>;\n" 23988 " };"); 23989 23990 verifyFormat( 23991 "template <typename T>\n" 23992 "concept C = requires(T x) {\n" 23993 " { *x } -> std::convertible_to<typename T::inner>;\n" 23994 " { x + 1 } noexcept -> std::same_as<int>;\n" 23995 " { x * 1 } -> std::convertible_to<T>;\n" 23996 " };"); 23997 23998 verifyFormat( 23999 "template <typename T, typename U = T>\n" 24000 "concept Swappable = requires(T &&t, U &&u) {\n" 24001 " swap(std::forward<T>(t), std::forward<U>(u));\n" 24002 " swap(std::forward<U>(u), std::forward<T>(t));\n" 24003 " };"); 24004 24005 verifyFormat("template <typename T, typename U>\n" 24006 "concept Common = requires(T &&t, U &&u) {\n" 24007 " typename CommonType<T, U>;\n" 24008 " { CommonType<T, U>(std::forward<T>(t)) };\n" 24009 " };"); 24010 24011 verifyFormat("template <typename T, typename U>\n" 24012 "concept Common = requires(T &&t, U &&u) {\n" 24013 " typename CommonType<T, U>;\n" 24014 " { CommonType<T, U>{std::forward<T>(t)} };\n" 24015 " };"); 24016 24017 verifyFormat( 24018 "template <typename T>\n" 24019 "concept C = requires(T t) {\n" 24020 " requires Bar<T> && Foo<T>;\n" 24021 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24022 " };"); 24023 24024 verifyFormat("template <typename T>\n" 24025 "concept HasFoo = requires(T t) {\n" 24026 " { t.foo() };\n" 24027 " t.foo();\n" 24028 " };\n" 24029 "template <typename T>\n" 24030 "concept HasBar = requires(T t) {\n" 24031 " { t.bar() };\n" 24032 " t.bar();\n" 24033 " };"); 24034 24035 verifyFormat("template <typename T>\n" 24036 "concept Large = sizeof(T) > 10;"); 24037 24038 verifyFormat("template <typename T, typename U>\n" 24039 "concept FooableWith = requires(T t, U u) {\n" 24040 " typename T::foo_type;\n" 24041 " { t.foo(u) } -> typename T::foo_type;\n" 24042 " t++;\n" 24043 " };\n" 24044 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 24045 24046 verifyFormat("template <typename T>\n" 24047 "concept Context = is_specialization_of_v<context, T>;"); 24048 24049 verifyFormat("template <typename T>\n" 24050 "concept Node = std::is_object_v<T>;"); 24051 24052 verifyFormat("template <class T>\n" 24053 "concept integral = __is_integral(T);"); 24054 24055 verifyFormat("template <class T>\n" 24056 "concept is2D = __array_extent(T, 1) == 2;"); 24057 24058 verifyFormat("template <class T>\n" 24059 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24060 24061 verifyFormat("template <class T, class T2>\n" 24062 "concept Same = __is_same_as<T, T2>;"); 24063 24064 auto Style = getLLVMStyle(); 24065 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24066 24067 verifyFormat( 24068 "template <typename T>\n" 24069 "concept C = requires(T t) {\n" 24070 " requires Bar<T> && Foo<T>;\n" 24071 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24072 " };", 24073 Style); 24074 24075 verifyFormat("template <typename T>\n" 24076 "concept HasFoo = requires(T t) {\n" 24077 " { t.foo() };\n" 24078 " t.foo();\n" 24079 " };\n" 24080 "template <typename T>\n" 24081 "concept HasBar = requires(T t) {\n" 24082 " { t.bar() };\n" 24083 " t.bar();\n" 24084 " };", 24085 Style); 24086 24087 verifyFormat("template <typename T> concept True = true;", Style); 24088 24089 verifyFormat("template <typename T>\n" 24090 "concept C = decltype([]() -> std::true_type { return {}; " 24091 "}())::value &&\n" 24092 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24093 Style); 24094 24095 verifyFormat("template <typename T>\n" 24096 "concept Semiregular =\n" 24097 " DefaultConstructible<T> && CopyConstructible<T> && " 24098 "CopyAssignable<T> &&\n" 24099 " requires(T a, std::size_t n) {\n" 24100 " requires Same<T *, decltype(&a)>;\n" 24101 " { a.~T() } noexcept;\n" 24102 " requires Same<T *, decltype(new T)>;\n" 24103 " requires Same<T *, decltype(new T[n])>;\n" 24104 " { delete new T; };\n" 24105 " { delete new T[n]; };\n" 24106 " };", 24107 Style); 24108 24109 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24110 24111 verifyFormat("template <typename T> concept C =\n" 24112 " requires(T t) {\n" 24113 " requires Bar<T> && Foo<T>;\n" 24114 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24115 " };", 24116 Style); 24117 24118 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24119 " { t.foo() };\n" 24120 " t.foo();\n" 24121 " };\n" 24122 "template <typename T> concept HasBar = requires(T t) {\n" 24123 " { t.bar() };\n" 24124 " t.bar();\n" 24125 " };", 24126 Style); 24127 24128 verifyFormat("template <typename T> concept True = true;", Style); 24129 24130 verifyFormat( 24131 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24132 " return {};\n" 24133 " }())::value &&\n" 24134 " requires(T t) { t.bar(); } && " 24135 "sizeof(T) <= 8;", 24136 Style); 24137 24138 verifyFormat("template <typename T> concept Semiregular =\n" 24139 " DefaultConstructible<T> && CopyConstructible<T> && " 24140 "CopyAssignable<T> &&\n" 24141 " requires(T a, std::size_t n) {\n" 24142 " requires Same<T *, decltype(&a)>;\n" 24143 " { a.~T() } noexcept;\n" 24144 " requires Same<T *, decltype(new T)>;\n" 24145 " requires Same<T *, decltype(new T[n])>;\n" 24146 " { delete new T; };\n" 24147 " { delete new T[n]; };\n" 24148 " };", 24149 Style); 24150 24151 // The following tests are invalid C++, we just want to make sure we don't 24152 // assert. 24153 verifyFormat("template <typename T>\n" 24154 "concept C = requires C2<T>;"); 24155 24156 verifyFormat("template <typename T>\n" 24157 "concept C = 5 + 4;"); 24158 24159 verifyFormat("template <typename T>\n" 24160 "concept C =\n" 24161 "class X;"); 24162 24163 verifyFormat("template <typename T>\n" 24164 "concept C = [] && true;"); 24165 24166 verifyFormat("template <typename T>\n" 24167 "concept C = [] && requires(T t) { typename T::size_type; };"); 24168 } 24169 24170 TEST_F(FormatTest, RequiresClausesPositions) { 24171 auto Style = getLLVMStyle(); 24172 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24173 EXPECT_EQ(Style.IndentRequiresClause, true); 24174 24175 verifyFormat("template <typename T>\n" 24176 " requires(Foo<T> && std::trait<T>)\n" 24177 "struct Bar;", 24178 Style); 24179 24180 verifyFormat("template <typename T>\n" 24181 " requires(Foo<T> && std::trait<T>)\n" 24182 "class Bar {\n" 24183 "public:\n" 24184 " Bar(T t);\n" 24185 " bool baz();\n" 24186 "};", 24187 Style); 24188 24189 verifyFormat( 24190 "template <typename T>\n" 24191 " requires requires(T &&t) {\n" 24192 " typename T::I;\n" 24193 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24194 " }\n" 24195 "Bar(T) -> Bar<typename T::I>;", 24196 Style); 24197 24198 verifyFormat("template <typename T>\n" 24199 " requires(Foo<T> && std::trait<T>)\n" 24200 "constexpr T MyGlobal;", 24201 Style); 24202 24203 verifyFormat("template <typename T>\n" 24204 " requires Foo<T> && requires(T t) {\n" 24205 " { t.baz() } -> std::same_as<bool>;\n" 24206 " requires std::same_as<T::Factor, int>;\n" 24207 " }\n" 24208 "inline int bar(T t) {\n" 24209 " return t.baz() ? T::Factor : 5;\n" 24210 "}", 24211 Style); 24212 24213 verifyFormat("template <typename T>\n" 24214 "inline int bar(T t)\n" 24215 " requires Foo<T> && requires(T t) {\n" 24216 " { t.baz() } -> std::same_as<bool>;\n" 24217 " requires std::same_as<T::Factor, int>;\n" 24218 " }\n" 24219 "{\n" 24220 " return t.baz() ? T::Factor : 5;\n" 24221 "}", 24222 Style); 24223 24224 verifyFormat("template <typename T>\n" 24225 " requires F<T>\n" 24226 "int bar(T t) {\n" 24227 " return 5;\n" 24228 "}", 24229 Style); 24230 24231 verifyFormat("template <typename T>\n" 24232 "int bar(T t)\n" 24233 " requires F<T>\n" 24234 "{\n" 24235 " return 5;\n" 24236 "}", 24237 Style); 24238 24239 verifyFormat("template <typename T>\n" 24240 "int bar(T t)\n" 24241 " requires F<T>;", 24242 Style); 24243 24244 Style.IndentRequiresClause = false; 24245 verifyFormat("template <typename T>\n" 24246 "requires F<T>\n" 24247 "int bar(T t) {\n" 24248 " return 5;\n" 24249 "}", 24250 Style); 24251 24252 verifyFormat("template <typename T>\n" 24253 "int bar(T t)\n" 24254 "requires F<T>\n" 24255 "{\n" 24256 " return 5;\n" 24257 "}", 24258 Style); 24259 24260 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24261 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24262 "template <typename T> requires Foo<T> void bar() {}\n" 24263 "template <typename T> void bar() requires Foo<T> {}\n" 24264 "template <typename T> void bar() requires Foo<T>;\n" 24265 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24266 Style); 24267 24268 auto ColumnStyle = Style; 24269 ColumnStyle.ColumnLimit = 40; 24270 verifyFormat("template <typename AAAAAAA>\n" 24271 "requires Foo<T> struct Bar {};\n" 24272 "template <typename AAAAAAA>\n" 24273 "requires Foo<T> void bar() {}\n" 24274 "template <typename AAAAAAA>\n" 24275 "void bar() requires Foo<T> {}\n" 24276 "template <typename AAAAAAA>\n" 24277 "requires Foo<T> Baz(T) -> Baz<T>;", 24278 ColumnStyle); 24279 24280 verifyFormat("template <typename T>\n" 24281 "requires Foo<AAAAAAA> struct Bar {};\n" 24282 "template <typename T>\n" 24283 "requires Foo<AAAAAAA> void bar() {}\n" 24284 "template <typename T>\n" 24285 "void bar() requires Foo<AAAAAAA> {}\n" 24286 "template <typename T>\n" 24287 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24288 ColumnStyle); 24289 24290 verifyFormat("template <typename AAAAAAA>\n" 24291 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24292 "struct Bar {};\n" 24293 "template <typename AAAAAAA>\n" 24294 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24295 "void bar() {}\n" 24296 "template <typename AAAAAAA>\n" 24297 "void bar()\n" 24298 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24299 "template <typename AAAAAAA>\n" 24300 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24301 "template <typename AAAAAAA>\n" 24302 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24303 "Bar(T) -> Bar<T>;", 24304 ColumnStyle); 24305 24306 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24307 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24308 24309 verifyFormat("template <typename T>\n" 24310 "requires Foo<T> struct Bar {};\n" 24311 "template <typename T>\n" 24312 "requires Foo<T> void bar() {}\n" 24313 "template <typename T>\n" 24314 "void bar()\n" 24315 "requires Foo<T> {}\n" 24316 "template <typename T>\n" 24317 "void bar()\n" 24318 "requires Foo<T>;\n" 24319 "template <typename T>\n" 24320 "requires Foo<T> Bar(T) -> Bar<T>;", 24321 Style); 24322 24323 verifyFormat("template <typename AAAAAAA>\n" 24324 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24325 "struct Bar {};\n" 24326 "template <typename AAAAAAA>\n" 24327 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24328 "void bar() {}\n" 24329 "template <typename AAAAAAA>\n" 24330 "void bar()\n" 24331 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24332 "template <typename AAAAAAA>\n" 24333 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24334 "template <typename AAAAAAA>\n" 24335 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24336 "Bar(T) -> Bar<T>;", 24337 ColumnStyle); 24338 24339 Style.IndentRequiresClause = true; 24340 ColumnStyle.IndentRequiresClause = true; 24341 24342 verifyFormat("template <typename T>\n" 24343 " requires Foo<T> struct Bar {};\n" 24344 "template <typename T>\n" 24345 " requires Foo<T> void bar() {}\n" 24346 "template <typename T>\n" 24347 "void bar()\n" 24348 " requires Foo<T> {}\n" 24349 "template <typename T>\n" 24350 " requires Foo<T> Bar(T) -> Bar<T>;", 24351 Style); 24352 24353 verifyFormat("template <typename AAAAAAA>\n" 24354 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24355 "struct Bar {};\n" 24356 "template <typename AAAAAAA>\n" 24357 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24358 "void bar() {}\n" 24359 "template <typename AAAAAAA>\n" 24360 "void bar()\n" 24361 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24362 "template <typename AAAAAAA>\n" 24363 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24364 "template <typename AAAAAAA>\n" 24365 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24366 "Bar(T) -> Bar<T>;", 24367 ColumnStyle); 24368 24369 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24370 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24371 24372 verifyFormat("template <typename T> requires Foo<T>\n" 24373 "struct Bar {};\n" 24374 "template <typename T> requires Foo<T>\n" 24375 "void bar() {}\n" 24376 "template <typename T>\n" 24377 "void bar() requires Foo<T>\n" 24378 "{}\n" 24379 "template <typename T> void bar() requires Foo<T>;\n" 24380 "template <typename T> requires Foo<T>\n" 24381 "Bar(T) -> Bar<T>;", 24382 Style); 24383 24384 verifyFormat("template <typename AAAAAAA>\n" 24385 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24386 "struct Bar {};\n" 24387 "template <typename AAAAAAA>\n" 24388 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24389 "void bar() {}\n" 24390 "template <typename AAAAAAA>\n" 24391 "void bar()\n" 24392 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24393 "{}\n" 24394 "template <typename AAAAAAA>\n" 24395 "requires Foo<AAAAAAAA>\n" 24396 "Bar(T) -> Bar<T>;\n" 24397 "template <typename AAAAAAA>\n" 24398 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24399 "Bar(T) -> Bar<T>;", 24400 ColumnStyle); 24401 } 24402 24403 TEST_F(FormatTest, RequiresClauses) { 24404 verifyFormat("struct [[nodiscard]] zero_t {\n" 24405 " template <class T>\n" 24406 " requires requires { number_zero_v<T>; }\n" 24407 " [[nodiscard]] constexpr operator T() const {\n" 24408 " return number_zero_v<T>;\n" 24409 " }\n" 24410 "};"); 24411 24412 auto Style = getLLVMStyle(); 24413 24414 verifyFormat( 24415 "template <typename T>\n" 24416 " requires is_default_constructible_v<hash<T>> and\n" 24417 " is_copy_constructible_v<hash<T>> and\n" 24418 " is_move_constructible_v<hash<T>> and\n" 24419 " is_copy_assignable_v<hash<T>> and " 24420 "is_move_assignable_v<hash<T>> and\n" 24421 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24422 " is_callable_v<hash<T>(T)> and\n" 24423 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24424 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24425 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24426 "struct S {};", 24427 Style); 24428 24429 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24430 verifyFormat( 24431 "template <typename T>\n" 24432 " requires is_default_constructible_v<hash<T>>\n" 24433 " and is_copy_constructible_v<hash<T>>\n" 24434 " and is_move_constructible_v<hash<T>>\n" 24435 " and is_copy_assignable_v<hash<T>> and " 24436 "is_move_assignable_v<hash<T>>\n" 24437 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24438 " and is_callable_v<hash<T>(T)>\n" 24439 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24440 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24441 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24442 "&>()))>\n" 24443 "struct S {};", 24444 Style); 24445 24446 // Not a clause, but we once hit an assert. 24447 verifyFormat("#if 0\n" 24448 "#else\n" 24449 "foo();\n" 24450 "#endif\n" 24451 "bar(requires);"); 24452 } 24453 24454 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24455 FormatStyle Style = getLLVMStyle(); 24456 StringRef Source = "void Foo::slot() {\n" 24457 " unsigned char MyChar = 'x';\n" 24458 " emit signal(MyChar);\n" 24459 " Q_EMIT signal(MyChar);\n" 24460 "}"; 24461 24462 EXPECT_EQ(Source, format(Source, Style)); 24463 24464 Style.AlignConsecutiveDeclarations.Enabled = true; 24465 EXPECT_EQ("void Foo::slot() {\n" 24466 " unsigned char MyChar = 'x';\n" 24467 " emit signal(MyChar);\n" 24468 " Q_EMIT signal(MyChar);\n" 24469 "}", 24470 format(Source, Style)); 24471 24472 Style.StatementAttributeLikeMacros.push_back("emit"); 24473 EXPECT_EQ(Source, format(Source, Style)); 24474 24475 Style.StatementAttributeLikeMacros = {}; 24476 EXPECT_EQ("void Foo::slot() {\n" 24477 " unsigned char MyChar = 'x';\n" 24478 " emit signal(MyChar);\n" 24479 " Q_EMIT signal(MyChar);\n" 24480 "}", 24481 format(Source, Style)); 24482 } 24483 24484 TEST_F(FormatTest, IndentAccessModifiers) { 24485 FormatStyle Style = getLLVMStyle(); 24486 Style.IndentAccessModifiers = true; 24487 // Members are *two* levels below the record; 24488 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24489 verifyFormat("class C {\n" 24490 " int i;\n" 24491 "};\n", 24492 Style); 24493 verifyFormat("union C {\n" 24494 " int i;\n" 24495 " unsigned u;\n" 24496 "};\n", 24497 Style); 24498 // Access modifiers should be indented one level below the record. 24499 verifyFormat("class C {\n" 24500 " public:\n" 24501 " int i;\n" 24502 "};\n", 24503 Style); 24504 verifyFormat("struct S {\n" 24505 " private:\n" 24506 " class C {\n" 24507 " int j;\n" 24508 "\n" 24509 " public:\n" 24510 " C();\n" 24511 " };\n" 24512 "\n" 24513 " public:\n" 24514 " int i;\n" 24515 "};\n", 24516 Style); 24517 // Enumerations are not records and should be unaffected. 24518 Style.AllowShortEnumsOnASingleLine = false; 24519 verifyFormat("enum class E {\n" 24520 " A,\n" 24521 " B\n" 24522 "};\n", 24523 Style); 24524 // Test with a different indentation width; 24525 // also proves that the result is Style.AccessModifierOffset agnostic. 24526 Style.IndentWidth = 3; 24527 verifyFormat("class C {\n" 24528 " public:\n" 24529 " int i;\n" 24530 "};\n", 24531 Style); 24532 } 24533 24534 TEST_F(FormatTest, LimitlessStringsAndComments) { 24535 auto Style = getLLVMStyleWithColumns(0); 24536 constexpr StringRef Code = 24537 "/**\n" 24538 " * This is a multiline comment with quite some long lines, at least for " 24539 "the LLVM Style.\n" 24540 " * We will redo this with strings and line comments. Just to check if " 24541 "everything is working.\n" 24542 " */\n" 24543 "bool foo() {\n" 24544 " /* Single line multi line comment. */\n" 24545 " const std::string String = \"This is a multiline string with quite " 24546 "some long lines, at least for the LLVM Style.\"\n" 24547 " \"We already did it with multi line " 24548 "comments, and we will do it with line comments. Just to check if " 24549 "everything is working.\";\n" 24550 " // This is a line comment (block) with quite some long lines, at " 24551 "least for the LLVM Style.\n" 24552 " // We already did this with multi line comments and strings. Just to " 24553 "check if everything is working.\n" 24554 " const std::string SmallString = \"Hello World\";\n" 24555 " // Small line comment\n" 24556 " return String.size() > SmallString.size();\n" 24557 "}"; 24558 EXPECT_EQ(Code, format(Code, Style)); 24559 } 24560 24561 TEST_F(FormatTest, FormatDecayCopy) { 24562 // error cases from unit tests 24563 verifyFormat("foo(auto())"); 24564 verifyFormat("foo(auto{})"); 24565 verifyFormat("foo(auto({}))"); 24566 verifyFormat("foo(auto{{}})"); 24567 24568 verifyFormat("foo(auto(1))"); 24569 verifyFormat("foo(auto{1})"); 24570 verifyFormat("foo(new auto(1))"); 24571 verifyFormat("foo(new auto{1})"); 24572 verifyFormat("decltype(auto(1)) x;"); 24573 verifyFormat("decltype(auto{1}) x;"); 24574 verifyFormat("auto(x);"); 24575 verifyFormat("auto{x};"); 24576 verifyFormat("new auto{x};"); 24577 verifyFormat("auto{x} = y;"); 24578 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24579 // the user's own fault 24580 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24581 // clearly the user's own fault 24582 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24583 } 24584 24585 TEST_F(FormatTest, Cpp20ModulesSupport) { 24586 FormatStyle Style = getLLVMStyle(); 24587 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24588 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24589 24590 verifyFormat("export import foo;", Style); 24591 verifyFormat("export import foo:bar;", Style); 24592 verifyFormat("export import foo.bar;", Style); 24593 verifyFormat("export import foo.bar:baz;", Style); 24594 verifyFormat("export import :bar;", Style); 24595 verifyFormat("export module foo:bar;", Style); 24596 verifyFormat("export module foo;", Style); 24597 verifyFormat("export module foo.bar;", Style); 24598 verifyFormat("export module foo.bar:baz;", Style); 24599 verifyFormat("export import <string_view>;", Style); 24600 24601 verifyFormat("export type_name var;", Style); 24602 verifyFormat("template <class T> export using A = B<T>;", Style); 24603 verifyFormat("export using A = B;", Style); 24604 verifyFormat("export int func() {\n" 24605 " foo();\n" 24606 "}", 24607 Style); 24608 verifyFormat("export struct {\n" 24609 " int foo;\n" 24610 "};", 24611 Style); 24612 verifyFormat("export {\n" 24613 " int foo;\n" 24614 "};", 24615 Style); 24616 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24617 24618 verifyFormat("import bar;", Style); 24619 verifyFormat("import foo.bar;", Style); 24620 verifyFormat("import foo:bar;", Style); 24621 verifyFormat("import :bar;", Style); 24622 verifyFormat("import <ctime>;", Style); 24623 verifyFormat("import \"header\";", Style); 24624 24625 verifyFormat("module foo;", Style); 24626 verifyFormat("module foo:bar;", Style); 24627 verifyFormat("module foo.bar;", Style); 24628 verifyFormat("module;", Style); 24629 24630 verifyFormat("export namespace hi {\n" 24631 "const char *sayhi();\n" 24632 "}", 24633 Style); 24634 24635 verifyFormat("module :private;", Style); 24636 verifyFormat("import <foo/bar.h>;", Style); 24637 verifyFormat("import foo...bar;", Style); 24638 verifyFormat("import ..........;", Style); 24639 verifyFormat("module foo:private;", Style); 24640 verifyFormat("import a", Style); 24641 verifyFormat("module a", Style); 24642 verifyFormat("export import a", Style); 24643 verifyFormat("export module a", Style); 24644 24645 verifyFormat("import", Style); 24646 verifyFormat("module", Style); 24647 verifyFormat("export", Style); 24648 } 24649 24650 TEST_F(FormatTest, CoroutineForCoawait) { 24651 FormatStyle Style = getLLVMStyle(); 24652 verifyFormat("for co_await (auto x : range())\n ;"); 24653 verifyFormat("for (auto i : arr) {\n" 24654 "}", 24655 Style); 24656 verifyFormat("for co_await (auto i : arr) {\n" 24657 "}", 24658 Style); 24659 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24660 "}", 24661 Style); 24662 } 24663 24664 TEST_F(FormatTest, CoroutineCoAwait) { 24665 verifyFormat("int x = co_await foo();"); 24666 verifyFormat("int x = (co_await foo());"); 24667 verifyFormat("co_await (42);"); 24668 verifyFormat("void operator co_await(int);"); 24669 verifyFormat("void operator co_await(a);"); 24670 verifyFormat("co_await a;"); 24671 verifyFormat("co_await missing_await_resume{};"); 24672 verifyFormat("co_await a; // comment"); 24673 verifyFormat("void test0() { co_await a; }"); 24674 verifyFormat("co_await co_await co_await foo();"); 24675 verifyFormat("co_await foo().bar();"); 24676 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24677 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24678 "foo(); }(x, y);"); 24679 24680 FormatStyle Style = getLLVMStyleWithColumns(40); 24681 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24682 " co_return co_await foo();\n" 24683 "}(x, y);", 24684 Style); 24685 verifyFormat("co_await;"); 24686 } 24687 24688 TEST_F(FormatTest, CoroutineCoYield) { 24689 verifyFormat("int x = co_yield foo();"); 24690 verifyFormat("int x = (co_yield foo());"); 24691 verifyFormat("co_yield (42);"); 24692 verifyFormat("co_yield {42};"); 24693 verifyFormat("co_yield 42;"); 24694 verifyFormat("co_yield n++;"); 24695 verifyFormat("co_yield ++n;"); 24696 verifyFormat("co_yield;"); 24697 } 24698 24699 TEST_F(FormatTest, CoroutineCoReturn) { 24700 verifyFormat("co_return (42);"); 24701 verifyFormat("co_return;"); 24702 verifyFormat("co_return {};"); 24703 verifyFormat("co_return x;"); 24704 verifyFormat("co_return co_await foo();"); 24705 verifyFormat("co_return co_yield foo();"); 24706 } 24707 24708 TEST_F(FormatTest, EmptyShortBlock) { 24709 auto Style = getLLVMStyle(); 24710 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24711 24712 verifyFormat("try {\n" 24713 " doA();\n" 24714 "} catch (Exception &e) {\n" 24715 " e.printStackTrace();\n" 24716 "}\n", 24717 Style); 24718 24719 verifyFormat("try {\n" 24720 " doA();\n" 24721 "} catch (Exception &e) {}\n", 24722 Style); 24723 } 24724 24725 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24726 auto Style = getLLVMStyle(); 24727 24728 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24729 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24730 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24731 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24732 24733 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24734 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24735 } 24736 24737 TEST_F(FormatTest, InsertBraces) { 24738 FormatStyle Style = getLLVMStyle(); 24739 Style.InsertBraces = true; 24740 24741 verifyFormat("// clang-format off\n" 24742 "// comment\n" 24743 "if (a) f();\n" 24744 "// clang-format on\n" 24745 "if (b) {\n" 24746 " g();\n" 24747 "}", 24748 "// clang-format off\n" 24749 "// comment\n" 24750 "if (a) f();\n" 24751 "// clang-format on\n" 24752 "if (b) g();", 24753 Style); 24754 24755 verifyFormat("if (a) {\n" 24756 " switch (b) {\n" 24757 " case 1:\n" 24758 " c = 0;\n" 24759 " break;\n" 24760 " default:\n" 24761 " c = 1;\n" 24762 " }\n" 24763 "}", 24764 "if (a)\n" 24765 " switch (b) {\n" 24766 " case 1:\n" 24767 " c = 0;\n" 24768 " break;\n" 24769 " default:\n" 24770 " c = 1;\n" 24771 " }", 24772 Style); 24773 24774 verifyFormat("for (auto node : nodes) {\n" 24775 " if (node) {\n" 24776 " break;\n" 24777 " }\n" 24778 "}", 24779 "for (auto node : nodes)\n" 24780 " if (node)\n" 24781 " break;", 24782 Style); 24783 24784 verifyFormat("for (auto node : nodes) {\n" 24785 " if (node)\n" 24786 "}", 24787 "for (auto node : nodes)\n" 24788 " if (node)", 24789 Style); 24790 24791 verifyFormat("do {\n" 24792 " --a;\n" 24793 "} while (a);", 24794 "do\n" 24795 " --a;\n" 24796 "while (a);", 24797 Style); 24798 24799 verifyFormat("if (i) {\n" 24800 " ++i;\n" 24801 "} else {\n" 24802 " --i;\n" 24803 "}", 24804 "if (i)\n" 24805 " ++i;\n" 24806 "else {\n" 24807 " --i;\n" 24808 "}", 24809 Style); 24810 24811 verifyFormat("void f() {\n" 24812 " while (j--) {\n" 24813 " while (i) {\n" 24814 " --i;\n" 24815 " }\n" 24816 " }\n" 24817 "}", 24818 "void f() {\n" 24819 " while (j--)\n" 24820 " while (i)\n" 24821 " --i;\n" 24822 "}", 24823 Style); 24824 24825 verifyFormat("f({\n" 24826 " if (a) {\n" 24827 " g();\n" 24828 " }\n" 24829 "});", 24830 "f({\n" 24831 " if (a)\n" 24832 " g();\n" 24833 "});", 24834 Style); 24835 24836 verifyFormat("if (a) {\n" 24837 " f();\n" 24838 "} else if (b) {\n" 24839 " g();\n" 24840 "} else {\n" 24841 " h();\n" 24842 "}", 24843 "if (a)\n" 24844 " f();\n" 24845 "else if (b)\n" 24846 " g();\n" 24847 "else\n" 24848 " h();", 24849 Style); 24850 24851 verifyFormat("if (a) {\n" 24852 " f();\n" 24853 "}\n" 24854 "// comment\n" 24855 "/* comment */", 24856 "if (a)\n" 24857 " f();\n" 24858 "// comment\n" 24859 "/* comment */", 24860 Style); 24861 24862 verifyFormat("if (a) {\n" 24863 " // foo\n" 24864 " // bar\n" 24865 " f();\n" 24866 "}", 24867 "if (a)\n" 24868 " // foo\n" 24869 " // bar\n" 24870 " f();", 24871 Style); 24872 24873 verifyFormat("if (a) { // comment\n" 24874 " // comment\n" 24875 " f();\n" 24876 "}", 24877 "if (a) // comment\n" 24878 " // comment\n" 24879 " f();", 24880 Style); 24881 24882 verifyFormat("if (a) {\n" 24883 " f(); // comment\n" 24884 "}", 24885 "if (a)\n" 24886 " f(); // comment", 24887 Style); 24888 24889 verifyFormat("if (a) {\n" 24890 " f();\n" 24891 "}\n" 24892 "#undef A\n" 24893 "#undef B", 24894 "if (a)\n" 24895 " f();\n" 24896 "#undef A\n" 24897 "#undef B", 24898 Style); 24899 24900 verifyFormat("if (a)\n" 24901 "#ifdef A\n" 24902 " f();\n" 24903 "#else\n" 24904 " g();\n" 24905 "#endif", 24906 Style); 24907 24908 verifyFormat("#if 0\n" 24909 "#elif 1\n" 24910 "#endif\n" 24911 "void f() {\n" 24912 " if (a) {\n" 24913 " g();\n" 24914 " }\n" 24915 "}", 24916 "#if 0\n" 24917 "#elif 1\n" 24918 "#endif\n" 24919 "void f() {\n" 24920 " if (a) g();\n" 24921 "}", 24922 Style); 24923 24924 Style.ColumnLimit = 15; 24925 24926 verifyFormat("#define A \\\n" 24927 " if (a) \\\n" 24928 " f();", 24929 Style); 24930 24931 verifyFormat("if (a + b >\n" 24932 " c) {\n" 24933 " f();\n" 24934 "}", 24935 "if (a + b > c)\n" 24936 " f();", 24937 Style); 24938 } 24939 24940 TEST_F(FormatTest, RemoveBraces) { 24941 FormatStyle Style = getLLVMStyle(); 24942 Style.RemoveBracesLLVM = true; 24943 24944 // The following eight test cases are fully-braced versions of the examples at 24945 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24946 // statement-bodies-of-if-else-loop-statements". 24947 24948 // 1. Omit the braces, since the body is simple and clearly associated with 24949 // the if. 24950 verifyFormat("if (isa<FunctionDecl>(D))\n" 24951 " handleFunctionDecl(D);\n" 24952 "else if (isa<VarDecl>(D))\n" 24953 " handleVarDecl(D);", 24954 "if (isa<FunctionDecl>(D)) {\n" 24955 " handleFunctionDecl(D);\n" 24956 "} else if (isa<VarDecl>(D)) {\n" 24957 " handleVarDecl(D);\n" 24958 "}", 24959 Style); 24960 24961 // 2. Here we document the condition itself and not the body. 24962 verifyFormat("if (isa<VarDecl>(D)) {\n" 24963 " // It is necessary that we explain the situation with this\n" 24964 " // surprisingly long comment, so it would be unclear\n" 24965 " // without the braces whether the following statement is in\n" 24966 " // the scope of the `if`.\n" 24967 " // Because the condition is documented, we can't really\n" 24968 " // hoist this comment that applies to the body above the\n" 24969 " // if.\n" 24970 " handleOtherDecl(D);\n" 24971 "}", 24972 Style); 24973 24974 // 3. Use braces on the outer `if` to avoid a potential dangling else 24975 // situation. 24976 verifyFormat("if (isa<VarDecl>(D)) {\n" 24977 " for (auto *A : D.attrs())\n" 24978 " if (shouldProcessAttr(A))\n" 24979 " handleAttr(A);\n" 24980 "}", 24981 "if (isa<VarDecl>(D)) {\n" 24982 " for (auto *A : D.attrs()) {\n" 24983 " if (shouldProcessAttr(A)) {\n" 24984 " handleAttr(A);\n" 24985 " }\n" 24986 " }\n" 24987 "}", 24988 Style); 24989 24990 // 4. Use braces for the `if` block to keep it uniform with the else block. 24991 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24992 " handleFunctionDecl(D);\n" 24993 "} else {\n" 24994 " // In this else case, it is necessary that we explain the\n" 24995 " // situation with this surprisingly long comment, so it\n" 24996 " // would be unclear without the braces whether the\n" 24997 " // following statement is in the scope of the `if`.\n" 24998 " handleOtherDecl(D);\n" 24999 "}", 25000 Style); 25001 25002 // 5. This should also omit braces. The `for` loop contains only a single 25003 // statement, so it shouldn't have braces. The `if` also only contains a 25004 // single simple statement (the for loop), so it also should omit braces. 25005 verifyFormat("if (isa<FunctionDecl>(D))\n" 25006 " for (auto *A : D.attrs())\n" 25007 " handleAttr(A);", 25008 "if (isa<FunctionDecl>(D)) {\n" 25009 " for (auto *A : D.attrs()) {\n" 25010 " handleAttr(A);\n" 25011 " }\n" 25012 "}", 25013 Style); 25014 25015 // 6. Use braces for the outer `if` since the nested `for` is braced. 25016 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25017 " for (auto *A : D.attrs()) {\n" 25018 " // In this for loop body, it is necessary that we explain\n" 25019 " // the situation with this surprisingly long comment,\n" 25020 " // forcing braces on the `for` block.\n" 25021 " handleAttr(A);\n" 25022 " }\n" 25023 "}", 25024 Style); 25025 25026 // 7. Use braces on the outer block because there are more than two levels of 25027 // nesting. 25028 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25029 " for (auto *A : D.attrs())\n" 25030 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 25031 " handleAttrOnDecl(D, A, i);\n" 25032 "}", 25033 "if (isa<FunctionDecl>(D)) {\n" 25034 " for (auto *A : D.attrs()) {\n" 25035 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 25036 " handleAttrOnDecl(D, A, i);\n" 25037 " }\n" 25038 " }\n" 25039 "}", 25040 Style); 25041 25042 // 8. Use braces on the outer block because of a nested `if`, otherwise the 25043 // compiler would warn: `add explicit braces to avoid dangling else` 25044 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25045 " if (shouldProcess(D))\n" 25046 " handleVarDecl(D);\n" 25047 " else\n" 25048 " markAsIgnored(D);\n" 25049 "}", 25050 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25051 " if (shouldProcess(D)) {\n" 25052 " handleVarDecl(D);\n" 25053 " } else {\n" 25054 " markAsIgnored(D);\n" 25055 " }\n" 25056 "}", 25057 Style); 25058 25059 verifyFormat("// clang-format off\n" 25060 "// comment\n" 25061 "while (i > 0) { --i; }\n" 25062 "// clang-format on\n" 25063 "while (j < 0)\n" 25064 " ++j;", 25065 "// clang-format off\n" 25066 "// comment\n" 25067 "while (i > 0) { --i; }\n" 25068 "// clang-format on\n" 25069 "while (j < 0) { ++j; }", 25070 Style); 25071 25072 verifyFormat("if (a)\n" 25073 " b; // comment\n" 25074 "else if (c)\n" 25075 " d; /* comment */\n" 25076 "else\n" 25077 " e;", 25078 "if (a) {\n" 25079 " b; // comment\n" 25080 "} else if (c) {\n" 25081 " d; /* comment */\n" 25082 "} else {\n" 25083 " e;\n" 25084 "}", 25085 Style); 25086 25087 verifyFormat("if (a) {\n" 25088 " b;\n" 25089 " c;\n" 25090 "} else if (d) {\n" 25091 " e;\n" 25092 "}", 25093 Style); 25094 25095 verifyFormat("if (a) {\n" 25096 "#undef NDEBUG\n" 25097 " b;\n" 25098 "} else {\n" 25099 " c;\n" 25100 "}", 25101 Style); 25102 25103 verifyFormat("if (a) {\n" 25104 " // comment\n" 25105 "} else if (b) {\n" 25106 " c;\n" 25107 "}", 25108 Style); 25109 25110 verifyFormat("if (a) {\n" 25111 " b;\n" 25112 "} else {\n" 25113 " { c; }\n" 25114 "}", 25115 Style); 25116 25117 verifyFormat("if (a) {\n" 25118 " if (b) // comment\n" 25119 " c;\n" 25120 "} else if (d) {\n" 25121 " e;\n" 25122 "}", 25123 "if (a) {\n" 25124 " if (b) { // comment\n" 25125 " c;\n" 25126 " }\n" 25127 "} else if (d) {\n" 25128 " e;\n" 25129 "}", 25130 Style); 25131 25132 verifyFormat("if (a) {\n" 25133 " if (b) {\n" 25134 " c;\n" 25135 " // comment\n" 25136 " } else if (d) {\n" 25137 " e;\n" 25138 " }\n" 25139 "}", 25140 Style); 25141 25142 verifyFormat("if (a) {\n" 25143 " if (b)\n" 25144 " c;\n" 25145 "}", 25146 "if (a) {\n" 25147 " if (b) {\n" 25148 " c;\n" 25149 " }\n" 25150 "}", 25151 Style); 25152 25153 verifyFormat("if (a)\n" 25154 " if (b)\n" 25155 " c;\n" 25156 " else\n" 25157 " d;\n" 25158 "else\n" 25159 " e;", 25160 "if (a) {\n" 25161 " if (b) {\n" 25162 " c;\n" 25163 " } else {\n" 25164 " d;\n" 25165 " }\n" 25166 "} else {\n" 25167 " e;\n" 25168 "}", 25169 Style); 25170 25171 verifyFormat("if (a) {\n" 25172 " // comment\n" 25173 " if (b)\n" 25174 " c;\n" 25175 " else if (d)\n" 25176 " e;\n" 25177 "} else {\n" 25178 " g;\n" 25179 "}", 25180 "if (a) {\n" 25181 " // comment\n" 25182 " if (b) {\n" 25183 " c;\n" 25184 " } else if (d) {\n" 25185 " e;\n" 25186 " }\n" 25187 "} else {\n" 25188 " g;\n" 25189 "}", 25190 Style); 25191 25192 verifyFormat("if (a)\n" 25193 " b;\n" 25194 "else if (c)\n" 25195 " d;\n" 25196 "else\n" 25197 " e;", 25198 "if (a) {\n" 25199 " b;\n" 25200 "} else {\n" 25201 " if (c) {\n" 25202 " d;\n" 25203 " } else {\n" 25204 " e;\n" 25205 " }\n" 25206 "}", 25207 Style); 25208 25209 verifyFormat("if (a) {\n" 25210 " if (b)\n" 25211 " c;\n" 25212 " else if (d)\n" 25213 " e;\n" 25214 "} else {\n" 25215 " g;\n" 25216 "}", 25217 "if (a) {\n" 25218 " if (b)\n" 25219 " c;\n" 25220 " else {\n" 25221 " if (d)\n" 25222 " e;\n" 25223 " }\n" 25224 "} else {\n" 25225 " g;\n" 25226 "}", 25227 Style); 25228 25229 verifyFormat("if (a)\n" 25230 " b;\n" 25231 "else if (c)\n" 25232 " while (d)\n" 25233 " e;\n" 25234 "// comment", 25235 "if (a)\n" 25236 "{\n" 25237 " b;\n" 25238 "} else if (c) {\n" 25239 " while (d) {\n" 25240 " e;\n" 25241 " }\n" 25242 "}\n" 25243 "// comment", 25244 Style); 25245 25246 verifyFormat("if (a) {\n" 25247 " b;\n" 25248 "} else if (c) {\n" 25249 " d;\n" 25250 "} else {\n" 25251 " e;\n" 25252 " g;\n" 25253 "}", 25254 Style); 25255 25256 verifyFormat("if (a) {\n" 25257 " b;\n" 25258 "} else if (c) {\n" 25259 " d;\n" 25260 "} else {\n" 25261 " e;\n" 25262 "} // comment", 25263 Style); 25264 25265 verifyFormat("int abs = [](int i) {\n" 25266 " if (i >= 0)\n" 25267 " return i;\n" 25268 " return -i;\n" 25269 "};", 25270 "int abs = [](int i) {\n" 25271 " if (i >= 0) {\n" 25272 " return i;\n" 25273 " }\n" 25274 " return -i;\n" 25275 "};", 25276 Style); 25277 25278 verifyFormat("if (a)\n" 25279 " foo();\n" 25280 "else\n" 25281 " bar();", 25282 "if (a)\n" 25283 "{\n" 25284 " foo();\n" 25285 "}\n" 25286 "else\n" 25287 "{\n" 25288 " bar();\n" 25289 "}", 25290 Style); 25291 25292 verifyFormat("if (a) {\n" 25293 "Label:\n" 25294 "}", 25295 Style); 25296 25297 verifyFormat("if (a) {\n" 25298 "Label:\n" 25299 " f();\n" 25300 "}", 25301 Style); 25302 25303 verifyFormat("if (a) {\n" 25304 " f();\n" 25305 "Label:\n" 25306 "}", 25307 Style); 25308 25309 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 25310 #if 0 25311 Style.ColumnLimit = 65; 25312 25313 verifyFormat("if (condition) {\n" 25314 " ff(Indices,\n" 25315 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25316 "} else {\n" 25317 " ff(Indices,\n" 25318 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25319 "}", 25320 Style); 25321 25322 Style.ColumnLimit = 20; 25323 25324 verifyFormat("if (a) {\n" 25325 " b = c + // 1 -\n" 25326 " d;\n" 25327 "}", 25328 Style); 25329 25330 verifyFormat("if (a) {\n" 25331 " b = c >= 0 ? d\n" 25332 " : e;\n" 25333 "}", 25334 "if (a) {\n" 25335 " b = c >= 0 ? d : e;\n" 25336 "}", 25337 Style); 25338 #endif 25339 25340 Style.ColumnLimit = 20; 25341 25342 verifyFormat("if (a)\n" 25343 " b = c > 0 ? d : e;", 25344 "if (a) {\n" 25345 " b = c > 0 ? d : e;\n" 25346 "}", 25347 Style); 25348 25349 Style.ColumnLimit = 0; 25350 25351 verifyFormat("if (a)\n" 25352 " b234567890223456789032345678904234567890 = " 25353 "c234567890223456789032345678904234567890;", 25354 "if (a) {\n" 25355 " b234567890223456789032345678904234567890 = " 25356 "c234567890223456789032345678904234567890;\n" 25357 "}", 25358 Style); 25359 } 25360 25361 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25362 auto Style = getLLVMStyle(); 25363 25364 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25365 "void functionDecl(int a, int b, int c);"; 25366 25367 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25368 "paramF, paramG, paramH, paramI);\n" 25369 "void functionDecl(int argumentA, int argumentB, int " 25370 "argumentC, int argumentD, int argumentE);"; 25371 25372 verifyFormat(Short, Style); 25373 25374 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25375 "paramF, paramG, paramH,\n" 25376 " paramI);\n" 25377 "void functionDecl(int argumentA, int argumentB, int " 25378 "argumentC, int argumentD,\n" 25379 " int argumentE);"; 25380 25381 verifyFormat(NoBreak, Medium, Style); 25382 verifyFormat(NoBreak, 25383 "functionCall(\n" 25384 " paramA,\n" 25385 " paramB,\n" 25386 " paramC,\n" 25387 " paramD,\n" 25388 " paramE,\n" 25389 " paramF,\n" 25390 " paramG,\n" 25391 " paramH,\n" 25392 " paramI\n" 25393 ");\n" 25394 "void functionDecl(\n" 25395 " int argumentA,\n" 25396 " int argumentB,\n" 25397 " int argumentC,\n" 25398 " int argumentD,\n" 25399 " int argumentE\n" 25400 ");", 25401 Style); 25402 25403 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25404 " nestedLongFunctionCall(argument1, " 25405 "argument2, argument3,\n" 25406 " argument4, " 25407 "argument5));", 25408 Style); 25409 25410 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25411 25412 verifyFormat(Short, Style); 25413 verifyFormat( 25414 "functionCall(\n" 25415 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25416 "paramI\n" 25417 ");\n" 25418 "void functionDecl(\n" 25419 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25420 "argumentE\n" 25421 ");", 25422 Medium, Style); 25423 25424 Style.AllowAllArgumentsOnNextLine = false; 25425 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25426 25427 verifyFormat(Short, Style); 25428 verifyFormat( 25429 "functionCall(\n" 25430 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25431 "paramI\n" 25432 ");\n" 25433 "void functionDecl(\n" 25434 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25435 "argumentE\n" 25436 ");", 25437 Medium, Style); 25438 25439 Style.BinPackArguments = false; 25440 Style.BinPackParameters = false; 25441 25442 verifyFormat(Short, Style); 25443 25444 verifyFormat("functionCall(\n" 25445 " paramA,\n" 25446 " paramB,\n" 25447 " paramC,\n" 25448 " paramD,\n" 25449 " paramE,\n" 25450 " paramF,\n" 25451 " paramG,\n" 25452 " paramH,\n" 25453 " paramI\n" 25454 ");\n" 25455 "void functionDecl(\n" 25456 " int argumentA,\n" 25457 " int argumentB,\n" 25458 " int argumentC,\n" 25459 " int argumentD,\n" 25460 " int argumentE\n" 25461 ");", 25462 Medium, Style); 25463 25464 verifyFormat("outerFunctionCall(\n" 25465 " nestedFunctionCall(argument1),\n" 25466 " nestedLongFunctionCall(\n" 25467 " argument1,\n" 25468 " argument2,\n" 25469 " argument3,\n" 25470 " argument4,\n" 25471 " argument5\n" 25472 " )\n" 25473 ");", 25474 Style); 25475 25476 verifyFormat("int a = (int)b;", Style); 25477 verifyFormat("int a = (int)b;", 25478 "int a = (\n" 25479 " int\n" 25480 ") b;", 25481 Style); 25482 25483 verifyFormat("return (true);", Style); 25484 verifyFormat("return (true);", 25485 "return (\n" 25486 " true\n" 25487 ");", 25488 Style); 25489 25490 verifyFormat("void foo();", Style); 25491 verifyFormat("void foo();", 25492 "void foo(\n" 25493 ");", 25494 Style); 25495 25496 verifyFormat("void foo() {}", Style); 25497 verifyFormat("void foo() {}", 25498 "void foo(\n" 25499 ") {\n" 25500 "}", 25501 Style); 25502 25503 verifyFormat("auto string = std::string();", Style); 25504 verifyFormat("auto string = std::string();", 25505 "auto string = std::string(\n" 25506 ");", 25507 Style); 25508 25509 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25510 verifyFormat("void (*functionPointer)() = nullptr;", 25511 "void (\n" 25512 " *functionPointer\n" 25513 ")\n" 25514 "(\n" 25515 ") = nullptr;", 25516 Style); 25517 } 25518 25519 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25520 auto Style = getLLVMStyle(); 25521 25522 verifyFormat("if (foo()) {\n" 25523 " return;\n" 25524 "}", 25525 Style); 25526 25527 verifyFormat("if (quitelongarg !=\n" 25528 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25529 "comment\n" 25530 " return;\n" 25531 "}", 25532 Style); 25533 25534 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25535 25536 verifyFormat("if (foo()) {\n" 25537 " return;\n" 25538 "}", 25539 Style); 25540 25541 verifyFormat("if (quitelongarg !=\n" 25542 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25543 "comment\n" 25544 " return;\n" 25545 "}", 25546 Style); 25547 } 25548 25549 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25550 auto Style = getLLVMStyle(); 25551 25552 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25553 " doSomething();\n" 25554 "}", 25555 Style); 25556 25557 verifyFormat("for (int myReallyLongCountVariable = 0; " 25558 "myReallyLongCountVariable < count;\n" 25559 " myReallyLongCountVariable++) {\n" 25560 " doSomething();\n" 25561 "}", 25562 Style); 25563 25564 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25565 25566 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25567 " doSomething();\n" 25568 "}", 25569 Style); 25570 25571 verifyFormat("for (int myReallyLongCountVariable = 0; " 25572 "myReallyLongCountVariable < count;\n" 25573 " myReallyLongCountVariable++) {\n" 25574 " doSomething();\n" 25575 "}", 25576 Style); 25577 } 25578 25579 TEST_F(FormatTest, UnderstandsDigraphs) { 25580 verifyFormat("int arr<:5:> = {};"); 25581 verifyFormat("int arr[5] = <%%>;"); 25582 verifyFormat("int arr<:::qualified_variable:> = {};"); 25583 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25584 verifyFormat("%:include <header>"); 25585 verifyFormat("%:define A x##y"); 25586 verifyFormat("#define A x%:%:y"); 25587 } 25588 25589 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 25590 auto Style = getLLVMStyle(); 25591 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 25592 Style.AlignConsecutiveAssignments.Enabled = true; 25593 Style.AlignConsecutiveDeclarations.Enabled = true; 25594 25595 // The AlignArray code is incorrect for non square Arrays and can cause 25596 // crashes, these tests assert that the array is not changed but will 25597 // also act as regression tests for when it is properly fixed 25598 verifyFormat("struct test demo[] = {\n" 25599 " {1, 2},\n" 25600 " {3, 4, 5},\n" 25601 " {6, 7, 8}\n" 25602 "};", 25603 Style); 25604 verifyFormat("struct test demo[] = {\n" 25605 " {1, 2, 3, 4, 5},\n" 25606 " {3, 4, 5},\n" 25607 " {6, 7, 8}\n" 25608 "};", 25609 Style); 25610 verifyFormat("struct test demo[] = {\n" 25611 " {1, 2, 3, 4, 5},\n" 25612 " {3, 4, 5},\n" 25613 " {6, 7, 8, 9, 10, 11, 12}\n" 25614 "};", 25615 Style); 25616 verifyFormat("struct test demo[] = {\n" 25617 " {1, 2, 3},\n" 25618 " {3, 4, 5},\n" 25619 " {6, 7, 8, 9, 10, 11, 12}\n" 25620 "};", 25621 Style); 25622 25623 verifyFormat("S{\n" 25624 " {},\n" 25625 " {},\n" 25626 " {a, b}\n" 25627 "};", 25628 Style); 25629 verifyFormat("S{\n" 25630 " {},\n" 25631 " {},\n" 25632 " {a, b},\n" 25633 "};", 25634 Style); 25635 verifyFormat("void foo() {\n" 25636 " auto thing = test{\n" 25637 " {\n" 25638 " {13}, {something}, // A\n" 25639 " }\n" 25640 " };\n" 25641 "}", 25642 "void foo() {\n" 25643 " auto thing = test{\n" 25644 " {\n" 25645 " {13},\n" 25646 " {something}, // A\n" 25647 " }\n" 25648 " };\n" 25649 "}", 25650 Style); 25651 } 25652 25653 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 25654 auto Style = getLLVMStyle(); 25655 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 25656 Style.AlignConsecutiveAssignments.Enabled = true; 25657 Style.AlignConsecutiveDeclarations.Enabled = true; 25658 25659 // The AlignArray code is incorrect for non square Arrays and can cause 25660 // crashes, these tests assert that the array is not changed but will 25661 // also act as regression tests for when it is properly fixed 25662 verifyFormat("struct test demo[] = {\n" 25663 " {1, 2},\n" 25664 " {3, 4, 5},\n" 25665 " {6, 7, 8}\n" 25666 "};", 25667 Style); 25668 verifyFormat("struct test demo[] = {\n" 25669 " {1, 2, 3, 4, 5},\n" 25670 " {3, 4, 5},\n" 25671 " {6, 7, 8}\n" 25672 "};", 25673 Style); 25674 verifyFormat("struct test demo[] = {\n" 25675 " {1, 2, 3, 4, 5},\n" 25676 " {3, 4, 5},\n" 25677 " {6, 7, 8, 9, 10, 11, 12}\n" 25678 "};", 25679 Style); 25680 verifyFormat("struct test demo[] = {\n" 25681 " {1, 2, 3},\n" 25682 " {3, 4, 5},\n" 25683 " {6, 7, 8, 9, 10, 11, 12}\n" 25684 "};", 25685 Style); 25686 25687 verifyFormat("S{\n" 25688 " {},\n" 25689 " {},\n" 25690 " {a, b}\n" 25691 "};", 25692 Style); 25693 verifyFormat("S{\n" 25694 " {},\n" 25695 " {},\n" 25696 " {a, b},\n" 25697 "};", 25698 Style); 25699 verifyFormat("void foo() {\n" 25700 " auto thing = test{\n" 25701 " {\n" 25702 " {13}, {something}, // A\n" 25703 " }\n" 25704 " };\n" 25705 "}", 25706 "void foo() {\n" 25707 " auto thing = test{\n" 25708 " {\n" 25709 " {13},\n" 25710 " {something}, // A\n" 25711 " }\n" 25712 " };\n" 25713 "}", 25714 Style); 25715 } 25716 25717 TEST_F(FormatTest, FormatsVariableTemplates) { 25718 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 25719 verifyFormat("template <typename T> " 25720 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 25721 } 25722 25723 } // namespace 25724 } // namespace format 25725 } // namespace clang 25726