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 Style.AllowShortEnumsOnASingleLine = true; 2771 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2772 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2773 Style.AllowShortEnumsOnASingleLine = false; 2774 verifyFormat("enum {\n" 2775 " A,\n" 2776 " B,\n" 2777 " C\n" 2778 "} ShortEnum1, ShortEnum2;", 2779 Style); 2780 verifyFormat("typedef enum {\n" 2781 " A,\n" 2782 " B,\n" 2783 " C\n" 2784 "} ShortEnum1, ShortEnum2;", 2785 Style); 2786 verifyFormat("enum {\n" 2787 " A,\n" 2788 "} ShortEnum1, ShortEnum2;", 2789 Style); 2790 verifyFormat("typedef enum {\n" 2791 " A,\n" 2792 "} ShortEnum1, ShortEnum2;", 2793 Style); 2794 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2795 Style.BraceWrapping.AfterEnum = true; 2796 verifyFormat("enum\n" 2797 "{\n" 2798 " A,\n" 2799 " B,\n" 2800 " C\n" 2801 "} ShortEnum1, ShortEnum2;", 2802 Style); 2803 verifyFormat("typedef enum\n" 2804 "{\n" 2805 " A,\n" 2806 " B,\n" 2807 " C\n" 2808 "} ShortEnum1, ShortEnum2;", 2809 Style); 2810 } 2811 2812 TEST_F(FormatTest, ShortCaseLabels) { 2813 FormatStyle Style = getLLVMStyle(); 2814 Style.AllowShortCaseLabelsOnASingleLine = true; 2815 verifyFormat("switch (a) {\n" 2816 "case 1: x = 1; break;\n" 2817 "case 2: return;\n" 2818 "case 3:\n" 2819 "case 4:\n" 2820 "case 5: return;\n" 2821 "case 6: // comment\n" 2822 " return;\n" 2823 "case 7:\n" 2824 " // comment\n" 2825 " return;\n" 2826 "case 8:\n" 2827 " x = 8; // comment\n" 2828 " break;\n" 2829 "default: y = 1; break;\n" 2830 "}", 2831 Style); 2832 verifyFormat("switch (a) {\n" 2833 "case 0: return; // comment\n" 2834 "case 1: break; // comment\n" 2835 "case 2: return;\n" 2836 "// comment\n" 2837 "case 3: return;\n" 2838 "// comment 1\n" 2839 "// comment 2\n" 2840 "// comment 3\n" 2841 "case 4: break; /* comment */\n" 2842 "case 5:\n" 2843 " // comment\n" 2844 " break;\n" 2845 "case 6: /* comment */ x = 1; break;\n" 2846 "case 7: x = /* comment */ 1; break;\n" 2847 "case 8:\n" 2848 " x = 1; /* comment */\n" 2849 " break;\n" 2850 "case 9:\n" 2851 " break; // comment line 1\n" 2852 " // comment line 2\n" 2853 "}", 2854 Style); 2855 EXPECT_EQ("switch (a) {\n" 2856 "case 1:\n" 2857 " x = 8;\n" 2858 " // fall through\n" 2859 "case 2: x = 8;\n" 2860 "// comment\n" 2861 "case 3:\n" 2862 " return; /* comment line 1\n" 2863 " * comment line 2 */\n" 2864 "case 4: i = 8;\n" 2865 "// something else\n" 2866 "#if FOO\n" 2867 "case 5: break;\n" 2868 "#endif\n" 2869 "}", 2870 format("switch (a) {\n" 2871 "case 1: x = 8;\n" 2872 " // fall through\n" 2873 "case 2:\n" 2874 " x = 8;\n" 2875 "// comment\n" 2876 "case 3:\n" 2877 " return; /* comment line 1\n" 2878 " * comment line 2 */\n" 2879 "case 4:\n" 2880 " i = 8;\n" 2881 "// something else\n" 2882 "#if FOO\n" 2883 "case 5: break;\n" 2884 "#endif\n" 2885 "}", 2886 Style)); 2887 EXPECT_EQ("switch (a) {\n" 2888 "case 0:\n" 2889 " return; // long long long long long long long long long long " 2890 "long long comment\n" 2891 " // line\n" 2892 "}", 2893 format("switch (a) {\n" 2894 "case 0: return; // long long long long long long long long " 2895 "long long long long comment line\n" 2896 "}", 2897 Style)); 2898 EXPECT_EQ("switch (a) {\n" 2899 "case 0:\n" 2900 " return; /* long long long long long long long long long long " 2901 "long long comment\n" 2902 " line */\n" 2903 "}", 2904 format("switch (a) {\n" 2905 "case 0: return; /* long long long long long long long long " 2906 "long long long long comment line */\n" 2907 "}", 2908 Style)); 2909 verifyFormat("switch (a) {\n" 2910 "#if FOO\n" 2911 "case 0: return 0;\n" 2912 "#endif\n" 2913 "}", 2914 Style); 2915 verifyFormat("switch (a) {\n" 2916 "case 1: {\n" 2917 "}\n" 2918 "case 2: {\n" 2919 " return;\n" 2920 "}\n" 2921 "case 3: {\n" 2922 " x = 1;\n" 2923 " return;\n" 2924 "}\n" 2925 "case 4:\n" 2926 " if (x)\n" 2927 " return;\n" 2928 "}", 2929 Style); 2930 Style.ColumnLimit = 21; 2931 verifyFormat("switch (a) {\n" 2932 "case 1: x = 1; break;\n" 2933 "case 2: return;\n" 2934 "case 3:\n" 2935 "case 4:\n" 2936 "case 5: return;\n" 2937 "default:\n" 2938 " y = 1;\n" 2939 " break;\n" 2940 "}", 2941 Style); 2942 Style.ColumnLimit = 80; 2943 Style.AllowShortCaseLabelsOnASingleLine = false; 2944 Style.IndentCaseLabels = true; 2945 EXPECT_EQ("switch (n) {\n" 2946 " default /*comments*/:\n" 2947 " return true;\n" 2948 " case 0:\n" 2949 " return false;\n" 2950 "}", 2951 format("switch (n) {\n" 2952 "default/*comments*/:\n" 2953 " return true;\n" 2954 "case 0:\n" 2955 " return false;\n" 2956 "}", 2957 Style)); 2958 Style.AllowShortCaseLabelsOnASingleLine = true; 2959 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2960 Style.BraceWrapping.AfterCaseLabel = true; 2961 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2962 EXPECT_EQ("switch (n)\n" 2963 "{\n" 2964 " case 0:\n" 2965 " {\n" 2966 " return false;\n" 2967 " }\n" 2968 " default:\n" 2969 " {\n" 2970 " return true;\n" 2971 " }\n" 2972 "}", 2973 format("switch (n) {\n" 2974 " case 0: {\n" 2975 " return false;\n" 2976 " }\n" 2977 " default:\n" 2978 " {\n" 2979 " return true;\n" 2980 " }\n" 2981 "}", 2982 Style)); 2983 } 2984 2985 TEST_F(FormatTest, FormatsLabels) { 2986 verifyFormat("void f() {\n" 2987 " some_code();\n" 2988 "test_label:\n" 2989 " some_other_code();\n" 2990 " {\n" 2991 " some_more_code();\n" 2992 " another_label:\n" 2993 " some_more_code();\n" 2994 " }\n" 2995 "}"); 2996 verifyFormat("{\n" 2997 " some_code();\n" 2998 "test_label:\n" 2999 " some_other_code();\n" 3000 "}"); 3001 verifyFormat("{\n" 3002 " some_code();\n" 3003 "test_label:;\n" 3004 " int i = 0;\n" 3005 "}"); 3006 FormatStyle Style = getLLVMStyle(); 3007 Style.IndentGotoLabels = false; 3008 verifyFormat("void f() {\n" 3009 " some_code();\n" 3010 "test_label:\n" 3011 " some_other_code();\n" 3012 " {\n" 3013 " some_more_code();\n" 3014 "another_label:\n" 3015 " some_more_code();\n" 3016 " }\n" 3017 "}", 3018 Style); 3019 verifyFormat("{\n" 3020 " some_code();\n" 3021 "test_label:\n" 3022 " some_other_code();\n" 3023 "}", 3024 Style); 3025 verifyFormat("{\n" 3026 " some_code();\n" 3027 "test_label:;\n" 3028 " int i = 0;\n" 3029 "}"); 3030 } 3031 3032 TEST_F(FormatTest, MultiLineControlStatements) { 3033 FormatStyle Style = getLLVMStyleWithColumns(20); 3034 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3035 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3036 // Short lines should keep opening brace on same line. 3037 EXPECT_EQ("if (foo) {\n" 3038 " bar();\n" 3039 "}", 3040 format("if(foo){bar();}", Style)); 3041 EXPECT_EQ("if (foo) {\n" 3042 " bar();\n" 3043 "} else {\n" 3044 " baz();\n" 3045 "}", 3046 format("if(foo){bar();}else{baz();}", Style)); 3047 EXPECT_EQ("if (foo && bar) {\n" 3048 " baz();\n" 3049 "}", 3050 format("if(foo&&bar){baz();}", Style)); 3051 EXPECT_EQ("if (foo) {\n" 3052 " bar();\n" 3053 "} else if (baz) {\n" 3054 " quux();\n" 3055 "}", 3056 format("if(foo){bar();}else if(baz){quux();}", Style)); 3057 EXPECT_EQ( 3058 "if (foo) {\n" 3059 " bar();\n" 3060 "} else if (baz) {\n" 3061 " quux();\n" 3062 "} else {\n" 3063 " foobar();\n" 3064 "}", 3065 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 3066 EXPECT_EQ("for (;;) {\n" 3067 " foo();\n" 3068 "}", 3069 format("for(;;){foo();}")); 3070 EXPECT_EQ("while (1) {\n" 3071 " foo();\n" 3072 "}", 3073 format("while(1){foo();}", Style)); 3074 EXPECT_EQ("switch (foo) {\n" 3075 "case bar:\n" 3076 " return;\n" 3077 "}", 3078 format("switch(foo){case bar:return;}", Style)); 3079 EXPECT_EQ("try {\n" 3080 " foo();\n" 3081 "} catch (...) {\n" 3082 " bar();\n" 3083 "}", 3084 format("try{foo();}catch(...){bar();}", Style)); 3085 EXPECT_EQ("do {\n" 3086 " foo();\n" 3087 "} while (bar &&\n" 3088 " baz);", 3089 format("do{foo();}while(bar&&baz);", Style)); 3090 // Long lines should put opening brace on new line. 3091 EXPECT_EQ("if (foo && bar &&\n" 3092 " baz)\n" 3093 "{\n" 3094 " quux();\n" 3095 "}", 3096 format("if(foo&&bar&&baz){quux();}", Style)); 3097 EXPECT_EQ("if (foo && bar &&\n" 3098 " baz)\n" 3099 "{\n" 3100 " quux();\n" 3101 "}", 3102 format("if (foo && bar &&\n" 3103 " baz) {\n" 3104 " quux();\n" 3105 "}", 3106 Style)); 3107 EXPECT_EQ("if (foo) {\n" 3108 " bar();\n" 3109 "} else if (baz ||\n" 3110 " quux)\n" 3111 "{\n" 3112 " foobar();\n" 3113 "}", 3114 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3115 EXPECT_EQ( 3116 "if (foo) {\n" 3117 " bar();\n" 3118 "} else if (baz ||\n" 3119 " quux)\n" 3120 "{\n" 3121 " foobar();\n" 3122 "} else {\n" 3123 " barbaz();\n" 3124 "}", 3125 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3126 Style)); 3127 EXPECT_EQ("for (int i = 0;\n" 3128 " i < 10; ++i)\n" 3129 "{\n" 3130 " foo();\n" 3131 "}", 3132 format("for(int i=0;i<10;++i){foo();}", Style)); 3133 EXPECT_EQ("foreach (int i,\n" 3134 " list)\n" 3135 "{\n" 3136 " foo();\n" 3137 "}", 3138 format("foreach(int i, list){foo();}", Style)); 3139 Style.ColumnLimit = 3140 40; // to concentrate at brace wrapping, not line wrap due to column limit 3141 EXPECT_EQ("foreach (int i, list) {\n" 3142 " foo();\n" 3143 "}", 3144 format("foreach(int i, list){foo();}", Style)); 3145 Style.ColumnLimit = 3146 20; // to concentrate at brace wrapping, not line wrap due to column limit 3147 EXPECT_EQ("while (foo || bar ||\n" 3148 " baz)\n" 3149 "{\n" 3150 " quux();\n" 3151 "}", 3152 format("while(foo||bar||baz){quux();}", Style)); 3153 EXPECT_EQ("switch (\n" 3154 " foo = barbaz)\n" 3155 "{\n" 3156 "case quux:\n" 3157 " return;\n" 3158 "}", 3159 format("switch(foo=barbaz){case quux:return;}", Style)); 3160 EXPECT_EQ("try {\n" 3161 " foo();\n" 3162 "} catch (\n" 3163 " Exception &bar)\n" 3164 "{\n" 3165 " baz();\n" 3166 "}", 3167 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3168 Style.ColumnLimit = 3169 40; // to concentrate at brace wrapping, not line wrap due to column limit 3170 EXPECT_EQ("try {\n" 3171 " foo();\n" 3172 "} catch (Exception &bar) {\n" 3173 " baz();\n" 3174 "}", 3175 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3176 Style.ColumnLimit = 3177 20; // to concentrate at brace wrapping, not line wrap due to column limit 3178 3179 Style.BraceWrapping.BeforeElse = true; 3180 EXPECT_EQ( 3181 "if (foo) {\n" 3182 " bar();\n" 3183 "}\n" 3184 "else if (baz ||\n" 3185 " quux)\n" 3186 "{\n" 3187 " foobar();\n" 3188 "}\n" 3189 "else {\n" 3190 " barbaz();\n" 3191 "}", 3192 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3193 Style)); 3194 3195 Style.BraceWrapping.BeforeCatch = true; 3196 EXPECT_EQ("try {\n" 3197 " foo();\n" 3198 "}\n" 3199 "catch (...) {\n" 3200 " baz();\n" 3201 "}", 3202 format("try{foo();}catch(...){baz();}", Style)); 3203 3204 Style.BraceWrapping.AfterFunction = true; 3205 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3206 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3207 Style.ColumnLimit = 80; 3208 verifyFormat("void shortfunction() { bar(); }", Style); 3209 3210 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3211 verifyFormat("void shortfunction()\n" 3212 "{\n" 3213 " bar();\n" 3214 "}", 3215 Style); 3216 } 3217 3218 TEST_F(FormatTest, BeforeWhile) { 3219 FormatStyle Style = getLLVMStyle(); 3220 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3221 3222 verifyFormat("do {\n" 3223 " foo();\n" 3224 "} while (1);", 3225 Style); 3226 Style.BraceWrapping.BeforeWhile = true; 3227 verifyFormat("do {\n" 3228 " foo();\n" 3229 "}\n" 3230 "while (1);", 3231 Style); 3232 } 3233 3234 //===----------------------------------------------------------------------===// 3235 // Tests for classes, namespaces, etc. 3236 //===----------------------------------------------------------------------===// 3237 3238 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3239 verifyFormat("class A {};"); 3240 } 3241 3242 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3243 verifyFormat("class A {\n" 3244 "public:\n" 3245 "public: // comment\n" 3246 "protected:\n" 3247 "private:\n" 3248 " void f() {}\n" 3249 "};"); 3250 verifyFormat("export class A {\n" 3251 "public:\n" 3252 "public: // comment\n" 3253 "protected:\n" 3254 "private:\n" 3255 " void f() {}\n" 3256 "};"); 3257 verifyGoogleFormat("class A {\n" 3258 " public:\n" 3259 " protected:\n" 3260 " private:\n" 3261 " void f() {}\n" 3262 "};"); 3263 verifyGoogleFormat("export class A {\n" 3264 " public:\n" 3265 " protected:\n" 3266 " private:\n" 3267 " void f() {}\n" 3268 "};"); 3269 verifyFormat("class A {\n" 3270 "public slots:\n" 3271 " void f1() {}\n" 3272 "public Q_SLOTS:\n" 3273 " void f2() {}\n" 3274 "protected slots:\n" 3275 " void f3() {}\n" 3276 "protected Q_SLOTS:\n" 3277 " void f4() {}\n" 3278 "private slots:\n" 3279 " void f5() {}\n" 3280 "private Q_SLOTS:\n" 3281 " void f6() {}\n" 3282 "signals:\n" 3283 " void g1();\n" 3284 "Q_SIGNALS:\n" 3285 " void g2();\n" 3286 "};"); 3287 3288 // Don't interpret 'signals' the wrong way. 3289 verifyFormat("signals.set();"); 3290 verifyFormat("for (Signals signals : f()) {\n}"); 3291 verifyFormat("{\n" 3292 " signals.set(); // This needs indentation.\n" 3293 "}"); 3294 verifyFormat("void f() {\n" 3295 "label:\n" 3296 " signals.baz();\n" 3297 "}"); 3298 verifyFormat("private[1];"); 3299 verifyFormat("testArray[public] = 1;"); 3300 verifyFormat("public();"); 3301 verifyFormat("myFunc(public);"); 3302 verifyFormat("std::vector<int> testVec = {private};"); 3303 verifyFormat("private.p = 1;"); 3304 verifyFormat("void function(private...){};"); 3305 verifyFormat("if (private && public)\n"); 3306 verifyFormat("private &= true;"); 3307 verifyFormat("int x = private * public;"); 3308 verifyFormat("public *= private;"); 3309 verifyFormat("int x = public + private;"); 3310 verifyFormat("private++;"); 3311 verifyFormat("++private;"); 3312 verifyFormat("public += private;"); 3313 verifyFormat("public = public - private;"); 3314 verifyFormat("public->foo();"); 3315 verifyFormat("private--;"); 3316 verifyFormat("--private;"); 3317 verifyFormat("public -= 1;"); 3318 verifyFormat("if (!private && !public)\n"); 3319 verifyFormat("public != private;"); 3320 verifyFormat("int x = public / private;"); 3321 verifyFormat("public /= 2;"); 3322 verifyFormat("public = public % 2;"); 3323 verifyFormat("public %= 2;"); 3324 verifyFormat("if (public < private)\n"); 3325 verifyFormat("public << private;"); 3326 verifyFormat("public <<= private;"); 3327 verifyFormat("if (public > private)\n"); 3328 verifyFormat("public >> private;"); 3329 verifyFormat("public >>= private;"); 3330 verifyFormat("public ^ private;"); 3331 verifyFormat("public ^= private;"); 3332 verifyFormat("public | private;"); 3333 verifyFormat("public |= private;"); 3334 verifyFormat("auto x = private ? 1 : 2;"); 3335 verifyFormat("if (public == private)\n"); 3336 verifyFormat("void foo(public, private)"); 3337 verifyFormat("public::foo();"); 3338 } 3339 3340 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3341 EXPECT_EQ("class A {\n" 3342 "public:\n" 3343 " void f();\n" 3344 "\n" 3345 "private:\n" 3346 " void g() {}\n" 3347 " // test\n" 3348 "protected:\n" 3349 " int h;\n" 3350 "};", 3351 format("class A {\n" 3352 "public:\n" 3353 "void f();\n" 3354 "private:\n" 3355 "void g() {}\n" 3356 "// test\n" 3357 "protected:\n" 3358 "int h;\n" 3359 "};")); 3360 EXPECT_EQ("class A {\n" 3361 "protected:\n" 3362 "public:\n" 3363 " void f();\n" 3364 "};", 3365 format("class A {\n" 3366 "protected:\n" 3367 "\n" 3368 "public:\n" 3369 "\n" 3370 " void f();\n" 3371 "};")); 3372 3373 // Even ensure proper spacing inside macros. 3374 EXPECT_EQ("#define B \\\n" 3375 " class A { \\\n" 3376 " protected: \\\n" 3377 " public: \\\n" 3378 " void f(); \\\n" 3379 " };", 3380 format("#define B \\\n" 3381 " class A { \\\n" 3382 " protected: \\\n" 3383 " \\\n" 3384 " public: \\\n" 3385 " \\\n" 3386 " void f(); \\\n" 3387 " };", 3388 getGoogleStyle())); 3389 // But don't remove empty lines after macros ending in access specifiers. 3390 EXPECT_EQ("#define A private:\n" 3391 "\n" 3392 "int i;", 3393 format("#define A private:\n" 3394 "\n" 3395 "int i;")); 3396 } 3397 3398 TEST_F(FormatTest, FormatsClasses) { 3399 verifyFormat("class A : public B {};"); 3400 verifyFormat("class A : public ::B {};"); 3401 3402 verifyFormat( 3403 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3404 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3405 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3406 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3407 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3408 verifyFormat( 3409 "class A : public B, public C, public D, public E, public F {};"); 3410 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3411 " public C,\n" 3412 " public D,\n" 3413 " public E,\n" 3414 " public F,\n" 3415 " public G {};"); 3416 3417 verifyFormat("class\n" 3418 " ReallyReallyLongClassName {\n" 3419 " int i;\n" 3420 "};", 3421 getLLVMStyleWithColumns(32)); 3422 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3423 " aaaaaaaaaaaaaaaa> {};"); 3424 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3425 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3426 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3427 verifyFormat("template <class R, class C>\n" 3428 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3429 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3430 verifyFormat("class ::A::B {};"); 3431 } 3432 3433 TEST_F(FormatTest, BreakInheritanceStyle) { 3434 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3435 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3436 FormatStyle::BILS_BeforeComma; 3437 verifyFormat("class MyClass : public X {};", 3438 StyleWithInheritanceBreakBeforeComma); 3439 verifyFormat("class MyClass\n" 3440 " : public X\n" 3441 " , public Y {};", 3442 StyleWithInheritanceBreakBeforeComma); 3443 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3444 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3445 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3446 StyleWithInheritanceBreakBeforeComma); 3447 verifyFormat("struct aaaaaaaaaaaaa\n" 3448 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3449 " aaaaaaaaaaaaaaaa> {};", 3450 StyleWithInheritanceBreakBeforeComma); 3451 3452 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3453 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3454 FormatStyle::BILS_AfterColon; 3455 verifyFormat("class MyClass : public X {};", 3456 StyleWithInheritanceBreakAfterColon); 3457 verifyFormat("class MyClass : public X, public Y {};", 3458 StyleWithInheritanceBreakAfterColon); 3459 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3460 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3461 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3462 StyleWithInheritanceBreakAfterColon); 3463 verifyFormat("struct aaaaaaaaaaaaa :\n" 3464 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3465 " aaaaaaaaaaaaaaaa> {};", 3466 StyleWithInheritanceBreakAfterColon); 3467 3468 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3469 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3470 FormatStyle::BILS_AfterComma; 3471 verifyFormat("class MyClass : public X {};", 3472 StyleWithInheritanceBreakAfterComma); 3473 verifyFormat("class MyClass : public X,\n" 3474 " public Y {};", 3475 StyleWithInheritanceBreakAfterComma); 3476 verifyFormat( 3477 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3478 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3479 "{};", 3480 StyleWithInheritanceBreakAfterComma); 3481 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3482 " aaaaaaaaaaaaaaaa> {};", 3483 StyleWithInheritanceBreakAfterComma); 3484 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3485 " : public OnceBreak,\n" 3486 " public AlwaysBreak,\n" 3487 " EvenBasesFitInOneLine {};", 3488 StyleWithInheritanceBreakAfterComma); 3489 } 3490 3491 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3492 verifyFormat("class A {\n} a, b;"); 3493 verifyFormat("struct A {\n} a, b;"); 3494 verifyFormat("union A {\n} a, b;"); 3495 3496 verifyFormat("constexpr class A {\n} a, b;"); 3497 verifyFormat("constexpr struct A {\n} a, b;"); 3498 verifyFormat("constexpr union A {\n} a, b;"); 3499 3500 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3501 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3502 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3503 3504 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3505 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3506 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3507 3508 verifyFormat("namespace ns {\n" 3509 "class {\n" 3510 "} a, b;\n" 3511 "} // namespace ns"); 3512 verifyFormat("namespace ns {\n" 3513 "const class {\n" 3514 "} a, b;\n" 3515 "} // namespace ns"); 3516 verifyFormat("namespace ns {\n" 3517 "constexpr class C {\n" 3518 "} a, b;\n" 3519 "} // namespace ns"); 3520 verifyFormat("namespace ns {\n" 3521 "class { /* comment */\n" 3522 "} a, b;\n" 3523 "} // namespace ns"); 3524 verifyFormat("namespace ns {\n" 3525 "const class { /* comment */\n" 3526 "} a, b;\n" 3527 "} // namespace ns"); 3528 } 3529 3530 TEST_F(FormatTest, FormatsEnum) { 3531 verifyFormat("enum {\n" 3532 " Zero,\n" 3533 " One = 1,\n" 3534 " Two = One + 1,\n" 3535 " Three = (One + Two),\n" 3536 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3537 " Five = (One, Two, Three, Four, 5)\n" 3538 "};"); 3539 verifyGoogleFormat("enum {\n" 3540 " Zero,\n" 3541 " One = 1,\n" 3542 " Two = One + 1,\n" 3543 " Three = (One + Two),\n" 3544 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3545 " Five = (One, Two, Three, Four, 5)\n" 3546 "};"); 3547 verifyFormat("enum Enum {};"); 3548 verifyFormat("enum {};"); 3549 verifyFormat("enum X E {} d;"); 3550 verifyFormat("enum __attribute__((...)) E {} d;"); 3551 verifyFormat("enum __declspec__((...)) E {} d;"); 3552 verifyFormat("enum {\n" 3553 " Bar = Foo<int, int>::value\n" 3554 "};", 3555 getLLVMStyleWithColumns(30)); 3556 3557 verifyFormat("enum ShortEnum { A, B, C };"); 3558 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3559 3560 EXPECT_EQ("enum KeepEmptyLines {\n" 3561 " ONE,\n" 3562 "\n" 3563 " TWO,\n" 3564 "\n" 3565 " THREE\n" 3566 "}", 3567 format("enum KeepEmptyLines {\n" 3568 " ONE,\n" 3569 "\n" 3570 " TWO,\n" 3571 "\n" 3572 "\n" 3573 " THREE\n" 3574 "}")); 3575 verifyFormat("enum E { // comment\n" 3576 " ONE,\n" 3577 " TWO\n" 3578 "};\n" 3579 "int i;"); 3580 3581 FormatStyle EightIndent = getLLVMStyle(); 3582 EightIndent.IndentWidth = 8; 3583 verifyFormat("enum {\n" 3584 " VOID,\n" 3585 " CHAR,\n" 3586 " SHORT,\n" 3587 " INT,\n" 3588 " LONG,\n" 3589 " SIGNED,\n" 3590 " UNSIGNED,\n" 3591 " BOOL,\n" 3592 " FLOAT,\n" 3593 " DOUBLE,\n" 3594 " COMPLEX\n" 3595 "};", 3596 EightIndent); 3597 3598 // Not enums. 3599 verifyFormat("enum X f() {\n" 3600 " a();\n" 3601 " return 42;\n" 3602 "}"); 3603 verifyFormat("enum X Type::f() {\n" 3604 " a();\n" 3605 " return 42;\n" 3606 "}"); 3607 verifyFormat("enum ::X f() {\n" 3608 " a();\n" 3609 " return 42;\n" 3610 "}"); 3611 verifyFormat("enum ns::X f() {\n" 3612 " a();\n" 3613 " return 42;\n" 3614 "}"); 3615 } 3616 3617 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3618 verifyFormat("enum Type {\n" 3619 " One = 0; // These semicolons should be commas.\n" 3620 " Two = 1;\n" 3621 "};"); 3622 verifyFormat("namespace n {\n" 3623 "enum Type {\n" 3624 " One,\n" 3625 " Two, // missing };\n" 3626 " int i;\n" 3627 "}\n" 3628 "void g() {}"); 3629 } 3630 3631 TEST_F(FormatTest, FormatsEnumStruct) { 3632 verifyFormat("enum struct {\n" 3633 " Zero,\n" 3634 " One = 1,\n" 3635 " Two = One + 1,\n" 3636 " Three = (One + Two),\n" 3637 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3638 " Five = (One, Two, Three, Four, 5)\n" 3639 "};"); 3640 verifyFormat("enum struct Enum {};"); 3641 verifyFormat("enum struct {};"); 3642 verifyFormat("enum struct X E {} d;"); 3643 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3644 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3645 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3646 } 3647 3648 TEST_F(FormatTest, FormatsEnumClass) { 3649 verifyFormat("enum class {\n" 3650 " Zero,\n" 3651 " One = 1,\n" 3652 " Two = One + 1,\n" 3653 " Three = (One + Two),\n" 3654 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3655 " Five = (One, Two, Three, Four, 5)\n" 3656 "};"); 3657 verifyFormat("enum class Enum {};"); 3658 verifyFormat("enum class {};"); 3659 verifyFormat("enum class X E {} d;"); 3660 verifyFormat("enum class __attribute__((...)) E {} d;"); 3661 verifyFormat("enum class __declspec__((...)) E {} d;"); 3662 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3663 } 3664 3665 TEST_F(FormatTest, FormatsEnumTypes) { 3666 verifyFormat("enum X : int {\n" 3667 " A, // Force multiple lines.\n" 3668 " B\n" 3669 "};"); 3670 verifyFormat("enum X : int { A, B };"); 3671 verifyFormat("enum X : std::uint32_t { A, B };"); 3672 } 3673 3674 TEST_F(FormatTest, FormatsTypedefEnum) { 3675 FormatStyle Style = getLLVMStyleWithColumns(40); 3676 verifyFormat("typedef enum {} EmptyEnum;"); 3677 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3678 verifyFormat("typedef enum {\n" 3679 " ZERO = 0,\n" 3680 " ONE = 1,\n" 3681 " TWO = 2,\n" 3682 " THREE = 3\n" 3683 "} LongEnum;", 3684 Style); 3685 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3686 Style.BraceWrapping.AfterEnum = true; 3687 verifyFormat("typedef enum {} EmptyEnum;"); 3688 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3689 verifyFormat("typedef enum\n" 3690 "{\n" 3691 " ZERO = 0,\n" 3692 " ONE = 1,\n" 3693 " TWO = 2,\n" 3694 " THREE = 3\n" 3695 "} LongEnum;", 3696 Style); 3697 } 3698 3699 TEST_F(FormatTest, FormatsNSEnums) { 3700 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3701 verifyGoogleFormat( 3702 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3703 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3704 " // Information about someDecentlyLongValue.\n" 3705 " someDecentlyLongValue,\n" 3706 " // Information about anotherDecentlyLongValue.\n" 3707 " anotherDecentlyLongValue,\n" 3708 " // Information about aThirdDecentlyLongValue.\n" 3709 " aThirdDecentlyLongValue\n" 3710 "};"); 3711 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3712 " // Information about someDecentlyLongValue.\n" 3713 " someDecentlyLongValue,\n" 3714 " // Information about anotherDecentlyLongValue.\n" 3715 " anotherDecentlyLongValue,\n" 3716 " // Information about aThirdDecentlyLongValue.\n" 3717 " aThirdDecentlyLongValue\n" 3718 "};"); 3719 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3720 " a = 1,\n" 3721 " b = 2,\n" 3722 " c = 3,\n" 3723 "};"); 3724 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3725 " a = 1,\n" 3726 " b = 2,\n" 3727 " c = 3,\n" 3728 "};"); 3729 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3730 " a = 1,\n" 3731 " b = 2,\n" 3732 " c = 3,\n" 3733 "};"); 3734 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3735 " a = 1,\n" 3736 " b = 2,\n" 3737 " c = 3,\n" 3738 "};"); 3739 } 3740 3741 TEST_F(FormatTest, FormatsBitfields) { 3742 verifyFormat("struct Bitfields {\n" 3743 " unsigned sClass : 8;\n" 3744 " unsigned ValueKind : 2;\n" 3745 "};"); 3746 verifyFormat("struct A {\n" 3747 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3748 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3749 "};"); 3750 verifyFormat("struct MyStruct {\n" 3751 " uchar data;\n" 3752 " uchar : 8;\n" 3753 " uchar : 8;\n" 3754 " uchar other;\n" 3755 "};"); 3756 FormatStyle Style = getLLVMStyle(); 3757 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3758 verifyFormat("struct Bitfields {\n" 3759 " unsigned sClass:8;\n" 3760 " unsigned ValueKind:2;\n" 3761 " uchar other;\n" 3762 "};", 3763 Style); 3764 verifyFormat("struct A {\n" 3765 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3766 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3767 "};", 3768 Style); 3769 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3770 verifyFormat("struct Bitfields {\n" 3771 " unsigned sClass :8;\n" 3772 " unsigned ValueKind :2;\n" 3773 " uchar other;\n" 3774 "};", 3775 Style); 3776 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3777 verifyFormat("struct Bitfields {\n" 3778 " unsigned sClass: 8;\n" 3779 " unsigned ValueKind: 2;\n" 3780 " uchar other;\n" 3781 "};", 3782 Style); 3783 } 3784 3785 TEST_F(FormatTest, FormatsNamespaces) { 3786 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3787 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3788 3789 verifyFormat("namespace some_namespace {\n" 3790 "class A {};\n" 3791 "void f() { f(); }\n" 3792 "}", 3793 LLVMWithNoNamespaceFix); 3794 verifyFormat("#define M(x) x##x\n" 3795 "namespace M(x) {\n" 3796 "class A {};\n" 3797 "void f() { f(); }\n" 3798 "}", 3799 LLVMWithNoNamespaceFix); 3800 verifyFormat("#define M(x) x##x\n" 3801 "namespace N::inline M(x) {\n" 3802 "class A {};\n" 3803 "void f() { f(); }\n" 3804 "}", 3805 LLVMWithNoNamespaceFix); 3806 verifyFormat("#define M(x) x##x\n" 3807 "namespace M(x)::inline N {\n" 3808 "class A {};\n" 3809 "void f() { f(); }\n" 3810 "}", 3811 LLVMWithNoNamespaceFix); 3812 verifyFormat("#define M(x) x##x\n" 3813 "namespace N::M(x) {\n" 3814 "class A {};\n" 3815 "void f() { f(); }\n" 3816 "}", 3817 LLVMWithNoNamespaceFix); 3818 verifyFormat("#define M(x) x##x\n" 3819 "namespace M::N(x) {\n" 3820 "class A {};\n" 3821 "void f() { f(); }\n" 3822 "}", 3823 LLVMWithNoNamespaceFix); 3824 verifyFormat("namespace N::inline D {\n" 3825 "class A {};\n" 3826 "void f() { f(); }\n" 3827 "}", 3828 LLVMWithNoNamespaceFix); 3829 verifyFormat("namespace N::inline D::E {\n" 3830 "class A {};\n" 3831 "void f() { f(); }\n" 3832 "}", 3833 LLVMWithNoNamespaceFix); 3834 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3835 "class A {};\n" 3836 "void f() { f(); }\n" 3837 "}", 3838 LLVMWithNoNamespaceFix); 3839 verifyFormat("/* something */ namespace some_namespace {\n" 3840 "class A {};\n" 3841 "void f() { f(); }\n" 3842 "}", 3843 LLVMWithNoNamespaceFix); 3844 verifyFormat("namespace {\n" 3845 "class A {};\n" 3846 "void f() { f(); }\n" 3847 "}", 3848 LLVMWithNoNamespaceFix); 3849 verifyFormat("/* something */ namespace {\n" 3850 "class A {};\n" 3851 "void f() { f(); }\n" 3852 "}", 3853 LLVMWithNoNamespaceFix); 3854 verifyFormat("inline namespace X {\n" 3855 "class A {};\n" 3856 "void f() { f(); }\n" 3857 "}", 3858 LLVMWithNoNamespaceFix); 3859 verifyFormat("/* something */ inline namespace X {\n" 3860 "class A {};\n" 3861 "void f() { f(); }\n" 3862 "}", 3863 LLVMWithNoNamespaceFix); 3864 verifyFormat("export namespace X {\n" 3865 "class A {};\n" 3866 "void f() { f(); }\n" 3867 "}", 3868 LLVMWithNoNamespaceFix); 3869 verifyFormat("using namespace some_namespace;\n" 3870 "class A {};\n" 3871 "void f() { f(); }", 3872 LLVMWithNoNamespaceFix); 3873 3874 // This code is more common than we thought; if we 3875 // layout this correctly the semicolon will go into 3876 // its own line, which is undesirable. 3877 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3878 verifyFormat("namespace {\n" 3879 "class A {};\n" 3880 "};", 3881 LLVMWithNoNamespaceFix); 3882 3883 verifyFormat("namespace {\n" 3884 "int SomeVariable = 0; // comment\n" 3885 "} // namespace", 3886 LLVMWithNoNamespaceFix); 3887 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3888 "#define HEADER_GUARD\n" 3889 "namespace my_namespace {\n" 3890 "int i;\n" 3891 "} // my_namespace\n" 3892 "#endif // HEADER_GUARD", 3893 format("#ifndef HEADER_GUARD\n" 3894 " #define HEADER_GUARD\n" 3895 " namespace my_namespace {\n" 3896 "int i;\n" 3897 "} // my_namespace\n" 3898 "#endif // HEADER_GUARD", 3899 LLVMWithNoNamespaceFix)); 3900 3901 EXPECT_EQ("namespace A::B {\n" 3902 "class C {};\n" 3903 "}", 3904 format("namespace A::B {\n" 3905 "class C {};\n" 3906 "}", 3907 LLVMWithNoNamespaceFix)); 3908 3909 FormatStyle Style = getLLVMStyle(); 3910 Style.NamespaceIndentation = FormatStyle::NI_All; 3911 EXPECT_EQ("namespace out {\n" 3912 " int i;\n" 3913 " namespace in {\n" 3914 " int i;\n" 3915 " } // namespace in\n" 3916 "} // namespace out", 3917 format("namespace out {\n" 3918 "int i;\n" 3919 "namespace in {\n" 3920 "int i;\n" 3921 "} // namespace in\n" 3922 "} // namespace out", 3923 Style)); 3924 3925 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3926 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3927 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3928 FormatStyle::SFS_Inline; 3929 verifyFormat("namespace {\n" 3930 " void f() {\n" 3931 " return;\n" 3932 " }\n" 3933 "} // namespace\n", 3934 ShortInlineFunctions); 3935 verifyFormat("namespace { /* comment */\n" 3936 " void f() {\n" 3937 " return;\n" 3938 " }\n" 3939 "} // namespace\n", 3940 ShortInlineFunctions); 3941 verifyFormat("namespace { // comment\n" 3942 " void f() {\n" 3943 " return;\n" 3944 " }\n" 3945 "} // namespace\n", 3946 ShortInlineFunctions); 3947 verifyFormat("namespace {\n" 3948 " int some_int;\n" 3949 " void f() {\n" 3950 " return;\n" 3951 " }\n" 3952 "} // namespace\n", 3953 ShortInlineFunctions); 3954 verifyFormat("namespace interface {\n" 3955 " void f() {\n" 3956 " return;\n" 3957 " }\n" 3958 "} // namespace interface\n", 3959 ShortInlineFunctions); 3960 verifyFormat("namespace {\n" 3961 " class X {\n" 3962 " void f() { return; }\n" 3963 " };\n" 3964 "} // namespace\n", 3965 ShortInlineFunctions); 3966 verifyFormat("namespace {\n" 3967 " class X { /* comment */\n" 3968 " void f() { return; }\n" 3969 " };\n" 3970 "} // namespace\n", 3971 ShortInlineFunctions); 3972 verifyFormat("namespace {\n" 3973 " class X { // comment\n" 3974 " void f() { return; }\n" 3975 " };\n" 3976 "} // namespace\n", 3977 ShortInlineFunctions); 3978 verifyFormat("namespace {\n" 3979 " struct X {\n" 3980 " void f() { return; }\n" 3981 " };\n" 3982 "} // namespace\n", 3983 ShortInlineFunctions); 3984 verifyFormat("namespace {\n" 3985 " union X {\n" 3986 " void f() { return; }\n" 3987 " };\n" 3988 "} // namespace\n", 3989 ShortInlineFunctions); 3990 verifyFormat("extern \"C\" {\n" 3991 "void f() {\n" 3992 " return;\n" 3993 "}\n" 3994 "} // namespace\n", 3995 ShortInlineFunctions); 3996 verifyFormat("namespace {\n" 3997 " class X {\n" 3998 " void f() { return; }\n" 3999 " } x;\n" 4000 "} // namespace\n", 4001 ShortInlineFunctions); 4002 verifyFormat("namespace {\n" 4003 " [[nodiscard]] class X {\n" 4004 " void f() { return; }\n" 4005 " };\n" 4006 "} // namespace\n", 4007 ShortInlineFunctions); 4008 verifyFormat("namespace {\n" 4009 " static class X {\n" 4010 " void f() { return; }\n" 4011 " } x;\n" 4012 "} // namespace\n", 4013 ShortInlineFunctions); 4014 verifyFormat("namespace {\n" 4015 " constexpr class X {\n" 4016 " void f() { return; }\n" 4017 " } x;\n" 4018 "} // namespace\n", 4019 ShortInlineFunctions); 4020 4021 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4022 verifyFormat("extern \"C\" {\n" 4023 " void f() {\n" 4024 " return;\n" 4025 " }\n" 4026 "} // namespace\n", 4027 ShortInlineFunctions); 4028 4029 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4030 EXPECT_EQ("namespace out {\n" 4031 "int i;\n" 4032 "namespace in {\n" 4033 " int i;\n" 4034 "} // namespace in\n" 4035 "} // namespace out", 4036 format("namespace out {\n" 4037 "int i;\n" 4038 "namespace in {\n" 4039 "int i;\n" 4040 "} // namespace in\n" 4041 "} // namespace out", 4042 Style)); 4043 4044 Style.NamespaceIndentation = FormatStyle::NI_None; 4045 verifyFormat("template <class T>\n" 4046 "concept a_concept = X<>;\n" 4047 "namespace B {\n" 4048 "struct b_struct {};\n" 4049 "} // namespace B\n", 4050 Style); 4051 verifyFormat("template <int I>\n" 4052 "constexpr void foo()\n" 4053 " requires(I == 42)\n" 4054 "{}\n" 4055 "namespace ns {\n" 4056 "void foo() {}\n" 4057 "} // namespace ns\n", 4058 Style); 4059 } 4060 4061 TEST_F(FormatTest, NamespaceMacros) { 4062 FormatStyle Style = getLLVMStyle(); 4063 Style.NamespaceMacros.push_back("TESTSUITE"); 4064 4065 verifyFormat("TESTSUITE(A) {\n" 4066 "int foo();\n" 4067 "} // TESTSUITE(A)", 4068 Style); 4069 4070 verifyFormat("TESTSUITE(A, B) {\n" 4071 "int foo();\n" 4072 "} // TESTSUITE(A)", 4073 Style); 4074 4075 // Properly indent according to NamespaceIndentation style 4076 Style.NamespaceIndentation = FormatStyle::NI_All; 4077 verifyFormat("TESTSUITE(A) {\n" 4078 " int foo();\n" 4079 "} // TESTSUITE(A)", 4080 Style); 4081 verifyFormat("TESTSUITE(A) {\n" 4082 " namespace B {\n" 4083 " int foo();\n" 4084 " } // namespace B\n" 4085 "} // TESTSUITE(A)", 4086 Style); 4087 verifyFormat("namespace A {\n" 4088 " TESTSUITE(B) {\n" 4089 " int foo();\n" 4090 " } // TESTSUITE(B)\n" 4091 "} // namespace A", 4092 Style); 4093 4094 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4095 verifyFormat("TESTSUITE(A) {\n" 4096 "TESTSUITE(B) {\n" 4097 " int foo();\n" 4098 "} // TESTSUITE(B)\n" 4099 "} // TESTSUITE(A)", 4100 Style); 4101 verifyFormat("TESTSUITE(A) {\n" 4102 "namespace B {\n" 4103 " int foo();\n" 4104 "} // namespace B\n" 4105 "} // TESTSUITE(A)", 4106 Style); 4107 verifyFormat("namespace A {\n" 4108 "TESTSUITE(B) {\n" 4109 " int foo();\n" 4110 "} // TESTSUITE(B)\n" 4111 "} // namespace A", 4112 Style); 4113 4114 // Properly merge namespace-macros blocks in CompactNamespaces mode 4115 Style.NamespaceIndentation = FormatStyle::NI_None; 4116 Style.CompactNamespaces = true; 4117 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4118 "}} // TESTSUITE(A::B)", 4119 Style); 4120 4121 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4122 "}} // TESTSUITE(out::in)", 4123 format("TESTSUITE(out) {\n" 4124 "TESTSUITE(in) {\n" 4125 "} // TESTSUITE(in)\n" 4126 "} // TESTSUITE(out)", 4127 Style)); 4128 4129 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4130 "}} // TESTSUITE(out::in)", 4131 format("TESTSUITE(out) {\n" 4132 "TESTSUITE(in) {\n" 4133 "} // TESTSUITE(in)\n" 4134 "} // TESTSUITE(out)", 4135 Style)); 4136 4137 // Do not merge different namespaces/macros 4138 EXPECT_EQ("namespace out {\n" 4139 "TESTSUITE(in) {\n" 4140 "} // TESTSUITE(in)\n" 4141 "} // namespace out", 4142 format("namespace out {\n" 4143 "TESTSUITE(in) {\n" 4144 "} // TESTSUITE(in)\n" 4145 "} // namespace out", 4146 Style)); 4147 EXPECT_EQ("TESTSUITE(out) {\n" 4148 "namespace in {\n" 4149 "} // namespace in\n" 4150 "} // TESTSUITE(out)", 4151 format("TESTSUITE(out) {\n" 4152 "namespace in {\n" 4153 "} // namespace in\n" 4154 "} // TESTSUITE(out)", 4155 Style)); 4156 Style.NamespaceMacros.push_back("FOOBAR"); 4157 EXPECT_EQ("TESTSUITE(out) {\n" 4158 "FOOBAR(in) {\n" 4159 "} // FOOBAR(in)\n" 4160 "} // TESTSUITE(out)", 4161 format("TESTSUITE(out) {\n" 4162 "FOOBAR(in) {\n" 4163 "} // FOOBAR(in)\n" 4164 "} // TESTSUITE(out)", 4165 Style)); 4166 } 4167 4168 TEST_F(FormatTest, FormatsCompactNamespaces) { 4169 FormatStyle Style = getLLVMStyle(); 4170 Style.CompactNamespaces = true; 4171 Style.NamespaceMacros.push_back("TESTSUITE"); 4172 4173 verifyFormat("namespace A { namespace B {\n" 4174 "}} // namespace A::B", 4175 Style); 4176 4177 EXPECT_EQ("namespace out { namespace in {\n" 4178 "}} // namespace out::in", 4179 format("namespace out {\n" 4180 "namespace in {\n" 4181 "} // namespace in\n" 4182 "} // namespace out", 4183 Style)); 4184 4185 // Only namespaces which have both consecutive opening and end get compacted 4186 EXPECT_EQ("namespace out {\n" 4187 "namespace in1 {\n" 4188 "} // namespace in1\n" 4189 "namespace in2 {\n" 4190 "} // namespace in2\n" 4191 "} // namespace out", 4192 format("namespace out {\n" 4193 "namespace in1 {\n" 4194 "} // namespace in1\n" 4195 "namespace in2 {\n" 4196 "} // namespace in2\n" 4197 "} // namespace out", 4198 Style)); 4199 4200 EXPECT_EQ("namespace out {\n" 4201 "int i;\n" 4202 "namespace in {\n" 4203 "int j;\n" 4204 "} // namespace in\n" 4205 "int k;\n" 4206 "} // namespace out", 4207 format("namespace out { int i;\n" 4208 "namespace in { int j; } // namespace in\n" 4209 "int k; } // namespace out", 4210 Style)); 4211 4212 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4213 "}}} // namespace A::B::C\n", 4214 format("namespace A { namespace B {\n" 4215 "namespace C {\n" 4216 "}} // namespace B::C\n" 4217 "} // namespace A\n", 4218 Style)); 4219 4220 Style.ColumnLimit = 40; 4221 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4222 "namespace bbbbbbbbbb {\n" 4223 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4224 format("namespace aaaaaaaaaa {\n" 4225 "namespace bbbbbbbbbb {\n" 4226 "} // namespace bbbbbbbbbb\n" 4227 "} // namespace aaaaaaaaaa", 4228 Style)); 4229 4230 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4231 "namespace cccccc {\n" 4232 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4233 format("namespace aaaaaa {\n" 4234 "namespace bbbbbb {\n" 4235 "namespace cccccc {\n" 4236 "} // namespace cccccc\n" 4237 "} // namespace bbbbbb\n" 4238 "} // namespace aaaaaa", 4239 Style)); 4240 Style.ColumnLimit = 80; 4241 4242 // Extra semicolon after 'inner' closing brace prevents merging 4243 EXPECT_EQ("namespace out { namespace in {\n" 4244 "}; } // namespace out::in", 4245 format("namespace out {\n" 4246 "namespace in {\n" 4247 "}; // namespace in\n" 4248 "} // namespace out", 4249 Style)); 4250 4251 // Extra semicolon after 'outer' closing brace is conserved 4252 EXPECT_EQ("namespace out { namespace in {\n" 4253 "}}; // namespace out::in", 4254 format("namespace out {\n" 4255 "namespace in {\n" 4256 "} // namespace in\n" 4257 "}; // namespace out", 4258 Style)); 4259 4260 Style.NamespaceIndentation = FormatStyle::NI_All; 4261 EXPECT_EQ("namespace out { namespace in {\n" 4262 " int i;\n" 4263 "}} // namespace out::in", 4264 format("namespace out {\n" 4265 "namespace in {\n" 4266 "int i;\n" 4267 "} // namespace in\n" 4268 "} // namespace out", 4269 Style)); 4270 EXPECT_EQ("namespace out { namespace mid {\n" 4271 " namespace in {\n" 4272 " int j;\n" 4273 " } // namespace in\n" 4274 " int k;\n" 4275 "}} // namespace out::mid", 4276 format("namespace out { namespace mid {\n" 4277 "namespace in { int j; } // namespace in\n" 4278 "int k; }} // namespace out::mid", 4279 Style)); 4280 4281 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4282 EXPECT_EQ("namespace out { namespace in {\n" 4283 " int i;\n" 4284 "}} // namespace out::in", 4285 format("namespace out {\n" 4286 "namespace in {\n" 4287 "int i;\n" 4288 "} // namespace in\n" 4289 "} // namespace out", 4290 Style)); 4291 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4292 " int i;\n" 4293 "}}} // namespace out::mid::in", 4294 format("namespace out {\n" 4295 "namespace mid {\n" 4296 "namespace in {\n" 4297 "int i;\n" 4298 "} // namespace in\n" 4299 "} // namespace mid\n" 4300 "} // namespace out", 4301 Style)); 4302 4303 Style.CompactNamespaces = true; 4304 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4305 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4306 Style.BraceWrapping.BeforeLambdaBody = true; 4307 verifyFormat("namespace out { namespace in {\n" 4308 "}} // namespace out::in", 4309 Style); 4310 EXPECT_EQ("namespace out { namespace in {\n" 4311 "}} // namespace out::in", 4312 format("namespace out {\n" 4313 "namespace in {\n" 4314 "} // namespace in\n" 4315 "} // namespace out", 4316 Style)); 4317 } 4318 4319 TEST_F(FormatTest, FormatsExternC) { 4320 verifyFormat("extern \"C\" {\nint a;"); 4321 verifyFormat("extern \"C\" {}"); 4322 verifyFormat("extern \"C\" {\n" 4323 "int foo();\n" 4324 "}"); 4325 verifyFormat("extern \"C\" int foo() {}"); 4326 verifyFormat("extern \"C\" int foo();"); 4327 verifyFormat("extern \"C\" int foo() {\n" 4328 " int i = 42;\n" 4329 " return i;\n" 4330 "}"); 4331 4332 FormatStyle Style = getLLVMStyle(); 4333 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4334 Style.BraceWrapping.AfterFunction = true; 4335 verifyFormat("extern \"C\" int foo() {}", Style); 4336 verifyFormat("extern \"C\" int foo();", Style); 4337 verifyFormat("extern \"C\" int foo()\n" 4338 "{\n" 4339 " int i = 42;\n" 4340 " return i;\n" 4341 "}", 4342 Style); 4343 4344 Style.BraceWrapping.AfterExternBlock = true; 4345 Style.BraceWrapping.SplitEmptyRecord = false; 4346 verifyFormat("extern \"C\"\n" 4347 "{}", 4348 Style); 4349 verifyFormat("extern \"C\"\n" 4350 "{\n" 4351 " int foo();\n" 4352 "}", 4353 Style); 4354 } 4355 4356 TEST_F(FormatTest, IndentExternBlockStyle) { 4357 FormatStyle Style = getLLVMStyle(); 4358 Style.IndentWidth = 2; 4359 4360 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4361 verifyFormat("extern \"C\" { /*9*/\n" 4362 "}", 4363 Style); 4364 verifyFormat("extern \"C\" {\n" 4365 " int foo10();\n" 4366 "}", 4367 Style); 4368 4369 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4370 verifyFormat("extern \"C\" { /*11*/\n" 4371 "}", 4372 Style); 4373 verifyFormat("extern \"C\" {\n" 4374 "int foo12();\n" 4375 "}", 4376 Style); 4377 4378 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4379 Style.BraceWrapping.AfterExternBlock = true; 4380 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4381 verifyFormat("extern \"C\"\n" 4382 "{ /*13*/\n" 4383 "}", 4384 Style); 4385 verifyFormat("extern \"C\"\n{\n" 4386 " int foo14();\n" 4387 "}", 4388 Style); 4389 4390 Style.BraceWrapping.AfterExternBlock = false; 4391 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4392 verifyFormat("extern \"C\" { /*15*/\n" 4393 "}", 4394 Style); 4395 verifyFormat("extern \"C\" {\n" 4396 "int foo16();\n" 4397 "}", 4398 Style); 4399 4400 Style.BraceWrapping.AfterExternBlock = true; 4401 verifyFormat("extern \"C\"\n" 4402 "{ /*13*/\n" 4403 "}", 4404 Style); 4405 verifyFormat("extern \"C\"\n" 4406 "{\n" 4407 "int foo14();\n" 4408 "}", 4409 Style); 4410 4411 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4412 verifyFormat("extern \"C\"\n" 4413 "{ /*13*/\n" 4414 "}", 4415 Style); 4416 verifyFormat("extern \"C\"\n" 4417 "{\n" 4418 " int foo14();\n" 4419 "}", 4420 Style); 4421 } 4422 4423 TEST_F(FormatTest, FormatsInlineASM) { 4424 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4425 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4426 verifyFormat( 4427 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4428 " \"cpuid\\n\\t\"\n" 4429 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4430 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4431 " : \"a\"(value));"); 4432 EXPECT_EQ( 4433 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4434 " __asm {\n" 4435 " mov edx,[that] // vtable in edx\n" 4436 " mov eax,methodIndex\n" 4437 " call [edx][eax*4] // stdcall\n" 4438 " }\n" 4439 "}", 4440 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4441 " __asm {\n" 4442 " mov edx,[that] // vtable in edx\n" 4443 " mov eax,methodIndex\n" 4444 " call [edx][eax*4] // stdcall\n" 4445 " }\n" 4446 "}")); 4447 EXPECT_EQ("_asm {\n" 4448 " xor eax, eax;\n" 4449 " cpuid;\n" 4450 "}", 4451 format("_asm {\n" 4452 " xor eax, eax;\n" 4453 " cpuid;\n" 4454 "}")); 4455 verifyFormat("void function() {\n" 4456 " // comment\n" 4457 " asm(\"\");\n" 4458 "}"); 4459 EXPECT_EQ("__asm {\n" 4460 "}\n" 4461 "int i;", 4462 format("__asm {\n" 4463 "}\n" 4464 "int i;")); 4465 } 4466 4467 TEST_F(FormatTest, FormatTryCatch) { 4468 verifyFormat("try {\n" 4469 " throw a * b;\n" 4470 "} catch (int a) {\n" 4471 " // Do nothing.\n" 4472 "} catch (...) {\n" 4473 " exit(42);\n" 4474 "}"); 4475 4476 // Function-level try statements. 4477 verifyFormat("int f() try { return 4; } catch (...) {\n" 4478 " return 5;\n" 4479 "}"); 4480 verifyFormat("class A {\n" 4481 " int a;\n" 4482 " A() try : a(0) {\n" 4483 " } catch (...) {\n" 4484 " throw;\n" 4485 " }\n" 4486 "};\n"); 4487 verifyFormat("class A {\n" 4488 " int a;\n" 4489 " A() try : a(0), b{1} {\n" 4490 " } catch (...) {\n" 4491 " throw;\n" 4492 " }\n" 4493 "};\n"); 4494 verifyFormat("class A {\n" 4495 " int a;\n" 4496 " A() try : a(0), b{1}, c{2} {\n" 4497 " } catch (...) {\n" 4498 " throw;\n" 4499 " }\n" 4500 "};\n"); 4501 verifyFormat("class A {\n" 4502 " int a;\n" 4503 " A() try : a(0), b{1}, c{2} {\n" 4504 " { // New scope.\n" 4505 " }\n" 4506 " } catch (...) {\n" 4507 " throw;\n" 4508 " }\n" 4509 "};\n"); 4510 4511 // Incomplete try-catch blocks. 4512 verifyIncompleteFormat("try {} catch ("); 4513 } 4514 4515 TEST_F(FormatTest, FormatTryAsAVariable) { 4516 verifyFormat("int try;"); 4517 verifyFormat("int try, size;"); 4518 verifyFormat("try = foo();"); 4519 verifyFormat("if (try < size) {\n return true;\n}"); 4520 4521 verifyFormat("int catch;"); 4522 verifyFormat("int catch, size;"); 4523 verifyFormat("catch = foo();"); 4524 verifyFormat("if (catch < size) {\n return true;\n}"); 4525 4526 FormatStyle Style = getLLVMStyle(); 4527 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4528 Style.BraceWrapping.AfterFunction = true; 4529 Style.BraceWrapping.BeforeCatch = true; 4530 verifyFormat("try {\n" 4531 " int bar = 1;\n" 4532 "}\n" 4533 "catch (...) {\n" 4534 " int bar = 1;\n" 4535 "}", 4536 Style); 4537 verifyFormat("#if NO_EX\n" 4538 "try\n" 4539 "#endif\n" 4540 "{\n" 4541 "}\n" 4542 "#if NO_EX\n" 4543 "catch (...) {\n" 4544 "}", 4545 Style); 4546 verifyFormat("try /* abc */ {\n" 4547 " int bar = 1;\n" 4548 "}\n" 4549 "catch (...) {\n" 4550 " int bar = 1;\n" 4551 "}", 4552 Style); 4553 verifyFormat("try\n" 4554 "// abc\n" 4555 "{\n" 4556 " int bar = 1;\n" 4557 "}\n" 4558 "catch (...) {\n" 4559 " int bar = 1;\n" 4560 "}", 4561 Style); 4562 } 4563 4564 TEST_F(FormatTest, FormatSEHTryCatch) { 4565 verifyFormat("__try {\n" 4566 " int a = b * c;\n" 4567 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4568 " // Do nothing.\n" 4569 "}"); 4570 4571 verifyFormat("__try {\n" 4572 " int a = b * c;\n" 4573 "} __finally {\n" 4574 " // Do nothing.\n" 4575 "}"); 4576 4577 verifyFormat("DEBUG({\n" 4578 " __try {\n" 4579 " } __finally {\n" 4580 " }\n" 4581 "});\n"); 4582 } 4583 4584 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4585 verifyFormat("try {\n" 4586 " f();\n" 4587 "} catch {\n" 4588 " g();\n" 4589 "}"); 4590 verifyFormat("try {\n" 4591 " f();\n" 4592 "} catch (A a) MACRO(x) {\n" 4593 " g();\n" 4594 "} catch (B b) MACRO(x) {\n" 4595 " g();\n" 4596 "}"); 4597 } 4598 4599 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4600 FormatStyle Style = getLLVMStyle(); 4601 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4602 FormatStyle::BS_WebKit}) { 4603 Style.BreakBeforeBraces = BraceStyle; 4604 verifyFormat("try {\n" 4605 " // something\n" 4606 "} catch (...) {\n" 4607 " // something\n" 4608 "}", 4609 Style); 4610 } 4611 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4612 verifyFormat("try {\n" 4613 " // something\n" 4614 "}\n" 4615 "catch (...) {\n" 4616 " // something\n" 4617 "}", 4618 Style); 4619 verifyFormat("__try {\n" 4620 " // something\n" 4621 "}\n" 4622 "__finally {\n" 4623 " // something\n" 4624 "}", 4625 Style); 4626 verifyFormat("@try {\n" 4627 " // something\n" 4628 "}\n" 4629 "@finally {\n" 4630 " // something\n" 4631 "}", 4632 Style); 4633 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4634 verifyFormat("try\n" 4635 "{\n" 4636 " // something\n" 4637 "}\n" 4638 "catch (...)\n" 4639 "{\n" 4640 " // something\n" 4641 "}", 4642 Style); 4643 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4644 verifyFormat("try\n" 4645 " {\n" 4646 " // something white\n" 4647 " }\n" 4648 "catch (...)\n" 4649 " {\n" 4650 " // something white\n" 4651 " }", 4652 Style); 4653 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4654 verifyFormat("try\n" 4655 " {\n" 4656 " // something\n" 4657 " }\n" 4658 "catch (...)\n" 4659 " {\n" 4660 " // something\n" 4661 " }", 4662 Style); 4663 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4664 Style.BraceWrapping.BeforeCatch = true; 4665 verifyFormat("try {\n" 4666 " // something\n" 4667 "}\n" 4668 "catch (...) {\n" 4669 " // something\n" 4670 "}", 4671 Style); 4672 } 4673 4674 TEST_F(FormatTest, StaticInitializers) { 4675 verifyFormat("static SomeClass SC = {1, 'a'};"); 4676 4677 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4678 " 100000000, " 4679 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4680 4681 // Here, everything other than the "}" would fit on a line. 4682 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4683 " 10000000000000000000000000};"); 4684 EXPECT_EQ("S s = {a,\n" 4685 "\n" 4686 " b};", 4687 format("S s = {\n" 4688 " a,\n" 4689 "\n" 4690 " b\n" 4691 "};")); 4692 4693 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4694 // line. However, the formatting looks a bit off and this probably doesn't 4695 // happen often in practice. 4696 verifyFormat("static int Variable[1] = {\n" 4697 " {1000000000000000000000000000000000000}};", 4698 getLLVMStyleWithColumns(40)); 4699 } 4700 4701 TEST_F(FormatTest, DesignatedInitializers) { 4702 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4703 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4704 " .bbbbbbbbbb = 2,\n" 4705 " .cccccccccc = 3,\n" 4706 " .dddddddddd = 4,\n" 4707 " .eeeeeeeeee = 5};"); 4708 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4709 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4710 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4711 " .ccccccccccccccccccccccccccc = 3,\n" 4712 " .ddddddddddddddddddddddddddd = 4,\n" 4713 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4714 4715 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4716 4717 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4718 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4719 " [2] = bbbbbbbbbb,\n" 4720 " [3] = cccccccccc,\n" 4721 " [4] = dddddddddd,\n" 4722 " [5] = eeeeeeeeee};"); 4723 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4724 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4725 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4726 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4727 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4728 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4729 } 4730 4731 TEST_F(FormatTest, NestedStaticInitializers) { 4732 verifyFormat("static A x = {{{}}};\n"); 4733 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4734 " {init1, init2, init3, init4}}};", 4735 getLLVMStyleWithColumns(50)); 4736 4737 verifyFormat("somes Status::global_reps[3] = {\n" 4738 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4739 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4740 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4741 getLLVMStyleWithColumns(60)); 4742 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4743 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4744 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4745 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4746 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4747 " {rect.fRight - rect.fLeft, rect.fBottom - " 4748 "rect.fTop}};"); 4749 4750 verifyFormat( 4751 "SomeArrayOfSomeType a = {\n" 4752 " {{1, 2, 3},\n" 4753 " {1, 2, 3},\n" 4754 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4755 " 333333333333333333333333333333},\n" 4756 " {1, 2, 3},\n" 4757 " {1, 2, 3}}};"); 4758 verifyFormat( 4759 "SomeArrayOfSomeType a = {\n" 4760 " {{1, 2, 3}},\n" 4761 " {{1, 2, 3}},\n" 4762 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4763 " 333333333333333333333333333333}},\n" 4764 " {{1, 2, 3}},\n" 4765 " {{1, 2, 3}}};"); 4766 4767 verifyFormat("struct {\n" 4768 " unsigned bit;\n" 4769 " const char *const name;\n" 4770 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4771 " {kOsWin, \"Windows\"},\n" 4772 " {kOsLinux, \"Linux\"},\n" 4773 " {kOsCrOS, \"Chrome OS\"}};"); 4774 verifyFormat("struct {\n" 4775 " unsigned bit;\n" 4776 " const char *const name;\n" 4777 "} kBitsToOs[] = {\n" 4778 " {kOsMac, \"Mac\"},\n" 4779 " {kOsWin, \"Windows\"},\n" 4780 " {kOsLinux, \"Linux\"},\n" 4781 " {kOsCrOS, \"Chrome OS\"},\n" 4782 "};"); 4783 } 4784 4785 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4786 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4787 " \\\n" 4788 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4789 } 4790 4791 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4792 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4793 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4794 4795 // Do break defaulted and deleted functions. 4796 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4797 " default;", 4798 getLLVMStyleWithColumns(40)); 4799 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4800 " delete;", 4801 getLLVMStyleWithColumns(40)); 4802 } 4803 4804 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4805 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4806 getLLVMStyleWithColumns(40)); 4807 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4808 getLLVMStyleWithColumns(40)); 4809 EXPECT_EQ("#define Q \\\n" 4810 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4811 " \"aaaaaaaa.cpp\"", 4812 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4813 getLLVMStyleWithColumns(40))); 4814 } 4815 4816 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4817 EXPECT_EQ("# 123 \"A string literal\"", 4818 format(" # 123 \"A string literal\"")); 4819 } 4820 4821 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4822 EXPECT_EQ("#;", format("#;")); 4823 verifyFormat("#\n;\n;\n;"); 4824 } 4825 4826 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4827 EXPECT_EQ("#line 42 \"test\"\n", 4828 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4829 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4830 getLLVMStyleWithColumns(12))); 4831 } 4832 4833 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4834 EXPECT_EQ("#line 42 \"test\"", 4835 format("# \\\n line \\\n 42 \\\n \"test\"")); 4836 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4837 } 4838 4839 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4840 verifyFormat("#define A \\x20"); 4841 verifyFormat("#define A \\ x20"); 4842 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4843 verifyFormat("#define A ''"); 4844 verifyFormat("#define A ''qqq"); 4845 verifyFormat("#define A `qqq"); 4846 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4847 EXPECT_EQ("const char *c = STRINGIFY(\n" 4848 "\\na : b);", 4849 format("const char * c = STRINGIFY(\n" 4850 "\\na : b);")); 4851 4852 verifyFormat("a\r\\"); 4853 verifyFormat("a\v\\"); 4854 verifyFormat("a\f\\"); 4855 } 4856 4857 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4858 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4859 style.IndentWidth = 4; 4860 style.PPIndentWidth = 1; 4861 4862 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4863 verifyFormat("#ifdef __linux__\n" 4864 "void foo() {\n" 4865 " int x = 0;\n" 4866 "}\n" 4867 "#define FOO\n" 4868 "#endif\n" 4869 "void bar() {\n" 4870 " int y = 0;\n" 4871 "}\n", 4872 style); 4873 4874 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4875 verifyFormat("#ifdef __linux__\n" 4876 "void foo() {\n" 4877 " int x = 0;\n" 4878 "}\n" 4879 "# define FOO foo\n" 4880 "#endif\n" 4881 "void bar() {\n" 4882 " int y = 0;\n" 4883 "}\n", 4884 style); 4885 4886 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4887 verifyFormat("#ifdef __linux__\n" 4888 "void foo() {\n" 4889 " int x = 0;\n" 4890 "}\n" 4891 " #define FOO foo\n" 4892 "#endif\n" 4893 "void bar() {\n" 4894 " int y = 0;\n" 4895 "}\n", 4896 style); 4897 } 4898 4899 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4900 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4901 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4902 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4903 // FIXME: We never break before the macro name. 4904 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4905 4906 verifyFormat("#define A A\n#define A A"); 4907 verifyFormat("#define A(X) A\n#define A A"); 4908 4909 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4910 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4911 } 4912 4913 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4914 EXPECT_EQ("// somecomment\n" 4915 "#include \"a.h\"\n" 4916 "#define A( \\\n" 4917 " A, B)\n" 4918 "#include \"b.h\"\n" 4919 "// somecomment\n", 4920 format(" // somecomment\n" 4921 " #include \"a.h\"\n" 4922 "#define A(A,\\\n" 4923 " B)\n" 4924 " #include \"b.h\"\n" 4925 " // somecomment\n", 4926 getLLVMStyleWithColumns(13))); 4927 } 4928 4929 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4930 4931 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4932 EXPECT_EQ("#define A \\\n" 4933 " c; \\\n" 4934 " e;\n" 4935 "f;", 4936 format("#define A c; e;\n" 4937 "f;", 4938 getLLVMStyleWithColumns(14))); 4939 } 4940 4941 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4942 4943 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4944 EXPECT_EQ("int x,\n" 4945 "#define A\n" 4946 " y;", 4947 format("int x,\n#define A\ny;")); 4948 } 4949 4950 TEST_F(FormatTest, HashInMacroDefinition) { 4951 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4952 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4953 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4954 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4955 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4956 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4957 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4958 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4959 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4960 verifyFormat("#define A \\\n" 4961 " { \\\n" 4962 " f(#c); \\\n" 4963 " }", 4964 getLLVMStyleWithColumns(11)); 4965 4966 verifyFormat("#define A(X) \\\n" 4967 " void function##X()", 4968 getLLVMStyleWithColumns(22)); 4969 4970 verifyFormat("#define A(a, b, c) \\\n" 4971 " void a##b##c()", 4972 getLLVMStyleWithColumns(22)); 4973 4974 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4975 } 4976 4977 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4978 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4979 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4980 4981 FormatStyle Style = getLLVMStyle(); 4982 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4983 verifyFormat("#define true ((foo)1)", Style); 4984 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4985 verifyFormat("#define false((foo)0)", Style); 4986 } 4987 4988 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4989 EXPECT_EQ("#define A b;", format("#define A \\\n" 4990 " \\\n" 4991 " b;", 4992 getLLVMStyleWithColumns(25))); 4993 EXPECT_EQ("#define A \\\n" 4994 " \\\n" 4995 " a; \\\n" 4996 " b;", 4997 format("#define A \\\n" 4998 " \\\n" 4999 " a; \\\n" 5000 " b;", 5001 getLLVMStyleWithColumns(11))); 5002 EXPECT_EQ("#define A \\\n" 5003 " a; \\\n" 5004 " \\\n" 5005 " b;", 5006 format("#define A \\\n" 5007 " a; \\\n" 5008 " \\\n" 5009 " b;", 5010 getLLVMStyleWithColumns(11))); 5011 } 5012 5013 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5014 verifyIncompleteFormat("#define A :"); 5015 verifyFormat("#define SOMECASES \\\n" 5016 " case 1: \\\n" 5017 " case 2\n", 5018 getLLVMStyleWithColumns(20)); 5019 verifyFormat("#define MACRO(a) \\\n" 5020 " if (a) \\\n" 5021 " f(); \\\n" 5022 " else \\\n" 5023 " g()", 5024 getLLVMStyleWithColumns(18)); 5025 verifyFormat("#define A template <typename T>"); 5026 verifyIncompleteFormat("#define STR(x) #x\n" 5027 "f(STR(this_is_a_string_literal{));"); 5028 verifyFormat("#pragma omp threadprivate( \\\n" 5029 " y)), // expected-warning", 5030 getLLVMStyleWithColumns(28)); 5031 verifyFormat("#d, = };"); 5032 verifyFormat("#if \"a"); 5033 verifyIncompleteFormat("({\n" 5034 "#define b \\\n" 5035 " } \\\n" 5036 " a\n" 5037 "a", 5038 getLLVMStyleWithColumns(15)); 5039 verifyFormat("#define A \\\n" 5040 " { \\\n" 5041 " {\n" 5042 "#define B \\\n" 5043 " } \\\n" 5044 " }", 5045 getLLVMStyleWithColumns(15)); 5046 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5047 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5048 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5049 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5050 } 5051 5052 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5053 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5054 EXPECT_EQ("class A : public QObject {\n" 5055 " Q_OBJECT\n" 5056 "\n" 5057 " A() {}\n" 5058 "};", 5059 format("class A : public QObject {\n" 5060 " Q_OBJECT\n" 5061 "\n" 5062 " A() {\n}\n" 5063 "} ;")); 5064 EXPECT_EQ("MACRO\n" 5065 "/*static*/ int i;", 5066 format("MACRO\n" 5067 " /*static*/ int i;")); 5068 EXPECT_EQ("SOME_MACRO\n" 5069 "namespace {\n" 5070 "void f();\n" 5071 "} // namespace", 5072 format("SOME_MACRO\n" 5073 " namespace {\n" 5074 "void f( );\n" 5075 "} // namespace")); 5076 // Only if the identifier contains at least 5 characters. 5077 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5078 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5079 // Only if everything is upper case. 5080 EXPECT_EQ("class A : public QObject {\n" 5081 " Q_Object A() {}\n" 5082 "};", 5083 format("class A : public QObject {\n" 5084 " Q_Object\n" 5085 " A() {\n}\n" 5086 "} ;")); 5087 5088 // Only if the next line can actually start an unwrapped line. 5089 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5090 format("SOME_WEIRD_LOG_MACRO\n" 5091 "<< SomeThing;")); 5092 5093 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5094 "(n, buffers))\n", 5095 getChromiumStyle(FormatStyle::LK_Cpp)); 5096 5097 // See PR41483 5098 EXPECT_EQ("/**/ FOO(a)\n" 5099 "FOO(b)", 5100 format("/**/ FOO(a)\n" 5101 "FOO(b)")); 5102 } 5103 5104 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5105 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5106 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5107 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5108 "class X {};\n" 5109 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5110 "int *createScopDetectionPass() { return 0; }", 5111 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5112 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5113 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5114 " class X {};\n" 5115 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5116 " int *createScopDetectionPass() { return 0; }")); 5117 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5118 // braces, so that inner block is indented one level more. 5119 EXPECT_EQ("int q() {\n" 5120 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5121 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5122 " IPC_END_MESSAGE_MAP()\n" 5123 "}", 5124 format("int q() {\n" 5125 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5126 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5127 " IPC_END_MESSAGE_MAP()\n" 5128 "}")); 5129 5130 // Same inside macros. 5131 EXPECT_EQ("#define LIST(L) \\\n" 5132 " L(A) \\\n" 5133 " L(B) \\\n" 5134 " L(C)", 5135 format("#define LIST(L) \\\n" 5136 " L(A) \\\n" 5137 " L(B) \\\n" 5138 " L(C)", 5139 getGoogleStyle())); 5140 5141 // These must not be recognized as macros. 5142 EXPECT_EQ("int q() {\n" 5143 " f(x);\n" 5144 " f(x) {}\n" 5145 " f(x)->g();\n" 5146 " f(x)->*g();\n" 5147 " f(x).g();\n" 5148 " f(x) = x;\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)[y].z();\n" 5160 " LOG(INFO) << x;\n" 5161 " ifstream(x) >> x;\n" 5162 "}\n", 5163 format("int q() {\n" 5164 " f(x)\n;\n" 5165 " f(x)\n {}\n" 5166 " f(x)\n->g();\n" 5167 " f(x)\n->*g();\n" 5168 " f(x)\n.g();\n" 5169 " f(x)\n = x;\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[y].z();\n" 5181 " LOG(INFO)\n << x;\n" 5182 " ifstream(x)\n >> x;\n" 5183 "}\n")); 5184 EXPECT_EQ("int q() {\n" 5185 " F(x)\n" 5186 " if (1) {\n" 5187 " }\n" 5188 " F(x)\n" 5189 " while (1) {\n" 5190 " }\n" 5191 " F(x)\n" 5192 " G(x);\n" 5193 " F(x)\n" 5194 " try {\n" 5195 " Q();\n" 5196 " } catch (...) {\n" 5197 " }\n" 5198 "}\n", 5199 format("int q() {\n" 5200 "F(x)\n" 5201 "if (1) {}\n" 5202 "F(x)\n" 5203 "while (1) {}\n" 5204 "F(x)\n" 5205 "G(x);\n" 5206 "F(x)\n" 5207 "try { Q(); } catch (...) {}\n" 5208 "}\n")); 5209 EXPECT_EQ("class A {\n" 5210 " A() : t(0) {}\n" 5211 " A(int i) noexcept() : {}\n" 5212 " A(X x)\n" // FIXME: function-level try blocks are broken. 5213 " try : t(0) {\n" 5214 " } catch (...) {\n" 5215 " }\n" 5216 "};", 5217 format("class A {\n" 5218 " A()\n : t(0) {}\n" 5219 " A(int i)\n noexcept() : {}\n" 5220 " A(X x)\n" 5221 " try : t(0) {} catch (...) {}\n" 5222 "};")); 5223 FormatStyle Style = getLLVMStyle(); 5224 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5225 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5226 Style.BraceWrapping.AfterFunction = true; 5227 EXPECT_EQ("void f()\n" 5228 "try\n" 5229 "{\n" 5230 "}", 5231 format("void f() try {\n" 5232 "}", 5233 Style)); 5234 EXPECT_EQ("class SomeClass {\n" 5235 "public:\n" 5236 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5237 "};", 5238 format("class SomeClass {\n" 5239 "public:\n" 5240 " SomeClass()\n" 5241 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5242 "};")); 5243 EXPECT_EQ("class SomeClass {\n" 5244 "public:\n" 5245 " SomeClass()\n" 5246 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5247 "};", 5248 format("class SomeClass {\n" 5249 "public:\n" 5250 " SomeClass()\n" 5251 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5252 "};", 5253 getLLVMStyleWithColumns(40))); 5254 5255 verifyFormat("MACRO(>)"); 5256 5257 // Some macros contain an implicit semicolon. 5258 Style = getLLVMStyle(); 5259 Style.StatementMacros.push_back("FOO"); 5260 verifyFormat("FOO(a) int b = 0;"); 5261 verifyFormat("FOO(a)\n" 5262 "int b = 0;", 5263 Style); 5264 verifyFormat("FOO(a);\n" 5265 "int b = 0;", 5266 Style); 5267 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5268 "int b = 0;", 5269 Style); 5270 verifyFormat("FOO()\n" 5271 "int b = 0;", 5272 Style); 5273 verifyFormat("FOO\n" 5274 "int b = 0;", 5275 Style); 5276 verifyFormat("void f() {\n" 5277 " FOO(a)\n" 5278 " return a;\n" 5279 "}", 5280 Style); 5281 verifyFormat("FOO(a)\n" 5282 "FOO(b)", 5283 Style); 5284 verifyFormat("int a = 0;\n" 5285 "FOO(b)\n" 5286 "int c = 0;", 5287 Style); 5288 verifyFormat("int a = 0;\n" 5289 "int x = FOO(a)\n" 5290 "int b = 0;", 5291 Style); 5292 verifyFormat("void foo(int a) { FOO(a) }\n" 5293 "uint32_t bar() {}", 5294 Style); 5295 } 5296 5297 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5298 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5299 5300 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5301 ZeroColumn); 5302 } 5303 5304 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5305 verifyFormat("#define A \\\n" 5306 " f({ \\\n" 5307 " g(); \\\n" 5308 " });", 5309 getLLVMStyleWithColumns(11)); 5310 } 5311 5312 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5313 FormatStyle Style = getLLVMStyleWithColumns(40); 5314 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5315 verifyFormat("#ifdef _WIN32\n" 5316 "#define A 0\n" 5317 "#ifdef VAR2\n" 5318 "#define B 1\n" 5319 "#include <someheader.h>\n" 5320 "#define MACRO \\\n" 5321 " some_very_long_func_aaaaaaaaaa();\n" 5322 "#endif\n" 5323 "#else\n" 5324 "#define A 1\n" 5325 "#endif", 5326 Style); 5327 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5328 verifyFormat("#ifdef _WIN32\n" 5329 "# define A 0\n" 5330 "# ifdef VAR2\n" 5331 "# define B 1\n" 5332 "# include <someheader.h>\n" 5333 "# define MACRO \\\n" 5334 " some_very_long_func_aaaaaaaaaa();\n" 5335 "# endif\n" 5336 "#else\n" 5337 "# define A 1\n" 5338 "#endif", 5339 Style); 5340 verifyFormat("#if A\n" 5341 "# define MACRO \\\n" 5342 " void a(int x) { \\\n" 5343 " b(); \\\n" 5344 " c(); \\\n" 5345 " d(); \\\n" 5346 " e(); \\\n" 5347 " f(); \\\n" 5348 " }\n" 5349 "#endif", 5350 Style); 5351 // Comments before include guard. 5352 verifyFormat("// file comment\n" 5353 "// file comment\n" 5354 "#ifndef HEADER_H\n" 5355 "#define HEADER_H\n" 5356 "code();\n" 5357 "#endif", 5358 Style); 5359 // Test with include guards. 5360 verifyFormat("#ifndef HEADER_H\n" 5361 "#define HEADER_H\n" 5362 "code();\n" 5363 "#endif", 5364 Style); 5365 // Include guards must have a #define with the same variable immediately 5366 // after #ifndef. 5367 verifyFormat("#ifndef NOT_GUARD\n" 5368 "# define FOO\n" 5369 "code();\n" 5370 "#endif", 5371 Style); 5372 5373 // Include guards must cover the entire file. 5374 verifyFormat("code();\n" 5375 "code();\n" 5376 "#ifndef NOT_GUARD\n" 5377 "# define NOT_GUARD\n" 5378 "code();\n" 5379 "#endif", 5380 Style); 5381 verifyFormat("#ifndef NOT_GUARD\n" 5382 "# define NOT_GUARD\n" 5383 "code();\n" 5384 "#endif\n" 5385 "code();", 5386 Style); 5387 // Test with trailing blank lines. 5388 verifyFormat("#ifndef HEADER_H\n" 5389 "#define HEADER_H\n" 5390 "code();\n" 5391 "#endif\n", 5392 Style); 5393 // Include guards don't have #else. 5394 verifyFormat("#ifndef NOT_GUARD\n" 5395 "# define NOT_GUARD\n" 5396 "code();\n" 5397 "#else\n" 5398 "#endif", 5399 Style); 5400 verifyFormat("#ifndef NOT_GUARD\n" 5401 "# define NOT_GUARD\n" 5402 "code();\n" 5403 "#elif FOO\n" 5404 "#endif", 5405 Style); 5406 // Non-identifier #define after potential include guard. 5407 verifyFormat("#ifndef FOO\n" 5408 "# define 1\n" 5409 "#endif\n", 5410 Style); 5411 // #if closes past last non-preprocessor line. 5412 verifyFormat("#ifndef FOO\n" 5413 "#define FOO\n" 5414 "#if 1\n" 5415 "int i;\n" 5416 "# define A 0\n" 5417 "#endif\n" 5418 "#endif\n", 5419 Style); 5420 // Don't crash if there is an #elif directive without a condition. 5421 verifyFormat("#if 1\n" 5422 "int x;\n" 5423 "#elif\n" 5424 "int y;\n" 5425 "#else\n" 5426 "int z;\n" 5427 "#endif", 5428 Style); 5429 // FIXME: This doesn't handle the case where there's code between the 5430 // #ifndef and #define but all other conditions hold. This is because when 5431 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5432 // previous code line yet, so we can't detect it. 5433 EXPECT_EQ("#ifndef NOT_GUARD\n" 5434 "code();\n" 5435 "#define NOT_GUARD\n" 5436 "code();\n" 5437 "#endif", 5438 format("#ifndef NOT_GUARD\n" 5439 "code();\n" 5440 "# define NOT_GUARD\n" 5441 "code();\n" 5442 "#endif", 5443 Style)); 5444 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5445 // be outside an include guard. Examples are #pragma once and 5446 // #pragma GCC diagnostic, or anything else that does not change the meaning 5447 // of the file if it's included multiple times. 5448 EXPECT_EQ("#ifdef WIN32\n" 5449 "# pragma once\n" 5450 "#endif\n" 5451 "#ifndef HEADER_H\n" 5452 "# define HEADER_H\n" 5453 "code();\n" 5454 "#endif", 5455 format("#ifdef WIN32\n" 5456 "# pragma once\n" 5457 "#endif\n" 5458 "#ifndef HEADER_H\n" 5459 "#define HEADER_H\n" 5460 "code();\n" 5461 "#endif", 5462 Style)); 5463 // FIXME: This does not detect when there is a single non-preprocessor line 5464 // in front of an include-guard-like structure where other conditions hold 5465 // because ScopedLineState hides the line. 5466 EXPECT_EQ("code();\n" 5467 "#ifndef HEADER_H\n" 5468 "#define HEADER_H\n" 5469 "code();\n" 5470 "#endif", 5471 format("code();\n" 5472 "#ifndef HEADER_H\n" 5473 "# define HEADER_H\n" 5474 "code();\n" 5475 "#endif", 5476 Style)); 5477 // Keep comments aligned with #, otherwise indent comments normally. These 5478 // tests cannot use verifyFormat because messUp manipulates leading 5479 // whitespace. 5480 { 5481 const char *Expected = "" 5482 "void f() {\n" 5483 "#if 1\n" 5484 "// Preprocessor aligned.\n" 5485 "# define A 0\n" 5486 " // Code. Separated by blank line.\n" 5487 "\n" 5488 "# define B 0\n" 5489 " // Code. Not aligned with #\n" 5490 "# define C 0\n" 5491 "#endif"; 5492 const char *ToFormat = "" 5493 "void f() {\n" 5494 "#if 1\n" 5495 "// Preprocessor aligned.\n" 5496 "# define A 0\n" 5497 "// Code. Separated by blank line.\n" 5498 "\n" 5499 "# define B 0\n" 5500 " // Code. Not aligned with #\n" 5501 "# define C 0\n" 5502 "#endif"; 5503 EXPECT_EQ(Expected, format(ToFormat, Style)); 5504 EXPECT_EQ(Expected, format(Expected, Style)); 5505 } 5506 // Keep block quotes aligned. 5507 { 5508 const char *Expected = "" 5509 "void f() {\n" 5510 "#if 1\n" 5511 "/* Preprocessor aligned. */\n" 5512 "# define A 0\n" 5513 " /* Code. Separated by blank line. */\n" 5514 "\n" 5515 "# define B 0\n" 5516 " /* Code. Not aligned with # */\n" 5517 "# define C 0\n" 5518 "#endif"; 5519 const char *ToFormat = "" 5520 "void f() {\n" 5521 "#if 1\n" 5522 "/* Preprocessor aligned. */\n" 5523 "# define A 0\n" 5524 "/* Code. Separated by blank line. */\n" 5525 "\n" 5526 "# define B 0\n" 5527 " /* Code. Not aligned with # */\n" 5528 "# define C 0\n" 5529 "#endif"; 5530 EXPECT_EQ(Expected, format(ToFormat, Style)); 5531 EXPECT_EQ(Expected, format(Expected, Style)); 5532 } 5533 // Keep comments aligned with un-indented directives. 5534 { 5535 const char *Expected = "" 5536 "void f() {\n" 5537 "// Preprocessor aligned.\n" 5538 "#define A 0\n" 5539 " // Code. Separated by blank line.\n" 5540 "\n" 5541 "#define B 0\n" 5542 " // Code. Not aligned with #\n" 5543 "#define C 0\n"; 5544 const char *ToFormat = "" 5545 "void f() {\n" 5546 "// Preprocessor aligned.\n" 5547 "#define A 0\n" 5548 "// Code. Separated by blank line.\n" 5549 "\n" 5550 "#define B 0\n" 5551 " // Code. Not aligned with #\n" 5552 "#define C 0\n"; 5553 EXPECT_EQ(Expected, format(ToFormat, Style)); 5554 EXPECT_EQ(Expected, format(Expected, Style)); 5555 } 5556 // Test AfterHash with tabs. 5557 { 5558 FormatStyle Tabbed = Style; 5559 Tabbed.UseTab = FormatStyle::UT_Always; 5560 Tabbed.IndentWidth = 8; 5561 Tabbed.TabWidth = 8; 5562 verifyFormat("#ifdef _WIN32\n" 5563 "#\tdefine A 0\n" 5564 "#\tifdef VAR2\n" 5565 "#\t\tdefine B 1\n" 5566 "#\t\tinclude <someheader.h>\n" 5567 "#\t\tdefine MACRO \\\n" 5568 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5569 "#\tendif\n" 5570 "#else\n" 5571 "#\tdefine A 1\n" 5572 "#endif", 5573 Tabbed); 5574 } 5575 5576 // Regression test: Multiline-macro inside include guards. 5577 verifyFormat("#ifndef HEADER_H\n" 5578 "#define HEADER_H\n" 5579 "#define A() \\\n" 5580 " int i; \\\n" 5581 " int j;\n" 5582 "#endif // HEADER_H", 5583 getLLVMStyleWithColumns(20)); 5584 5585 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5586 // Basic before hash indent tests 5587 verifyFormat("#ifdef _WIN32\n" 5588 " #define A 0\n" 5589 " #ifdef VAR2\n" 5590 " #define B 1\n" 5591 " #include <someheader.h>\n" 5592 " #define MACRO \\\n" 5593 " some_very_long_func_aaaaaaaaaa();\n" 5594 " #endif\n" 5595 "#else\n" 5596 " #define A 1\n" 5597 "#endif", 5598 Style); 5599 verifyFormat("#if A\n" 5600 " #define MACRO \\\n" 5601 " void a(int x) { \\\n" 5602 " b(); \\\n" 5603 " c(); \\\n" 5604 " d(); \\\n" 5605 " e(); \\\n" 5606 " f(); \\\n" 5607 " }\n" 5608 "#endif", 5609 Style); 5610 // Keep comments aligned with indented directives. These 5611 // tests cannot use verifyFormat because messUp manipulates leading 5612 // whitespace. 5613 { 5614 const char *Expected = "void f() {\n" 5615 "// Aligned to preprocessor.\n" 5616 "#if 1\n" 5617 " // Aligned to code.\n" 5618 " int a;\n" 5619 " #if 1\n" 5620 " // Aligned to preprocessor.\n" 5621 " #define A 0\n" 5622 " // Aligned to code.\n" 5623 " int b;\n" 5624 " #endif\n" 5625 "#endif\n" 5626 "}"; 5627 const char *ToFormat = "void f() {\n" 5628 "// Aligned to preprocessor.\n" 5629 "#if 1\n" 5630 "// Aligned to code.\n" 5631 "int a;\n" 5632 "#if 1\n" 5633 "// Aligned to preprocessor.\n" 5634 "#define A 0\n" 5635 "// Aligned to code.\n" 5636 "int b;\n" 5637 "#endif\n" 5638 "#endif\n" 5639 "}"; 5640 EXPECT_EQ(Expected, format(ToFormat, Style)); 5641 EXPECT_EQ(Expected, format(Expected, Style)); 5642 } 5643 { 5644 const char *Expected = "void f() {\n" 5645 "/* Aligned to preprocessor. */\n" 5646 "#if 1\n" 5647 " /* Aligned to code. */\n" 5648 " int a;\n" 5649 " #if 1\n" 5650 " /* Aligned to preprocessor. */\n" 5651 " #define A 0\n" 5652 " /* Aligned to code. */\n" 5653 " int b;\n" 5654 " #endif\n" 5655 "#endif\n" 5656 "}"; 5657 const char *ToFormat = "void f() {\n" 5658 "/* Aligned to preprocessor. */\n" 5659 "#if 1\n" 5660 "/* Aligned to code. */\n" 5661 "int a;\n" 5662 "#if 1\n" 5663 "/* Aligned to preprocessor. */\n" 5664 "#define A 0\n" 5665 "/* Aligned to code. */\n" 5666 "int b;\n" 5667 "#endif\n" 5668 "#endif\n" 5669 "}"; 5670 EXPECT_EQ(Expected, format(ToFormat, Style)); 5671 EXPECT_EQ(Expected, format(Expected, Style)); 5672 } 5673 5674 // Test single comment before preprocessor 5675 verifyFormat("// Comment\n" 5676 "\n" 5677 "#if 1\n" 5678 "#endif", 5679 Style); 5680 } 5681 5682 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5683 verifyFormat("{\n { a #c; }\n}"); 5684 } 5685 5686 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5687 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5688 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5689 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5690 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5691 } 5692 5693 TEST_F(FormatTest, EscapedNewlines) { 5694 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5695 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5696 format("#define A \\\nint i;\\\n int j;", Narrow)); 5697 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5698 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5699 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5700 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5701 5702 FormatStyle AlignLeft = getLLVMStyle(); 5703 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5704 EXPECT_EQ("#define MACRO(x) \\\n" 5705 "private: \\\n" 5706 " int x(int a);\n", 5707 format("#define MACRO(x) \\\n" 5708 "private: \\\n" 5709 " int x(int a);\n", 5710 AlignLeft)); 5711 5712 // CRLF line endings 5713 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5714 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5715 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5716 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5717 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5718 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5719 EXPECT_EQ("#define MACRO(x) \\\r\n" 5720 "private: \\\r\n" 5721 " int x(int a);\r\n", 5722 format("#define MACRO(x) \\\r\n" 5723 "private: \\\r\n" 5724 " int x(int a);\r\n", 5725 AlignLeft)); 5726 5727 FormatStyle DontAlign = getLLVMStyle(); 5728 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5729 DontAlign.MaxEmptyLinesToKeep = 3; 5730 // FIXME: can't use verifyFormat here because the newline before 5731 // "public:" is not inserted the first time it's reformatted 5732 EXPECT_EQ("#define A \\\n" 5733 " class Foo { \\\n" 5734 " void bar(); \\\n" 5735 "\\\n" 5736 "\\\n" 5737 "\\\n" 5738 " public: \\\n" 5739 " void baz(); \\\n" 5740 " };", 5741 format("#define A \\\n" 5742 " class Foo { \\\n" 5743 " void bar(); \\\n" 5744 "\\\n" 5745 "\\\n" 5746 "\\\n" 5747 " public: \\\n" 5748 " void baz(); \\\n" 5749 " };", 5750 DontAlign)); 5751 } 5752 5753 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5754 verifyFormat("#define A \\\n" 5755 " int v( \\\n" 5756 " a); \\\n" 5757 " int i;", 5758 getLLVMStyleWithColumns(11)); 5759 } 5760 5761 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5762 EXPECT_EQ( 5763 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5764 " \\\n" 5765 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5766 "\n" 5767 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5768 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5769 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5770 "\\\n" 5771 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5772 " \n" 5773 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5774 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5775 } 5776 5777 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5778 EXPECT_EQ("int\n" 5779 "#define A\n" 5780 " a;", 5781 format("int\n#define A\na;")); 5782 verifyFormat("functionCallTo(\n" 5783 " someOtherFunction(\n" 5784 " withSomeParameters, whichInSequence,\n" 5785 " areLongerThanALine(andAnotherCall,\n" 5786 "#define A B\n" 5787 " withMoreParamters,\n" 5788 " whichStronglyInfluenceTheLayout),\n" 5789 " andMoreParameters),\n" 5790 " trailing);", 5791 getLLVMStyleWithColumns(69)); 5792 verifyFormat("Foo::Foo()\n" 5793 "#ifdef BAR\n" 5794 " : baz(0)\n" 5795 "#endif\n" 5796 "{\n" 5797 "}"); 5798 verifyFormat("void f() {\n" 5799 " if (true)\n" 5800 "#ifdef A\n" 5801 " f(42);\n" 5802 " x();\n" 5803 "#else\n" 5804 " g();\n" 5805 " x();\n" 5806 "#endif\n" 5807 "}"); 5808 verifyFormat("void f(param1, param2,\n" 5809 " param3,\n" 5810 "#ifdef A\n" 5811 " param4(param5,\n" 5812 "#ifdef A1\n" 5813 " param6,\n" 5814 "#ifdef A2\n" 5815 " param7),\n" 5816 "#else\n" 5817 " param8),\n" 5818 " param9,\n" 5819 "#endif\n" 5820 " param10,\n" 5821 "#endif\n" 5822 " param11)\n" 5823 "#else\n" 5824 " param12)\n" 5825 "#endif\n" 5826 "{\n" 5827 " x();\n" 5828 "}", 5829 getLLVMStyleWithColumns(28)); 5830 verifyFormat("#if 1\n" 5831 "int i;"); 5832 verifyFormat("#if 1\n" 5833 "#endif\n" 5834 "#if 1\n" 5835 "#else\n" 5836 "#endif\n"); 5837 verifyFormat("DEBUG({\n" 5838 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5839 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5840 "});\n" 5841 "#if a\n" 5842 "#else\n" 5843 "#endif"); 5844 5845 verifyIncompleteFormat("void f(\n" 5846 "#if A\n" 5847 ");\n" 5848 "#else\n" 5849 "#endif"); 5850 } 5851 5852 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5853 verifyFormat("#endif\n" 5854 "#if B"); 5855 } 5856 5857 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5858 FormatStyle SingleLine = getLLVMStyle(); 5859 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5860 verifyFormat("#if 0\n" 5861 "#elif 1\n" 5862 "#endif\n" 5863 "void foo() {\n" 5864 " if (test) foo2();\n" 5865 "}", 5866 SingleLine); 5867 } 5868 5869 TEST_F(FormatTest, LayoutBlockInsideParens) { 5870 verifyFormat("functionCall({ int i; });"); 5871 verifyFormat("functionCall({\n" 5872 " int i;\n" 5873 " int j;\n" 5874 "});"); 5875 verifyFormat("functionCall(\n" 5876 " {\n" 5877 " int i;\n" 5878 " int j;\n" 5879 " },\n" 5880 " aaaa, bbbb, cccc);"); 5881 verifyFormat("functionA(functionB({\n" 5882 " int i;\n" 5883 " int j;\n" 5884 " }),\n" 5885 " aaaa, bbbb, cccc);"); 5886 verifyFormat("functionCall(\n" 5887 " {\n" 5888 " int i;\n" 5889 " int j;\n" 5890 " },\n" 5891 " aaaa, bbbb, // comment\n" 5892 " cccc);"); 5893 verifyFormat("functionA(functionB({\n" 5894 " int i;\n" 5895 " int j;\n" 5896 " }),\n" 5897 " aaaa, bbbb, // comment\n" 5898 " cccc);"); 5899 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5900 verifyFormat("functionCall(aaaa, bbbb, {\n" 5901 " int i;\n" 5902 " int j;\n" 5903 "});"); 5904 verifyFormat( 5905 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5906 " {\n" 5907 " int i; // break\n" 5908 " },\n" 5909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5910 " ccccccccccccccccc));"); 5911 verifyFormat("DEBUG({\n" 5912 " if (a)\n" 5913 " f();\n" 5914 "});"); 5915 } 5916 5917 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5918 EXPECT_EQ("SOME_MACRO { int i; }\n" 5919 "int i;", 5920 format(" SOME_MACRO {int i;} int i;")); 5921 } 5922 5923 TEST_F(FormatTest, LayoutNestedBlocks) { 5924 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5925 " struct s {\n" 5926 " int i;\n" 5927 " };\n" 5928 " s kBitsToOs[] = {{10}};\n" 5929 " for (int i = 0; i < 10; ++i)\n" 5930 " return;\n" 5931 "}"); 5932 verifyFormat("call(parameter, {\n" 5933 " something();\n" 5934 " // Comment using all columns.\n" 5935 " somethingelse();\n" 5936 "});", 5937 getLLVMStyleWithColumns(40)); 5938 verifyFormat("DEBUG( //\n" 5939 " { f(); }, a);"); 5940 verifyFormat("DEBUG( //\n" 5941 " {\n" 5942 " f(); //\n" 5943 " },\n" 5944 " a);"); 5945 5946 EXPECT_EQ("call(parameter, {\n" 5947 " something();\n" 5948 " // Comment too\n" 5949 " // looooooooooong.\n" 5950 " somethingElse();\n" 5951 "});", 5952 format("call(parameter, {\n" 5953 " something();\n" 5954 " // Comment too looooooooooong.\n" 5955 " somethingElse();\n" 5956 "});", 5957 getLLVMStyleWithColumns(29))); 5958 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5959 EXPECT_EQ("DEBUG({ // comment\n" 5960 " int i;\n" 5961 "});", 5962 format("DEBUG({ // comment\n" 5963 "int i;\n" 5964 "});")); 5965 EXPECT_EQ("DEBUG({\n" 5966 " int i;\n" 5967 "\n" 5968 " // comment\n" 5969 " int j;\n" 5970 "});", 5971 format("DEBUG({\n" 5972 " int i;\n" 5973 "\n" 5974 " // comment\n" 5975 " int j;\n" 5976 "});")); 5977 5978 verifyFormat("DEBUG({\n" 5979 " if (a)\n" 5980 " return;\n" 5981 "});"); 5982 verifyGoogleFormat("DEBUG({\n" 5983 " if (a) return;\n" 5984 "});"); 5985 FormatStyle Style = getGoogleStyle(); 5986 Style.ColumnLimit = 45; 5987 verifyFormat("Debug(\n" 5988 " aaaaa,\n" 5989 " {\n" 5990 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5991 " },\n" 5992 " a);", 5993 Style); 5994 5995 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5996 5997 verifyNoCrash("^{v^{a}}"); 5998 } 5999 6000 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6001 EXPECT_EQ("#define MACRO() \\\n" 6002 " Debug(aaa, /* force line break */ \\\n" 6003 " { \\\n" 6004 " int i; \\\n" 6005 " int j; \\\n" 6006 " })", 6007 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6008 " { int i; int j; })", 6009 getGoogleStyle())); 6010 6011 EXPECT_EQ("#define A \\\n" 6012 " [] { \\\n" 6013 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6014 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6015 " }", 6016 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6017 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6018 getGoogleStyle())); 6019 } 6020 6021 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6022 EXPECT_EQ("{}", format("{}")); 6023 verifyFormat("enum E {};"); 6024 verifyFormat("enum E {}"); 6025 FormatStyle Style = getLLVMStyle(); 6026 Style.SpaceInEmptyBlock = true; 6027 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6028 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6029 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6030 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6031 Style.BraceWrapping.BeforeElse = false; 6032 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6033 verifyFormat("if (a)\n" 6034 "{\n" 6035 "} else if (b)\n" 6036 "{\n" 6037 "} else\n" 6038 "{ }", 6039 Style); 6040 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6041 verifyFormat("if (a) {\n" 6042 "} else if (b) {\n" 6043 "} else {\n" 6044 "}", 6045 Style); 6046 Style.BraceWrapping.BeforeElse = true; 6047 verifyFormat("if (a) { }\n" 6048 "else if (b) { }\n" 6049 "else { }", 6050 Style); 6051 } 6052 6053 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6054 FormatStyle Style = getLLVMStyle(); 6055 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6056 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6057 verifyFormat("FOO_BEGIN\n" 6058 " FOO_ENTRY\n" 6059 "FOO_END", 6060 Style); 6061 verifyFormat("FOO_BEGIN\n" 6062 " NESTED_FOO_BEGIN\n" 6063 " NESTED_FOO_ENTRY\n" 6064 " NESTED_FOO_END\n" 6065 "FOO_END", 6066 Style); 6067 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6068 " int x;\n" 6069 " x = 1;\n" 6070 "FOO_END(Baz)", 6071 Style); 6072 } 6073 6074 //===----------------------------------------------------------------------===// 6075 // Line break tests. 6076 //===----------------------------------------------------------------------===// 6077 6078 TEST_F(FormatTest, PreventConfusingIndents) { 6079 verifyFormat( 6080 "void f() {\n" 6081 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6082 " parameter, parameter, parameter)),\n" 6083 " SecondLongCall(parameter));\n" 6084 "}"); 6085 verifyFormat( 6086 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6087 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6088 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6089 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6090 verifyFormat( 6091 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6092 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6093 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6094 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6095 verifyFormat( 6096 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6097 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6098 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6099 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6100 verifyFormat("int a = bbbb && ccc &&\n" 6101 " fffff(\n" 6102 "#define A Just forcing a new line\n" 6103 " ddd);"); 6104 } 6105 6106 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6107 verifyFormat( 6108 "bool aaaaaaa =\n" 6109 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6110 " bbbbbbbb();"); 6111 verifyFormat( 6112 "bool aaaaaaa =\n" 6113 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6114 " bbbbbbbb();"); 6115 6116 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6117 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6118 " ccccccccc == ddddddddddd;"); 6119 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6120 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6121 " ccccccccc == ddddddddddd;"); 6122 verifyFormat( 6123 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6125 " ccccccccc == ddddddddddd;"); 6126 6127 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6128 " aaaaaa) &&\n" 6129 " bbbbbb && cccccc;"); 6130 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6131 " aaaaaa) >>\n" 6132 " bbbbbb;"); 6133 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6134 " SourceMgr.getSpellingColumnNumber(\n" 6135 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6136 " 1);"); 6137 6138 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6139 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6140 " cccccc) {\n}"); 6141 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6142 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6143 " cccccc) {\n}"); 6144 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6145 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6146 " cccccc) {\n}"); 6147 verifyFormat("b = a &&\n" 6148 " // Comment\n" 6149 " b.c && d;"); 6150 6151 // If the LHS of a comparison is not a binary expression itself, the 6152 // additional linebreak confuses many people. 6153 verifyFormat( 6154 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6155 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6156 "}"); 6157 verifyFormat( 6158 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6160 "}"); 6161 verifyFormat( 6162 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6163 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6164 "}"); 6165 verifyFormat( 6166 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6167 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6168 "}"); 6169 // Even explicit parentheses stress the precedence enough to make the 6170 // additional break unnecessary. 6171 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6172 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6173 "}"); 6174 // This cases is borderline, but with the indentation it is still readable. 6175 verifyFormat( 6176 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6177 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6178 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6179 "}", 6180 getLLVMStyleWithColumns(75)); 6181 6182 // If the LHS is a binary expression, we should still use the additional break 6183 // as otherwise the formatting hides the operator precedence. 6184 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6185 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6186 " 5) {\n" 6187 "}"); 6188 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6189 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6190 " 5) {\n" 6191 "}"); 6192 6193 FormatStyle OnePerLine = getLLVMStyle(); 6194 OnePerLine.BinPackParameters = false; 6195 verifyFormat( 6196 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6197 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6199 OnePerLine); 6200 6201 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6202 " .aaa(aaaaaaaaaaaaa) *\n" 6203 " aaaaaaa +\n" 6204 " aaaaaaa;", 6205 getLLVMStyleWithColumns(40)); 6206 } 6207 6208 TEST_F(FormatTest, ExpressionIndentation) { 6209 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6210 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6211 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6212 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6213 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6214 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6215 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6216 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6217 " ccccccccccccccccccccccccccccccccccccccccc;"); 6218 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6219 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6220 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6221 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6222 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6224 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6225 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6226 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6227 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6229 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6230 verifyFormat("if () {\n" 6231 "} else if (aaaaa && bbbbb > // break\n" 6232 " ccccc) {\n" 6233 "}"); 6234 verifyFormat("if () {\n" 6235 "} else if constexpr (aaaaa && bbbbb > // break\n" 6236 " ccccc) {\n" 6237 "}"); 6238 verifyFormat("if () {\n" 6239 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6240 " ccccc) {\n" 6241 "}"); 6242 verifyFormat("if () {\n" 6243 "} else if (aaaaa &&\n" 6244 " bbbbb > // break\n" 6245 " ccccc &&\n" 6246 " ddddd) {\n" 6247 "}"); 6248 6249 // Presence of a trailing comment used to change indentation of b. 6250 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6251 " b;\n" 6252 "return aaaaaaaaaaaaaaaaaaa +\n" 6253 " b; //", 6254 getLLVMStyleWithColumns(30)); 6255 } 6256 6257 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6258 // Not sure what the best system is here. Like this, the LHS can be found 6259 // immediately above an operator (everything with the same or a higher 6260 // indent). The RHS is aligned right of the operator and so compasses 6261 // everything until something with the same indent as the operator is found. 6262 // FIXME: Is this a good system? 6263 FormatStyle Style = getLLVMStyle(); 6264 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6265 verifyFormat( 6266 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6267 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6268 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6269 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6270 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6271 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6272 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6273 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6274 " > ccccccccccccccccccccccccccccccccccccccccc;", 6275 Style); 6276 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6277 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6278 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6279 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6280 Style); 6281 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6282 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6283 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6284 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6285 Style); 6286 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6287 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6288 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6289 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6290 Style); 6291 verifyFormat("if () {\n" 6292 "} else if (aaaaa\n" 6293 " && bbbbb // break\n" 6294 " > ccccc) {\n" 6295 "}", 6296 Style); 6297 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6298 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6299 Style); 6300 verifyFormat("return (a)\n" 6301 " // comment\n" 6302 " + b;", 6303 Style); 6304 verifyFormat( 6305 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6306 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6307 " + cc;", 6308 Style); 6309 6310 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6311 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6312 Style); 6313 6314 // Forced by comments. 6315 verifyFormat( 6316 "unsigned ContentSize =\n" 6317 " sizeof(int16_t) // DWARF ARange version number\n" 6318 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6319 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6320 " + sizeof(int8_t); // Segment Size (in bytes)"); 6321 6322 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6323 " == boost::fusion::at_c<1>(iiii).second;", 6324 Style); 6325 6326 Style.ColumnLimit = 60; 6327 verifyFormat("zzzzzzzzzz\n" 6328 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6329 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6330 Style); 6331 6332 Style.ColumnLimit = 80; 6333 Style.IndentWidth = 4; 6334 Style.TabWidth = 4; 6335 Style.UseTab = FormatStyle::UT_Always; 6336 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6337 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6338 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6339 "\t&& (someOtherLongishConditionPart1\n" 6340 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6341 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6342 "(someOtherLongishConditionPart1 || " 6343 "someOtherEvenLongerNestedConditionPart2);", 6344 Style)); 6345 } 6346 6347 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6348 FormatStyle Style = getLLVMStyle(); 6349 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6350 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6351 6352 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6353 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6354 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6355 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6356 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6357 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6358 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6359 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6360 " > ccccccccccccccccccccccccccccccccccccccccc;", 6361 Style); 6362 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6363 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6364 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6365 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6366 Style); 6367 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6368 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6369 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6370 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6371 Style); 6372 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6373 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6374 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6375 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6376 Style); 6377 verifyFormat("if () {\n" 6378 "} else if (aaaaa\n" 6379 " && bbbbb // break\n" 6380 " > ccccc) {\n" 6381 "}", 6382 Style); 6383 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6384 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6385 Style); 6386 verifyFormat("return (a)\n" 6387 " // comment\n" 6388 " + b;", 6389 Style); 6390 verifyFormat( 6391 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6392 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6393 " + cc;", 6394 Style); 6395 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6396 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6397 " : 3333333333333333;", 6398 Style); 6399 verifyFormat( 6400 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6401 " : ccccccccccccccc ? dddddddddddddddddd\n" 6402 " : eeeeeeeeeeeeeeeeee)\n" 6403 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6404 " : 3333333333333333;", 6405 Style); 6406 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6407 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6408 Style); 6409 6410 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6411 " == boost::fusion::at_c<1>(iiii).second;", 6412 Style); 6413 6414 Style.ColumnLimit = 60; 6415 verifyFormat("zzzzzzzzzzzzz\n" 6416 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6417 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6418 Style); 6419 6420 // Forced by comments. 6421 Style.ColumnLimit = 80; 6422 verifyFormat( 6423 "unsigned ContentSize\n" 6424 " = sizeof(int16_t) // DWARF ARange version number\n" 6425 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6426 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6427 " + sizeof(int8_t); // Segment Size (in bytes)", 6428 Style); 6429 6430 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6431 verifyFormat( 6432 "unsigned ContentSize =\n" 6433 " sizeof(int16_t) // DWARF ARange version number\n" 6434 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6435 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6436 " + sizeof(int8_t); // Segment Size (in bytes)", 6437 Style); 6438 6439 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6440 verifyFormat( 6441 "unsigned ContentSize =\n" 6442 " sizeof(int16_t) // DWARF ARange version number\n" 6443 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6444 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6445 " + sizeof(int8_t); // Segment Size (in bytes)", 6446 Style); 6447 } 6448 6449 TEST_F(FormatTest, EnforcedOperatorWraps) { 6450 // Here we'd like to wrap after the || operators, but a comment is forcing an 6451 // earlier wrap. 6452 verifyFormat("bool x = aaaaa //\n" 6453 " || bbbbb\n" 6454 " //\n" 6455 " || cccc;"); 6456 } 6457 6458 TEST_F(FormatTest, NoOperandAlignment) { 6459 FormatStyle Style = getLLVMStyle(); 6460 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6461 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6462 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6464 Style); 6465 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6466 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6467 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6468 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6469 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6470 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6471 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6472 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6473 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6474 " > ccccccccccccccccccccccccccccccccccccccccc;", 6475 Style); 6476 6477 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6478 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6479 " + cc;", 6480 Style); 6481 verifyFormat("int a = aa\n" 6482 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6483 " * cccccccccccccccccccccccccccccccccccc;\n", 6484 Style); 6485 6486 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6487 verifyFormat("return (a > b\n" 6488 " // comment1\n" 6489 " // comment2\n" 6490 " || c);", 6491 Style); 6492 } 6493 6494 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6495 FormatStyle Style = getLLVMStyle(); 6496 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6497 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6498 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6499 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6500 Style); 6501 } 6502 6503 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6504 FormatStyle Style = getLLVMStyleWithColumns(40); 6505 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6506 Style.BinPackArguments = false; 6507 verifyFormat("void test() {\n" 6508 " someFunction(\n" 6509 " this + argument + is + quite\n" 6510 " + long + so + it + gets + wrapped\n" 6511 " + but + remains + bin - packed);\n" 6512 "}", 6513 Style); 6514 verifyFormat("void test() {\n" 6515 " someFunction(arg1,\n" 6516 " this + argument + is\n" 6517 " + quite + long + so\n" 6518 " + it + gets + wrapped\n" 6519 " + but + remains + bin\n" 6520 " - packed,\n" 6521 " arg3);\n" 6522 "}", 6523 Style); 6524 verifyFormat("void test() {\n" 6525 " someFunction(\n" 6526 " arg1,\n" 6527 " this + argument + has\n" 6528 " + anotherFunc(nested,\n" 6529 " calls + whose\n" 6530 " + arguments\n" 6531 " + are + also\n" 6532 " + wrapped,\n" 6533 " in + addition)\n" 6534 " + to + being + bin - packed,\n" 6535 " arg3);\n" 6536 "}", 6537 Style); 6538 6539 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6540 verifyFormat("void test() {\n" 6541 " someFunction(\n" 6542 " arg1,\n" 6543 " this + argument + has +\n" 6544 " anotherFunc(nested,\n" 6545 " calls + whose +\n" 6546 " arguments +\n" 6547 " are + also +\n" 6548 " wrapped,\n" 6549 " in + addition) +\n" 6550 " to + being + bin - packed,\n" 6551 " arg3);\n" 6552 "}", 6553 Style); 6554 } 6555 6556 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6557 auto Style = getLLVMStyleWithColumns(45); 6558 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6559 verifyFormat("bool b =\n" 6560 " is_default_constructible_v<hash<T>> and\n" 6561 " is_copy_constructible_v<hash<T>> and\n" 6562 " is_move_constructible_v<hash<T>> and\n" 6563 " is_copy_assignable_v<hash<T>> and\n" 6564 " is_move_assignable_v<hash<T>> and\n" 6565 " is_destructible_v<hash<T>> and\n" 6566 " is_swappable_v<hash<T>> and\n" 6567 " is_callable_v<hash<T>(T)>;", 6568 Style); 6569 6570 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6571 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6572 " and is_copy_constructible_v<hash<T>>\n" 6573 " and is_move_constructible_v<hash<T>>\n" 6574 " and is_copy_assignable_v<hash<T>>\n" 6575 " and is_move_assignable_v<hash<T>>\n" 6576 " and is_destructible_v<hash<T>>\n" 6577 " and is_swappable_v<hash<T>>\n" 6578 " and is_callable_v<hash<T>(T)>;", 6579 Style); 6580 6581 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6582 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6583 " and is_copy_constructible_v<hash<T>>\n" 6584 " and is_move_constructible_v<hash<T>>\n" 6585 " and is_copy_assignable_v<hash<T>>\n" 6586 " and is_move_assignable_v<hash<T>>\n" 6587 " and is_destructible_v<hash<T>>\n" 6588 " and is_swappable_v<hash<T>>\n" 6589 " and is_callable_v<hash<T>(T)>;", 6590 Style); 6591 } 6592 6593 TEST_F(FormatTest, ConstructorInitializers) { 6594 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6595 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6596 getLLVMStyleWithColumns(45)); 6597 verifyFormat("Constructor()\n" 6598 " : Inttializer(FitsOnTheLine) {}", 6599 getLLVMStyleWithColumns(44)); 6600 verifyFormat("Constructor()\n" 6601 " : Inttializer(FitsOnTheLine) {}", 6602 getLLVMStyleWithColumns(43)); 6603 6604 verifyFormat("template <typename T>\n" 6605 "Constructor() : Initializer(FitsOnTheLine) {}", 6606 getLLVMStyleWithColumns(45)); 6607 6608 verifyFormat( 6609 "SomeClass::Constructor()\n" 6610 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6611 6612 verifyFormat( 6613 "SomeClass::Constructor()\n" 6614 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6615 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6616 verifyFormat( 6617 "SomeClass::Constructor()\n" 6618 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6619 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6620 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6621 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6622 " : aaaaaaaaaa(aaaaaa) {}"); 6623 6624 verifyFormat("Constructor()\n" 6625 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6626 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6627 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6628 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6629 6630 verifyFormat("Constructor()\n" 6631 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6632 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6633 6634 verifyFormat("Constructor(int Parameter = 0)\n" 6635 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6636 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6637 verifyFormat("Constructor()\n" 6638 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6639 "}", 6640 getLLVMStyleWithColumns(60)); 6641 verifyFormat("Constructor()\n" 6642 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6643 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6644 6645 // Here a line could be saved by splitting the second initializer onto two 6646 // lines, but that is not desirable. 6647 verifyFormat("Constructor()\n" 6648 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6649 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6650 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6651 6652 FormatStyle OnePerLine = getLLVMStyle(); 6653 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6654 verifyFormat("MyClass::MyClass()\n" 6655 " : a(a),\n" 6656 " b(b),\n" 6657 " c(c) {}", 6658 OnePerLine); 6659 verifyFormat("MyClass::MyClass()\n" 6660 " : a(a), // comment\n" 6661 " b(b),\n" 6662 " c(c) {}", 6663 OnePerLine); 6664 verifyFormat("MyClass::MyClass(int a)\n" 6665 " : b(a), // comment\n" 6666 " c(a + 1) { // lined up\n" 6667 "}", 6668 OnePerLine); 6669 verifyFormat("Constructor()\n" 6670 " : a(b, b, b) {}", 6671 OnePerLine); 6672 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6673 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6674 verifyFormat("SomeClass::Constructor()\n" 6675 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6676 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6677 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6678 OnePerLine); 6679 verifyFormat("SomeClass::Constructor()\n" 6680 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6681 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6682 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6683 OnePerLine); 6684 verifyFormat("MyClass::MyClass(int var)\n" 6685 " : some_var_(var), // 4 space indent\n" 6686 " some_other_var_(var + 1) { // lined up\n" 6687 "}", 6688 OnePerLine); 6689 verifyFormat("Constructor()\n" 6690 " : aaaaa(aaaaaa),\n" 6691 " aaaaa(aaaaaa),\n" 6692 " aaaaa(aaaaaa),\n" 6693 " aaaaa(aaaaaa),\n" 6694 " aaaaa(aaaaaa) {}", 6695 OnePerLine); 6696 verifyFormat("Constructor()\n" 6697 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6698 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6699 OnePerLine); 6700 OnePerLine.BinPackParameters = false; 6701 verifyFormat( 6702 "Constructor()\n" 6703 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6704 " aaaaaaaaaaa().aaa(),\n" 6705 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6706 OnePerLine); 6707 OnePerLine.ColumnLimit = 60; 6708 verifyFormat("Constructor()\n" 6709 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6710 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6711 OnePerLine); 6712 6713 EXPECT_EQ("Constructor()\n" 6714 " : // Comment forcing unwanted break.\n" 6715 " aaaa(aaaa) {}", 6716 format("Constructor() :\n" 6717 " // Comment forcing unwanted break.\n" 6718 " aaaa(aaaa) {}")); 6719 } 6720 6721 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6722 FormatStyle Style = getLLVMStyleWithColumns(60); 6723 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6724 Style.BinPackParameters = false; 6725 6726 for (int i = 0; i < 4; ++i) { 6727 // Test all combinations of parameters that should not have an effect. 6728 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6729 Style.AllowAllArgumentsOnNextLine = i & 2; 6730 6731 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6732 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6733 verifyFormat("Constructor()\n" 6734 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6735 Style); 6736 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6737 6738 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6739 verifyFormat("Constructor()\n" 6740 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6741 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6742 Style); 6743 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6744 6745 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6746 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6747 verifyFormat("Constructor()\n" 6748 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6749 Style); 6750 6751 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6752 verifyFormat("Constructor()\n" 6753 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6754 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6755 Style); 6756 6757 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6758 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6759 verifyFormat("Constructor() :\n" 6760 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6761 Style); 6762 6763 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6764 verifyFormat("Constructor() :\n" 6765 " aaaaaaaaaaaaaaaaaa(a),\n" 6766 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6767 Style); 6768 } 6769 6770 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6771 // AllowAllConstructorInitializersOnNextLine in all 6772 // BreakConstructorInitializers modes 6773 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6774 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6775 verifyFormat("SomeClassWithALongName::Constructor(\n" 6776 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6777 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6778 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6779 Style); 6780 6781 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6782 verifyFormat("SomeClassWithALongName::Constructor(\n" 6783 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6784 " int bbbbbbbbbbbbb,\n" 6785 " int cccccccccccccccc)\n" 6786 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6787 Style); 6788 6789 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6790 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6791 verifyFormat("SomeClassWithALongName::Constructor(\n" 6792 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6793 " int bbbbbbbbbbbbb)\n" 6794 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6795 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6796 Style); 6797 6798 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6799 6800 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6801 verifyFormat("SomeClassWithALongName::Constructor(\n" 6802 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6803 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6804 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6805 Style); 6806 6807 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6808 verifyFormat("SomeClassWithALongName::Constructor(\n" 6809 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6810 " int bbbbbbbbbbbbb,\n" 6811 " int cccccccccccccccc)\n" 6812 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6813 Style); 6814 6815 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6816 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6817 verifyFormat("SomeClassWithALongName::Constructor(\n" 6818 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6819 " int bbbbbbbbbbbbb)\n" 6820 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6821 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6822 Style); 6823 6824 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6825 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6826 verifyFormat("SomeClassWithALongName::Constructor(\n" 6827 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6828 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6829 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6830 Style); 6831 6832 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6833 verifyFormat("SomeClassWithALongName::Constructor(\n" 6834 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6835 " int bbbbbbbbbbbbb,\n" 6836 " int cccccccccccccccc) :\n" 6837 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6838 Style); 6839 6840 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6841 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6842 verifyFormat("SomeClassWithALongName::Constructor(\n" 6843 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6844 " int bbbbbbbbbbbbb) :\n" 6845 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6846 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6847 Style); 6848 } 6849 6850 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6851 FormatStyle Style = getLLVMStyleWithColumns(60); 6852 Style.BinPackArguments = false; 6853 for (int i = 0; i < 4; ++i) { 6854 // Test all combinations of parameters that should not have an effect. 6855 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6856 Style.PackConstructorInitializers = 6857 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6858 6859 Style.AllowAllArgumentsOnNextLine = true; 6860 verifyFormat("void foo() {\n" 6861 " FunctionCallWithReallyLongName(\n" 6862 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6863 "}", 6864 Style); 6865 Style.AllowAllArgumentsOnNextLine = false; 6866 verifyFormat("void foo() {\n" 6867 " FunctionCallWithReallyLongName(\n" 6868 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6869 " bbbbbbbbbbbb);\n" 6870 "}", 6871 Style); 6872 6873 Style.AllowAllArgumentsOnNextLine = true; 6874 verifyFormat("void foo() {\n" 6875 " auto VariableWithReallyLongName = {\n" 6876 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6877 "}", 6878 Style); 6879 Style.AllowAllArgumentsOnNextLine = false; 6880 verifyFormat("void foo() {\n" 6881 " auto VariableWithReallyLongName = {\n" 6882 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6883 " bbbbbbbbbbbb};\n" 6884 "}", 6885 Style); 6886 } 6887 6888 // This parameter should not affect declarations. 6889 Style.BinPackParameters = false; 6890 Style.AllowAllArgumentsOnNextLine = false; 6891 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6892 verifyFormat("void FunctionCallWithReallyLongName(\n" 6893 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6894 Style); 6895 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6896 verifyFormat("void FunctionCallWithReallyLongName(\n" 6897 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6898 " int bbbbbbbbbbbb);", 6899 Style); 6900 } 6901 6902 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6903 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6904 // and BAS_Align. 6905 FormatStyle Style = getLLVMStyleWithColumns(35); 6906 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6907 "void functionDecl(int A, int B, int C);"; 6908 Style.AllowAllArgumentsOnNextLine = false; 6909 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6910 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6911 " paramC);\n" 6912 "void functionDecl(int A, int B,\n" 6913 " int C);"), 6914 format(Input, Style)); 6915 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6916 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6917 " paramC);\n" 6918 "void functionDecl(int A, int B,\n" 6919 " int C);"), 6920 format(Input, Style)); 6921 // However, BAS_AlwaysBreak should take precedence over 6922 // AllowAllArgumentsOnNextLine. 6923 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6924 EXPECT_EQ(StringRef("functionCall(\n" 6925 " paramA, paramB, paramC);\n" 6926 "void functionDecl(\n" 6927 " int A, int B, int C);"), 6928 format(Input, Style)); 6929 6930 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6931 // first argument. 6932 Style.AllowAllArgumentsOnNextLine = true; 6933 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6934 EXPECT_EQ(StringRef("functionCall(\n" 6935 " paramA, paramB, paramC);\n" 6936 "void functionDecl(\n" 6937 " int A, int B, int C);"), 6938 format(Input, Style)); 6939 // It wouldn't fit on one line with aligned parameters so this setting 6940 // doesn't change anything for BAS_Align. 6941 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6942 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6943 " paramC);\n" 6944 "void functionDecl(int A, int B,\n" 6945 " int C);"), 6946 format(Input, Style)); 6947 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6948 EXPECT_EQ(StringRef("functionCall(\n" 6949 " paramA, paramB, paramC);\n" 6950 "void functionDecl(\n" 6951 " int A, int B, int C);"), 6952 format(Input, Style)); 6953 } 6954 6955 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6956 FormatStyle Style = getLLVMStyle(); 6957 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6958 6959 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6960 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6961 getStyleWithColumns(Style, 45)); 6962 verifyFormat("Constructor() :\n" 6963 " Initializer(FitsOnTheLine) {}", 6964 getStyleWithColumns(Style, 44)); 6965 verifyFormat("Constructor() :\n" 6966 " Initializer(FitsOnTheLine) {}", 6967 getStyleWithColumns(Style, 43)); 6968 6969 verifyFormat("template <typename T>\n" 6970 "Constructor() : Initializer(FitsOnTheLine) {}", 6971 getStyleWithColumns(Style, 50)); 6972 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6973 verifyFormat( 6974 "SomeClass::Constructor() :\n" 6975 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6976 Style); 6977 6978 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6979 verifyFormat( 6980 "SomeClass::Constructor() :\n" 6981 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6982 Style); 6983 6984 verifyFormat( 6985 "SomeClass::Constructor() :\n" 6986 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6987 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6988 Style); 6989 verifyFormat( 6990 "SomeClass::Constructor() :\n" 6991 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6992 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6993 Style); 6994 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6995 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6996 " aaaaaaaaaa(aaaaaa) {}", 6997 Style); 6998 6999 verifyFormat("Constructor() :\n" 7000 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7001 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7002 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7003 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7004 Style); 7005 7006 verifyFormat("Constructor() :\n" 7007 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7008 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7009 Style); 7010 7011 verifyFormat("Constructor(int Parameter = 0) :\n" 7012 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7013 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7014 Style); 7015 verifyFormat("Constructor() :\n" 7016 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7017 "}", 7018 getStyleWithColumns(Style, 60)); 7019 verifyFormat("Constructor() :\n" 7020 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7021 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7022 Style); 7023 7024 // Here a line could be saved by splitting the second initializer onto two 7025 // lines, but that is not desirable. 7026 verifyFormat("Constructor() :\n" 7027 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7028 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7029 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7030 Style); 7031 7032 FormatStyle OnePerLine = Style; 7033 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7034 verifyFormat("SomeClass::Constructor() :\n" 7035 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7036 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7037 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7038 OnePerLine); 7039 verifyFormat("SomeClass::Constructor() :\n" 7040 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7041 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7042 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7043 OnePerLine); 7044 verifyFormat("MyClass::MyClass(int var) :\n" 7045 " some_var_(var), // 4 space indent\n" 7046 " some_other_var_(var + 1) { // lined up\n" 7047 "}", 7048 OnePerLine); 7049 verifyFormat("Constructor() :\n" 7050 " aaaaa(aaaaaa),\n" 7051 " aaaaa(aaaaaa),\n" 7052 " aaaaa(aaaaaa),\n" 7053 " aaaaa(aaaaaa),\n" 7054 " aaaaa(aaaaaa) {}", 7055 OnePerLine); 7056 verifyFormat("Constructor() :\n" 7057 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7058 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7059 OnePerLine); 7060 OnePerLine.BinPackParameters = false; 7061 verifyFormat("Constructor() :\n" 7062 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7063 " aaaaaaaaaaa().aaa(),\n" 7064 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7065 OnePerLine); 7066 OnePerLine.ColumnLimit = 60; 7067 verifyFormat("Constructor() :\n" 7068 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7069 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7070 OnePerLine); 7071 7072 EXPECT_EQ("Constructor() :\n" 7073 " // Comment forcing unwanted break.\n" 7074 " aaaa(aaaa) {}", 7075 format("Constructor() :\n" 7076 " // Comment forcing unwanted break.\n" 7077 " aaaa(aaaa) {}", 7078 Style)); 7079 7080 Style.ColumnLimit = 0; 7081 verifyFormat("SomeClass::Constructor() :\n" 7082 " a(a) {}", 7083 Style); 7084 verifyFormat("SomeClass::Constructor() noexcept :\n" 7085 " a(a) {}", 7086 Style); 7087 verifyFormat("SomeClass::Constructor() :\n" 7088 " a(a), b(b), c(c) {}", 7089 Style); 7090 verifyFormat("SomeClass::Constructor() :\n" 7091 " a(a) {\n" 7092 " foo();\n" 7093 " bar();\n" 7094 "}", 7095 Style); 7096 7097 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7098 verifyFormat("SomeClass::Constructor() :\n" 7099 " a(a), b(b), c(c) {\n" 7100 "}", 7101 Style); 7102 verifyFormat("SomeClass::Constructor() :\n" 7103 " a(a) {\n" 7104 "}", 7105 Style); 7106 7107 Style.ColumnLimit = 80; 7108 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7109 Style.ConstructorInitializerIndentWidth = 2; 7110 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7111 verifyFormat("SomeClass::Constructor() :\n" 7112 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7113 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7114 Style); 7115 7116 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7117 // well 7118 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7119 verifyFormat( 7120 "class SomeClass\n" 7121 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7122 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7123 Style); 7124 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7125 verifyFormat( 7126 "class SomeClass\n" 7127 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7128 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7129 Style); 7130 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7131 verifyFormat( 7132 "class SomeClass :\n" 7133 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7134 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7135 Style); 7136 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7137 verifyFormat( 7138 "class SomeClass\n" 7139 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7140 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7141 Style); 7142 } 7143 7144 #ifndef EXPENSIVE_CHECKS 7145 // Expensive checks enables libstdc++ checking which includes validating the 7146 // state of ranges used in std::priority_queue - this blows out the 7147 // runtime/scalability of the function and makes this test unacceptably slow. 7148 TEST_F(FormatTest, MemoizationTests) { 7149 // This breaks if the memoization lookup does not take \c Indent and 7150 // \c LastSpace into account. 7151 verifyFormat( 7152 "extern CFRunLoopTimerRef\n" 7153 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7154 " CFTimeInterval interval, CFOptionFlags flags,\n" 7155 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7156 " CFRunLoopTimerContext *context) {}"); 7157 7158 // Deep nesting somewhat works around our memoization. 7159 verifyFormat( 7160 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7161 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7162 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7163 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7164 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7165 getLLVMStyleWithColumns(65)); 7166 verifyFormat( 7167 "aaaaa(\n" 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))))))))))));", 7192 getLLVMStyleWithColumns(65)); 7193 verifyFormat( 7194 "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" 7195 " 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)", 7212 getLLVMStyleWithColumns(65)); 7213 7214 // This test takes VERY long when memoization is broken. 7215 FormatStyle OnePerLine = getLLVMStyle(); 7216 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7217 OnePerLine.BinPackParameters = false; 7218 std::string input = "Constructor()\n" 7219 " : aaaa(a,\n"; 7220 for (unsigned i = 0, e = 80; i != e; ++i) { 7221 input += " a,\n"; 7222 } 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;", AlignLeft); 9923 verifyFormat("template <typename T> void operator=(T) & = default;", AlignLeft); 9924 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9925 verifyFormat("template <typename T> void operator=(T) && = delete;", AlignLeft); 9926 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9927 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9928 9929 FormatStyle AlignMiddle = getLLVMStyle(); 9930 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9931 verifyFormat("void A::b() && {}", AlignMiddle); 9932 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9933 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9934 AlignMiddle); 9935 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9936 AlignMiddle); 9937 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9938 AlignMiddle); 9939 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9940 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9941 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9942 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9943 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9944 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9945 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9946 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9947 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9948 AlignMiddle); 9949 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 9950 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 9951 verifyFormat("template <typename T> void operator=(T) & noexcept;", AlignMiddle); 9952 verifyFormat("template <typename T> void operator=(T) & = default;", AlignMiddle); 9953 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 9954 verifyFormat("template <typename T> void operator=(T) && = delete;", AlignMiddle); 9955 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 9956 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 9957 9958 FormatStyle Spaces = getLLVMStyle(); 9959 Spaces.SpacesInCStyleCastParentheses = true; 9960 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9961 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9962 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9963 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9964 9965 Spaces.SpacesInCStyleCastParentheses = false; 9966 Spaces.SpacesInParentheses = true; 9967 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9968 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9969 Spaces); 9970 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9971 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9972 9973 FormatStyle BreakTemplate = getLLVMStyle(); 9974 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9975 9976 verifyFormat("struct f {\n" 9977 " template <class T>\n" 9978 " int &foo(const std::string &str) &noexcept {}\n" 9979 "};", 9980 BreakTemplate); 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) const &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 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10003 "};", 10004 BreakTemplate); 10005 10006 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10007 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10008 FormatStyle::BTDS_Yes; 10009 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10010 10011 verifyFormat("struct f {\n" 10012 " template <class T>\n" 10013 " int& foo(const std::string& str) & noexcept {}\n" 10014 "};", 10015 AlignLeftBreakTemplate); 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) const& 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 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10038 "};", 10039 AlignLeftBreakTemplate); 10040 10041 // The `&` in `Type&` should not be confused with a trailing `&` of 10042 // DEPRECATED(reason) member function. 10043 verifyFormat("struct f {\n" 10044 " template <class T>\n" 10045 " DEPRECATED(reason)\n" 10046 " Type &foo(arguments) {}\n" 10047 "};", 10048 BreakTemplate); 10049 10050 verifyFormat("struct f {\n" 10051 " template <class T>\n" 10052 " DEPRECATED(reason)\n" 10053 " Type& foo(arguments) {}\n" 10054 "};", 10055 AlignLeftBreakTemplate); 10056 10057 verifyFormat("void (*foopt)(int) = &func;"); 10058 10059 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10060 DerivePointerAlignment.DerivePointerAlignment = true; 10061 // There's always a space between the function and its trailing qualifiers. 10062 // This isn't evidence for PAS_Right (or for PAS_Left). 10063 std::string Prefix = "void a() &;\n" 10064 "void b() &;\n"; 10065 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10066 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10067 // Same if the function is an overloaded operator, and with &&. 10068 Prefix = "void operator()() &&;\n" 10069 "void operator()() &&;\n"; 10070 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10071 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10072 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10073 Prefix = "void a() const &;\n" 10074 "void b() const &;\n"; 10075 EXPECT_EQ(Prefix + "int *x;", 10076 format(Prefix + "int* x;", DerivePointerAlignment)); 10077 } 10078 10079 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10080 verifyFormat("void f() {\n" 10081 " A *a = new A;\n" 10082 " A *a = new (placement) A;\n" 10083 " delete a;\n" 10084 " delete (A *)a;\n" 10085 "}"); 10086 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10087 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10088 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10089 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10090 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10091 verifyFormat("delete[] h->p;"); 10092 verifyFormat("delete[] (void *)p;"); 10093 10094 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10095 verifyFormat("void operator new(void *foo) ATTRIB;"); 10096 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10097 verifyFormat("void operator delete(void *ptr) noexcept;"); 10098 10099 EXPECT_EQ("void new(link p);\n" 10100 "void delete(link p);\n", 10101 format("void new (link p);\n" 10102 "void delete (link p);\n")); 10103 } 10104 10105 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10106 verifyFormat("int *f(int *a) {}"); 10107 verifyFormat("int main(int argc, char **argv) {}"); 10108 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10109 verifyIndependentOfContext("f(a, *a);"); 10110 verifyFormat("void g() { f(*a); }"); 10111 verifyIndependentOfContext("int a = b * 10;"); 10112 verifyIndependentOfContext("int a = 10 * b;"); 10113 verifyIndependentOfContext("int a = b * c;"); 10114 verifyIndependentOfContext("int a += b * c;"); 10115 verifyIndependentOfContext("int a -= b * c;"); 10116 verifyIndependentOfContext("int a *= b * c;"); 10117 verifyIndependentOfContext("int a /= b * c;"); 10118 verifyIndependentOfContext("int a = *b;"); 10119 verifyIndependentOfContext("int a = *b * c;"); 10120 verifyIndependentOfContext("int a = b * *c;"); 10121 verifyIndependentOfContext("int a = b * (10);"); 10122 verifyIndependentOfContext("S << b * (10);"); 10123 verifyIndependentOfContext("return 10 * b;"); 10124 verifyIndependentOfContext("return *b * *c;"); 10125 verifyIndependentOfContext("return a & ~b;"); 10126 verifyIndependentOfContext("f(b ? *c : *d);"); 10127 verifyIndependentOfContext("int a = b ? *c : *d;"); 10128 verifyIndependentOfContext("*b = a;"); 10129 verifyIndependentOfContext("a * ~b;"); 10130 verifyIndependentOfContext("a * !b;"); 10131 verifyIndependentOfContext("a * +b;"); 10132 verifyIndependentOfContext("a * -b;"); 10133 verifyIndependentOfContext("a * ++b;"); 10134 verifyIndependentOfContext("a * --b;"); 10135 verifyIndependentOfContext("a[4] * b;"); 10136 verifyIndependentOfContext("a[a * a] = 1;"); 10137 verifyIndependentOfContext("f() * b;"); 10138 verifyIndependentOfContext("a * [self dostuff];"); 10139 verifyIndependentOfContext("int x = a * (a + b);"); 10140 verifyIndependentOfContext("(a *)(a + b);"); 10141 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10142 verifyIndependentOfContext("int *pa = (int *)&a;"); 10143 verifyIndependentOfContext("return sizeof(int **);"); 10144 verifyIndependentOfContext("return sizeof(int ******);"); 10145 verifyIndependentOfContext("return (int **&)a;"); 10146 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10147 verifyFormat("void f(Type (*parameter)[10]) {}"); 10148 verifyFormat("void f(Type (¶meter)[10]) {}"); 10149 verifyGoogleFormat("return sizeof(int**);"); 10150 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10151 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10152 verifyFormat("auto a = [](int **&, int ***) {};"); 10153 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10154 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10155 verifyFormat("[](const decltype(*a) &value) {}"); 10156 verifyFormat("[](const typeof(*a) &value) {}"); 10157 verifyFormat("[](const _Atomic(a *) &value) {}"); 10158 verifyFormat("[](const __underlying_type(a) &value) {}"); 10159 verifyFormat("decltype(a * b) F();"); 10160 verifyFormat("typeof(a * b) F();"); 10161 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10162 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10163 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10164 verifyIndependentOfContext("int i{a * b};"); 10165 verifyIndependentOfContext("aaa && aaa->f();"); 10166 verifyIndependentOfContext("int x = ~*p;"); 10167 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10168 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10169 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10170 verifyFormat("void f() { f(a, c * d); }"); 10171 verifyFormat("void f() { f(new a(), c * d); }"); 10172 verifyFormat("void f(const MyOverride &override);"); 10173 verifyFormat("void f(const MyFinal &final);"); 10174 verifyIndependentOfContext("bool a = f() && override.f();"); 10175 verifyIndependentOfContext("bool a = f() && final.f();"); 10176 10177 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10178 10179 verifyIndependentOfContext("A<int *> a;"); 10180 verifyIndependentOfContext("A<int **> a;"); 10181 verifyIndependentOfContext("A<int *, int *> a;"); 10182 verifyIndependentOfContext("A<int *[]> a;"); 10183 verifyIndependentOfContext( 10184 "const char *const p = reinterpret_cast<const char *const>(q);"); 10185 verifyIndependentOfContext("A<int **, int **> a;"); 10186 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10187 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10188 verifyFormat("for (; a && b;) {\n}"); 10189 verifyFormat("bool foo = true && [] { return false; }();"); 10190 10191 verifyFormat( 10192 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10193 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10194 10195 verifyGoogleFormat("int const* a = &b;"); 10196 verifyGoogleFormat("**outparam = 1;"); 10197 verifyGoogleFormat("*outparam = a * b;"); 10198 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10199 verifyGoogleFormat("A<int*> a;"); 10200 verifyGoogleFormat("A<int**> a;"); 10201 verifyGoogleFormat("A<int*, int*> a;"); 10202 verifyGoogleFormat("A<int**, int**> a;"); 10203 verifyGoogleFormat("f(b ? *c : *d);"); 10204 verifyGoogleFormat("int a = b ? *c : *d;"); 10205 verifyGoogleFormat("Type* t = **x;"); 10206 verifyGoogleFormat("Type* t = *++*x;"); 10207 verifyGoogleFormat("*++*x;"); 10208 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10209 verifyGoogleFormat("Type* t = x++ * y;"); 10210 verifyGoogleFormat( 10211 "const char* const p = reinterpret_cast<const char* const>(q);"); 10212 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10213 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10214 verifyGoogleFormat("template <typename T>\n" 10215 "void f(int i = 0, SomeType** temps = NULL);"); 10216 10217 FormatStyle Left = getLLVMStyle(); 10218 Left.PointerAlignment = FormatStyle::PAS_Left; 10219 verifyFormat("x = *a(x) = *a(y);", Left); 10220 verifyFormat("for (;; *a = b) {\n}", Left); 10221 verifyFormat("return *this += 1;", Left); 10222 verifyFormat("throw *x;", Left); 10223 verifyFormat("delete *x;", Left); 10224 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10225 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10226 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10227 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10228 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10229 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10230 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10231 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10232 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10233 10234 verifyIndependentOfContext("a = *(x + y);"); 10235 verifyIndependentOfContext("a = &(x + y);"); 10236 verifyIndependentOfContext("*(x + y).call();"); 10237 verifyIndependentOfContext("&(x + y)->call();"); 10238 verifyFormat("void f() { &(*I).first; }"); 10239 10240 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10241 verifyFormat("f(* /* confusing comment */ foo);"); 10242 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10243 verifyFormat("void foo(int * // this is the first paramters\n" 10244 " ,\n" 10245 " int second);"); 10246 verifyFormat("double term = a * // first\n" 10247 " b;"); 10248 verifyFormat( 10249 "int *MyValues = {\n" 10250 " *A, // Operator detection might be confused by the '{'\n" 10251 " *BB // Operator detection might be confused by previous comment\n" 10252 "};"); 10253 10254 verifyIndependentOfContext("if (int *a = &b)"); 10255 verifyIndependentOfContext("if (int &a = *b)"); 10256 verifyIndependentOfContext("if (a & b[i])"); 10257 verifyIndependentOfContext("if constexpr (a & b[i])"); 10258 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10259 verifyIndependentOfContext("if (a * (b * c))"); 10260 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10261 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10262 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10263 verifyIndependentOfContext("if (*b[i])"); 10264 verifyIndependentOfContext("if (int *a = (&b))"); 10265 verifyIndependentOfContext("while (int *a = &b)"); 10266 verifyIndependentOfContext("while (a * (b * c))"); 10267 verifyIndependentOfContext("size = sizeof *a;"); 10268 verifyIndependentOfContext("if (a && (b = c))"); 10269 verifyFormat("void f() {\n" 10270 " for (const int &v : Values) {\n" 10271 " }\n" 10272 "}"); 10273 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10274 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10275 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10276 10277 verifyFormat("#define A (!a * b)"); 10278 verifyFormat("#define MACRO \\\n" 10279 " int *i = a * b; \\\n" 10280 " void f(a *b);", 10281 getLLVMStyleWithColumns(19)); 10282 10283 verifyIndependentOfContext("A = new SomeType *[Length];"); 10284 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10285 verifyIndependentOfContext("T **t = new T *;"); 10286 verifyIndependentOfContext("T **t = new T *();"); 10287 verifyGoogleFormat("A = new SomeType*[Length]();"); 10288 verifyGoogleFormat("A = new SomeType*[Length];"); 10289 verifyGoogleFormat("T** t = new T*;"); 10290 verifyGoogleFormat("T** t = new T*();"); 10291 10292 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10293 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10294 verifyFormat("template <bool a, bool b> " 10295 "typename t::if<x && y>::type f() {}"); 10296 verifyFormat("template <int *y> f() {}"); 10297 verifyFormat("vector<int *> v;"); 10298 verifyFormat("vector<int *const> v;"); 10299 verifyFormat("vector<int *const **const *> v;"); 10300 verifyFormat("vector<int *volatile> v;"); 10301 verifyFormat("vector<a *_Nonnull> v;"); 10302 verifyFormat("vector<a *_Nullable> v;"); 10303 verifyFormat("vector<a *_Null_unspecified> v;"); 10304 verifyFormat("vector<a *__ptr32> v;"); 10305 verifyFormat("vector<a *__ptr64> v;"); 10306 verifyFormat("vector<a *__capability> v;"); 10307 FormatStyle TypeMacros = getLLVMStyle(); 10308 TypeMacros.TypenameMacros = {"LIST"}; 10309 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10310 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10311 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10312 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10313 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10314 10315 FormatStyle CustomQualifier = getLLVMStyle(); 10316 // Add identifiers that should not be parsed as a qualifier by default. 10317 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10318 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10319 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10320 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10321 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10322 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10323 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10324 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10325 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10326 verifyFormat("vector<a * _NotAQualifier> v;"); 10327 verifyFormat("vector<a * __not_a_qualifier> v;"); 10328 verifyFormat("vector<a * b> v;"); 10329 verifyFormat("foo<b && false>();"); 10330 verifyFormat("foo<b & 1>();"); 10331 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10332 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10333 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10334 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10335 verifyFormat( 10336 "template <class T, class = typename std::enable_if<\n" 10337 " std::is_integral<T>::value &&\n" 10338 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10339 "void F();", 10340 getLLVMStyleWithColumns(70)); 10341 verifyFormat("template <class T,\n" 10342 " class = typename std::enable_if<\n" 10343 " std::is_integral<T>::value &&\n" 10344 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10345 " class U>\n" 10346 "void F();", 10347 getLLVMStyleWithColumns(70)); 10348 verifyFormat( 10349 "template <class T,\n" 10350 " class = typename ::std::enable_if<\n" 10351 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10352 "void F();", 10353 getGoogleStyleWithColumns(68)); 10354 10355 verifyIndependentOfContext("MACRO(int *i);"); 10356 verifyIndependentOfContext("MACRO(auto *a);"); 10357 verifyIndependentOfContext("MACRO(const A *a);"); 10358 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10359 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10360 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10361 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10362 verifyIndependentOfContext("MACRO(A *const a);"); 10363 verifyIndependentOfContext("MACRO(A *restrict a);"); 10364 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10365 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10366 verifyIndependentOfContext("MACRO(A *volatile a);"); 10367 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10368 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10369 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10370 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10371 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10372 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10373 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10374 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10375 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10376 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10377 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10378 verifyIndependentOfContext("MACRO(A *__capability);"); 10379 verifyIndependentOfContext("MACRO(A &__capability);"); 10380 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10381 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10382 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10383 // a type declaration: 10384 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10385 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10386 // Also check that TypenameMacros prevents parsing it as multiplication: 10387 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10388 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10389 10390 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10391 verifyFormat("void f() { f(float{1}, a * a); }"); 10392 verifyFormat("void f() { f(float(1), a * a); }"); 10393 10394 verifyFormat("f((void (*)(int))g);"); 10395 verifyFormat("f((void (&)(int))g);"); 10396 verifyFormat("f((void (^)(int))g);"); 10397 10398 // FIXME: Is there a way to make this work? 10399 // verifyIndependentOfContext("MACRO(A *a);"); 10400 verifyFormat("MACRO(A &B);"); 10401 verifyFormat("MACRO(A *B);"); 10402 verifyFormat("void f() { MACRO(A * B); }"); 10403 verifyFormat("void f() { MACRO(A & B); }"); 10404 10405 // This lambda was mis-formatted after D88956 (treating it as a binop): 10406 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10407 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10408 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10409 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10410 10411 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10412 verifyFormat("return options != nullptr && operator==(*options);"); 10413 10414 EXPECT_EQ("#define OP(x) \\\n" 10415 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10416 " return s << a.DebugString(); \\\n" 10417 " }", 10418 format("#define OP(x) \\\n" 10419 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10420 " return s << a.DebugString(); \\\n" 10421 " }", 10422 getLLVMStyleWithColumns(50))); 10423 10424 // FIXME: We cannot handle this case yet; we might be able to figure out that 10425 // foo<x> d > v; doesn't make sense. 10426 verifyFormat("foo<a<b && c> d> v;"); 10427 10428 FormatStyle PointerMiddle = getLLVMStyle(); 10429 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10430 verifyFormat("delete *x;", PointerMiddle); 10431 verifyFormat("int * x;", PointerMiddle); 10432 verifyFormat("int *[] x;", PointerMiddle); 10433 verifyFormat("template <int * y> f() {}", PointerMiddle); 10434 verifyFormat("int * f(int * a) {}", PointerMiddle); 10435 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10436 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10437 verifyFormat("A<int *> a;", PointerMiddle); 10438 verifyFormat("A<int **> a;", PointerMiddle); 10439 verifyFormat("A<int *, int *> a;", PointerMiddle); 10440 verifyFormat("A<int *[]> a;", PointerMiddle); 10441 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10442 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10443 verifyFormat("T ** t = new T *;", PointerMiddle); 10444 10445 // Member function reference qualifiers aren't binary operators. 10446 verifyFormat("string // break\n" 10447 "operator()() & {}"); 10448 verifyFormat("string // break\n" 10449 "operator()() && {}"); 10450 verifyGoogleFormat("template <typename T>\n" 10451 "auto x() & -> int {}"); 10452 10453 // Should be binary operators when used as an argument expression (overloaded 10454 // operator invoked as a member function). 10455 verifyFormat("void f() { a.operator()(a * a); }"); 10456 verifyFormat("void f() { a->operator()(a & a); }"); 10457 verifyFormat("void f() { a.operator()(*a & *a); }"); 10458 verifyFormat("void f() { a->operator()(*a * *a); }"); 10459 10460 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10461 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10462 } 10463 10464 TEST_F(FormatTest, UnderstandsAttributes) { 10465 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10466 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10467 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10468 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10469 FormatStyle AfterType = getLLVMStyle(); 10470 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10471 verifyFormat("__attribute__((nodebug)) void\n" 10472 "foo() {}\n", 10473 AfterType); 10474 verifyFormat("__unused void\n" 10475 "foo() {}", 10476 AfterType); 10477 10478 FormatStyle CustomAttrs = getLLVMStyle(); 10479 CustomAttrs.AttributeMacros.push_back("__unused"); 10480 CustomAttrs.AttributeMacros.push_back("__attr1"); 10481 CustomAttrs.AttributeMacros.push_back("__attr2"); 10482 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10483 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10484 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10485 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10486 // Check that it is parsed as a multiplication without AttributeMacros and 10487 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10488 verifyFormat("vector<SomeType * __attr1> v;"); 10489 verifyFormat("vector<SomeType __attr1 *> v;"); 10490 verifyFormat("vector<SomeType __attr1 *const> v;"); 10491 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10492 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10493 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10494 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10495 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10496 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10497 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10498 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10499 10500 // Check that these are not parsed as function declarations: 10501 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10502 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10503 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10504 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10505 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10506 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10507 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10508 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10509 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10510 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10511 } 10512 10513 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10514 // Check that qualifiers on pointers don't break parsing of casts. 10515 verifyFormat("x = (foo *const)*v;"); 10516 verifyFormat("x = (foo *volatile)*v;"); 10517 verifyFormat("x = (foo *restrict)*v;"); 10518 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10519 verifyFormat("x = (foo *_Nonnull)*v;"); 10520 verifyFormat("x = (foo *_Nullable)*v;"); 10521 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10522 verifyFormat("x = (foo *_Nonnull)*v;"); 10523 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10524 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10525 verifyFormat("x = (foo *__ptr32)*v;"); 10526 verifyFormat("x = (foo *__ptr64)*v;"); 10527 verifyFormat("x = (foo *__capability)*v;"); 10528 10529 // Check that we handle multiple trailing qualifiers and skip them all to 10530 // determine that the expression is a cast to a pointer type. 10531 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10532 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10533 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10534 StringRef AllQualifiers = 10535 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10536 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10537 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10538 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10539 10540 // Also check that address-of is not parsed as a binary bitwise-and: 10541 verifyFormat("x = (foo *const)&v;"); 10542 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10543 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10544 10545 // Check custom qualifiers: 10546 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10547 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10548 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10549 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10550 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10551 CustomQualifier); 10552 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10553 CustomQualifier); 10554 10555 // Check that unknown identifiers result in binary operator parsing: 10556 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10557 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10558 } 10559 10560 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10561 verifyFormat("SomeType s [[unused]] (InitValue);"); 10562 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10563 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10564 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10565 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10566 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10567 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10568 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10569 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10570 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10571 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10572 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10573 10574 // Make sure we do not mistake attributes for array subscripts. 10575 verifyFormat("int a() {}\n" 10576 "[[unused]] int b() {}\n"); 10577 verifyFormat("NSArray *arr;\n" 10578 "arr[[Foo() bar]];"); 10579 10580 // On the other hand, we still need to correctly find array subscripts. 10581 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10582 10583 // Make sure that we do not mistake Objective-C method inside array literals 10584 // as attributes, even if those method names are also keywords. 10585 verifyFormat("@[ [foo bar] ];"); 10586 verifyFormat("@[ [NSArray class] ];"); 10587 verifyFormat("@[ [foo enum] ];"); 10588 10589 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10590 10591 // Make sure we do not parse attributes as lambda introducers. 10592 FormatStyle MultiLineFunctions = getLLVMStyle(); 10593 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10594 verifyFormat("[[unused]] int b() {\n" 10595 " return 42;\n" 10596 "}\n", 10597 MultiLineFunctions); 10598 } 10599 10600 TEST_F(FormatTest, AttributeClass) { 10601 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10602 verifyFormat("class S {\n" 10603 " S(S&&) = default;\n" 10604 "};", 10605 Style); 10606 verifyFormat("class [[nodiscard]] S {\n" 10607 " S(S&&) = default;\n" 10608 "};", 10609 Style); 10610 verifyFormat("class __attribute((maybeunused)) S {\n" 10611 " S(S&&) = default;\n" 10612 "};", 10613 Style); 10614 verifyFormat("struct S {\n" 10615 " S(S&&) = default;\n" 10616 "};", 10617 Style); 10618 verifyFormat("struct [[nodiscard]] S {\n" 10619 " S(S&&) = default;\n" 10620 "};", 10621 Style); 10622 } 10623 10624 TEST_F(FormatTest, AttributesAfterMacro) { 10625 FormatStyle Style = getLLVMStyle(); 10626 verifyFormat("MACRO;\n" 10627 "__attribute__((maybe_unused)) int foo() {\n" 10628 " //...\n" 10629 "}"); 10630 10631 verifyFormat("MACRO;\n" 10632 "[[nodiscard]] int foo() {\n" 10633 " //...\n" 10634 "}"); 10635 10636 EXPECT_EQ("MACRO\n\n" 10637 "__attribute__((maybe_unused)) int foo() {\n" 10638 " //...\n" 10639 "}", 10640 format("MACRO\n\n" 10641 "__attribute__((maybe_unused)) int foo() {\n" 10642 " //...\n" 10643 "}")); 10644 10645 EXPECT_EQ("MACRO\n\n" 10646 "[[nodiscard]] int foo() {\n" 10647 " //...\n" 10648 "}", 10649 format("MACRO\n\n" 10650 "[[nodiscard]] int foo() {\n" 10651 " //...\n" 10652 "}")); 10653 } 10654 10655 TEST_F(FormatTest, AttributePenaltyBreaking) { 10656 FormatStyle Style = getLLVMStyle(); 10657 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10658 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10659 Style); 10660 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10661 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10662 Style); 10663 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10664 "shared_ptr<ALongTypeName> &C d) {\n}", 10665 Style); 10666 } 10667 10668 TEST_F(FormatTest, UnderstandsEllipsis) { 10669 FormatStyle Style = getLLVMStyle(); 10670 verifyFormat("int printf(const char *fmt, ...);"); 10671 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10672 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10673 10674 verifyFormat("template <int *...PP> a;", Style); 10675 10676 Style.PointerAlignment = FormatStyle::PAS_Left; 10677 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10678 10679 verifyFormat("template <int*... PP> a;", Style); 10680 10681 Style.PointerAlignment = FormatStyle::PAS_Middle; 10682 verifyFormat("template <int *... PP> a;", Style); 10683 } 10684 10685 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10686 EXPECT_EQ("int *a;\n" 10687 "int *a;\n" 10688 "int *a;", 10689 format("int *a;\n" 10690 "int* a;\n" 10691 "int *a;", 10692 getGoogleStyle())); 10693 EXPECT_EQ("int* a;\n" 10694 "int* a;\n" 10695 "int* a;", 10696 format("int* a;\n" 10697 "int* a;\n" 10698 "int *a;", 10699 getGoogleStyle())); 10700 EXPECT_EQ("int *a;\n" 10701 "int *a;\n" 10702 "int *a;", 10703 format("int *a;\n" 10704 "int * a;\n" 10705 "int * a;", 10706 getGoogleStyle())); 10707 EXPECT_EQ("auto x = [] {\n" 10708 " int *a;\n" 10709 " int *a;\n" 10710 " int *a;\n" 10711 "};", 10712 format("auto x=[]{int *a;\n" 10713 "int * a;\n" 10714 "int * a;};", 10715 getGoogleStyle())); 10716 } 10717 10718 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10719 verifyFormat("int f(int &&a) {}"); 10720 verifyFormat("int f(int a, char &&b) {}"); 10721 verifyFormat("void f() { int &&a = b; }"); 10722 verifyGoogleFormat("int f(int a, char&& b) {}"); 10723 verifyGoogleFormat("void f() { int&& a = b; }"); 10724 10725 verifyIndependentOfContext("A<int &&> a;"); 10726 verifyIndependentOfContext("A<int &&, int &&> a;"); 10727 verifyGoogleFormat("A<int&&> a;"); 10728 verifyGoogleFormat("A<int&&, int&&> a;"); 10729 10730 // Not rvalue references: 10731 verifyFormat("template <bool B, bool C> class A {\n" 10732 " static_assert(B && C, \"Something is wrong\");\n" 10733 "};"); 10734 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10735 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10736 verifyFormat("#define A(a, b) (a && b)"); 10737 } 10738 10739 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10740 verifyFormat("void f() {\n" 10741 " x[aaaaaaaaa -\n" 10742 " b] = 23;\n" 10743 "}", 10744 getLLVMStyleWithColumns(15)); 10745 } 10746 10747 TEST_F(FormatTest, FormatsCasts) { 10748 verifyFormat("Type *A = static_cast<Type *>(P);"); 10749 verifyFormat("static_cast<Type *>(P);"); 10750 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10751 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10752 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10753 // Check that static_cast<...>(...) does not require the next token to be on 10754 // the same line. 10755 verifyFormat("some_loooong_output << something_something__ << " 10756 "static_cast<const void *>(R)\n" 10757 " << something;"); 10758 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10759 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10760 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10761 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10762 verifyFormat("Type *A = (Type *)P;"); 10763 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10764 verifyFormat("int a = (int)(2.0f);"); 10765 verifyFormat("int a = (int)2.0f;"); 10766 verifyFormat("x[(int32)y];"); 10767 verifyFormat("x = (int32)y;"); 10768 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10769 verifyFormat("int a = (int)*b;"); 10770 verifyFormat("int a = (int)2.0f;"); 10771 verifyFormat("int a = (int)~0;"); 10772 verifyFormat("int a = (int)++a;"); 10773 verifyFormat("int a = (int)sizeof(int);"); 10774 verifyFormat("int a = (int)+2;"); 10775 verifyFormat("my_int a = (my_int)2.0f;"); 10776 verifyFormat("my_int a = (my_int)sizeof(int);"); 10777 verifyFormat("return (my_int)aaa;"); 10778 verifyFormat("#define x ((int)-1)"); 10779 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10780 verifyFormat("#define p(q) ((int *)&q)"); 10781 verifyFormat("fn(a)(b) + 1;"); 10782 10783 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10784 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10785 verifyFormat("my_int a = (my_int)~0;"); 10786 verifyFormat("my_int a = (my_int)++a;"); 10787 verifyFormat("my_int a = (my_int)-2;"); 10788 verifyFormat("my_int a = (my_int)1;"); 10789 verifyFormat("my_int a = (my_int *)1;"); 10790 verifyFormat("my_int a = (const my_int)-1;"); 10791 verifyFormat("my_int a = (const my_int *)-1;"); 10792 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10793 verifyFormat("my_int a = (ns::my_int)-2;"); 10794 verifyFormat("case (my_int)ONE:"); 10795 verifyFormat("auto x = (X)this;"); 10796 // Casts in Obj-C style calls used to not be recognized as such. 10797 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10798 10799 // FIXME: single value wrapped with paren will be treated as cast. 10800 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10801 10802 verifyFormat("{ (void)F; }"); 10803 10804 // Don't break after a cast's 10805 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10806 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10807 " bbbbbbbbbbbbbbbbbbbbbb);"); 10808 10809 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10810 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10811 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10812 verifyFormat("bool *y = (bool *)(void *)(x);"); 10813 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10814 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10815 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10816 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10817 10818 // These are not casts. 10819 verifyFormat("void f(int *) {}"); 10820 verifyFormat("f(foo)->b;"); 10821 verifyFormat("f(foo).b;"); 10822 verifyFormat("f(foo)(b);"); 10823 verifyFormat("f(foo)[b];"); 10824 verifyFormat("[](foo) { return 4; }(bar);"); 10825 verifyFormat("(*funptr)(foo)[4];"); 10826 verifyFormat("funptrs[4](foo)[4];"); 10827 verifyFormat("void f(int *);"); 10828 verifyFormat("void f(int *) = 0;"); 10829 verifyFormat("void f(SmallVector<int>) {}"); 10830 verifyFormat("void f(SmallVector<int>);"); 10831 verifyFormat("void f(SmallVector<int>) = 0;"); 10832 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10833 verifyFormat("int a = sizeof(int) * b;"); 10834 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10835 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10836 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10837 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10838 10839 // These are not casts, but at some point were confused with casts. 10840 verifyFormat("virtual void foo(int *) override;"); 10841 verifyFormat("virtual void foo(char &) const;"); 10842 verifyFormat("virtual void foo(int *a, char *) const;"); 10843 verifyFormat("int a = sizeof(int *) + b;"); 10844 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10845 verifyFormat("bool b = f(g<int>) && c;"); 10846 verifyFormat("typedef void (*f)(int i) func;"); 10847 verifyFormat("void operator++(int) noexcept;"); 10848 verifyFormat("void operator++(int &) noexcept;"); 10849 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10850 "&) noexcept;"); 10851 verifyFormat( 10852 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10853 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10854 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10855 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10856 verifyFormat("void operator delete(foo &) noexcept;"); 10857 verifyFormat("void operator delete(foo) noexcept;"); 10858 verifyFormat("void operator delete(int) noexcept;"); 10859 verifyFormat("void operator delete(int &) noexcept;"); 10860 verifyFormat("void operator delete(int &) volatile noexcept;"); 10861 verifyFormat("void operator delete(int &) const"); 10862 verifyFormat("void operator delete(int &) = default"); 10863 verifyFormat("void operator delete(int &) = delete"); 10864 verifyFormat("void operator delete(int &) [[noreturn]]"); 10865 verifyFormat("void operator delete(int &) throw();"); 10866 verifyFormat("void operator delete(int &) throw(int);"); 10867 verifyFormat("auto operator delete(int &) -> int;"); 10868 verifyFormat("auto operator delete(int &) override"); 10869 verifyFormat("auto operator delete(int &) final"); 10870 10871 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10872 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10873 // FIXME: The indentation here is not ideal. 10874 verifyFormat( 10875 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10876 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10877 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10878 } 10879 10880 TEST_F(FormatTest, FormatsFunctionTypes) { 10881 verifyFormat("A<bool()> a;"); 10882 verifyFormat("A<SomeType()> a;"); 10883 verifyFormat("A<void (*)(int, std::string)> a;"); 10884 verifyFormat("A<void *(int)>;"); 10885 verifyFormat("void *(*a)(int *, SomeType *);"); 10886 verifyFormat("int (*func)(void *);"); 10887 verifyFormat("void f() { int (*func)(void *); }"); 10888 verifyFormat("template <class CallbackClass>\n" 10889 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10890 10891 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10892 verifyGoogleFormat("void* (*a)(int);"); 10893 verifyGoogleFormat( 10894 "template <class CallbackClass>\n" 10895 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10896 10897 // Other constructs can look somewhat like function types: 10898 verifyFormat("A<sizeof(*x)> a;"); 10899 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10900 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10901 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10902 verifyFormat("int x = f(&h)();"); 10903 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10904 verifyFormat("std::function<\n" 10905 " LooooooooooongTemplatedType<\n" 10906 " SomeType>*(\n" 10907 " LooooooooooooooooongType type)>\n" 10908 " function;", 10909 getGoogleStyleWithColumns(40)); 10910 } 10911 10912 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10913 verifyFormat("A (*foo_)[6];"); 10914 verifyFormat("vector<int> (*foo_)[6];"); 10915 } 10916 10917 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10918 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10919 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10920 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10921 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10922 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10923 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10924 10925 // Different ways of ()-initializiation. 10926 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10927 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10928 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10929 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10930 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10931 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10932 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10933 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10934 10935 // Lambdas should not confuse the variable declaration heuristic. 10936 verifyFormat("LooooooooooooooooongType\n" 10937 " variable(nullptr, [](A *a) {});", 10938 getLLVMStyleWithColumns(40)); 10939 } 10940 10941 TEST_F(FormatTest, BreaksLongDeclarations) { 10942 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10943 " AnotherNameForTheLongType;"); 10944 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10945 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10946 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10947 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10948 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10949 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10950 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10951 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10952 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10953 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10954 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10955 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10956 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10957 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10958 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10959 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10960 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10961 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10962 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10963 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10964 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10965 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10966 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10967 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10968 FormatStyle Indented = getLLVMStyle(); 10969 Indented.IndentWrappedFunctionNames = true; 10970 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10971 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10972 Indented); 10973 verifyFormat( 10974 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10975 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10976 Indented); 10977 verifyFormat( 10978 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10979 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10980 Indented); 10981 verifyFormat( 10982 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10983 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10984 Indented); 10985 10986 // FIXME: Without the comment, this breaks after "(". 10987 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10988 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10989 getGoogleStyle()); 10990 10991 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10992 " int LoooooooooooooooooooongParam2) {}"); 10993 verifyFormat( 10994 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10995 " SourceLocation L, IdentifierIn *II,\n" 10996 " Type *T) {}"); 10997 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10998 "ReallyReaaallyLongFunctionName(\n" 10999 " const std::string &SomeParameter,\n" 11000 " const SomeType<string, SomeOtherTemplateParameter>\n" 11001 " &ReallyReallyLongParameterName,\n" 11002 " const SomeType<string, SomeOtherTemplateParameter>\n" 11003 " &AnotherLongParameterName) {}"); 11004 verifyFormat("template <typename A>\n" 11005 "SomeLoooooooooooooooooooooongType<\n" 11006 " typename some_namespace::SomeOtherType<A>::Type>\n" 11007 "Function() {}"); 11008 11009 verifyGoogleFormat( 11010 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11011 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11012 verifyGoogleFormat( 11013 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11014 " SourceLocation L) {}"); 11015 verifyGoogleFormat( 11016 "some_namespace::LongReturnType\n" 11017 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11018 " int first_long_parameter, int second_parameter) {}"); 11019 11020 verifyGoogleFormat("template <typename T>\n" 11021 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11022 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11023 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11024 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11025 11026 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11027 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11028 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11029 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11030 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11031 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11032 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11033 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11034 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11035 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11036 11037 verifyFormat("template <typename T> // Templates on own line.\n" 11038 "static int // Some comment.\n" 11039 "MyFunction(int a);", 11040 getLLVMStyle()); 11041 } 11042 11043 TEST_F(FormatTest, FormatsAccessModifiers) { 11044 FormatStyle Style = getLLVMStyle(); 11045 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11046 FormatStyle::ELBAMS_LogicalBlock); 11047 verifyFormat("struct foo {\n" 11048 "private:\n" 11049 " void f() {}\n" 11050 "\n" 11051 "private:\n" 11052 " int i;\n" 11053 "\n" 11054 "protected:\n" 11055 " int j;\n" 11056 "};\n", 11057 Style); 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 "struct foo {\n" 11069 "private:\n" 11070 " void f() {}\n" 11071 "private:\n" 11072 " int i;\n" 11073 "protected:\n" 11074 " int j;\n" 11075 "};\n", 11076 Style); 11077 verifyFormat("struct foo { /* comment */\n" 11078 "private:\n" 11079 " int i;\n" 11080 " // comment\n" 11081 "private:\n" 11082 " int j;\n" 11083 "};\n", 11084 Style); 11085 verifyFormat("struct foo {\n" 11086 "#ifdef FOO\n" 11087 "#endif\n" 11088 "private:\n" 11089 " int i;\n" 11090 "#ifdef FOO\n" 11091 "private:\n" 11092 "#endif\n" 11093 " int j;\n" 11094 "};\n", 11095 Style); 11096 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11097 verifyFormat("struct foo {\n" 11098 "private:\n" 11099 " void f() {}\n" 11100 "private:\n" 11101 " int i;\n" 11102 "protected:\n" 11103 " int j;\n" 11104 "};\n", 11105 Style); 11106 verifyFormat("struct foo {\n" 11107 "private:\n" 11108 " void f() {}\n" 11109 "private:\n" 11110 " int i;\n" 11111 "protected:\n" 11112 " int j;\n" 11113 "};\n", 11114 "struct foo {\n" 11115 "\n" 11116 "private:\n" 11117 " void f() {}\n" 11118 "\n" 11119 "private:\n" 11120 " int i;\n" 11121 "\n" 11122 "protected:\n" 11123 " int j;\n" 11124 "};\n", 11125 Style); 11126 verifyFormat("struct foo { /* comment */\n" 11127 "private:\n" 11128 " int i;\n" 11129 " // comment\n" 11130 "private:\n" 11131 " int j;\n" 11132 "};\n", 11133 "struct foo { /* comment */\n" 11134 "\n" 11135 "private:\n" 11136 " int i;\n" 11137 " // comment\n" 11138 "\n" 11139 "private:\n" 11140 " int j;\n" 11141 "};\n", 11142 Style); 11143 verifyFormat("struct foo {\n" 11144 "#ifdef FOO\n" 11145 "#endif\n" 11146 "private:\n" 11147 " int i;\n" 11148 "#ifdef FOO\n" 11149 "private:\n" 11150 "#endif\n" 11151 " int j;\n" 11152 "};\n", 11153 "struct foo {\n" 11154 "#ifdef FOO\n" 11155 "#endif\n" 11156 "\n" 11157 "private:\n" 11158 " int i;\n" 11159 "#ifdef FOO\n" 11160 "\n" 11161 "private:\n" 11162 "#endif\n" 11163 " int j;\n" 11164 "};\n", 11165 Style); 11166 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11167 verifyFormat("struct foo {\n" 11168 "private:\n" 11169 " void f() {}\n" 11170 "\n" 11171 "private:\n" 11172 " int i;\n" 11173 "\n" 11174 "protected:\n" 11175 " int j;\n" 11176 "};\n", 11177 Style); 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 "struct foo {\n" 11189 "private:\n" 11190 " void f() {}\n" 11191 "private:\n" 11192 " int i;\n" 11193 "protected:\n" 11194 " int j;\n" 11195 "};\n", 11196 Style); 11197 verifyFormat("struct foo { /* comment */\n" 11198 "private:\n" 11199 " int i;\n" 11200 " // comment\n" 11201 "\n" 11202 "private:\n" 11203 " int j;\n" 11204 "};\n", 11205 "struct foo { /* comment */\n" 11206 "private:\n" 11207 " int i;\n" 11208 " // comment\n" 11209 "\n" 11210 "private:\n" 11211 " int j;\n" 11212 "};\n", 11213 Style); 11214 verifyFormat("struct foo {\n" 11215 "#ifdef FOO\n" 11216 "#endif\n" 11217 "\n" 11218 "private:\n" 11219 " int i;\n" 11220 "#ifdef FOO\n" 11221 "\n" 11222 "private:\n" 11223 "#endif\n" 11224 " int j;\n" 11225 "};\n", 11226 "struct foo {\n" 11227 "#ifdef FOO\n" 11228 "#endif\n" 11229 "private:\n" 11230 " int i;\n" 11231 "#ifdef FOO\n" 11232 "private:\n" 11233 "#endif\n" 11234 " int j;\n" 11235 "};\n", 11236 Style); 11237 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11238 EXPECT_EQ("struct foo {\n" 11239 "\n" 11240 "private:\n" 11241 " void f() {}\n" 11242 "\n" 11243 "private:\n" 11244 " int i;\n" 11245 "\n" 11246 "protected:\n" 11247 " int j;\n" 11248 "};\n", 11249 format("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 Style)); 11261 verifyFormat("struct foo {\n" 11262 "private:\n" 11263 " void f() {}\n" 11264 "private:\n" 11265 " int i;\n" 11266 "protected:\n" 11267 " int j;\n" 11268 "};\n", 11269 Style); 11270 EXPECT_EQ("struct foo { /* comment */\n" 11271 "\n" 11272 "private:\n" 11273 " int i;\n" 11274 " // comment\n" 11275 "\n" 11276 "private:\n" 11277 " int j;\n" 11278 "};\n", 11279 format("struct foo { /* comment */\n" 11280 "\n" 11281 "private:\n" 11282 " int i;\n" 11283 " // comment\n" 11284 "\n" 11285 "private:\n" 11286 " int j;\n" 11287 "};\n", 11288 Style)); 11289 verifyFormat("struct foo { /* comment */\n" 11290 "private:\n" 11291 " int i;\n" 11292 " // comment\n" 11293 "private:\n" 11294 " int j;\n" 11295 "};\n", 11296 Style); 11297 EXPECT_EQ("struct foo {\n" 11298 "#ifdef FOO\n" 11299 "#endif\n" 11300 "\n" 11301 "private:\n" 11302 " int i;\n" 11303 "#ifdef FOO\n" 11304 "\n" 11305 "private:\n" 11306 "#endif\n" 11307 " int j;\n" 11308 "};\n", 11309 format("struct foo {\n" 11310 "#ifdef FOO\n" 11311 "#endif\n" 11312 "\n" 11313 "private:\n" 11314 " int i;\n" 11315 "#ifdef FOO\n" 11316 "\n" 11317 "private:\n" 11318 "#endif\n" 11319 " int j;\n" 11320 "};\n", 11321 Style)); 11322 verifyFormat("struct foo {\n" 11323 "#ifdef FOO\n" 11324 "#endif\n" 11325 "private:\n" 11326 " int i;\n" 11327 "#ifdef FOO\n" 11328 "private:\n" 11329 "#endif\n" 11330 " int j;\n" 11331 "};\n", 11332 Style); 11333 11334 FormatStyle NoEmptyLines = getLLVMStyle(); 11335 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11336 verifyFormat("struct foo {\n" 11337 "private:\n" 11338 " void f() {}\n" 11339 "\n" 11340 "private:\n" 11341 " int i;\n" 11342 "\n" 11343 "public:\n" 11344 "protected:\n" 11345 " int j;\n" 11346 "};\n", 11347 NoEmptyLines); 11348 11349 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11350 verifyFormat("struct foo {\n" 11351 "private:\n" 11352 " void f() {}\n" 11353 "private:\n" 11354 " int i;\n" 11355 "public:\n" 11356 "protected:\n" 11357 " int j;\n" 11358 "};\n", 11359 NoEmptyLines); 11360 11361 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11362 verifyFormat("struct foo {\n" 11363 "private:\n" 11364 " void f() {}\n" 11365 "\n" 11366 "private:\n" 11367 " int i;\n" 11368 "\n" 11369 "public:\n" 11370 "\n" 11371 "protected:\n" 11372 " int j;\n" 11373 "};\n", 11374 NoEmptyLines); 11375 } 11376 11377 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11378 11379 FormatStyle Style = getLLVMStyle(); 11380 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11381 verifyFormat("struct foo {\n" 11382 "private:\n" 11383 " void f() {}\n" 11384 "\n" 11385 "private:\n" 11386 " int i;\n" 11387 "\n" 11388 "protected:\n" 11389 " int j;\n" 11390 "};\n", 11391 Style); 11392 11393 // Check if lines are removed. 11394 verifyFormat("struct foo {\n" 11395 "private:\n" 11396 " void f() {}\n" 11397 "\n" 11398 "private:\n" 11399 " int i;\n" 11400 "\n" 11401 "protected:\n" 11402 " int j;\n" 11403 "};\n", 11404 "struct foo {\n" 11405 "private:\n" 11406 "\n" 11407 " void f() {}\n" 11408 "\n" 11409 "private:\n" 11410 "\n" 11411 " int i;\n" 11412 "\n" 11413 "protected:\n" 11414 "\n" 11415 " int j;\n" 11416 "};\n", 11417 Style); 11418 11419 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11420 verifyFormat("struct foo {\n" 11421 "private:\n" 11422 "\n" 11423 " void f() {}\n" 11424 "\n" 11425 "private:\n" 11426 "\n" 11427 " int i;\n" 11428 "\n" 11429 "protected:\n" 11430 "\n" 11431 " int j;\n" 11432 "};\n", 11433 Style); 11434 11435 // Check if lines are added. 11436 verifyFormat("struct foo {\n" 11437 "private:\n" 11438 "\n" 11439 " void f() {}\n" 11440 "\n" 11441 "private:\n" 11442 "\n" 11443 " int i;\n" 11444 "\n" 11445 "protected:\n" 11446 "\n" 11447 " int j;\n" 11448 "};\n", 11449 "struct foo {\n" 11450 "private:\n" 11451 " void f() {}\n" 11452 "\n" 11453 "private:\n" 11454 " int i;\n" 11455 "\n" 11456 "protected:\n" 11457 " int j;\n" 11458 "};\n", 11459 Style); 11460 11461 // Leave tests rely on the code layout, test::messUp can not be used. 11462 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11463 Style.MaxEmptyLinesToKeep = 0u; 11464 verifyFormat("struct foo {\n" 11465 "private:\n" 11466 " void f() {}\n" 11467 "\n" 11468 "private:\n" 11469 " int i;\n" 11470 "\n" 11471 "protected:\n" 11472 " int j;\n" 11473 "};\n", 11474 Style); 11475 11476 // Check if MaxEmptyLinesToKeep is respected. 11477 EXPECT_EQ("struct foo {\n" 11478 "private:\n" 11479 " void f() {}\n" 11480 "\n" 11481 "private:\n" 11482 " int i;\n" 11483 "\n" 11484 "protected:\n" 11485 " int j;\n" 11486 "};\n", 11487 format("struct foo {\n" 11488 "private:\n" 11489 "\n\n\n" 11490 " void f() {}\n" 11491 "\n" 11492 "private:\n" 11493 "\n\n\n" 11494 " int i;\n" 11495 "\n" 11496 "protected:\n" 11497 "\n\n\n" 11498 " int j;\n" 11499 "};\n", 11500 Style)); 11501 11502 Style.MaxEmptyLinesToKeep = 1u; 11503 EXPECT_EQ("struct foo {\n" 11504 "private:\n" 11505 "\n" 11506 " void f() {}\n" 11507 "\n" 11508 "private:\n" 11509 "\n" 11510 " int i;\n" 11511 "\n" 11512 "protected:\n" 11513 "\n" 11514 " int j;\n" 11515 "};\n", 11516 format("struct foo {\n" 11517 "private:\n" 11518 "\n" 11519 " void f() {}\n" 11520 "\n" 11521 "private:\n" 11522 "\n" 11523 " int i;\n" 11524 "\n" 11525 "protected:\n" 11526 "\n" 11527 " int j;\n" 11528 "};\n", 11529 Style)); 11530 // Check if no lines are kept. 11531 EXPECT_EQ("struct foo {\n" 11532 "private:\n" 11533 " void f() {}\n" 11534 "\n" 11535 "private:\n" 11536 " int i;\n" 11537 "\n" 11538 "protected:\n" 11539 " int j;\n" 11540 "};\n", 11541 format("struct foo {\n" 11542 "private:\n" 11543 " void f() {}\n" 11544 "\n" 11545 "private:\n" 11546 " int i;\n" 11547 "\n" 11548 "protected:\n" 11549 " int j;\n" 11550 "};\n", 11551 Style)); 11552 // Check if MaxEmptyLinesToKeep is respected. 11553 EXPECT_EQ("struct foo {\n" 11554 "private:\n" 11555 "\n" 11556 " void f() {}\n" 11557 "\n" 11558 "private:\n" 11559 "\n" 11560 " int i;\n" 11561 "\n" 11562 "protected:\n" 11563 "\n" 11564 " int j;\n" 11565 "};\n", 11566 format("struct foo {\n" 11567 "private:\n" 11568 "\n\n\n" 11569 " void f() {}\n" 11570 "\n" 11571 "private:\n" 11572 "\n\n\n" 11573 " int i;\n" 11574 "\n" 11575 "protected:\n" 11576 "\n\n\n" 11577 " int j;\n" 11578 "};\n", 11579 Style)); 11580 11581 Style.MaxEmptyLinesToKeep = 10u; 11582 EXPECT_EQ("struct foo {\n" 11583 "private:\n" 11584 "\n\n\n" 11585 " void f() {}\n" 11586 "\n" 11587 "private:\n" 11588 "\n\n\n" 11589 " int i;\n" 11590 "\n" 11591 "protected:\n" 11592 "\n\n\n" 11593 " int j;\n" 11594 "};\n", 11595 format("struct foo {\n" 11596 "private:\n" 11597 "\n\n\n" 11598 " void f() {}\n" 11599 "\n" 11600 "private:\n" 11601 "\n\n\n" 11602 " int i;\n" 11603 "\n" 11604 "protected:\n" 11605 "\n\n\n" 11606 " int j;\n" 11607 "};\n", 11608 Style)); 11609 11610 // Test with comments. 11611 Style = getLLVMStyle(); 11612 verifyFormat("struct foo {\n" 11613 "private:\n" 11614 " // comment\n" 11615 " void f() {}\n" 11616 "\n" 11617 "private: /* comment */\n" 11618 " int i;\n" 11619 "};\n", 11620 Style); 11621 verifyFormat("struct foo {\n" 11622 "private:\n" 11623 " // comment\n" 11624 " void f() {}\n" 11625 "\n" 11626 "private: /* comment */\n" 11627 " int i;\n" 11628 "};\n", 11629 "struct foo {\n" 11630 "private:\n" 11631 "\n" 11632 " // comment\n" 11633 " void f() {}\n" 11634 "\n" 11635 "private: /* comment */\n" 11636 "\n" 11637 " int i;\n" 11638 "};\n", 11639 Style); 11640 11641 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11642 verifyFormat("struct foo {\n" 11643 "private:\n" 11644 "\n" 11645 " // comment\n" 11646 " void f() {}\n" 11647 "\n" 11648 "private: /* comment */\n" 11649 "\n" 11650 " int i;\n" 11651 "};\n", 11652 "struct foo {\n" 11653 "private:\n" 11654 " // comment\n" 11655 " void f() {}\n" 11656 "\n" 11657 "private: /* comment */\n" 11658 " int i;\n" 11659 "};\n", 11660 Style); 11661 verifyFormat("struct foo {\n" 11662 "private:\n" 11663 "\n" 11664 " // comment\n" 11665 " void f() {}\n" 11666 "\n" 11667 "private: /* comment */\n" 11668 "\n" 11669 " int i;\n" 11670 "};\n", 11671 Style); 11672 11673 // Test with preprocessor defines. 11674 Style = getLLVMStyle(); 11675 verifyFormat("struct foo {\n" 11676 "private:\n" 11677 "#ifdef FOO\n" 11678 "#endif\n" 11679 " void f() {}\n" 11680 "};\n", 11681 Style); 11682 verifyFormat("struct foo {\n" 11683 "private:\n" 11684 "#ifdef FOO\n" 11685 "#endif\n" 11686 " void f() {}\n" 11687 "};\n", 11688 "struct foo {\n" 11689 "private:\n" 11690 "\n" 11691 "#ifdef FOO\n" 11692 "#endif\n" 11693 " void f() {}\n" 11694 "};\n", 11695 Style); 11696 11697 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11698 verifyFormat("struct foo {\n" 11699 "private:\n" 11700 "\n" 11701 "#ifdef FOO\n" 11702 "#endif\n" 11703 " void f() {}\n" 11704 "};\n", 11705 "struct foo {\n" 11706 "private:\n" 11707 "#ifdef FOO\n" 11708 "#endif\n" 11709 " void f() {}\n" 11710 "};\n", 11711 Style); 11712 verifyFormat("struct foo {\n" 11713 "private:\n" 11714 "\n" 11715 "#ifdef FOO\n" 11716 "#endif\n" 11717 " void f() {}\n" 11718 "};\n", 11719 Style); 11720 } 11721 11722 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11723 // Combined tests of EmptyLineAfterAccessModifier and 11724 // EmptyLineBeforeAccessModifier. 11725 FormatStyle Style = getLLVMStyle(); 11726 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11727 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11728 verifyFormat("struct foo {\n" 11729 "private:\n" 11730 "\n" 11731 "protected:\n" 11732 "};\n", 11733 Style); 11734 11735 Style.MaxEmptyLinesToKeep = 10u; 11736 // Both remove all new lines. 11737 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11738 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11739 verifyFormat("struct foo {\n" 11740 "private:\n" 11741 "protected:\n" 11742 "};\n", 11743 "struct foo {\n" 11744 "private:\n" 11745 "\n\n\n" 11746 "protected:\n" 11747 "};\n", 11748 Style); 11749 11750 // Leave tests rely on the code layout, test::messUp can not be used. 11751 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11752 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11753 Style.MaxEmptyLinesToKeep = 10u; 11754 EXPECT_EQ("struct foo {\n" 11755 "private:\n" 11756 "\n\n\n" 11757 "protected:\n" 11758 "};\n", 11759 format("struct foo {\n" 11760 "private:\n" 11761 "\n\n\n" 11762 "protected:\n" 11763 "};\n", 11764 Style)); 11765 Style.MaxEmptyLinesToKeep = 3u; 11766 EXPECT_EQ("struct foo {\n" 11767 "private:\n" 11768 "\n\n\n" 11769 "protected:\n" 11770 "};\n", 11771 format("struct foo {\n" 11772 "private:\n" 11773 "\n\n\n" 11774 "protected:\n" 11775 "};\n", 11776 Style)); 11777 Style.MaxEmptyLinesToKeep = 1u; 11778 EXPECT_EQ("struct foo {\n" 11779 "private:\n" 11780 "\n\n\n" 11781 "protected:\n" 11782 "};\n", 11783 format("struct foo {\n" 11784 "private:\n" 11785 "\n\n\n" 11786 "protected:\n" 11787 "};\n", 11788 Style)); // Based on new lines in original document and not 11789 // on the setting. 11790 11791 Style.MaxEmptyLinesToKeep = 10u; 11792 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11793 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11794 // Newlines are kept if they are greater than zero, 11795 // test::messUp removes all new lines which changes the logic 11796 EXPECT_EQ("struct foo {\n" 11797 "private:\n" 11798 "\n\n\n" 11799 "protected:\n" 11800 "};\n", 11801 format("struct foo {\n" 11802 "private:\n" 11803 "\n\n\n" 11804 "protected:\n" 11805 "};\n", 11806 Style)); 11807 11808 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11809 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11810 // test::messUp removes all new lines which changes the logic 11811 EXPECT_EQ("struct foo {\n" 11812 "private:\n" 11813 "\n\n\n" 11814 "protected:\n" 11815 "};\n", 11816 format("struct foo {\n" 11817 "private:\n" 11818 "\n\n\n" 11819 "protected:\n" 11820 "};\n", 11821 Style)); 11822 11823 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11824 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11825 EXPECT_EQ("struct foo {\n" 11826 "private:\n" 11827 "\n\n\n" 11828 "protected:\n" 11829 "};\n", 11830 format("struct foo {\n" 11831 "private:\n" 11832 "\n\n\n" 11833 "protected:\n" 11834 "};\n", 11835 Style)); // test::messUp removes all new lines which changes 11836 // the logic. 11837 11838 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11839 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11840 verifyFormat("struct foo {\n" 11841 "private:\n" 11842 "protected:\n" 11843 "};\n", 11844 "struct foo {\n" 11845 "private:\n" 11846 "\n\n\n" 11847 "protected:\n" 11848 "};\n", 11849 Style); 11850 11851 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11852 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11853 EXPECT_EQ("struct foo {\n" 11854 "private:\n" 11855 "\n\n\n" 11856 "protected:\n" 11857 "};\n", 11858 format("struct foo {\n" 11859 "private:\n" 11860 "\n\n\n" 11861 "protected:\n" 11862 "};\n", 11863 Style)); // test::messUp removes all new lines which changes 11864 // the logic. 11865 11866 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11867 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11868 verifyFormat("struct foo {\n" 11869 "private:\n" 11870 "protected:\n" 11871 "};\n", 11872 "struct foo {\n" 11873 "private:\n" 11874 "\n\n\n" 11875 "protected:\n" 11876 "};\n", 11877 Style); 11878 11879 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11880 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11881 verifyFormat("struct foo {\n" 11882 "private:\n" 11883 "protected:\n" 11884 "};\n", 11885 "struct foo {\n" 11886 "private:\n" 11887 "\n\n\n" 11888 "protected:\n" 11889 "};\n", 11890 Style); 11891 11892 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11893 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11894 verifyFormat("struct foo {\n" 11895 "private:\n" 11896 "protected:\n" 11897 "};\n", 11898 "struct foo {\n" 11899 "private:\n" 11900 "\n\n\n" 11901 "protected:\n" 11902 "};\n", 11903 Style); 11904 11905 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11906 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11907 verifyFormat("struct foo {\n" 11908 "private:\n" 11909 "protected:\n" 11910 "};\n", 11911 "struct foo {\n" 11912 "private:\n" 11913 "\n\n\n" 11914 "protected:\n" 11915 "};\n", 11916 Style); 11917 } 11918 11919 TEST_F(FormatTest, FormatsArrays) { 11920 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11921 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11922 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11923 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11924 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11925 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11926 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11927 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11928 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11929 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11930 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11931 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11932 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11933 verifyFormat( 11934 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11935 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11936 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11937 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11938 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11939 11940 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11941 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11942 verifyFormat( 11943 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11944 " .aaaaaaa[0]\n" 11945 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11946 verifyFormat("a[::b::c];"); 11947 11948 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11949 11950 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11951 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11952 } 11953 11954 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11955 verifyFormat("(a)->b();"); 11956 verifyFormat("--a;"); 11957 } 11958 11959 TEST_F(FormatTest, HandlesIncludeDirectives) { 11960 verifyFormat("#include <string>\n" 11961 "#include <a/b/c.h>\n" 11962 "#include \"a/b/string\"\n" 11963 "#include \"string.h\"\n" 11964 "#include \"string.h\"\n" 11965 "#include <a-a>\n" 11966 "#include < path with space >\n" 11967 "#include_next <test.h>" 11968 "#include \"abc.h\" // this is included for ABC\n" 11969 "#include \"some long include\" // with a comment\n" 11970 "#include \"some very long include path\"\n" 11971 "#include <some/very/long/include/path>\n", 11972 getLLVMStyleWithColumns(35)); 11973 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11974 EXPECT_EQ("#include <a>", format("#include<a>")); 11975 11976 verifyFormat("#import <string>"); 11977 verifyFormat("#import <a/b/c.h>"); 11978 verifyFormat("#import \"a/b/string\""); 11979 verifyFormat("#import \"string.h\""); 11980 verifyFormat("#import \"string.h\""); 11981 verifyFormat("#if __has_include(<strstream>)\n" 11982 "#include <strstream>\n" 11983 "#endif"); 11984 11985 verifyFormat("#define MY_IMPORT <a/b>"); 11986 11987 verifyFormat("#if __has_include(<a/b>)"); 11988 verifyFormat("#if __has_include_next(<a/b>)"); 11989 verifyFormat("#define F __has_include(<a/b>)"); 11990 verifyFormat("#define F __has_include_next(<a/b>)"); 11991 11992 // Protocol buffer definition or missing "#". 11993 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11994 getLLVMStyleWithColumns(30)); 11995 11996 FormatStyle Style = getLLVMStyle(); 11997 Style.AlwaysBreakBeforeMultilineStrings = true; 11998 Style.ColumnLimit = 0; 11999 verifyFormat("#import \"abc.h\"", Style); 12000 12001 // But 'import' might also be a regular C++ namespace. 12002 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12003 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12004 } 12005 12006 //===----------------------------------------------------------------------===// 12007 // Error recovery tests. 12008 //===----------------------------------------------------------------------===// 12009 12010 TEST_F(FormatTest, IncompleteParameterLists) { 12011 FormatStyle NoBinPacking = getLLVMStyle(); 12012 NoBinPacking.BinPackParameters = false; 12013 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12014 " double *min_x,\n" 12015 " double *max_x,\n" 12016 " double *min_y,\n" 12017 " double *max_y,\n" 12018 " double *min_z,\n" 12019 " double *max_z, ) {}", 12020 NoBinPacking); 12021 } 12022 12023 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12024 verifyFormat("void f() { return; }\n42"); 12025 verifyFormat("void f() {\n" 12026 " if (0)\n" 12027 " return;\n" 12028 "}\n" 12029 "42"); 12030 verifyFormat("void f() { return }\n42"); 12031 verifyFormat("void f() {\n" 12032 " if (0)\n" 12033 " return\n" 12034 "}\n" 12035 "42"); 12036 } 12037 12038 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12039 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12040 EXPECT_EQ("void f() {\n" 12041 " if (a)\n" 12042 " return\n" 12043 "}", 12044 format("void f ( ) { if ( a ) return }")); 12045 EXPECT_EQ("namespace N {\n" 12046 "void f()\n" 12047 "}", 12048 format("namespace N { void f() }")); 12049 EXPECT_EQ("namespace N {\n" 12050 "void f() {}\n" 12051 "void g()\n" 12052 "} // namespace N", 12053 format("namespace N { void f( ) { } void g( ) }")); 12054 } 12055 12056 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12057 verifyFormat("int aaaaaaaa =\n" 12058 " // Overlylongcomment\n" 12059 " b;", 12060 getLLVMStyleWithColumns(20)); 12061 verifyFormat("function(\n" 12062 " ShortArgument,\n" 12063 " LoooooooooooongArgument);\n", 12064 getLLVMStyleWithColumns(20)); 12065 } 12066 12067 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12068 verifyFormat("public:"); 12069 verifyFormat("class A {\n" 12070 "public\n" 12071 " void f() {}\n" 12072 "};"); 12073 verifyFormat("public\n" 12074 "int qwerty;"); 12075 verifyFormat("public\n" 12076 "B {}"); 12077 verifyFormat("public\n" 12078 "{}"); 12079 verifyFormat("public\n" 12080 "B { int x; }"); 12081 } 12082 12083 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12084 verifyFormat("{"); 12085 verifyFormat("#})"); 12086 verifyNoCrash("(/**/[:!] ?[)."); 12087 } 12088 12089 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12090 // Found by oss-fuzz: 12091 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12092 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12093 Style.ColumnLimit = 60; 12094 verifyNoCrash( 12095 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12096 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12097 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12098 Style); 12099 } 12100 12101 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12102 verifyFormat("do {\n}"); 12103 verifyFormat("do {\n}\n" 12104 "f();"); 12105 verifyFormat("do {\n}\n" 12106 "wheeee(fun);"); 12107 verifyFormat("do {\n" 12108 " f();\n" 12109 "}"); 12110 } 12111 12112 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12113 verifyFormat("if {\n foo;\n foo();\n}"); 12114 verifyFormat("switch {\n foo;\n foo();\n}"); 12115 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12116 verifyIncompleteFormat("ERROR: for target;"); 12117 verifyFormat("while {\n foo;\n foo();\n}"); 12118 verifyFormat("do {\n foo;\n foo();\n} while;"); 12119 } 12120 12121 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12122 verifyIncompleteFormat("namespace {\n" 12123 "class Foo { Foo (\n" 12124 "};\n" 12125 "} // namespace"); 12126 } 12127 12128 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12129 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12130 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12131 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12132 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12133 12134 EXPECT_EQ("{\n" 12135 " {\n" 12136 " breakme(\n" 12137 " qwe);\n" 12138 " }\n", 12139 format("{\n" 12140 " {\n" 12141 " breakme(qwe);\n" 12142 "}\n", 12143 getLLVMStyleWithColumns(10))); 12144 } 12145 12146 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12147 verifyFormat("int x = {\n" 12148 " avariable,\n" 12149 " b(alongervariable)};", 12150 getLLVMStyleWithColumns(25)); 12151 } 12152 12153 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12154 verifyFormat("return (a)(b){1, 2, 3};"); 12155 } 12156 12157 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12158 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12159 verifyFormat("vector<int> x{\n" 12160 " 1,\n" 12161 " 2,\n" 12162 " 3,\n" 12163 " 4,\n" 12164 "};"); 12165 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12166 verifyFormat("f({1, 2});"); 12167 verifyFormat("auto v = Foo{-1};"); 12168 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12169 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12170 verifyFormat("new vector<int>{1, 2, 3};"); 12171 verifyFormat("new int[3]{1, 2, 3};"); 12172 verifyFormat("new int{1};"); 12173 verifyFormat("return {arg1, arg2};"); 12174 verifyFormat("return {arg1, SomeType{parameter}};"); 12175 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12176 verifyFormat("new T{arg1, arg2};"); 12177 verifyFormat("f(MyMap[{composite, key}]);"); 12178 verifyFormat("class Class {\n" 12179 " T member = {arg1, arg2};\n" 12180 "};"); 12181 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12182 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12183 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12184 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12185 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12186 12187 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12188 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12189 verifyFormat("auto i = decltype(x){};"); 12190 verifyFormat("auto i = typeof(x){};"); 12191 verifyFormat("auto i = _Atomic(x){};"); 12192 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12193 verifyFormat("Node n{1, Node{1000}, //\n" 12194 " 2};"); 12195 verifyFormat("Aaaa aaaaaaa{\n" 12196 " {\n" 12197 " aaaa,\n" 12198 " },\n" 12199 "};"); 12200 verifyFormat("class C : public D {\n" 12201 " SomeClass SC{2};\n" 12202 "};"); 12203 verifyFormat("class C : public A {\n" 12204 " class D : public B {\n" 12205 " void f() { int i{2}; }\n" 12206 " };\n" 12207 "};"); 12208 verifyFormat("#define A {a, a},"); 12209 // Don't confuse braced list initializers with compound statements. 12210 verifyFormat( 12211 "class A {\n" 12212 " A() : a{} {}\n" 12213 " A(int b) : b(b) {}\n" 12214 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12215 " int a, b;\n" 12216 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12217 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12218 "{}\n" 12219 "};"); 12220 12221 // Avoid breaking between equal sign and opening brace 12222 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12223 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12224 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12225 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12226 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12227 " {\"ccccccccccccccccccccc\", 2}};", 12228 AvoidBreakingFirstArgument); 12229 12230 // Binpacking only if there is no trailing comma 12231 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12232 " cccccccccc, dddddddddd};", 12233 getLLVMStyleWithColumns(50)); 12234 verifyFormat("const Aaaaaa aaaaa = {\n" 12235 " aaaaaaaaaaa,\n" 12236 " bbbbbbbbbbb,\n" 12237 " ccccccccccc,\n" 12238 " ddddddddddd,\n" 12239 "};", 12240 getLLVMStyleWithColumns(50)); 12241 12242 // Cases where distinguising braced lists and blocks is hard. 12243 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12244 verifyFormat("void f() {\n" 12245 " return; // comment\n" 12246 "}\n" 12247 "SomeType t;"); 12248 verifyFormat("void f() {\n" 12249 " if (a) {\n" 12250 " f();\n" 12251 " }\n" 12252 "}\n" 12253 "SomeType t;"); 12254 12255 // In combination with BinPackArguments = false. 12256 FormatStyle NoBinPacking = getLLVMStyle(); 12257 NoBinPacking.BinPackArguments = false; 12258 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12259 " bbbbb,\n" 12260 " ccccc,\n" 12261 " ddddd,\n" 12262 " eeeee,\n" 12263 " ffffff,\n" 12264 " ggggg,\n" 12265 " hhhhhh,\n" 12266 " iiiiii,\n" 12267 " jjjjjj,\n" 12268 " kkkkkk};", 12269 NoBinPacking); 12270 verifyFormat("const Aaaaaa aaaaa = {\n" 12271 " aaaaa,\n" 12272 " bbbbb,\n" 12273 " ccccc,\n" 12274 " ddddd,\n" 12275 " eeeee,\n" 12276 " ffffff,\n" 12277 " ggggg,\n" 12278 " hhhhhh,\n" 12279 " iiiiii,\n" 12280 " jjjjjj,\n" 12281 " kkkkkk,\n" 12282 "};", 12283 NoBinPacking); 12284 verifyFormat( 12285 "const Aaaaaa aaaaa = {\n" 12286 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12287 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12288 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12289 "};", 12290 NoBinPacking); 12291 12292 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12293 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12294 " CDDDP83848_BMCR_REGISTER,\n" 12295 " CDDDP83848_BMSR_REGISTER,\n" 12296 " CDDDP83848_RBR_REGISTER};", 12297 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12298 " CDDDP83848_BMSR_REGISTER,\n" 12299 " CDDDP83848_RBR_REGISTER};", 12300 NoBinPacking)); 12301 12302 // FIXME: The alignment of these trailing comments might be bad. Then again, 12303 // this might be utterly useless in real code. 12304 verifyFormat("Constructor::Constructor()\n" 12305 " : some_value{ //\n" 12306 " aaaaaaa, //\n" 12307 " bbbbbbb} {}"); 12308 12309 // In braced lists, the first comment is always assumed to belong to the 12310 // first element. Thus, it can be moved to the next or previous line as 12311 // appropriate. 12312 EXPECT_EQ("function({// First element:\n" 12313 " 1,\n" 12314 " // Second element:\n" 12315 " 2});", 12316 format("function({\n" 12317 " // First element:\n" 12318 " 1,\n" 12319 " // Second element:\n" 12320 " 2});")); 12321 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12322 " // First element:\n" 12323 " 1,\n" 12324 " // Second element:\n" 12325 " 2};", 12326 format("std::vector<int> MyNumbers{// First element:\n" 12327 " 1,\n" 12328 " // Second element:\n" 12329 " 2};", 12330 getLLVMStyleWithColumns(30))); 12331 // A trailing comma should still lead to an enforced line break and no 12332 // binpacking. 12333 EXPECT_EQ("vector<int> SomeVector = {\n" 12334 " // aaa\n" 12335 " 1,\n" 12336 " 2,\n" 12337 "};", 12338 format("vector<int> SomeVector = { // aaa\n" 12339 " 1, 2, };")); 12340 12341 // C++11 brace initializer list l-braces should not be treated any differently 12342 // when breaking before lambda bodies is enabled 12343 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12344 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12345 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12346 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12347 verifyFormat( 12348 "std::runtime_error{\n" 12349 " \"Long string which will force a break onto the next line...\"};", 12350 BreakBeforeLambdaBody); 12351 12352 FormatStyle ExtraSpaces = getLLVMStyle(); 12353 ExtraSpaces.Cpp11BracedListStyle = false; 12354 ExtraSpaces.ColumnLimit = 75; 12355 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12356 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12357 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12358 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12359 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12360 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12361 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12362 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12363 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12364 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12365 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12366 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12367 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12368 verifyFormat("class Class {\n" 12369 " T member = { arg1, arg2 };\n" 12370 "};", 12371 ExtraSpaces); 12372 verifyFormat( 12373 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12374 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12375 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12376 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12377 ExtraSpaces); 12378 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12379 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12380 ExtraSpaces); 12381 verifyFormat( 12382 "someFunction(OtherParam,\n" 12383 " BracedList{ // comment 1 (Forcing interesting break)\n" 12384 " param1, param2,\n" 12385 " // comment 2\n" 12386 " param3, param4 });", 12387 ExtraSpaces); 12388 verifyFormat( 12389 "std::this_thread::sleep_for(\n" 12390 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12391 ExtraSpaces); 12392 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12393 " aaaaaaa,\n" 12394 " aaaaaaaaaa,\n" 12395 " aaaaa,\n" 12396 " aaaaaaaaaaaaaaa,\n" 12397 " aaa,\n" 12398 " aaaaaaaaaa,\n" 12399 " a,\n" 12400 " aaaaaaaaaaaaaaaaaaaaa,\n" 12401 " aaaaaaaaaaaa,\n" 12402 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12403 " aaaaaaa,\n" 12404 " a};"); 12405 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12406 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12407 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12408 12409 // Avoid breaking between initializer/equal sign and opening brace 12410 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12411 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12412 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12413 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12414 " { \"ccccccccccccccccccccc\", 2 }\n" 12415 "};", 12416 ExtraSpaces); 12417 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12418 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12419 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12420 " { \"ccccccccccccccccccccc\", 2 }\n" 12421 "};", 12422 ExtraSpaces); 12423 12424 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12425 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12426 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12427 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12428 12429 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12430 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12431 SpaceBetweenBraces.SpacesInParentheses = true; 12432 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12433 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12434 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12435 verifyFormat("vector< int > x{ // comment 1\n" 12436 " 1, 2, 3, 4 };", 12437 SpaceBetweenBraces); 12438 SpaceBetweenBraces.ColumnLimit = 20; 12439 EXPECT_EQ("vector< int > x{\n" 12440 " 1, 2, 3, 4 };", 12441 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12442 SpaceBetweenBraces.ColumnLimit = 24; 12443 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12444 " 3, 4 };", 12445 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12446 EXPECT_EQ("vector< int > x{\n" 12447 " 1,\n" 12448 " 2,\n" 12449 " 3,\n" 12450 " 4,\n" 12451 "};", 12452 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12453 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12454 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12455 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12456 } 12457 12458 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12459 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12460 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12461 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12462 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12463 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12464 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12465 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12466 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12467 " 1, 22, 333, 4444, 55555, //\n" 12468 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12469 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12470 verifyFormat( 12471 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12472 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12473 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12474 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12475 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12476 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12477 " 7777777};"); 12478 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12479 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12480 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12481 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12482 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12483 " // Separating comment.\n" 12484 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12485 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12486 " // Leading comment\n" 12487 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12488 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12489 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12490 " 1, 1, 1, 1};", 12491 getLLVMStyleWithColumns(39)); 12492 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12493 " 1, 1, 1, 1};", 12494 getLLVMStyleWithColumns(38)); 12495 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12496 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12497 getLLVMStyleWithColumns(43)); 12498 verifyFormat( 12499 "static unsigned SomeValues[10][3] = {\n" 12500 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12501 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12502 verifyFormat("static auto fields = new vector<string>{\n" 12503 " \"aaaaaaaaaaaaa\",\n" 12504 " \"aaaaaaaaaaaaa\",\n" 12505 " \"aaaaaaaaaaaa\",\n" 12506 " \"aaaaaaaaaaaaaa\",\n" 12507 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12508 " \"aaaaaaaaaaaa\",\n" 12509 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12510 "};"); 12511 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12512 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12513 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12514 " 3, cccccccccccccccccccccc};", 12515 getLLVMStyleWithColumns(60)); 12516 12517 // Trailing commas. 12518 verifyFormat("vector<int> x = {\n" 12519 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12520 "};", 12521 getLLVMStyleWithColumns(39)); 12522 verifyFormat("vector<int> x = {\n" 12523 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12524 "};", 12525 getLLVMStyleWithColumns(39)); 12526 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12527 " 1, 1, 1, 1,\n" 12528 " /**/ /**/};", 12529 getLLVMStyleWithColumns(39)); 12530 12531 // Trailing comment in the first line. 12532 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12533 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12534 " 111111111, 222222222, 3333333333, 444444444, //\n" 12535 " 11111111, 22222222, 333333333, 44444444};"); 12536 // Trailing comment in the last line. 12537 verifyFormat("int aaaaa[] = {\n" 12538 " 1, 2, 3, // comment\n" 12539 " 4, 5, 6 // comment\n" 12540 "};"); 12541 12542 // With nested lists, we should either format one item per line or all nested 12543 // lists one on line. 12544 // FIXME: For some nested lists, we can do better. 12545 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12546 " {aaaaaaaaaaaaaaaaaaa},\n" 12547 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12548 " {aaaaaaaaaaaaaaaaa}};", 12549 getLLVMStyleWithColumns(60)); 12550 verifyFormat( 12551 "SomeStruct my_struct_array = {\n" 12552 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12553 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12554 " {aaa, aaa},\n" 12555 " {aaa, aaa},\n" 12556 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12557 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12558 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12559 12560 // No column layout should be used here. 12561 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12562 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12563 12564 verifyNoCrash("a<,"); 12565 12566 // No braced initializer here. 12567 verifyFormat("void f() {\n" 12568 " struct Dummy {};\n" 12569 " f(v);\n" 12570 "}"); 12571 12572 // Long lists should be formatted in columns even if they are nested. 12573 verifyFormat( 12574 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12575 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12576 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12577 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12578 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12579 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12580 12581 // Allow "single-column" layout even if that violates the column limit. There 12582 // isn't going to be a better way. 12583 verifyFormat("std::vector<int> a = {\n" 12584 " aaaaaaaa,\n" 12585 " aaaaaaaa,\n" 12586 " aaaaaaaa,\n" 12587 " aaaaaaaa,\n" 12588 " aaaaaaaaaa,\n" 12589 " aaaaaaaa,\n" 12590 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12591 getLLVMStyleWithColumns(30)); 12592 verifyFormat("vector<int> aaaa = {\n" 12593 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12594 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12595 " aaaaaa.aaaaaaa,\n" 12596 " aaaaaa.aaaaaaa,\n" 12597 " aaaaaa.aaaaaaa,\n" 12598 " aaaaaa.aaaaaaa,\n" 12599 "};"); 12600 12601 // Don't create hanging lists. 12602 verifyFormat("someFunction(Param, {List1, List2,\n" 12603 " List3});", 12604 getLLVMStyleWithColumns(35)); 12605 verifyFormat("someFunction(Param, Param,\n" 12606 " {List1, List2,\n" 12607 " List3});", 12608 getLLVMStyleWithColumns(35)); 12609 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12610 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12611 } 12612 12613 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12614 FormatStyle DoNotMerge = getLLVMStyle(); 12615 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12616 12617 verifyFormat("void f() { return 42; }"); 12618 verifyFormat("void f() {\n" 12619 " return 42;\n" 12620 "}", 12621 DoNotMerge); 12622 verifyFormat("void f() {\n" 12623 " // Comment\n" 12624 "}"); 12625 verifyFormat("{\n" 12626 "#error {\n" 12627 " int a;\n" 12628 "}"); 12629 verifyFormat("{\n" 12630 " int a;\n" 12631 "#error {\n" 12632 "}"); 12633 verifyFormat("void f() {} // comment"); 12634 verifyFormat("void f() { int a; } // comment"); 12635 verifyFormat("void f() {\n" 12636 "} // comment", 12637 DoNotMerge); 12638 verifyFormat("void f() {\n" 12639 " int a;\n" 12640 "} // comment", 12641 DoNotMerge); 12642 verifyFormat("void f() {\n" 12643 "} // comment", 12644 getLLVMStyleWithColumns(15)); 12645 12646 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12647 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12648 12649 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12650 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12651 verifyFormat("class C {\n" 12652 " C()\n" 12653 " : iiiiiiii(nullptr),\n" 12654 " kkkkkkk(nullptr),\n" 12655 " mmmmmmm(nullptr),\n" 12656 " nnnnnnn(nullptr) {}\n" 12657 "};", 12658 getGoogleStyle()); 12659 12660 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12661 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12662 EXPECT_EQ("class C {\n" 12663 " A() : b(0) {}\n" 12664 "};", 12665 format("class C{A():b(0){}};", NoColumnLimit)); 12666 EXPECT_EQ("A()\n" 12667 " : b(0) {\n" 12668 "}", 12669 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12670 12671 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12672 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12673 FormatStyle::SFS_None; 12674 EXPECT_EQ("A()\n" 12675 " : b(0) {\n" 12676 "}", 12677 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12678 EXPECT_EQ("A()\n" 12679 " : b(0) {\n" 12680 "}", 12681 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12682 12683 verifyFormat("#define A \\\n" 12684 " void f() { \\\n" 12685 " int i; \\\n" 12686 " }", 12687 getLLVMStyleWithColumns(20)); 12688 verifyFormat("#define A \\\n" 12689 " void f() { int i; }", 12690 getLLVMStyleWithColumns(21)); 12691 verifyFormat("#define A \\\n" 12692 " void f() { \\\n" 12693 " int i; \\\n" 12694 " } \\\n" 12695 " int j;", 12696 getLLVMStyleWithColumns(22)); 12697 verifyFormat("#define A \\\n" 12698 " void f() { int i; } \\\n" 12699 " int j;", 12700 getLLVMStyleWithColumns(23)); 12701 } 12702 12703 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12704 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12705 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12706 verifyFormat("class C {\n" 12707 " int f() {}\n" 12708 "};", 12709 MergeEmptyOnly); 12710 verifyFormat("class C {\n" 12711 " int f() {\n" 12712 " return 42;\n" 12713 " }\n" 12714 "};", 12715 MergeEmptyOnly); 12716 verifyFormat("int f() {}", MergeEmptyOnly); 12717 verifyFormat("int f() {\n" 12718 " return 42;\n" 12719 "}", 12720 MergeEmptyOnly); 12721 12722 // Also verify behavior when BraceWrapping.AfterFunction = true 12723 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12724 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12725 verifyFormat("int f() {}", MergeEmptyOnly); 12726 verifyFormat("class C {\n" 12727 " int f() {}\n" 12728 "};", 12729 MergeEmptyOnly); 12730 } 12731 12732 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12733 FormatStyle MergeInlineOnly = getLLVMStyle(); 12734 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12735 verifyFormat("class C {\n" 12736 " int f() { return 42; }\n" 12737 "};", 12738 MergeInlineOnly); 12739 verifyFormat("int f() {\n" 12740 " return 42;\n" 12741 "}", 12742 MergeInlineOnly); 12743 12744 // SFS_Inline implies SFS_Empty 12745 verifyFormat("class C {\n" 12746 " int f() {}\n" 12747 "};", 12748 MergeInlineOnly); 12749 verifyFormat("int f() {}", MergeInlineOnly); 12750 // https://llvm.org/PR54147 12751 verifyFormat("auto lambda = []() {\n" 12752 " // comment\n" 12753 " f();\n" 12754 " g();\n" 12755 "};", 12756 MergeInlineOnly); 12757 12758 // Also verify behavior when BraceWrapping.AfterFunction = true 12759 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12760 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12761 verifyFormat("class C {\n" 12762 " int f() { return 42; }\n" 12763 "};", 12764 MergeInlineOnly); 12765 verifyFormat("int f()\n" 12766 "{\n" 12767 " return 42;\n" 12768 "}", 12769 MergeInlineOnly); 12770 12771 // SFS_Inline implies SFS_Empty 12772 verifyFormat("int f() {}", MergeInlineOnly); 12773 verifyFormat("class C {\n" 12774 " int f() {}\n" 12775 "};", 12776 MergeInlineOnly); 12777 12778 MergeInlineOnly.BraceWrapping.AfterClass = true; 12779 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12780 verifyFormat("class C\n" 12781 "{\n" 12782 " int f() { return 42; }\n" 12783 "};", 12784 MergeInlineOnly); 12785 verifyFormat("struct C\n" 12786 "{\n" 12787 " int f() { return 42; }\n" 12788 "};", 12789 MergeInlineOnly); 12790 verifyFormat("int f()\n" 12791 "{\n" 12792 " return 42;\n" 12793 "}", 12794 MergeInlineOnly); 12795 verifyFormat("int f() {}", MergeInlineOnly); 12796 verifyFormat("class C\n" 12797 "{\n" 12798 " int f() { return 42; }\n" 12799 "};", 12800 MergeInlineOnly); 12801 verifyFormat("struct C\n" 12802 "{\n" 12803 " int f() { return 42; }\n" 12804 "};", 12805 MergeInlineOnly); 12806 verifyFormat("struct C\n" 12807 "// comment\n" 12808 "/* comment */\n" 12809 "// comment\n" 12810 "{\n" 12811 " int f() { return 42; }\n" 12812 "};", 12813 MergeInlineOnly); 12814 verifyFormat("/* comment */ struct C\n" 12815 "{\n" 12816 " int f() { return 42; }\n" 12817 "};", 12818 MergeInlineOnly); 12819 } 12820 12821 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12822 FormatStyle MergeInlineOnly = getLLVMStyle(); 12823 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12824 FormatStyle::SFS_InlineOnly; 12825 verifyFormat("class C {\n" 12826 " int f() { return 42; }\n" 12827 "};", 12828 MergeInlineOnly); 12829 verifyFormat("int f() {\n" 12830 " return 42;\n" 12831 "}", 12832 MergeInlineOnly); 12833 12834 // SFS_InlineOnly does not imply SFS_Empty 12835 verifyFormat("class C {\n" 12836 " int f() {}\n" 12837 "};", 12838 MergeInlineOnly); 12839 verifyFormat("int f() {\n" 12840 "}", 12841 MergeInlineOnly); 12842 12843 // Also verify behavior when BraceWrapping.AfterFunction = true 12844 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12845 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12846 verifyFormat("class C {\n" 12847 " int f() { return 42; }\n" 12848 "};", 12849 MergeInlineOnly); 12850 verifyFormat("int f()\n" 12851 "{\n" 12852 " return 42;\n" 12853 "}", 12854 MergeInlineOnly); 12855 12856 // SFS_InlineOnly does not imply SFS_Empty 12857 verifyFormat("int f()\n" 12858 "{\n" 12859 "}", 12860 MergeInlineOnly); 12861 verifyFormat("class C {\n" 12862 " int f() {}\n" 12863 "};", 12864 MergeInlineOnly); 12865 } 12866 12867 TEST_F(FormatTest, SplitEmptyFunction) { 12868 FormatStyle Style = getLLVMStyleWithColumns(40); 12869 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12870 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12871 Style.BraceWrapping.AfterFunction = true; 12872 Style.BraceWrapping.SplitEmptyFunction = false; 12873 12874 verifyFormat("int f()\n" 12875 "{}", 12876 Style); 12877 verifyFormat("int f()\n" 12878 "{\n" 12879 " return 42;\n" 12880 "}", 12881 Style); 12882 verifyFormat("int f()\n" 12883 "{\n" 12884 " // some comment\n" 12885 "}", 12886 Style); 12887 12888 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12889 verifyFormat("int f() {}", Style); 12890 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12891 "{}", 12892 Style); 12893 verifyFormat("int f()\n" 12894 "{\n" 12895 " return 0;\n" 12896 "}", 12897 Style); 12898 12899 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12900 verifyFormat("class Foo {\n" 12901 " int f() {}\n" 12902 "};\n", 12903 Style); 12904 verifyFormat("class Foo {\n" 12905 " int f() { return 0; }\n" 12906 "};\n", 12907 Style); 12908 verifyFormat("class Foo {\n" 12909 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12910 " {}\n" 12911 "};\n", 12912 Style); 12913 verifyFormat("class Foo {\n" 12914 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12915 " {\n" 12916 " return 0;\n" 12917 " }\n" 12918 "};\n", 12919 Style); 12920 12921 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12922 verifyFormat("int f() {}", Style); 12923 verifyFormat("int f() { return 0; }", Style); 12924 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12925 "{}", 12926 Style); 12927 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12928 "{\n" 12929 " return 0;\n" 12930 "}", 12931 Style); 12932 } 12933 12934 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12935 FormatStyle Style = getLLVMStyleWithColumns(40); 12936 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12937 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12938 Style.BraceWrapping.AfterFunction = true; 12939 Style.BraceWrapping.SplitEmptyFunction = true; 12940 Style.BraceWrapping.SplitEmptyRecord = false; 12941 12942 verifyFormat("class C {};", Style); 12943 verifyFormat("struct C {};", Style); 12944 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12945 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12946 "{\n" 12947 "}", 12948 Style); 12949 verifyFormat("class C {\n" 12950 " C()\n" 12951 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12952 " bbbbbbbbbbbbbbbbbbb()\n" 12953 " {\n" 12954 " }\n" 12955 " void\n" 12956 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12957 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12958 " {\n" 12959 " }\n" 12960 "};", 12961 Style); 12962 } 12963 12964 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12965 FormatStyle Style = getLLVMStyle(); 12966 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12967 verifyFormat("#ifdef A\n" 12968 "int f() {}\n" 12969 "#else\n" 12970 "int g() {}\n" 12971 "#endif", 12972 Style); 12973 } 12974 12975 TEST_F(FormatTest, SplitEmptyClass) { 12976 FormatStyle Style = getLLVMStyle(); 12977 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12978 Style.BraceWrapping.AfterClass = true; 12979 Style.BraceWrapping.SplitEmptyRecord = false; 12980 12981 verifyFormat("class Foo\n" 12982 "{};", 12983 Style); 12984 verifyFormat("/* something */ class Foo\n" 12985 "{};", 12986 Style); 12987 verifyFormat("template <typename X> class Foo\n" 12988 "{};", 12989 Style); 12990 verifyFormat("class Foo\n" 12991 "{\n" 12992 " Foo();\n" 12993 "};", 12994 Style); 12995 verifyFormat("typedef class Foo\n" 12996 "{\n" 12997 "} Foo_t;", 12998 Style); 12999 13000 Style.BraceWrapping.SplitEmptyRecord = true; 13001 Style.BraceWrapping.AfterStruct = true; 13002 verifyFormat("class rep\n" 13003 "{\n" 13004 "};", 13005 Style); 13006 verifyFormat("struct rep\n" 13007 "{\n" 13008 "};", 13009 Style); 13010 verifyFormat("template <typename T> class rep\n" 13011 "{\n" 13012 "};", 13013 Style); 13014 verifyFormat("template <typename T> struct rep\n" 13015 "{\n" 13016 "};", 13017 Style); 13018 verifyFormat("class rep\n" 13019 "{\n" 13020 " int x;\n" 13021 "};", 13022 Style); 13023 verifyFormat("struct rep\n" 13024 "{\n" 13025 " int x;\n" 13026 "};", 13027 Style); 13028 verifyFormat("template <typename T> class rep\n" 13029 "{\n" 13030 " int x;\n" 13031 "};", 13032 Style); 13033 verifyFormat("template <typename T> struct rep\n" 13034 "{\n" 13035 " int x;\n" 13036 "};", 13037 Style); 13038 verifyFormat("template <typename T> class rep // Foo\n" 13039 "{\n" 13040 " int x;\n" 13041 "};", 13042 Style); 13043 verifyFormat("template <typename T> struct rep // Bar\n" 13044 "{\n" 13045 " int x;\n" 13046 "};", 13047 Style); 13048 13049 verifyFormat("template <typename T> class rep<T>\n" 13050 "{\n" 13051 " int x;\n" 13052 "};", 13053 Style); 13054 13055 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13056 "{\n" 13057 " int x;\n" 13058 "};", 13059 Style); 13060 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13061 "{\n" 13062 "};", 13063 Style); 13064 13065 verifyFormat("#include \"stdint.h\"\n" 13066 "namespace rep {}", 13067 Style); 13068 verifyFormat("#include <stdint.h>\n" 13069 "namespace rep {}", 13070 Style); 13071 verifyFormat("#include <stdint.h>\n" 13072 "namespace rep {}", 13073 "#include <stdint.h>\n" 13074 "namespace rep {\n" 13075 "\n" 13076 "\n" 13077 "}", 13078 Style); 13079 } 13080 13081 TEST_F(FormatTest, SplitEmptyStruct) { 13082 FormatStyle Style = getLLVMStyle(); 13083 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13084 Style.BraceWrapping.AfterStruct = true; 13085 Style.BraceWrapping.SplitEmptyRecord = false; 13086 13087 verifyFormat("struct Foo\n" 13088 "{};", 13089 Style); 13090 verifyFormat("/* something */ struct Foo\n" 13091 "{};", 13092 Style); 13093 verifyFormat("template <typename X> struct Foo\n" 13094 "{};", 13095 Style); 13096 verifyFormat("struct Foo\n" 13097 "{\n" 13098 " Foo();\n" 13099 "};", 13100 Style); 13101 verifyFormat("typedef struct Foo\n" 13102 "{\n" 13103 "} Foo_t;", 13104 Style); 13105 // typedef struct Bar {} Bar_t; 13106 } 13107 13108 TEST_F(FormatTest, SplitEmptyUnion) { 13109 FormatStyle Style = getLLVMStyle(); 13110 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13111 Style.BraceWrapping.AfterUnion = true; 13112 Style.BraceWrapping.SplitEmptyRecord = false; 13113 13114 verifyFormat("union Foo\n" 13115 "{};", 13116 Style); 13117 verifyFormat("/* something */ union Foo\n" 13118 "{};", 13119 Style); 13120 verifyFormat("union Foo\n" 13121 "{\n" 13122 " A,\n" 13123 "};", 13124 Style); 13125 verifyFormat("typedef union Foo\n" 13126 "{\n" 13127 "} Foo_t;", 13128 Style); 13129 } 13130 13131 TEST_F(FormatTest, SplitEmptyNamespace) { 13132 FormatStyle Style = getLLVMStyle(); 13133 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13134 Style.BraceWrapping.AfterNamespace = true; 13135 Style.BraceWrapping.SplitEmptyNamespace = false; 13136 13137 verifyFormat("namespace Foo\n" 13138 "{};", 13139 Style); 13140 verifyFormat("/* something */ namespace Foo\n" 13141 "{};", 13142 Style); 13143 verifyFormat("inline namespace Foo\n" 13144 "{};", 13145 Style); 13146 verifyFormat("/* something */ inline namespace Foo\n" 13147 "{};", 13148 Style); 13149 verifyFormat("export namespace Foo\n" 13150 "{};", 13151 Style); 13152 verifyFormat("namespace Foo\n" 13153 "{\n" 13154 "void Bar();\n" 13155 "};", 13156 Style); 13157 } 13158 13159 TEST_F(FormatTest, NeverMergeShortRecords) { 13160 FormatStyle Style = getLLVMStyle(); 13161 13162 verifyFormat("class Foo {\n" 13163 " Foo();\n" 13164 "};", 13165 Style); 13166 verifyFormat("typedef class Foo {\n" 13167 " Foo();\n" 13168 "} Foo_t;", 13169 Style); 13170 verifyFormat("struct Foo {\n" 13171 " Foo();\n" 13172 "};", 13173 Style); 13174 verifyFormat("typedef struct Foo {\n" 13175 " Foo();\n" 13176 "} Foo_t;", 13177 Style); 13178 verifyFormat("union Foo {\n" 13179 " A,\n" 13180 "};", 13181 Style); 13182 verifyFormat("typedef union Foo {\n" 13183 " A,\n" 13184 "} Foo_t;", 13185 Style); 13186 verifyFormat("namespace Foo {\n" 13187 "void Bar();\n" 13188 "};", 13189 Style); 13190 13191 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13192 Style.BraceWrapping.AfterClass = true; 13193 Style.BraceWrapping.AfterStruct = true; 13194 Style.BraceWrapping.AfterUnion = true; 13195 Style.BraceWrapping.AfterNamespace = true; 13196 verifyFormat("class Foo\n" 13197 "{\n" 13198 " Foo();\n" 13199 "};", 13200 Style); 13201 verifyFormat("typedef class Foo\n" 13202 "{\n" 13203 " Foo();\n" 13204 "} Foo_t;", 13205 Style); 13206 verifyFormat("struct Foo\n" 13207 "{\n" 13208 " Foo();\n" 13209 "};", 13210 Style); 13211 verifyFormat("typedef struct Foo\n" 13212 "{\n" 13213 " Foo();\n" 13214 "} Foo_t;", 13215 Style); 13216 verifyFormat("union Foo\n" 13217 "{\n" 13218 " A,\n" 13219 "};", 13220 Style); 13221 verifyFormat("typedef union Foo\n" 13222 "{\n" 13223 " A,\n" 13224 "} Foo_t;", 13225 Style); 13226 verifyFormat("namespace Foo\n" 13227 "{\n" 13228 "void Bar();\n" 13229 "};", 13230 Style); 13231 } 13232 13233 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13234 // Elaborate type variable declarations. 13235 verifyFormat("struct foo a = {bar};\nint n;"); 13236 verifyFormat("class foo a = {bar};\nint n;"); 13237 verifyFormat("union foo a = {bar};\nint n;"); 13238 13239 // Elaborate types inside function definitions. 13240 verifyFormat("struct foo f() {}\nint n;"); 13241 verifyFormat("class foo f() {}\nint n;"); 13242 verifyFormat("union foo f() {}\nint n;"); 13243 13244 // Templates. 13245 verifyFormat("template <class X> void f() {}\nint n;"); 13246 verifyFormat("template <struct X> void f() {}\nint n;"); 13247 verifyFormat("template <union X> void f() {}\nint n;"); 13248 13249 // Actual definitions... 13250 verifyFormat("struct {\n} n;"); 13251 verifyFormat( 13252 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13253 verifyFormat("union Z {\n int n;\n} x;"); 13254 verifyFormat("class MACRO Z {\n} n;"); 13255 verifyFormat("class MACRO(X) Z {\n} n;"); 13256 verifyFormat("class __attribute__(X) Z {\n} n;"); 13257 verifyFormat("class __declspec(X) Z {\n} n;"); 13258 verifyFormat("class A##B##C {\n} n;"); 13259 verifyFormat("class alignas(16) Z {\n} n;"); 13260 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13261 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13262 13263 // Redefinition from nested context: 13264 verifyFormat("class A::B::C {\n} n;"); 13265 13266 // Template definitions. 13267 verifyFormat( 13268 "template <typename F>\n" 13269 "Matcher(const Matcher<F> &Other,\n" 13270 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13271 " !is_same<F, T>::value>::type * = 0)\n" 13272 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13273 13274 // FIXME: This is still incorrectly handled at the formatter side. 13275 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13276 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13277 13278 // FIXME: 13279 // This now gets parsed incorrectly as class definition. 13280 // verifyFormat("class A<int> f() {\n}\nint n;"); 13281 13282 // Elaborate types where incorrectly parsing the structural element would 13283 // break the indent. 13284 verifyFormat("if (true)\n" 13285 " class X x;\n" 13286 "else\n" 13287 " f();\n"); 13288 13289 // This is simply incomplete. Formatting is not important, but must not crash. 13290 verifyFormat("class A:"); 13291 } 13292 13293 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13294 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13295 format("#error Leave all white!!!!! space* alone!\n")); 13296 EXPECT_EQ( 13297 "#warning Leave all white!!!!! space* alone!\n", 13298 format("#warning Leave all white!!!!! space* alone!\n")); 13299 EXPECT_EQ("#error 1", format(" # error 1")); 13300 EXPECT_EQ("#warning 1", format(" # warning 1")); 13301 } 13302 13303 TEST_F(FormatTest, FormatHashIfExpressions) { 13304 verifyFormat("#if AAAA && BBBB"); 13305 verifyFormat("#if (AAAA && BBBB)"); 13306 verifyFormat("#elif (AAAA && BBBB)"); 13307 // FIXME: Come up with a better indentation for #elif. 13308 verifyFormat( 13309 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13310 " defined(BBBBBBBB)\n" 13311 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13312 " defined(BBBBBBBB)\n" 13313 "#endif", 13314 getLLVMStyleWithColumns(65)); 13315 } 13316 13317 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13318 FormatStyle AllowsMergedIf = getGoogleStyle(); 13319 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13320 FormatStyle::SIS_WithoutElse; 13321 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13322 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13323 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13324 EXPECT_EQ("if (true) return 42;", 13325 format("if (true)\nreturn 42;", AllowsMergedIf)); 13326 FormatStyle ShortMergedIf = AllowsMergedIf; 13327 ShortMergedIf.ColumnLimit = 25; 13328 verifyFormat("#define A \\\n" 13329 " if (true) return 42;", 13330 ShortMergedIf); 13331 verifyFormat("#define A \\\n" 13332 " f(); \\\n" 13333 " if (true)\n" 13334 "#define B", 13335 ShortMergedIf); 13336 verifyFormat("#define A \\\n" 13337 " f(); \\\n" 13338 " if (true)\n" 13339 "g();", 13340 ShortMergedIf); 13341 verifyFormat("{\n" 13342 "#ifdef A\n" 13343 " // Comment\n" 13344 " if (true) continue;\n" 13345 "#endif\n" 13346 " // Comment\n" 13347 " if (true) continue;\n" 13348 "}", 13349 ShortMergedIf); 13350 ShortMergedIf.ColumnLimit = 33; 13351 verifyFormat("#define A \\\n" 13352 " if constexpr (true) return 42;", 13353 ShortMergedIf); 13354 verifyFormat("#define A \\\n" 13355 " if CONSTEXPR (true) return 42;", 13356 ShortMergedIf); 13357 ShortMergedIf.ColumnLimit = 29; 13358 verifyFormat("#define A \\\n" 13359 " if (aaaaaaaaaa) return 1; \\\n" 13360 " return 2;", 13361 ShortMergedIf); 13362 ShortMergedIf.ColumnLimit = 28; 13363 verifyFormat("#define A \\\n" 13364 " if (aaaaaaaaaa) \\\n" 13365 " return 1; \\\n" 13366 " return 2;", 13367 ShortMergedIf); 13368 verifyFormat("#define A \\\n" 13369 " if constexpr (aaaaaaa) \\\n" 13370 " return 1; \\\n" 13371 " return 2;", 13372 ShortMergedIf); 13373 verifyFormat("#define A \\\n" 13374 " if CONSTEXPR (aaaaaaa) \\\n" 13375 " return 1; \\\n" 13376 " return 2;", 13377 ShortMergedIf); 13378 } 13379 13380 TEST_F(FormatTest, FormatStarDependingOnContext) { 13381 verifyFormat("void f(int *a);"); 13382 verifyFormat("void f() { f(fint * b); }"); 13383 verifyFormat("class A {\n void f(int *a);\n};"); 13384 verifyFormat("class A {\n int *a;\n};"); 13385 verifyFormat("namespace a {\n" 13386 "namespace b {\n" 13387 "class A {\n" 13388 " void f() {}\n" 13389 " int *a;\n" 13390 "};\n" 13391 "} // namespace b\n" 13392 "} // namespace a"); 13393 } 13394 13395 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13396 verifyFormat("while"); 13397 verifyFormat("operator"); 13398 } 13399 13400 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13401 // This code would be painfully slow to format if we didn't skip it. 13402 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 13403 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13404 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13405 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13406 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13407 "A(1, 1)\n" 13408 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13409 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13410 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13411 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13412 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13413 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13414 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13415 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13416 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13417 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13418 // Deeply nested part is untouched, rest is formatted. 13419 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13420 format(std::string("int i;\n") + Code + "int j;\n", 13421 getLLVMStyle(), SC_ExpectIncomplete)); 13422 } 13423 13424 //===----------------------------------------------------------------------===// 13425 // Objective-C tests. 13426 //===----------------------------------------------------------------------===// 13427 13428 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13429 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13430 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13431 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13432 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13433 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13434 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13435 format("-(NSInteger)Method3:(id)anObject;")); 13436 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13437 format("-(NSInteger)Method4:(id)anObject;")); 13438 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13439 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13440 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13441 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13442 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13443 "forAllCells:(BOOL)flag;", 13444 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13445 "forAllCells:(BOOL)flag;")); 13446 13447 // Very long objectiveC method declaration. 13448 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13449 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13450 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13451 " inRange:(NSRange)range\n" 13452 " outRange:(NSRange)out_range\n" 13453 " outRange1:(NSRange)out_range1\n" 13454 " outRange2:(NSRange)out_range2\n" 13455 " outRange3:(NSRange)out_range3\n" 13456 " outRange4:(NSRange)out_range4\n" 13457 " outRange5:(NSRange)out_range5\n" 13458 " outRange6:(NSRange)out_range6\n" 13459 " outRange7:(NSRange)out_range7\n" 13460 " outRange8:(NSRange)out_range8\n" 13461 " outRange9:(NSRange)out_range9;"); 13462 13463 // When the function name has to be wrapped. 13464 FormatStyle Style = getLLVMStyle(); 13465 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13466 // and always indents instead. 13467 Style.IndentWrappedFunctionNames = false; 13468 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13469 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13470 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13471 "}", 13472 Style); 13473 Style.IndentWrappedFunctionNames = true; 13474 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13475 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13476 " anotherName:(NSString)dddddddddddddd {\n" 13477 "}", 13478 Style); 13479 13480 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13481 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13482 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13483 // protocol lists (but not for template classes): 13484 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13485 13486 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13487 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13488 13489 // If there's no return type (very rare in practice!), LLVM and Google style 13490 // agree. 13491 verifyFormat("- foo;"); 13492 verifyFormat("- foo:(int)f;"); 13493 verifyGoogleFormat("- foo:(int)foo;"); 13494 } 13495 13496 TEST_F(FormatTest, BreaksStringLiterals) { 13497 EXPECT_EQ("\"some text \"\n" 13498 "\"other\";", 13499 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13500 EXPECT_EQ("\"some text \"\n" 13501 "\"other\";", 13502 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13503 EXPECT_EQ( 13504 "#define A \\\n" 13505 " \"some \" \\\n" 13506 " \"text \" \\\n" 13507 " \"other\";", 13508 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13509 EXPECT_EQ( 13510 "#define A \\\n" 13511 " \"so \" \\\n" 13512 " \"text \" \\\n" 13513 " \"other\";", 13514 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13515 13516 EXPECT_EQ("\"some text\"", 13517 format("\"some text\"", getLLVMStyleWithColumns(1))); 13518 EXPECT_EQ("\"some text\"", 13519 format("\"some text\"", getLLVMStyleWithColumns(11))); 13520 EXPECT_EQ("\"some \"\n" 13521 "\"text\"", 13522 format("\"some text\"", getLLVMStyleWithColumns(10))); 13523 EXPECT_EQ("\"some \"\n" 13524 "\"text\"", 13525 format("\"some text\"", getLLVMStyleWithColumns(7))); 13526 EXPECT_EQ("\"some\"\n" 13527 "\" tex\"\n" 13528 "\"t\"", 13529 format("\"some text\"", getLLVMStyleWithColumns(6))); 13530 EXPECT_EQ("\"some\"\n" 13531 "\" tex\"\n" 13532 "\" and\"", 13533 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13534 EXPECT_EQ("\"some\"\n" 13535 "\"/tex\"\n" 13536 "\"/and\"", 13537 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13538 13539 EXPECT_EQ("variable =\n" 13540 " \"long string \"\n" 13541 " \"literal\";", 13542 format("variable = \"long string literal\";", 13543 getLLVMStyleWithColumns(20))); 13544 13545 EXPECT_EQ("variable = f(\n" 13546 " \"long string \"\n" 13547 " \"literal\",\n" 13548 " short,\n" 13549 " loooooooooooooooooooong);", 13550 format("variable = f(\"long string literal\", short, " 13551 "loooooooooooooooooooong);", 13552 getLLVMStyleWithColumns(20))); 13553 13554 EXPECT_EQ( 13555 "f(g(\"long string \"\n" 13556 " \"literal\"),\n" 13557 " b);", 13558 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13559 EXPECT_EQ("f(g(\"long string \"\n" 13560 " \"literal\",\n" 13561 " a),\n" 13562 " b);", 13563 format("f(g(\"long string literal\", a), b);", 13564 getLLVMStyleWithColumns(20))); 13565 EXPECT_EQ( 13566 "f(\"one two\".split(\n" 13567 " variable));", 13568 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13569 EXPECT_EQ("f(\"one two three four five six \"\n" 13570 " \"seven\".split(\n" 13571 " really_looooong_variable));", 13572 format("f(\"one two three four five six seven\"." 13573 "split(really_looooong_variable));", 13574 getLLVMStyleWithColumns(33))); 13575 13576 EXPECT_EQ("f(\"some \"\n" 13577 " \"text\",\n" 13578 " other);", 13579 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13580 13581 // Only break as a last resort. 13582 verifyFormat( 13583 "aaaaaaaaaaaaaaaaaaaa(\n" 13584 " aaaaaaaaaaaaaaaaaaaa,\n" 13585 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13586 13587 EXPECT_EQ("\"splitmea\"\n" 13588 "\"trandomp\"\n" 13589 "\"oint\"", 13590 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13591 13592 EXPECT_EQ("\"split/\"\n" 13593 "\"pathat/\"\n" 13594 "\"slashes\"", 13595 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13596 13597 EXPECT_EQ("\"split/\"\n" 13598 "\"pathat/\"\n" 13599 "\"slashes\"", 13600 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13601 EXPECT_EQ("\"split at \"\n" 13602 "\"spaces/at/\"\n" 13603 "\"slashes.at.any$\"\n" 13604 "\"non-alphanumeric%\"\n" 13605 "\"1111111111characte\"\n" 13606 "\"rs\"", 13607 format("\"split at " 13608 "spaces/at/" 13609 "slashes.at." 13610 "any$non-" 13611 "alphanumeric%" 13612 "1111111111characte" 13613 "rs\"", 13614 getLLVMStyleWithColumns(20))); 13615 13616 // Verify that splitting the strings understands 13617 // Style::AlwaysBreakBeforeMultilineStrings. 13618 EXPECT_EQ("aaaaaaaaaaaa(\n" 13619 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13620 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13621 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13622 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13623 "aaaaaaaaaaaaaaaaaaaaaa\");", 13624 getGoogleStyle())); 13625 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13626 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13627 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13628 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13629 "aaaaaaaaaaaaaaaaaaaaaa\";", 13630 getGoogleStyle())); 13631 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13632 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13633 format("llvm::outs() << " 13634 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13635 "aaaaaaaaaaaaaaaaaaa\";")); 13636 EXPECT_EQ("ffff(\n" 13637 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13638 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13639 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13640 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13641 getGoogleStyle())); 13642 13643 FormatStyle Style = getLLVMStyleWithColumns(12); 13644 Style.BreakStringLiterals = false; 13645 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13646 13647 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13648 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13649 EXPECT_EQ("#define A \\\n" 13650 " \"some \" \\\n" 13651 " \"text \" \\\n" 13652 " \"other\";", 13653 format("#define A \"some text other\";", AlignLeft)); 13654 } 13655 13656 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13657 EXPECT_EQ("C a = \"some more \"\n" 13658 " \"text\";", 13659 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13660 } 13661 13662 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13663 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13664 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13665 EXPECT_EQ("int i = a(b());", 13666 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13667 } 13668 13669 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13670 EXPECT_EQ( 13671 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13672 "(\n" 13673 " \"x\t\");", 13674 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13675 "aaaaaaa(" 13676 "\"x\t\");")); 13677 } 13678 13679 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13680 EXPECT_EQ( 13681 "u8\"utf8 string \"\n" 13682 "u8\"literal\";", 13683 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13684 EXPECT_EQ( 13685 "u\"utf16 string \"\n" 13686 "u\"literal\";", 13687 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13688 EXPECT_EQ( 13689 "U\"utf32 string \"\n" 13690 "U\"literal\";", 13691 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13692 EXPECT_EQ("L\"wide string \"\n" 13693 "L\"literal\";", 13694 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13695 EXPECT_EQ("@\"NSString \"\n" 13696 "@\"literal\";", 13697 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13698 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13699 13700 // This input makes clang-format try to split the incomplete unicode escape 13701 // sequence, which used to lead to a crasher. 13702 verifyNoCrash( 13703 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13704 getLLVMStyleWithColumns(60)); 13705 } 13706 13707 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13708 FormatStyle Style = getGoogleStyleWithColumns(15); 13709 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13710 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13711 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13712 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13713 EXPECT_EQ("u8R\"x(raw literal)x\";", 13714 format("u8R\"x(raw literal)x\";", Style)); 13715 } 13716 13717 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13718 FormatStyle Style = getLLVMStyleWithColumns(20); 13719 EXPECT_EQ( 13720 "_T(\"aaaaaaaaaaaaaa\")\n" 13721 "_T(\"aaaaaaaaaaaaaa\")\n" 13722 "_T(\"aaaaaaaaaaaa\")", 13723 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13724 EXPECT_EQ("f(x,\n" 13725 " _T(\"aaaaaaaaaaaa\")\n" 13726 " _T(\"aaa\"),\n" 13727 " z);", 13728 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13729 13730 // FIXME: Handle embedded spaces in one iteration. 13731 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13732 // "_T(\"aaaaaaaaaaaaa\")\n" 13733 // "_T(\"aaaaaaaaaaaaa\")\n" 13734 // "_T(\"a\")", 13735 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13736 // getLLVMStyleWithColumns(20))); 13737 EXPECT_EQ( 13738 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13739 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13740 EXPECT_EQ("f(\n" 13741 "#if !TEST\n" 13742 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13743 "#endif\n" 13744 ");", 13745 format("f(\n" 13746 "#if !TEST\n" 13747 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13748 "#endif\n" 13749 ");")); 13750 EXPECT_EQ("f(\n" 13751 "\n" 13752 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13753 format("f(\n" 13754 "\n" 13755 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13756 // Regression test for accessing tokens past the end of a vector in the 13757 // TokenLexer. 13758 verifyNoCrash(R"(_T( 13759 " 13760 ) 13761 )"); 13762 } 13763 13764 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13765 // In a function call with two operands, the second can be broken with no line 13766 // break before it. 13767 EXPECT_EQ( 13768 "func(a, \"long long \"\n" 13769 " \"long long\");", 13770 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13771 // In a function call with three operands, the second must be broken with a 13772 // line break before it. 13773 EXPECT_EQ("func(a,\n" 13774 " \"long long long \"\n" 13775 " \"long\",\n" 13776 " c);", 13777 format("func(a, \"long long long long\", c);", 13778 getLLVMStyleWithColumns(24))); 13779 // In a function call with three operands, the third must be broken with a 13780 // line break before it. 13781 EXPECT_EQ("func(a, b,\n" 13782 " \"long long long \"\n" 13783 " \"long\");", 13784 format("func(a, b, \"long long long long\");", 13785 getLLVMStyleWithColumns(24))); 13786 // In a function call with three operands, both the second and the third must 13787 // be broken with a line break before them. 13788 EXPECT_EQ("func(a,\n" 13789 " \"long long long \"\n" 13790 " \"long\",\n" 13791 " \"long long long \"\n" 13792 " \"long\");", 13793 format("func(a, \"long long long long\", \"long long long long\");", 13794 getLLVMStyleWithColumns(24))); 13795 // In a chain of << with two operands, the second can be broken with no line 13796 // break before it. 13797 EXPECT_EQ("a << \"line line \"\n" 13798 " \"line\";", 13799 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13800 // In a chain of << with three operands, the second can be broken with no line 13801 // break before it. 13802 EXPECT_EQ( 13803 "abcde << \"line \"\n" 13804 " \"line line\"\n" 13805 " << c;", 13806 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13807 // In a chain of << with three operands, the third must be broken with a line 13808 // break before it. 13809 EXPECT_EQ( 13810 "a << b\n" 13811 " << \"line line \"\n" 13812 " \"line\";", 13813 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13814 // In a chain of << with three operands, the second can be broken with no line 13815 // break before it and the third must be broken with a line break before it. 13816 EXPECT_EQ("abcd << \"line line \"\n" 13817 " \"line\"\n" 13818 " << \"line line \"\n" 13819 " \"line\";", 13820 format("abcd << \"line line line\" << \"line line line\";", 13821 getLLVMStyleWithColumns(20))); 13822 // In a chain of binary operators with two operands, the second can be broken 13823 // with no line break before it. 13824 EXPECT_EQ( 13825 "abcd + \"line line \"\n" 13826 " \"line line\";", 13827 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13828 // In a chain of binary operators with three operands, the second must be 13829 // broken with a line break before it. 13830 EXPECT_EQ("abcd +\n" 13831 " \"line line \"\n" 13832 " \"line line\" +\n" 13833 " e;", 13834 format("abcd + \"line line line line\" + e;", 13835 getLLVMStyleWithColumns(20))); 13836 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13837 // the first must be broken with a line break before it. 13838 FormatStyle Style = getLLVMStyleWithColumns(25); 13839 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13840 EXPECT_EQ("someFunction(\n" 13841 " \"long long long \"\n" 13842 " \"long\",\n" 13843 " a);", 13844 format("someFunction(\"long long long long\", a);", Style)); 13845 } 13846 13847 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13848 EXPECT_EQ( 13849 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13850 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13851 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13852 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13853 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13855 } 13856 13857 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13858 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13859 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13860 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13861 "multiline raw string literal xxxxxxxxxxxxxx\n" 13862 ")x\",\n" 13863 " a),\n" 13864 " b);", 13865 format("fffffffffff(g(R\"x(\n" 13866 "multiline raw string literal xxxxxxxxxxxxxx\n" 13867 ")x\", a), b);", 13868 getGoogleStyleWithColumns(20))); 13869 EXPECT_EQ("fffffffffff(\n" 13870 " g(R\"x(qqq\n" 13871 "multiline raw string literal xxxxxxxxxxxxxx\n" 13872 ")x\",\n" 13873 " a),\n" 13874 " b);", 13875 format("fffffffffff(g(R\"x(qqq\n" 13876 "multiline raw string literal xxxxxxxxxxxxxx\n" 13877 ")x\", a), b);", 13878 getGoogleStyleWithColumns(20))); 13879 13880 EXPECT_EQ("fffffffffff(R\"x(\n" 13881 "multiline raw string literal xxxxxxxxxxxxxx\n" 13882 ")x\");", 13883 format("fffffffffff(R\"x(\n" 13884 "multiline raw string literal xxxxxxxxxxxxxx\n" 13885 ")x\");", 13886 getGoogleStyleWithColumns(20))); 13887 EXPECT_EQ("fffffffffff(R\"x(\n" 13888 "multiline raw string literal xxxxxxxxxxxxxx\n" 13889 ")x\" + bbbbbb);", 13890 format("fffffffffff(R\"x(\n" 13891 "multiline raw string literal xxxxxxxxxxxxxx\n" 13892 ")x\" + bbbbbb);", 13893 getGoogleStyleWithColumns(20))); 13894 EXPECT_EQ("fffffffffff(\n" 13895 " R\"x(\n" 13896 "multiline raw string literal xxxxxxxxxxxxxx\n" 13897 ")x\" +\n" 13898 " bbbbbb);", 13899 format("fffffffffff(\n" 13900 " R\"x(\n" 13901 "multiline raw string literal xxxxxxxxxxxxxx\n" 13902 ")x\" + bbbbbb);", 13903 getGoogleStyleWithColumns(20))); 13904 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13905 format("fffffffffff(\n" 13906 " R\"(single line raw string)\" + bbbbbb);")); 13907 } 13908 13909 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13910 verifyFormat("string a = \"unterminated;"); 13911 EXPECT_EQ("function(\"unterminated,\n" 13912 " OtherParameter);", 13913 format("function( \"unterminated,\n" 13914 " OtherParameter);")); 13915 } 13916 13917 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13918 FormatStyle Style = getLLVMStyle(); 13919 Style.Standard = FormatStyle::LS_Cpp03; 13920 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13921 format("#define x(_a) printf(\"foo\"_a);", Style)); 13922 } 13923 13924 TEST_F(FormatTest, CppLexVersion) { 13925 FormatStyle Style = getLLVMStyle(); 13926 // Formatting of x * y differs if x is a type. 13927 verifyFormat("void foo() { MACRO(a * b); }", Style); 13928 verifyFormat("void foo() { MACRO(int *b); }", Style); 13929 13930 // LLVM style uses latest lexer. 13931 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13932 Style.Standard = FormatStyle::LS_Cpp17; 13933 // But in c++17, char8_t isn't a keyword. 13934 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13935 } 13936 13937 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13938 13939 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13940 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13941 " \"ddeeefff\");", 13942 format("someFunction(\"aaabbbcccdddeeefff\");", 13943 getLLVMStyleWithColumns(25))); 13944 EXPECT_EQ("someFunction1234567890(\n" 13945 " \"aaabbbcccdddeeefff\");", 13946 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13947 getLLVMStyleWithColumns(26))); 13948 EXPECT_EQ("someFunction1234567890(\n" 13949 " \"aaabbbcccdddeeeff\"\n" 13950 " \"f\");", 13951 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13952 getLLVMStyleWithColumns(25))); 13953 EXPECT_EQ("someFunction1234567890(\n" 13954 " \"aaabbbcccdddeeeff\"\n" 13955 " \"f\");", 13956 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13957 getLLVMStyleWithColumns(24))); 13958 EXPECT_EQ("someFunction(\n" 13959 " \"aaabbbcc ddde \"\n" 13960 " \"efff\");", 13961 format("someFunction(\"aaabbbcc ddde efff\");", 13962 getLLVMStyleWithColumns(25))); 13963 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13964 " \"ddeeefff\");", 13965 format("someFunction(\"aaabbbccc ddeeefff\");", 13966 getLLVMStyleWithColumns(25))); 13967 EXPECT_EQ("someFunction1234567890(\n" 13968 " \"aaabb \"\n" 13969 " \"cccdddeeefff\");", 13970 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13971 getLLVMStyleWithColumns(25))); 13972 EXPECT_EQ("#define A \\\n" 13973 " string s = \\\n" 13974 " \"123456789\" \\\n" 13975 " \"0\"; \\\n" 13976 " int i;", 13977 format("#define A string s = \"1234567890\"; int i;", 13978 getLLVMStyleWithColumns(20))); 13979 EXPECT_EQ("someFunction(\n" 13980 " \"aaabbbcc \"\n" 13981 " \"dddeeefff\");", 13982 format("someFunction(\"aaabbbcc dddeeefff\");", 13983 getLLVMStyleWithColumns(25))); 13984 } 13985 13986 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13987 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13988 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13989 EXPECT_EQ("\"test\"\n" 13990 "\"\\n\"", 13991 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13992 EXPECT_EQ("\"tes\\\\\"\n" 13993 "\"n\"", 13994 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13995 EXPECT_EQ("\"\\\\\\\\\"\n" 13996 "\"\\n\"", 13997 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13998 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13999 EXPECT_EQ("\"\\uff01\"\n" 14000 "\"test\"", 14001 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14002 EXPECT_EQ("\"\\Uff01ff02\"", 14003 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14004 EXPECT_EQ("\"\\x000000000001\"\n" 14005 "\"next\"", 14006 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14007 EXPECT_EQ("\"\\x000000000001next\"", 14008 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14009 EXPECT_EQ("\"\\x000000000001\"", 14010 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14011 EXPECT_EQ("\"test\"\n" 14012 "\"\\000000\"\n" 14013 "\"000001\"", 14014 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14015 EXPECT_EQ("\"test\\000\"\n" 14016 "\"00000000\"\n" 14017 "\"1\"", 14018 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14019 } 14020 14021 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14022 verifyFormat("void f() {\n" 14023 " return g() {}\n" 14024 " void h() {}"); 14025 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14026 "g();\n" 14027 "}"); 14028 } 14029 14030 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14031 verifyFormat( 14032 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14033 } 14034 14035 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14036 verifyFormat("class X {\n" 14037 " void f() {\n" 14038 " }\n" 14039 "};", 14040 getLLVMStyleWithColumns(12)); 14041 } 14042 14043 TEST_F(FormatTest, ConfigurableIndentWidth) { 14044 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14045 EightIndent.IndentWidth = 8; 14046 EightIndent.ContinuationIndentWidth = 8; 14047 verifyFormat("void f() {\n" 14048 " someFunction();\n" 14049 " if (true) {\n" 14050 " f();\n" 14051 " }\n" 14052 "}", 14053 EightIndent); 14054 verifyFormat("class X {\n" 14055 " void f() {\n" 14056 " }\n" 14057 "};", 14058 EightIndent); 14059 verifyFormat("int x[] = {\n" 14060 " call(),\n" 14061 " call()};", 14062 EightIndent); 14063 } 14064 14065 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14066 verifyFormat("double\n" 14067 "f();", 14068 getLLVMStyleWithColumns(8)); 14069 } 14070 14071 TEST_F(FormatTest, ConfigurableUseOfTab) { 14072 FormatStyle Tab = getLLVMStyleWithColumns(42); 14073 Tab.IndentWidth = 8; 14074 Tab.UseTab = FormatStyle::UT_Always; 14075 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14076 14077 EXPECT_EQ("if (aaaaaaaa && // q\n" 14078 " bb)\t\t// w\n" 14079 "\t;", 14080 format("if (aaaaaaaa &&// q\n" 14081 "bb)// w\n" 14082 ";", 14083 Tab)); 14084 EXPECT_EQ("if (aaa && bbb) // w\n" 14085 "\t;", 14086 format("if(aaa&&bbb)// w\n" 14087 ";", 14088 Tab)); 14089 14090 verifyFormat("class X {\n" 14091 "\tvoid f() {\n" 14092 "\t\tsomeFunction(parameter1,\n" 14093 "\t\t\t parameter2);\n" 14094 "\t}\n" 14095 "};", 14096 Tab); 14097 verifyFormat("#define A \\\n" 14098 "\tvoid f() { \\\n" 14099 "\t\tsomeFunction( \\\n" 14100 "\t\t parameter1, \\\n" 14101 "\t\t parameter2); \\\n" 14102 "\t}", 14103 Tab); 14104 verifyFormat("int a;\t // x\n" 14105 "int bbbbbbbb; // x\n", 14106 Tab); 14107 14108 Tab.TabWidth = 4; 14109 Tab.IndentWidth = 8; 14110 verifyFormat("class TabWidth4Indent8 {\n" 14111 "\t\tvoid f() {\n" 14112 "\t\t\t\tsomeFunction(parameter1,\n" 14113 "\t\t\t\t\t\t\t parameter2);\n" 14114 "\t\t}\n" 14115 "};", 14116 Tab); 14117 14118 Tab.TabWidth = 4; 14119 Tab.IndentWidth = 4; 14120 verifyFormat("class TabWidth4Indent4 {\n" 14121 "\tvoid f() {\n" 14122 "\t\tsomeFunction(parameter1,\n" 14123 "\t\t\t\t\t parameter2);\n" 14124 "\t}\n" 14125 "};", 14126 Tab); 14127 14128 Tab.TabWidth = 8; 14129 Tab.IndentWidth = 4; 14130 verifyFormat("class TabWidth8Indent4 {\n" 14131 " void f() {\n" 14132 "\tsomeFunction(parameter1,\n" 14133 "\t\t parameter2);\n" 14134 " }\n" 14135 "};", 14136 Tab); 14137 14138 Tab.TabWidth = 8; 14139 Tab.IndentWidth = 8; 14140 EXPECT_EQ("/*\n" 14141 "\t a\t\tcomment\n" 14142 "\t in multiple lines\n" 14143 " */", 14144 format(" /*\t \t \n" 14145 " \t \t a\t\tcomment\t \t\n" 14146 " \t \t in multiple lines\t\n" 14147 " \t */", 14148 Tab)); 14149 14150 Tab.UseTab = FormatStyle::UT_ForIndentation; 14151 verifyFormat("{\n" 14152 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14153 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14154 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14155 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14156 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14157 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14158 "};", 14159 Tab); 14160 verifyFormat("enum AA {\n" 14161 "\ta1, // Force multiple lines\n" 14162 "\ta2,\n" 14163 "\ta3\n" 14164 "};", 14165 Tab); 14166 EXPECT_EQ("if (aaaaaaaa && // q\n" 14167 " bb) // w\n" 14168 "\t;", 14169 format("if (aaaaaaaa &&// q\n" 14170 "bb)// w\n" 14171 ";", 14172 Tab)); 14173 verifyFormat("class X {\n" 14174 "\tvoid f() {\n" 14175 "\t\tsomeFunction(parameter1,\n" 14176 "\t\t parameter2);\n" 14177 "\t}\n" 14178 "};", 14179 Tab); 14180 verifyFormat("{\n" 14181 "\tQ(\n" 14182 "\t {\n" 14183 "\t\t int a;\n" 14184 "\t\t someFunction(aaaaaaaa,\n" 14185 "\t\t bbbbbbb);\n" 14186 "\t },\n" 14187 "\t p);\n" 14188 "}", 14189 Tab); 14190 EXPECT_EQ("{\n" 14191 "\t/* aaaa\n" 14192 "\t bbbb */\n" 14193 "}", 14194 format("{\n" 14195 "/* aaaa\n" 14196 " bbbb */\n" 14197 "}", 14198 Tab)); 14199 EXPECT_EQ("{\n" 14200 "\t/*\n" 14201 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14202 "\t bbbbbbbbbbbbb\n" 14203 "\t*/\n" 14204 "}", 14205 format("{\n" 14206 "/*\n" 14207 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14208 "*/\n" 14209 "}", 14210 Tab)); 14211 EXPECT_EQ("{\n" 14212 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14213 "\t// bbbbbbbbbbbbb\n" 14214 "}", 14215 format("{\n" 14216 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14217 "}", 14218 Tab)); 14219 EXPECT_EQ("{\n" 14220 "\t/*\n" 14221 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14222 "\t bbbbbbbbbbbbb\n" 14223 "\t*/\n" 14224 "}", 14225 format("{\n" 14226 "\t/*\n" 14227 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14228 "\t*/\n" 14229 "}", 14230 Tab)); 14231 EXPECT_EQ("{\n" 14232 "\t/*\n" 14233 "\n" 14234 "\t*/\n" 14235 "}", 14236 format("{\n" 14237 "\t/*\n" 14238 "\n" 14239 "\t*/\n" 14240 "}", 14241 Tab)); 14242 EXPECT_EQ("{\n" 14243 "\t/*\n" 14244 " asdf\n" 14245 "\t*/\n" 14246 "}", 14247 format("{\n" 14248 "\t/*\n" 14249 " asdf\n" 14250 "\t*/\n" 14251 "}", 14252 Tab)); 14253 14254 verifyFormat("void f() {\n" 14255 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14256 "\t : bbbbbbbbbbbbbbbbbb\n" 14257 "}", 14258 Tab); 14259 FormatStyle TabNoBreak = Tab; 14260 TabNoBreak.BreakBeforeTernaryOperators = false; 14261 verifyFormat("void f() {\n" 14262 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14263 "\t bbbbbbbbbbbbbbbbbb\n" 14264 "}", 14265 TabNoBreak); 14266 verifyFormat("void f() {\n" 14267 "\treturn true ?\n" 14268 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14269 "\t bbbbbbbbbbbbbbbbbbbb\n" 14270 "}", 14271 TabNoBreak); 14272 14273 Tab.UseTab = FormatStyle::UT_Never; 14274 EXPECT_EQ("/*\n" 14275 " a\t\tcomment\n" 14276 " in multiple lines\n" 14277 " */", 14278 format(" /*\t \t \n" 14279 " \t \t a\t\tcomment\t \t\n" 14280 " \t \t in multiple lines\t\n" 14281 " \t */", 14282 Tab)); 14283 EXPECT_EQ("/* some\n" 14284 " comment */", 14285 format(" \t \t /* some\n" 14286 " \t \t comment */", 14287 Tab)); 14288 EXPECT_EQ("int a; /* some\n" 14289 " comment */", 14290 format(" \t \t int a; /* some\n" 14291 " \t \t comment */", 14292 Tab)); 14293 14294 EXPECT_EQ("int a; /* some\n" 14295 "comment */", 14296 format(" \t \t int\ta; /* some\n" 14297 " \t \t comment */", 14298 Tab)); 14299 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14300 " comment */", 14301 format(" \t \t f(\"\t\t\"); /* some\n" 14302 " \t \t comment */", 14303 Tab)); 14304 EXPECT_EQ("{\n" 14305 " /*\n" 14306 " * Comment\n" 14307 " */\n" 14308 " int i;\n" 14309 "}", 14310 format("{\n" 14311 "\t/*\n" 14312 "\t * Comment\n" 14313 "\t */\n" 14314 "\t int i;\n" 14315 "}", 14316 Tab)); 14317 14318 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14319 Tab.TabWidth = 8; 14320 Tab.IndentWidth = 8; 14321 EXPECT_EQ("if (aaaaaaaa && // q\n" 14322 " bb) // w\n" 14323 "\t;", 14324 format("if (aaaaaaaa &&// q\n" 14325 "bb)// w\n" 14326 ";", 14327 Tab)); 14328 EXPECT_EQ("if (aaa && bbb) // w\n" 14329 "\t;", 14330 format("if(aaa&&bbb)// w\n" 14331 ";", 14332 Tab)); 14333 verifyFormat("class X {\n" 14334 "\tvoid f() {\n" 14335 "\t\tsomeFunction(parameter1,\n" 14336 "\t\t\t parameter2);\n" 14337 "\t}\n" 14338 "};", 14339 Tab); 14340 verifyFormat("#define A \\\n" 14341 "\tvoid f() { \\\n" 14342 "\t\tsomeFunction( \\\n" 14343 "\t\t parameter1, \\\n" 14344 "\t\t parameter2); \\\n" 14345 "\t}", 14346 Tab); 14347 Tab.TabWidth = 4; 14348 Tab.IndentWidth = 8; 14349 verifyFormat("class TabWidth4Indent8 {\n" 14350 "\t\tvoid f() {\n" 14351 "\t\t\t\tsomeFunction(parameter1,\n" 14352 "\t\t\t\t\t\t\t parameter2);\n" 14353 "\t\t}\n" 14354 "};", 14355 Tab); 14356 Tab.TabWidth = 4; 14357 Tab.IndentWidth = 4; 14358 verifyFormat("class TabWidth4Indent4 {\n" 14359 "\tvoid f() {\n" 14360 "\t\tsomeFunction(parameter1,\n" 14361 "\t\t\t\t\t parameter2);\n" 14362 "\t}\n" 14363 "};", 14364 Tab); 14365 Tab.TabWidth = 8; 14366 Tab.IndentWidth = 4; 14367 verifyFormat("class TabWidth8Indent4 {\n" 14368 " void f() {\n" 14369 "\tsomeFunction(parameter1,\n" 14370 "\t\t parameter2);\n" 14371 " }\n" 14372 "};", 14373 Tab); 14374 Tab.TabWidth = 8; 14375 Tab.IndentWidth = 8; 14376 EXPECT_EQ("/*\n" 14377 "\t a\t\tcomment\n" 14378 "\t in multiple lines\n" 14379 " */", 14380 format(" /*\t \t \n" 14381 " \t \t a\t\tcomment\t \t\n" 14382 " \t \t in multiple lines\t\n" 14383 " \t */", 14384 Tab)); 14385 verifyFormat("{\n" 14386 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14387 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14388 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14389 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14390 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14391 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14392 "};", 14393 Tab); 14394 verifyFormat("enum AA {\n" 14395 "\ta1, // Force multiple lines\n" 14396 "\ta2,\n" 14397 "\ta3\n" 14398 "};", 14399 Tab); 14400 EXPECT_EQ("if (aaaaaaaa && // q\n" 14401 " bb) // w\n" 14402 "\t;", 14403 format("if (aaaaaaaa &&// q\n" 14404 "bb)// w\n" 14405 ";", 14406 Tab)); 14407 verifyFormat("class X {\n" 14408 "\tvoid f() {\n" 14409 "\t\tsomeFunction(parameter1,\n" 14410 "\t\t\t parameter2);\n" 14411 "\t}\n" 14412 "};", 14413 Tab); 14414 verifyFormat("{\n" 14415 "\tQ(\n" 14416 "\t {\n" 14417 "\t\t int a;\n" 14418 "\t\t someFunction(aaaaaaaa,\n" 14419 "\t\t\t\t bbbbbbb);\n" 14420 "\t },\n" 14421 "\t p);\n" 14422 "}", 14423 Tab); 14424 EXPECT_EQ("{\n" 14425 "\t/* aaaa\n" 14426 "\t bbbb */\n" 14427 "}", 14428 format("{\n" 14429 "/* aaaa\n" 14430 " bbbb */\n" 14431 "}", 14432 Tab)); 14433 EXPECT_EQ("{\n" 14434 "\t/*\n" 14435 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14436 "\t bbbbbbbbbbbbb\n" 14437 "\t*/\n" 14438 "}", 14439 format("{\n" 14440 "/*\n" 14441 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14442 "*/\n" 14443 "}", 14444 Tab)); 14445 EXPECT_EQ("{\n" 14446 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14447 "\t// bbbbbbbbbbbbb\n" 14448 "}", 14449 format("{\n" 14450 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14451 "}", 14452 Tab)); 14453 EXPECT_EQ("{\n" 14454 "\t/*\n" 14455 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14456 "\t bbbbbbbbbbbbb\n" 14457 "\t*/\n" 14458 "}", 14459 format("{\n" 14460 "\t/*\n" 14461 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14462 "\t*/\n" 14463 "}", 14464 Tab)); 14465 EXPECT_EQ("{\n" 14466 "\t/*\n" 14467 "\n" 14468 "\t*/\n" 14469 "}", 14470 format("{\n" 14471 "\t/*\n" 14472 "\n" 14473 "\t*/\n" 14474 "}", 14475 Tab)); 14476 EXPECT_EQ("{\n" 14477 "\t/*\n" 14478 " asdf\n" 14479 "\t*/\n" 14480 "}", 14481 format("{\n" 14482 "\t/*\n" 14483 " asdf\n" 14484 "\t*/\n" 14485 "}", 14486 Tab)); 14487 EXPECT_EQ("/* some\n" 14488 " comment */", 14489 format(" \t \t /* some\n" 14490 " \t \t comment */", 14491 Tab)); 14492 EXPECT_EQ("int a; /* some\n" 14493 " comment */", 14494 format(" \t \t int a; /* some\n" 14495 " \t \t comment */", 14496 Tab)); 14497 EXPECT_EQ("int a; /* some\n" 14498 "comment */", 14499 format(" \t \t int\ta; /* some\n" 14500 " \t \t comment */", 14501 Tab)); 14502 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14503 " comment */", 14504 format(" \t \t f(\"\t\t\"); /* some\n" 14505 " \t \t comment */", 14506 Tab)); 14507 EXPECT_EQ("{\n" 14508 "\t/*\n" 14509 "\t * Comment\n" 14510 "\t */\n" 14511 "\tint i;\n" 14512 "}", 14513 format("{\n" 14514 "\t/*\n" 14515 "\t * Comment\n" 14516 "\t */\n" 14517 "\t int i;\n" 14518 "}", 14519 Tab)); 14520 Tab.TabWidth = 2; 14521 Tab.IndentWidth = 2; 14522 EXPECT_EQ("{\n" 14523 "\t/* aaaa\n" 14524 "\t\t bbbb */\n" 14525 "}", 14526 format("{\n" 14527 "/* aaaa\n" 14528 "\t bbbb */\n" 14529 "}", 14530 Tab)); 14531 EXPECT_EQ("{\n" 14532 "\t/*\n" 14533 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14534 "\t\tbbbbbbbbbbbbb\n" 14535 "\t*/\n" 14536 "}", 14537 format("{\n" 14538 "/*\n" 14539 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14540 "*/\n" 14541 "}", 14542 Tab)); 14543 Tab.AlignConsecutiveAssignments.Enabled = true; 14544 Tab.AlignConsecutiveDeclarations.Enabled = true; 14545 Tab.TabWidth = 4; 14546 Tab.IndentWidth = 4; 14547 verifyFormat("class Assign {\n" 14548 "\tvoid f() {\n" 14549 "\t\tint x = 123;\n" 14550 "\t\tint random = 4;\n" 14551 "\t\tstd::string alphabet =\n" 14552 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14553 "\t}\n" 14554 "};", 14555 Tab); 14556 14557 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14558 Tab.TabWidth = 8; 14559 Tab.IndentWidth = 8; 14560 EXPECT_EQ("if (aaaaaaaa && // q\n" 14561 " bb) // w\n" 14562 "\t;", 14563 format("if (aaaaaaaa &&// q\n" 14564 "bb)// w\n" 14565 ";", 14566 Tab)); 14567 EXPECT_EQ("if (aaa && bbb) // w\n" 14568 "\t;", 14569 format("if(aaa&&bbb)// w\n" 14570 ";", 14571 Tab)); 14572 verifyFormat("class X {\n" 14573 "\tvoid f() {\n" 14574 "\t\tsomeFunction(parameter1,\n" 14575 "\t\t parameter2);\n" 14576 "\t}\n" 14577 "};", 14578 Tab); 14579 verifyFormat("#define A \\\n" 14580 "\tvoid f() { \\\n" 14581 "\t\tsomeFunction( \\\n" 14582 "\t\t parameter1, \\\n" 14583 "\t\t parameter2); \\\n" 14584 "\t}", 14585 Tab); 14586 Tab.TabWidth = 4; 14587 Tab.IndentWidth = 8; 14588 verifyFormat("class TabWidth4Indent8 {\n" 14589 "\t\tvoid f() {\n" 14590 "\t\t\t\tsomeFunction(parameter1,\n" 14591 "\t\t\t\t parameter2);\n" 14592 "\t\t}\n" 14593 "};", 14594 Tab); 14595 Tab.TabWidth = 4; 14596 Tab.IndentWidth = 4; 14597 verifyFormat("class TabWidth4Indent4 {\n" 14598 "\tvoid f() {\n" 14599 "\t\tsomeFunction(parameter1,\n" 14600 "\t\t parameter2);\n" 14601 "\t}\n" 14602 "};", 14603 Tab); 14604 Tab.TabWidth = 8; 14605 Tab.IndentWidth = 4; 14606 verifyFormat("class TabWidth8Indent4 {\n" 14607 " void f() {\n" 14608 "\tsomeFunction(parameter1,\n" 14609 "\t parameter2);\n" 14610 " }\n" 14611 "};", 14612 Tab); 14613 Tab.TabWidth = 8; 14614 Tab.IndentWidth = 8; 14615 EXPECT_EQ("/*\n" 14616 " a\t\tcomment\n" 14617 " in multiple lines\n" 14618 " */", 14619 format(" /*\t \t \n" 14620 " \t \t a\t\tcomment\t \t\n" 14621 " \t \t in multiple lines\t\n" 14622 " \t */", 14623 Tab)); 14624 verifyFormat("{\n" 14625 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14626 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14627 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14628 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14629 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14630 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14631 "};", 14632 Tab); 14633 verifyFormat("enum AA {\n" 14634 "\ta1, // Force multiple lines\n" 14635 "\ta2,\n" 14636 "\ta3\n" 14637 "};", 14638 Tab); 14639 EXPECT_EQ("if (aaaaaaaa && // q\n" 14640 " bb) // w\n" 14641 "\t;", 14642 format("if (aaaaaaaa &&// q\n" 14643 "bb)// w\n" 14644 ";", 14645 Tab)); 14646 verifyFormat("class X {\n" 14647 "\tvoid f() {\n" 14648 "\t\tsomeFunction(parameter1,\n" 14649 "\t\t parameter2);\n" 14650 "\t}\n" 14651 "};", 14652 Tab); 14653 verifyFormat("{\n" 14654 "\tQ(\n" 14655 "\t {\n" 14656 "\t\t int a;\n" 14657 "\t\t someFunction(aaaaaaaa,\n" 14658 "\t\t bbbbbbb);\n" 14659 "\t },\n" 14660 "\t p);\n" 14661 "}", 14662 Tab); 14663 EXPECT_EQ("{\n" 14664 "\t/* aaaa\n" 14665 "\t bbbb */\n" 14666 "}", 14667 format("{\n" 14668 "/* aaaa\n" 14669 " bbbb */\n" 14670 "}", 14671 Tab)); 14672 EXPECT_EQ("{\n" 14673 "\t/*\n" 14674 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14675 "\t bbbbbbbbbbbbb\n" 14676 "\t*/\n" 14677 "}", 14678 format("{\n" 14679 "/*\n" 14680 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14681 "*/\n" 14682 "}", 14683 Tab)); 14684 EXPECT_EQ("{\n" 14685 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14686 "\t// bbbbbbbbbbbbb\n" 14687 "}", 14688 format("{\n" 14689 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14690 "}", 14691 Tab)); 14692 EXPECT_EQ("{\n" 14693 "\t/*\n" 14694 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14695 "\t bbbbbbbbbbbbb\n" 14696 "\t*/\n" 14697 "}", 14698 format("{\n" 14699 "\t/*\n" 14700 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14701 "\t*/\n" 14702 "}", 14703 Tab)); 14704 EXPECT_EQ("{\n" 14705 "\t/*\n" 14706 "\n" 14707 "\t*/\n" 14708 "}", 14709 format("{\n" 14710 "\t/*\n" 14711 "\n" 14712 "\t*/\n" 14713 "}", 14714 Tab)); 14715 EXPECT_EQ("{\n" 14716 "\t/*\n" 14717 " asdf\n" 14718 "\t*/\n" 14719 "}", 14720 format("{\n" 14721 "\t/*\n" 14722 " asdf\n" 14723 "\t*/\n" 14724 "}", 14725 Tab)); 14726 EXPECT_EQ("/* some\n" 14727 " comment */", 14728 format(" \t \t /* some\n" 14729 " \t \t comment */", 14730 Tab)); 14731 EXPECT_EQ("int a; /* some\n" 14732 " comment */", 14733 format(" \t \t int a; /* some\n" 14734 " \t \t comment */", 14735 Tab)); 14736 EXPECT_EQ("int a; /* some\n" 14737 "comment */", 14738 format(" \t \t int\ta; /* some\n" 14739 " \t \t comment */", 14740 Tab)); 14741 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14742 " comment */", 14743 format(" \t \t f(\"\t\t\"); /* some\n" 14744 " \t \t comment */", 14745 Tab)); 14746 EXPECT_EQ("{\n" 14747 "\t/*\n" 14748 "\t * Comment\n" 14749 "\t */\n" 14750 "\tint i;\n" 14751 "}", 14752 format("{\n" 14753 "\t/*\n" 14754 "\t * Comment\n" 14755 "\t */\n" 14756 "\t int i;\n" 14757 "}", 14758 Tab)); 14759 Tab.TabWidth = 2; 14760 Tab.IndentWidth = 2; 14761 EXPECT_EQ("{\n" 14762 "\t/* aaaa\n" 14763 "\t bbbb */\n" 14764 "}", 14765 format("{\n" 14766 "/* aaaa\n" 14767 " bbbb */\n" 14768 "}", 14769 Tab)); 14770 EXPECT_EQ("{\n" 14771 "\t/*\n" 14772 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14773 "\t bbbbbbbbbbbbb\n" 14774 "\t*/\n" 14775 "}", 14776 format("{\n" 14777 "/*\n" 14778 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14779 "*/\n" 14780 "}", 14781 Tab)); 14782 Tab.AlignConsecutiveAssignments.Enabled = true; 14783 Tab.AlignConsecutiveDeclarations.Enabled = true; 14784 Tab.TabWidth = 4; 14785 Tab.IndentWidth = 4; 14786 verifyFormat("class Assign {\n" 14787 "\tvoid f() {\n" 14788 "\t\tint x = 123;\n" 14789 "\t\tint random = 4;\n" 14790 "\t\tstd::string alphabet =\n" 14791 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14792 "\t}\n" 14793 "};", 14794 Tab); 14795 Tab.AlignOperands = FormatStyle::OAS_Align; 14796 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14797 " cccccccccccccccccccc;", 14798 Tab); 14799 // no alignment 14800 verifyFormat("int aaaaaaaaaa =\n" 14801 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14802 Tab); 14803 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14804 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14805 " : 333333333333333;", 14806 Tab); 14807 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14808 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14809 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14810 " + cccccccccccccccccccc;", 14811 Tab); 14812 } 14813 14814 TEST_F(FormatTest, ZeroTabWidth) { 14815 FormatStyle Tab = getLLVMStyleWithColumns(42); 14816 Tab.IndentWidth = 8; 14817 Tab.UseTab = FormatStyle::UT_Never; 14818 Tab.TabWidth = 0; 14819 EXPECT_EQ("void a(){\n" 14820 " // line starts with '\t'\n" 14821 "};", 14822 format("void a(){\n" 14823 "\t// line starts with '\t'\n" 14824 "};", 14825 Tab)); 14826 14827 EXPECT_EQ("void a(){\n" 14828 " // line starts with '\t'\n" 14829 "};", 14830 format("void a(){\n" 14831 "\t\t// line starts with '\t'\n" 14832 "};", 14833 Tab)); 14834 14835 Tab.UseTab = FormatStyle::UT_ForIndentation; 14836 EXPECT_EQ("void a(){\n" 14837 " // line starts with '\t'\n" 14838 "};", 14839 format("void a(){\n" 14840 "\t// line starts with '\t'\n" 14841 "};", 14842 Tab)); 14843 14844 EXPECT_EQ("void a(){\n" 14845 " // line starts with '\t'\n" 14846 "};", 14847 format("void a(){\n" 14848 "\t\t// line starts with '\t'\n" 14849 "};", 14850 Tab)); 14851 14852 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14853 EXPECT_EQ("void a(){\n" 14854 " // line starts with '\t'\n" 14855 "};", 14856 format("void a(){\n" 14857 "\t// line starts with '\t'\n" 14858 "};", 14859 Tab)); 14860 14861 EXPECT_EQ("void a(){\n" 14862 " // line starts with '\t'\n" 14863 "};", 14864 format("void a(){\n" 14865 "\t\t// line starts with '\t'\n" 14866 "};", 14867 Tab)); 14868 14869 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14870 EXPECT_EQ("void a(){\n" 14871 " // line starts with '\t'\n" 14872 "};", 14873 format("void a(){\n" 14874 "\t// line starts with '\t'\n" 14875 "};", 14876 Tab)); 14877 14878 EXPECT_EQ("void a(){\n" 14879 " // line starts with '\t'\n" 14880 "};", 14881 format("void a(){\n" 14882 "\t\t// line starts with '\t'\n" 14883 "};", 14884 Tab)); 14885 14886 Tab.UseTab = FormatStyle::UT_Always; 14887 EXPECT_EQ("void a(){\n" 14888 "// line starts with '\t'\n" 14889 "};", 14890 format("void a(){\n" 14891 "\t// line starts with '\t'\n" 14892 "};", 14893 Tab)); 14894 14895 EXPECT_EQ("void a(){\n" 14896 "// line starts with '\t'\n" 14897 "};", 14898 format("void a(){\n" 14899 "\t\t// line starts with '\t'\n" 14900 "};", 14901 Tab)); 14902 } 14903 14904 TEST_F(FormatTest, CalculatesOriginalColumn) { 14905 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14906 "q\"; /* some\n" 14907 " comment */", 14908 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14909 "q\"; /* some\n" 14910 " comment */", 14911 getLLVMStyle())); 14912 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14913 "/* some\n" 14914 " comment */", 14915 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14916 " /* some\n" 14917 " comment */", 14918 getLLVMStyle())); 14919 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14920 "qqq\n" 14921 "/* some\n" 14922 " comment */", 14923 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14924 "qqq\n" 14925 " /* some\n" 14926 " comment */", 14927 getLLVMStyle())); 14928 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14929 "wwww; /* some\n" 14930 " comment */", 14931 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14932 "wwww; /* some\n" 14933 " comment */", 14934 getLLVMStyle())); 14935 } 14936 14937 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14938 FormatStyle NoSpace = getLLVMStyle(); 14939 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14940 14941 verifyFormat("while(true)\n" 14942 " continue;", 14943 NoSpace); 14944 verifyFormat("for(;;)\n" 14945 " continue;", 14946 NoSpace); 14947 verifyFormat("if(true)\n" 14948 " f();\n" 14949 "else if(true)\n" 14950 " f();", 14951 NoSpace); 14952 verifyFormat("do {\n" 14953 " do_something();\n" 14954 "} while(something());", 14955 NoSpace); 14956 verifyFormat("switch(x) {\n" 14957 "default:\n" 14958 " break;\n" 14959 "}", 14960 NoSpace); 14961 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14962 verifyFormat("size_t x = sizeof(x);", NoSpace); 14963 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14964 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14965 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14966 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14967 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14968 verifyFormat("alignas(128) char a[128];", NoSpace); 14969 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14970 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14971 verifyFormat("int f() throw(Deprecated);", NoSpace); 14972 verifyFormat("typedef void (*cb)(int);", NoSpace); 14973 verifyFormat("T A::operator()();", NoSpace); 14974 verifyFormat("X A::operator++(T);", NoSpace); 14975 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14976 14977 FormatStyle Space = getLLVMStyle(); 14978 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14979 14980 verifyFormat("int f ();", Space); 14981 verifyFormat("void f (int a, T b) {\n" 14982 " while (true)\n" 14983 " continue;\n" 14984 "}", 14985 Space); 14986 verifyFormat("if (true)\n" 14987 " f ();\n" 14988 "else if (true)\n" 14989 " f ();", 14990 Space); 14991 verifyFormat("do {\n" 14992 " do_something ();\n" 14993 "} while (something ());", 14994 Space); 14995 verifyFormat("switch (x) {\n" 14996 "default:\n" 14997 " break;\n" 14998 "}", 14999 Space); 15000 verifyFormat("A::A () : a (1) {}", Space); 15001 verifyFormat("void f () __attribute__ ((asdf));", Space); 15002 verifyFormat("*(&a + 1);\n" 15003 "&((&a)[1]);\n" 15004 "a[(b + c) * d];\n" 15005 "(((a + 1) * 2) + 3) * 4;", 15006 Space); 15007 verifyFormat("#define A(x) x", Space); 15008 verifyFormat("#define A (x) x", Space); 15009 verifyFormat("#if defined(x)\n" 15010 "#endif", 15011 Space); 15012 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15013 verifyFormat("size_t x = sizeof (x);", Space); 15014 verifyFormat("auto f (int x) -> decltype (x);", Space); 15015 verifyFormat("auto f (int x) -> typeof (x);", Space); 15016 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15017 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15018 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15019 verifyFormat("alignas (128) char a[128];", Space); 15020 verifyFormat("size_t x = alignof (MyType);", Space); 15021 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15022 verifyFormat("int f () throw (Deprecated);", Space); 15023 verifyFormat("typedef void (*cb) (int);", Space); 15024 // FIXME these tests regressed behaviour. 15025 // verifyFormat("T A::operator() ();", Space); 15026 // verifyFormat("X A::operator++ (T);", Space); 15027 verifyFormat("auto lambda = [] () { return 0; };", Space); 15028 verifyFormat("int x = int (y);", Space); 15029 15030 FormatStyle SomeSpace = getLLVMStyle(); 15031 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15032 15033 verifyFormat("[]() -> float {}", SomeSpace); 15034 verifyFormat("[] (auto foo) {}", SomeSpace); 15035 verifyFormat("[foo]() -> int {}", SomeSpace); 15036 verifyFormat("int f();", SomeSpace); 15037 verifyFormat("void f (int a, T b) {\n" 15038 " while (true)\n" 15039 " continue;\n" 15040 "}", 15041 SomeSpace); 15042 verifyFormat("if (true)\n" 15043 " f();\n" 15044 "else if (true)\n" 15045 " f();", 15046 SomeSpace); 15047 verifyFormat("do {\n" 15048 " do_something();\n" 15049 "} while (something());", 15050 SomeSpace); 15051 verifyFormat("switch (x) {\n" 15052 "default:\n" 15053 " break;\n" 15054 "}", 15055 SomeSpace); 15056 verifyFormat("A::A() : a (1) {}", SomeSpace); 15057 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15058 verifyFormat("*(&a + 1);\n" 15059 "&((&a)[1]);\n" 15060 "a[(b + c) * d];\n" 15061 "(((a + 1) * 2) + 3) * 4;", 15062 SomeSpace); 15063 verifyFormat("#define A(x) x", SomeSpace); 15064 verifyFormat("#define A (x) x", SomeSpace); 15065 verifyFormat("#if defined(x)\n" 15066 "#endif", 15067 SomeSpace); 15068 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15069 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15070 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15071 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15072 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15073 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15074 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15075 verifyFormat("alignas (128) char a[128];", SomeSpace); 15076 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15077 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15078 SomeSpace); 15079 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15080 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15081 verifyFormat("T A::operator()();", SomeSpace); 15082 // FIXME these tests regressed behaviour. 15083 // verifyFormat("X A::operator++ (T);", SomeSpace); 15084 verifyFormat("int x = int (y);", SomeSpace); 15085 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15086 15087 FormatStyle SpaceControlStatements = getLLVMStyle(); 15088 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15089 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15090 15091 verifyFormat("while (true)\n" 15092 " continue;", 15093 SpaceControlStatements); 15094 verifyFormat("if (true)\n" 15095 " f();\n" 15096 "else if (true)\n" 15097 " f();", 15098 SpaceControlStatements); 15099 verifyFormat("for (;;) {\n" 15100 " do_something();\n" 15101 "}", 15102 SpaceControlStatements); 15103 verifyFormat("do {\n" 15104 " do_something();\n" 15105 "} while (something());", 15106 SpaceControlStatements); 15107 verifyFormat("switch (x) {\n" 15108 "default:\n" 15109 " break;\n" 15110 "}", 15111 SpaceControlStatements); 15112 15113 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15114 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15115 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15116 15117 verifyFormat("int f ();", SpaceFuncDecl); 15118 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15119 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15120 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15121 verifyFormat("#define A(x) x", SpaceFuncDecl); 15122 verifyFormat("#define A (x) x", SpaceFuncDecl); 15123 verifyFormat("#if defined(x)\n" 15124 "#endif", 15125 SpaceFuncDecl); 15126 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15127 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15128 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15129 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15130 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15131 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15132 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15133 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15134 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15135 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15136 SpaceFuncDecl); 15137 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15138 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15139 // FIXME these tests regressed behaviour. 15140 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15141 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15142 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15143 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15144 verifyFormat("int x = int(y);", SpaceFuncDecl); 15145 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15146 SpaceFuncDecl); 15147 15148 FormatStyle SpaceFuncDef = getLLVMStyle(); 15149 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15150 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15151 15152 verifyFormat("int f();", SpaceFuncDef); 15153 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15154 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15155 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15156 verifyFormat("#define A(x) x", SpaceFuncDef); 15157 verifyFormat("#define A (x) x", SpaceFuncDef); 15158 verifyFormat("#if defined(x)\n" 15159 "#endif", 15160 SpaceFuncDef); 15161 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15162 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15163 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15164 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15165 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15166 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15167 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15168 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15169 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15170 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15171 SpaceFuncDef); 15172 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15173 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15174 verifyFormat("T A::operator()();", SpaceFuncDef); 15175 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15176 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15177 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15178 verifyFormat("int x = int(y);", SpaceFuncDef); 15179 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15180 SpaceFuncDef); 15181 15182 FormatStyle SpaceIfMacros = getLLVMStyle(); 15183 SpaceIfMacros.IfMacros.clear(); 15184 SpaceIfMacros.IfMacros.push_back("MYIF"); 15185 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15186 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15187 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15188 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15189 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15190 15191 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15192 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15193 FormatStyle::SBS_Never); 15194 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15195 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15196 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15197 verifyFormat("for (;;) {\n" 15198 "}", 15199 SpaceForeachMacros); 15200 verifyFormat("foreach (Item *item, itemlist) {\n" 15201 "}", 15202 SpaceForeachMacros); 15203 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15204 "}", 15205 SpaceForeachMacros); 15206 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15207 "}", 15208 SpaceForeachMacros); 15209 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15210 15211 FormatStyle SomeSpace2 = getLLVMStyle(); 15212 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15213 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15214 verifyFormat("[]() -> float {}", SomeSpace2); 15215 verifyFormat("[] (auto foo) {}", SomeSpace2); 15216 verifyFormat("[foo]() -> int {}", SomeSpace2); 15217 verifyFormat("int f();", SomeSpace2); 15218 verifyFormat("void f (int a, T b) {\n" 15219 " while (true)\n" 15220 " continue;\n" 15221 "}", 15222 SomeSpace2); 15223 verifyFormat("if (true)\n" 15224 " f();\n" 15225 "else if (true)\n" 15226 " f();", 15227 SomeSpace2); 15228 verifyFormat("do {\n" 15229 " do_something();\n" 15230 "} while (something());", 15231 SomeSpace2); 15232 verifyFormat("switch (x) {\n" 15233 "default:\n" 15234 " break;\n" 15235 "}", 15236 SomeSpace2); 15237 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15238 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15239 verifyFormat("*(&a + 1);\n" 15240 "&((&a)[1]);\n" 15241 "a[(b + c) * d];\n" 15242 "(((a + 1) * 2) + 3) * 4;", 15243 SomeSpace2); 15244 verifyFormat("#define A(x) x", SomeSpace2); 15245 verifyFormat("#define A (x) x", SomeSpace2); 15246 verifyFormat("#if defined(x)\n" 15247 "#endif", 15248 SomeSpace2); 15249 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15250 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15251 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15252 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15253 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15254 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15255 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15256 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15257 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15258 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15259 SomeSpace2); 15260 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15261 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15262 verifyFormat("T A::operator()();", SomeSpace2); 15263 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15264 verifyFormat("int x = int (y);", SomeSpace2); 15265 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15266 15267 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15268 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15269 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15270 .AfterOverloadedOperator = true; 15271 15272 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15273 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15274 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15275 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15276 15277 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15278 .AfterOverloadedOperator = false; 15279 15280 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15281 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15282 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15283 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15284 15285 auto SpaceAfterRequires = getLLVMStyle(); 15286 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15287 EXPECT_FALSE( 15288 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15289 EXPECT_FALSE( 15290 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15291 verifyFormat("void f(auto x)\n" 15292 " requires requires(int i) { x + i; }\n" 15293 "{}", 15294 SpaceAfterRequires); 15295 verifyFormat("void f(auto x)\n" 15296 " requires(requires(int i) { x + i; })\n" 15297 "{}", 15298 SpaceAfterRequires); 15299 verifyFormat("if (requires(int i) { x + i; })\n" 15300 " return;", 15301 SpaceAfterRequires); 15302 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15303 verifyFormat("template <typename T>\n" 15304 " requires(Foo<T>)\n" 15305 "class Bar;", 15306 SpaceAfterRequires); 15307 15308 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15309 verifyFormat("void f(auto x)\n" 15310 " requires requires(int i) { x + i; }\n" 15311 "{}", 15312 SpaceAfterRequires); 15313 verifyFormat("void f(auto x)\n" 15314 " requires (requires(int i) { x + i; })\n" 15315 "{}", 15316 SpaceAfterRequires); 15317 verifyFormat("if (requires(int i) { x + i; })\n" 15318 " return;", 15319 SpaceAfterRequires); 15320 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15321 verifyFormat("template <typename T>\n" 15322 " requires (Foo<T>)\n" 15323 "class Bar;", 15324 SpaceAfterRequires); 15325 15326 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15327 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15328 verifyFormat("void f(auto x)\n" 15329 " requires requires (int i) { x + i; }\n" 15330 "{}", 15331 SpaceAfterRequires); 15332 verifyFormat("void f(auto x)\n" 15333 " requires(requires (int i) { x + i; })\n" 15334 "{}", 15335 SpaceAfterRequires); 15336 verifyFormat("if (requires (int i) { x + i; })\n" 15337 " return;", 15338 SpaceAfterRequires); 15339 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15340 verifyFormat("template <typename T>\n" 15341 " requires(Foo<T>)\n" 15342 "class Bar;", 15343 SpaceAfterRequires); 15344 15345 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15346 verifyFormat("void f(auto x)\n" 15347 " requires requires (int i) { x + i; }\n" 15348 "{}", 15349 SpaceAfterRequires); 15350 verifyFormat("void f(auto x)\n" 15351 " requires (requires (int i) { x + i; })\n" 15352 "{}", 15353 SpaceAfterRequires); 15354 verifyFormat("if (requires (int i) { x + i; })\n" 15355 " return;", 15356 SpaceAfterRequires); 15357 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15358 verifyFormat("template <typename T>\n" 15359 " requires (Foo<T>)\n" 15360 "class Bar;", 15361 SpaceAfterRequires); 15362 } 15363 15364 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15365 FormatStyle Spaces = getLLVMStyle(); 15366 Spaces.SpaceAfterLogicalNot = true; 15367 15368 verifyFormat("bool x = ! y", Spaces); 15369 verifyFormat("if (! isFailure())", Spaces); 15370 verifyFormat("if (! (a && b))", Spaces); 15371 verifyFormat("\"Error!\"", Spaces); 15372 verifyFormat("! ! x", Spaces); 15373 } 15374 15375 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15376 FormatStyle Spaces = getLLVMStyle(); 15377 15378 Spaces.SpacesInParentheses = true; 15379 verifyFormat("do_something( ::globalVar );", Spaces); 15380 verifyFormat("call( x, y, z );", Spaces); 15381 verifyFormat("call();", Spaces); 15382 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15383 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15384 Spaces); 15385 verifyFormat("while ( (bool)1 )\n" 15386 " continue;", 15387 Spaces); 15388 verifyFormat("for ( ;; )\n" 15389 " continue;", 15390 Spaces); 15391 verifyFormat("if ( true )\n" 15392 " f();\n" 15393 "else if ( true )\n" 15394 " f();", 15395 Spaces); 15396 verifyFormat("do {\n" 15397 " do_something( (int)i );\n" 15398 "} while ( something() );", 15399 Spaces); 15400 verifyFormat("switch ( x ) {\n" 15401 "default:\n" 15402 " break;\n" 15403 "}", 15404 Spaces); 15405 15406 Spaces.SpacesInParentheses = false; 15407 Spaces.SpacesInCStyleCastParentheses = true; 15408 verifyFormat("Type *A = ( Type * )P;", Spaces); 15409 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15410 verifyFormat("x = ( int32 )y;", Spaces); 15411 verifyFormat("int a = ( int )(2.0f);", Spaces); 15412 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15413 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15414 verifyFormat("#define x (( int )-1)", Spaces); 15415 15416 // Run the first set of tests again with: 15417 Spaces.SpacesInParentheses = false; 15418 Spaces.SpaceInEmptyParentheses = true; 15419 Spaces.SpacesInCStyleCastParentheses = true; 15420 verifyFormat("call(x, y, z);", Spaces); 15421 verifyFormat("call( );", Spaces); 15422 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15423 verifyFormat("while (( bool )1)\n" 15424 " continue;", 15425 Spaces); 15426 verifyFormat("for (;;)\n" 15427 " continue;", 15428 Spaces); 15429 verifyFormat("if (true)\n" 15430 " f( );\n" 15431 "else if (true)\n" 15432 " f( );", 15433 Spaces); 15434 verifyFormat("do {\n" 15435 " do_something(( int )i);\n" 15436 "} while (something( ));", 15437 Spaces); 15438 verifyFormat("switch (x) {\n" 15439 "default:\n" 15440 " break;\n" 15441 "}", 15442 Spaces); 15443 15444 // Run the first set of tests again with: 15445 Spaces.SpaceAfterCStyleCast = true; 15446 verifyFormat("call(x, y, z);", Spaces); 15447 verifyFormat("call( );", Spaces); 15448 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15449 verifyFormat("while (( bool ) 1)\n" 15450 " continue;", 15451 Spaces); 15452 verifyFormat("for (;;)\n" 15453 " continue;", 15454 Spaces); 15455 verifyFormat("if (true)\n" 15456 " f( );\n" 15457 "else if (true)\n" 15458 " f( );", 15459 Spaces); 15460 verifyFormat("do {\n" 15461 " do_something(( int ) i);\n" 15462 "} while (something( ));", 15463 Spaces); 15464 verifyFormat("switch (x) {\n" 15465 "default:\n" 15466 " break;\n" 15467 "}", 15468 Spaces); 15469 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15470 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15471 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15472 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15473 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15474 15475 // Run subset of tests again with: 15476 Spaces.SpacesInCStyleCastParentheses = false; 15477 Spaces.SpaceAfterCStyleCast = true; 15478 verifyFormat("while ((bool) 1)\n" 15479 " continue;", 15480 Spaces); 15481 verifyFormat("do {\n" 15482 " do_something((int) i);\n" 15483 "} while (something( ));", 15484 Spaces); 15485 15486 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15487 verifyFormat("size_t idx = (size_t) a;", Spaces); 15488 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15489 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15490 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15491 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15492 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15493 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15494 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15495 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15496 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15497 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15498 Spaces.ColumnLimit = 80; 15499 Spaces.IndentWidth = 4; 15500 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15501 verifyFormat("void foo( ) {\n" 15502 " size_t foo = (*(function))(\n" 15503 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15504 "BarrrrrrrrrrrrLong,\n" 15505 " FoooooooooLooooong);\n" 15506 "}", 15507 Spaces); 15508 Spaces.SpaceAfterCStyleCast = false; 15509 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15510 verifyFormat("size_t idx = (size_t)a;", Spaces); 15511 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15512 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15513 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15514 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15515 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15516 15517 verifyFormat("void foo( ) {\n" 15518 " size_t foo = (*(function))(\n" 15519 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15520 "BarrrrrrrrrrrrLong,\n" 15521 " FoooooooooLooooong);\n" 15522 "}", 15523 Spaces); 15524 } 15525 15526 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15527 verifyFormat("int a[5];"); 15528 verifyFormat("a[3] += 42;"); 15529 15530 FormatStyle Spaces = getLLVMStyle(); 15531 Spaces.SpacesInSquareBrackets = true; 15532 // Not lambdas. 15533 verifyFormat("int a[ 5 ];", Spaces); 15534 verifyFormat("a[ 3 ] += 42;", Spaces); 15535 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15536 verifyFormat("double &operator[](int i) { return 0; }\n" 15537 "int i;", 15538 Spaces); 15539 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15540 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15541 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15542 // Lambdas. 15543 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15544 verifyFormat("return [ i, args... ] {};", Spaces); 15545 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15546 verifyFormat("int foo = [ = ]() {};", Spaces); 15547 verifyFormat("int foo = [ & ]() {};", Spaces); 15548 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15549 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15550 } 15551 15552 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15553 FormatStyle NoSpaceStyle = getLLVMStyle(); 15554 verifyFormat("int a[5];", NoSpaceStyle); 15555 verifyFormat("a[3] += 42;", NoSpaceStyle); 15556 15557 verifyFormat("int a[1];", NoSpaceStyle); 15558 verifyFormat("int 1 [a];", NoSpaceStyle); 15559 verifyFormat("int a[1][2];", NoSpaceStyle); 15560 verifyFormat("a[7] = 5;", NoSpaceStyle); 15561 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15562 verifyFormat("f([] {})", NoSpaceStyle); 15563 15564 FormatStyle Space = getLLVMStyle(); 15565 Space.SpaceBeforeSquareBrackets = true; 15566 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15567 verifyFormat("return [i, args...] {};", Space); 15568 15569 verifyFormat("int a [5];", Space); 15570 verifyFormat("a [3] += 42;", Space); 15571 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15572 verifyFormat("double &operator[](int i) { return 0; }\n" 15573 "int i;", 15574 Space); 15575 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15576 verifyFormat("int i = a [a][a]->f();", Space); 15577 verifyFormat("int i = (*b) [a]->f();", Space); 15578 15579 verifyFormat("int a [1];", Space); 15580 verifyFormat("int 1 [a];", Space); 15581 verifyFormat("int a [1][2];", Space); 15582 verifyFormat("a [7] = 5;", Space); 15583 verifyFormat("int a = (f()) [23];", Space); 15584 verifyFormat("f([] {})", Space); 15585 } 15586 15587 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15588 verifyFormat("int a = 5;"); 15589 verifyFormat("a += 42;"); 15590 verifyFormat("a or_eq 8;"); 15591 15592 FormatStyle Spaces = getLLVMStyle(); 15593 Spaces.SpaceBeforeAssignmentOperators = false; 15594 verifyFormat("int a= 5;", Spaces); 15595 verifyFormat("a+= 42;", Spaces); 15596 verifyFormat("a or_eq 8;", Spaces); 15597 } 15598 15599 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15600 verifyFormat("class Foo : public Bar {};"); 15601 verifyFormat("Foo::Foo() : foo(1) {}"); 15602 verifyFormat("for (auto a : b) {\n}"); 15603 verifyFormat("int x = a ? b : c;"); 15604 verifyFormat("{\n" 15605 "label0:\n" 15606 " int x = 0;\n" 15607 "}"); 15608 verifyFormat("switch (x) {\n" 15609 "case 1:\n" 15610 "default:\n" 15611 "}"); 15612 verifyFormat("switch (allBraces) {\n" 15613 "case 1: {\n" 15614 " break;\n" 15615 "}\n" 15616 "case 2: {\n" 15617 " [[fallthrough]];\n" 15618 "}\n" 15619 "default: {\n" 15620 " break;\n" 15621 "}\n" 15622 "}"); 15623 15624 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15625 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15626 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15627 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15628 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15629 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15630 verifyFormat("{\n" 15631 "label1:\n" 15632 " int x = 0;\n" 15633 "}", 15634 CtorInitializerStyle); 15635 verifyFormat("switch (x) {\n" 15636 "case 1:\n" 15637 "default:\n" 15638 "}", 15639 CtorInitializerStyle); 15640 verifyFormat("switch (allBraces) {\n" 15641 "case 1: {\n" 15642 " break;\n" 15643 "}\n" 15644 "case 2: {\n" 15645 " [[fallthrough]];\n" 15646 "}\n" 15647 "default: {\n" 15648 " break;\n" 15649 "}\n" 15650 "}", 15651 CtorInitializerStyle); 15652 CtorInitializerStyle.BreakConstructorInitializers = 15653 FormatStyle::BCIS_AfterColon; 15654 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15655 " aaaaaaaaaaaaaaaa(1),\n" 15656 " bbbbbbbbbbbbbbbb(2) {}", 15657 CtorInitializerStyle); 15658 CtorInitializerStyle.BreakConstructorInitializers = 15659 FormatStyle::BCIS_BeforeComma; 15660 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15661 " : aaaaaaaaaaaaaaaa(1)\n" 15662 " , bbbbbbbbbbbbbbbb(2) {}", 15663 CtorInitializerStyle); 15664 CtorInitializerStyle.BreakConstructorInitializers = 15665 FormatStyle::BCIS_BeforeColon; 15666 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15667 " : aaaaaaaaaaaaaaaa(1),\n" 15668 " bbbbbbbbbbbbbbbb(2) {}", 15669 CtorInitializerStyle); 15670 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15671 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15672 ": aaaaaaaaaaaaaaaa(1),\n" 15673 " bbbbbbbbbbbbbbbb(2) {}", 15674 CtorInitializerStyle); 15675 15676 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15677 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15678 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15679 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15680 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15681 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15682 verifyFormat("{\n" 15683 "label2:\n" 15684 " int x = 0;\n" 15685 "}", 15686 InheritanceStyle); 15687 verifyFormat("switch (x) {\n" 15688 "case 1:\n" 15689 "default:\n" 15690 "}", 15691 InheritanceStyle); 15692 verifyFormat("switch (allBraces) {\n" 15693 "case 1: {\n" 15694 " break;\n" 15695 "}\n" 15696 "case 2: {\n" 15697 " [[fallthrough]];\n" 15698 "}\n" 15699 "default: {\n" 15700 " break;\n" 15701 "}\n" 15702 "}", 15703 InheritanceStyle); 15704 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15705 verifyFormat("class Foooooooooooooooooooooo\n" 15706 " : public aaaaaaaaaaaaaaaaaa,\n" 15707 " public bbbbbbbbbbbbbbbbbb {\n" 15708 "}", 15709 InheritanceStyle); 15710 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15711 verifyFormat("class Foooooooooooooooooooooo:\n" 15712 " public aaaaaaaaaaaaaaaaaa,\n" 15713 " public bbbbbbbbbbbbbbbbbb {\n" 15714 "}", 15715 InheritanceStyle); 15716 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15717 verifyFormat("class Foooooooooooooooooooooo\n" 15718 " : public aaaaaaaaaaaaaaaaaa\n" 15719 " , public bbbbbbbbbbbbbbbbbb {\n" 15720 "}", 15721 InheritanceStyle); 15722 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15723 verifyFormat("class Foooooooooooooooooooooo\n" 15724 " : public aaaaaaaaaaaaaaaaaa,\n" 15725 " public bbbbbbbbbbbbbbbbbb {\n" 15726 "}", 15727 InheritanceStyle); 15728 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15729 verifyFormat("class Foooooooooooooooooooooo\n" 15730 ": public aaaaaaaaaaaaaaaaaa,\n" 15731 " public bbbbbbbbbbbbbbbbbb {}", 15732 InheritanceStyle); 15733 15734 FormatStyle ForLoopStyle = getLLVMStyle(); 15735 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15736 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15737 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15738 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15739 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15740 verifyFormat("{\n" 15741 "label2:\n" 15742 " int x = 0;\n" 15743 "}", 15744 ForLoopStyle); 15745 verifyFormat("switch (x) {\n" 15746 "case 1:\n" 15747 "default:\n" 15748 "}", 15749 ForLoopStyle); 15750 verifyFormat("switch (allBraces) {\n" 15751 "case 1: {\n" 15752 " break;\n" 15753 "}\n" 15754 "case 2: {\n" 15755 " [[fallthrough]];\n" 15756 "}\n" 15757 "default: {\n" 15758 " break;\n" 15759 "}\n" 15760 "}", 15761 ForLoopStyle); 15762 15763 FormatStyle CaseStyle = getLLVMStyle(); 15764 CaseStyle.SpaceBeforeCaseColon = true; 15765 verifyFormat("class Foo : public Bar {};", CaseStyle); 15766 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15767 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15768 verifyFormat("int x = a ? b : c;", CaseStyle); 15769 verifyFormat("switch (x) {\n" 15770 "case 1 :\n" 15771 "default :\n" 15772 "}", 15773 CaseStyle); 15774 verifyFormat("switch (allBraces) {\n" 15775 "case 1 : {\n" 15776 " break;\n" 15777 "}\n" 15778 "case 2 : {\n" 15779 " [[fallthrough]];\n" 15780 "}\n" 15781 "default : {\n" 15782 " break;\n" 15783 "}\n" 15784 "}", 15785 CaseStyle); 15786 15787 FormatStyle NoSpaceStyle = getLLVMStyle(); 15788 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15789 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15790 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15791 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15792 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15793 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15794 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15795 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15796 verifyFormat("{\n" 15797 "label3:\n" 15798 " int x = 0;\n" 15799 "}", 15800 NoSpaceStyle); 15801 verifyFormat("switch (x) {\n" 15802 "case 1:\n" 15803 "default:\n" 15804 "}", 15805 NoSpaceStyle); 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 NoSpaceStyle); 15818 15819 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15820 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15821 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15822 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15823 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15824 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15825 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15826 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15827 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15828 verifyFormat("{\n" 15829 "label3:\n" 15830 " int x = 0;\n" 15831 "}", 15832 InvertedSpaceStyle); 15833 verifyFormat("switch (x) {\n" 15834 "case 1 :\n" 15835 "case 2 : {\n" 15836 " break;\n" 15837 "}\n" 15838 "default :\n" 15839 " break;\n" 15840 "}", 15841 InvertedSpaceStyle); 15842 verifyFormat("switch (allBraces) {\n" 15843 "case 1 : {\n" 15844 " break;\n" 15845 "}\n" 15846 "case 2 : {\n" 15847 " [[fallthrough]];\n" 15848 "}\n" 15849 "default : {\n" 15850 " break;\n" 15851 "}\n" 15852 "}", 15853 InvertedSpaceStyle); 15854 } 15855 15856 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15857 FormatStyle Style = getLLVMStyle(); 15858 15859 Style.PointerAlignment = FormatStyle::PAS_Left; 15860 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15861 verifyFormat("void* const* x = NULL;", Style); 15862 15863 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15864 do { \ 15865 Style.PointerAlignment = FormatStyle::Pointers; \ 15866 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15867 verifyFormat(Code, Style); \ 15868 } while (false) 15869 15870 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15871 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15872 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15873 15874 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15875 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15876 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15877 15878 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15879 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15880 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15881 15882 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15883 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15884 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15885 15886 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15887 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15888 SAPQ_Default); 15889 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15890 SAPQ_Default); 15891 15892 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15893 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15894 SAPQ_Before); 15895 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15896 SAPQ_Before); 15897 15898 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15899 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15900 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15901 SAPQ_After); 15902 15903 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15904 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15905 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15906 15907 #undef verifyQualifierSpaces 15908 15909 FormatStyle Spaces = getLLVMStyle(); 15910 Spaces.AttributeMacros.push_back("qualified"); 15911 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15912 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15913 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15914 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15915 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15916 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15917 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15918 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15919 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15920 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15921 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15922 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15923 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15924 15925 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15926 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15927 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15928 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15929 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15930 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15931 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15932 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15933 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15934 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15935 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15936 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15937 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15938 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15939 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15940 15941 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15942 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15943 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15944 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15945 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15946 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15947 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15948 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15949 } 15950 15951 TEST_F(FormatTest, AlignConsecutiveMacros) { 15952 FormatStyle Style = getLLVMStyle(); 15953 Style.AlignConsecutiveAssignments.Enabled = true; 15954 Style.AlignConsecutiveDeclarations.Enabled = true; 15955 15956 verifyFormat("#define a 3\n" 15957 "#define bbbb 4\n" 15958 "#define ccc (5)", 15959 Style); 15960 15961 verifyFormat("#define f(x) (x * x)\n" 15962 "#define fff(x, y, z) (x * y + z)\n" 15963 "#define ffff(x, y) (x - y)", 15964 Style); 15965 15966 verifyFormat("#define foo(x, y) (x + y)\n" 15967 "#define bar (5, 6)(2 + 2)", 15968 Style); 15969 15970 verifyFormat("#define a 3\n" 15971 "#define bbbb 4\n" 15972 "#define ccc (5)\n" 15973 "#define f(x) (x * x)\n" 15974 "#define fff(x, y, z) (x * y + z)\n" 15975 "#define ffff(x, y) (x - y)", 15976 Style); 15977 15978 Style.AlignConsecutiveMacros.Enabled = true; 15979 verifyFormat("#define a 3\n" 15980 "#define bbbb 4\n" 15981 "#define ccc (5)", 15982 Style); 15983 15984 verifyFormat("#define f(x) (x * x)\n" 15985 "#define fff(x, y, z) (x * y + z)\n" 15986 "#define ffff(x, y) (x - y)", 15987 Style); 15988 15989 verifyFormat("#define foo(x, y) (x + y)\n" 15990 "#define bar (5, 6)(2 + 2)", 15991 Style); 15992 15993 verifyFormat("#define a 3\n" 15994 "#define bbbb 4\n" 15995 "#define ccc (5)\n" 15996 "#define f(x) (x * x)\n" 15997 "#define fff(x, y, z) (x * y + z)\n" 15998 "#define ffff(x, y) (x - y)", 15999 Style); 16000 16001 verifyFormat("#define a 5\n" 16002 "#define foo(x, y) (x + y)\n" 16003 "#define CCC (6)\n" 16004 "auto lambda = []() {\n" 16005 " auto ii = 0;\n" 16006 " float j = 0;\n" 16007 " return 0;\n" 16008 "};\n" 16009 "int i = 0;\n" 16010 "float i2 = 0;\n" 16011 "auto v = type{\n" 16012 " i = 1, //\n" 16013 " (i = 2), //\n" 16014 " i = 3 //\n" 16015 "};", 16016 Style); 16017 16018 Style.AlignConsecutiveMacros.Enabled = false; 16019 Style.ColumnLimit = 20; 16020 16021 verifyFormat("#define a \\\n" 16022 " \"aabbbbbbbbbbbb\"\n" 16023 "#define D \\\n" 16024 " \"aabbbbbbbbbbbb\" \\\n" 16025 " \"ccddeeeeeeeee\"\n" 16026 "#define B \\\n" 16027 " \"QQQQQQQQQQQQQ\" \\\n" 16028 " \"FFFFFFFFFFFFF\" \\\n" 16029 " \"LLLLLLLL\"\n", 16030 Style); 16031 16032 Style.AlignConsecutiveMacros.Enabled = true; 16033 verifyFormat("#define a \\\n" 16034 " \"aabbbbbbbbbbbb\"\n" 16035 "#define D \\\n" 16036 " \"aabbbbbbbbbbbb\" \\\n" 16037 " \"ccddeeeeeeeee\"\n" 16038 "#define B \\\n" 16039 " \"QQQQQQQQQQQQQ\" \\\n" 16040 " \"FFFFFFFFFFFFF\" \\\n" 16041 " \"LLLLLLLL\"\n", 16042 Style); 16043 16044 // Test across comments 16045 Style.MaxEmptyLinesToKeep = 10; 16046 Style.ReflowComments = false; 16047 Style.AlignConsecutiveMacros.AcrossComments = true; 16048 EXPECT_EQ("#define a 3\n" 16049 "// line comment\n" 16050 "#define bbbb 4\n" 16051 "#define ccc (5)", 16052 format("#define a 3\n" 16053 "// line comment\n" 16054 "#define bbbb 4\n" 16055 "#define ccc (5)", 16056 Style)); 16057 16058 EXPECT_EQ("#define a 3\n" 16059 "/* block comment */\n" 16060 "#define bbbb 4\n" 16061 "#define ccc (5)", 16062 format("#define a 3\n" 16063 "/* block comment */\n" 16064 "#define bbbb 4\n" 16065 "#define ccc (5)", 16066 Style)); 16067 16068 EXPECT_EQ("#define a 3\n" 16069 "/* multi-line *\n" 16070 " * block comment */\n" 16071 "#define bbbb 4\n" 16072 "#define ccc (5)", 16073 format("#define a 3\n" 16074 "/* multi-line *\n" 16075 " * block comment */\n" 16076 "#define bbbb 4\n" 16077 "#define ccc (5)", 16078 Style)); 16079 16080 EXPECT_EQ("#define a 3\n" 16081 "// multi-line line comment\n" 16082 "//\n" 16083 "#define bbbb 4\n" 16084 "#define ccc (5)", 16085 format("#define a 3\n" 16086 "// multi-line line comment\n" 16087 "//\n" 16088 "#define bbbb 4\n" 16089 "#define ccc (5)", 16090 Style)); 16091 16092 EXPECT_EQ("#define a 3\n" 16093 "// empty lines still break.\n" 16094 "\n" 16095 "#define bbbb 4\n" 16096 "#define ccc (5)", 16097 format("#define a 3\n" 16098 "// empty lines still break.\n" 16099 "\n" 16100 "#define bbbb 4\n" 16101 "#define ccc (5)", 16102 Style)); 16103 16104 // Test across empty lines 16105 Style.AlignConsecutiveMacros.AcrossComments = false; 16106 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16107 EXPECT_EQ("#define a 3\n" 16108 "\n" 16109 "#define bbbb 4\n" 16110 "#define ccc (5)", 16111 format("#define a 3\n" 16112 "\n" 16113 "#define bbbb 4\n" 16114 "#define ccc (5)", 16115 Style)); 16116 16117 EXPECT_EQ("#define a 3\n" 16118 "\n" 16119 "\n" 16120 "\n" 16121 "#define bbbb 4\n" 16122 "#define ccc (5)", 16123 format("#define a 3\n" 16124 "\n" 16125 "\n" 16126 "\n" 16127 "#define bbbb 4\n" 16128 "#define ccc (5)", 16129 Style)); 16130 16131 EXPECT_EQ("#define a 3\n" 16132 "// comments should break alignment\n" 16133 "//\n" 16134 "#define bbbb 4\n" 16135 "#define ccc (5)", 16136 format("#define a 3\n" 16137 "// comments should break alignment\n" 16138 "//\n" 16139 "#define bbbb 4\n" 16140 "#define ccc (5)", 16141 Style)); 16142 16143 // Test across empty lines and comments 16144 Style.AlignConsecutiveMacros.AcrossComments = true; 16145 verifyFormat("#define a 3\n" 16146 "\n" 16147 "// line comment\n" 16148 "#define bbbb 4\n" 16149 "#define ccc (5)", 16150 Style); 16151 16152 EXPECT_EQ("#define a 3\n" 16153 "\n" 16154 "\n" 16155 "/* multi-line *\n" 16156 " * block comment */\n" 16157 "\n" 16158 "\n" 16159 "#define bbbb 4\n" 16160 "#define ccc (5)", 16161 format("#define a 3\n" 16162 "\n" 16163 "\n" 16164 "/* multi-line *\n" 16165 " * block comment */\n" 16166 "\n" 16167 "\n" 16168 "#define bbbb 4\n" 16169 "#define ccc (5)", 16170 Style)); 16171 16172 EXPECT_EQ("#define a 3\n" 16173 "\n" 16174 "\n" 16175 "/* multi-line *\n" 16176 " * block comment */\n" 16177 "\n" 16178 "\n" 16179 "#define bbbb 4\n" 16180 "#define ccc (5)", 16181 format("#define a 3\n" 16182 "\n" 16183 "\n" 16184 "/* multi-line *\n" 16185 " * block comment */\n" 16186 "\n" 16187 "\n" 16188 "#define bbbb 4\n" 16189 "#define ccc (5)", 16190 Style)); 16191 } 16192 16193 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16194 FormatStyle Alignment = getLLVMStyle(); 16195 Alignment.AlignConsecutiveMacros.Enabled = true; 16196 Alignment.AlignConsecutiveAssignments.Enabled = true; 16197 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16198 16199 Alignment.MaxEmptyLinesToKeep = 10; 16200 /* Test alignment across empty lines */ 16201 EXPECT_EQ("int a = 5;\n" 16202 "\n" 16203 "int oneTwoThree = 123;", 16204 format("int a = 5;\n" 16205 "\n" 16206 "int oneTwoThree= 123;", 16207 Alignment)); 16208 EXPECT_EQ("int a = 5;\n" 16209 "int one = 1;\n" 16210 "\n" 16211 "int oneTwoThree = 123;", 16212 format("int a = 5;\n" 16213 "int one = 1;\n" 16214 "\n" 16215 "int oneTwoThree = 123;", 16216 Alignment)); 16217 EXPECT_EQ("int a = 5;\n" 16218 "int one = 1;\n" 16219 "\n" 16220 "int oneTwoThree = 123;\n" 16221 "int oneTwo = 12;", 16222 format("int a = 5;\n" 16223 "int one = 1;\n" 16224 "\n" 16225 "int oneTwoThree = 123;\n" 16226 "int oneTwo = 12;", 16227 Alignment)); 16228 16229 /* Test across comments */ 16230 EXPECT_EQ("int a = 5;\n" 16231 "/* block comment */\n" 16232 "int oneTwoThree = 123;", 16233 format("int a = 5;\n" 16234 "/* block comment */\n" 16235 "int oneTwoThree=123;", 16236 Alignment)); 16237 16238 EXPECT_EQ("int a = 5;\n" 16239 "// line comment\n" 16240 "int oneTwoThree = 123;", 16241 format("int a = 5;\n" 16242 "// line comment\n" 16243 "int oneTwoThree=123;", 16244 Alignment)); 16245 16246 /* Test across comments and newlines */ 16247 EXPECT_EQ("int a = 5;\n" 16248 "\n" 16249 "/* block comment */\n" 16250 "int oneTwoThree = 123;", 16251 format("int a = 5;\n" 16252 "\n" 16253 "/* block comment */\n" 16254 "int oneTwoThree=123;", 16255 Alignment)); 16256 16257 EXPECT_EQ("int a = 5;\n" 16258 "\n" 16259 "// line comment\n" 16260 "int oneTwoThree = 123;", 16261 format("int a = 5;\n" 16262 "\n" 16263 "// line comment\n" 16264 "int oneTwoThree=123;", 16265 Alignment)); 16266 } 16267 16268 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16269 FormatStyle Alignment = getLLVMStyle(); 16270 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16271 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16272 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16273 16274 Alignment.MaxEmptyLinesToKeep = 10; 16275 /* Test alignment across empty lines */ 16276 EXPECT_EQ("int a = 5;\n" 16277 "\n" 16278 "float const oneTwoThree = 123;", 16279 format("int a = 5;\n" 16280 "\n" 16281 "float const oneTwoThree = 123;", 16282 Alignment)); 16283 EXPECT_EQ("int a = 5;\n" 16284 "float const one = 1;\n" 16285 "\n" 16286 "int oneTwoThree = 123;", 16287 format("int a = 5;\n" 16288 "float const one = 1;\n" 16289 "\n" 16290 "int oneTwoThree = 123;", 16291 Alignment)); 16292 16293 /* Test across comments */ 16294 EXPECT_EQ("float const a = 5;\n" 16295 "/* block comment */\n" 16296 "int oneTwoThree = 123;", 16297 format("float const a = 5;\n" 16298 "/* block comment */\n" 16299 "int oneTwoThree=123;", 16300 Alignment)); 16301 16302 EXPECT_EQ("float const a = 5;\n" 16303 "// line comment\n" 16304 "int oneTwoThree = 123;", 16305 format("float const a = 5;\n" 16306 "// line comment\n" 16307 "int oneTwoThree=123;", 16308 Alignment)); 16309 16310 /* Test across comments and newlines */ 16311 EXPECT_EQ("float const a = 5;\n" 16312 "\n" 16313 "/* block comment */\n" 16314 "int oneTwoThree = 123;", 16315 format("float const a = 5;\n" 16316 "\n" 16317 "/* block comment */\n" 16318 "int oneTwoThree=123;", 16319 Alignment)); 16320 16321 EXPECT_EQ("float const a = 5;\n" 16322 "\n" 16323 "// line comment\n" 16324 "int oneTwoThree = 123;", 16325 format("float const a = 5;\n" 16326 "\n" 16327 "// line comment\n" 16328 "int oneTwoThree=123;", 16329 Alignment)); 16330 } 16331 16332 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16333 FormatStyle Alignment = getLLVMStyle(); 16334 Alignment.AlignConsecutiveBitFields.Enabled = true; 16335 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16336 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16337 16338 Alignment.MaxEmptyLinesToKeep = 10; 16339 /* Test alignment across empty lines */ 16340 EXPECT_EQ("int a : 5;\n" 16341 "\n" 16342 "int longbitfield : 6;", 16343 format("int a : 5;\n" 16344 "\n" 16345 "int longbitfield : 6;", 16346 Alignment)); 16347 EXPECT_EQ("int a : 5;\n" 16348 "int one : 1;\n" 16349 "\n" 16350 "int longbitfield : 6;", 16351 format("int a : 5;\n" 16352 "int one : 1;\n" 16353 "\n" 16354 "int longbitfield : 6;", 16355 Alignment)); 16356 16357 /* Test across comments */ 16358 EXPECT_EQ("int a : 5;\n" 16359 "/* block comment */\n" 16360 "int longbitfield : 6;", 16361 format("int a : 5;\n" 16362 "/* block comment */\n" 16363 "int longbitfield : 6;", 16364 Alignment)); 16365 EXPECT_EQ("int a : 5;\n" 16366 "int one : 1;\n" 16367 "// line comment\n" 16368 "int longbitfield : 6;", 16369 format("int a : 5;\n" 16370 "int one : 1;\n" 16371 "// line comment\n" 16372 "int longbitfield : 6;", 16373 Alignment)); 16374 16375 /* Test across comments and newlines */ 16376 EXPECT_EQ("int a : 5;\n" 16377 "/* block comment */\n" 16378 "\n" 16379 "int longbitfield : 6;", 16380 format("int a : 5;\n" 16381 "/* block comment */\n" 16382 "\n" 16383 "int longbitfield : 6;", 16384 Alignment)); 16385 EXPECT_EQ("int a : 5;\n" 16386 "int one : 1;\n" 16387 "\n" 16388 "// line comment\n" 16389 "\n" 16390 "int longbitfield : 6;", 16391 format("int a : 5;\n" 16392 "int one : 1;\n" 16393 "\n" 16394 "// line comment \n" 16395 "\n" 16396 "int longbitfield : 6;", 16397 Alignment)); 16398 } 16399 16400 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16401 FormatStyle Alignment = getLLVMStyle(); 16402 Alignment.AlignConsecutiveMacros.Enabled = true; 16403 Alignment.AlignConsecutiveAssignments.Enabled = true; 16404 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16405 16406 Alignment.MaxEmptyLinesToKeep = 10; 16407 /* Test alignment across empty lines */ 16408 EXPECT_EQ("int a = 5;\n" 16409 "\n" 16410 "int oneTwoThree = 123;", 16411 format("int a = 5;\n" 16412 "\n" 16413 "int oneTwoThree= 123;", 16414 Alignment)); 16415 EXPECT_EQ("int a = 5;\n" 16416 "int one = 1;\n" 16417 "\n" 16418 "int oneTwoThree = 123;", 16419 format("int a = 5;\n" 16420 "int one = 1;\n" 16421 "\n" 16422 "int oneTwoThree = 123;", 16423 Alignment)); 16424 16425 /* Test across comments */ 16426 EXPECT_EQ("int a = 5;\n" 16427 "/* block comment */\n" 16428 "int oneTwoThree = 123;", 16429 format("int a = 5;\n" 16430 "/* block comment */\n" 16431 "int oneTwoThree=123;", 16432 Alignment)); 16433 16434 EXPECT_EQ("int a = 5;\n" 16435 "// line comment\n" 16436 "int oneTwoThree = 123;", 16437 format("int a = 5;\n" 16438 "// line comment\n" 16439 "int oneTwoThree=123;", 16440 Alignment)); 16441 16442 EXPECT_EQ("int a = 5;\n" 16443 "/*\n" 16444 " * multi-line block comment\n" 16445 " */\n" 16446 "int oneTwoThree = 123;", 16447 format("int a = 5;\n" 16448 "/*\n" 16449 " * multi-line block comment\n" 16450 " */\n" 16451 "int oneTwoThree=123;", 16452 Alignment)); 16453 16454 EXPECT_EQ("int a = 5;\n" 16455 "//\n" 16456 "// multi-line line comment\n" 16457 "//\n" 16458 "int oneTwoThree = 123;", 16459 format("int a = 5;\n" 16460 "//\n" 16461 "// multi-line line comment\n" 16462 "//\n" 16463 "int oneTwoThree=123;", 16464 Alignment)); 16465 16466 /* Test across comments and newlines */ 16467 EXPECT_EQ("int a = 5;\n" 16468 "\n" 16469 "/* block comment */\n" 16470 "int oneTwoThree = 123;", 16471 format("int a = 5;\n" 16472 "\n" 16473 "/* block comment */\n" 16474 "int oneTwoThree=123;", 16475 Alignment)); 16476 16477 EXPECT_EQ("int a = 5;\n" 16478 "\n" 16479 "// line comment\n" 16480 "int oneTwoThree = 123;", 16481 format("int a = 5;\n" 16482 "\n" 16483 "// line comment\n" 16484 "int oneTwoThree=123;", 16485 Alignment)); 16486 } 16487 16488 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16489 FormatStyle Alignment = getLLVMStyle(); 16490 Alignment.AlignConsecutiveMacros.Enabled = true; 16491 Alignment.AlignConsecutiveAssignments.Enabled = true; 16492 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16493 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16494 verifyFormat("int a = 5;\n" 16495 "int oneTwoThree = 123;", 16496 Alignment); 16497 verifyFormat("int a = method();\n" 16498 "int oneTwoThree = 133;", 16499 Alignment); 16500 verifyFormat("a &= 5;\n" 16501 "bcd *= 5;\n" 16502 "ghtyf += 5;\n" 16503 "dvfvdb -= 5;\n" 16504 "a /= 5;\n" 16505 "vdsvsv %= 5;\n" 16506 "sfdbddfbdfbb ^= 5;\n" 16507 "dvsdsv |= 5;\n" 16508 "int dsvvdvsdvvv = 123;", 16509 Alignment); 16510 verifyFormat("int i = 1, j = 10;\n" 16511 "something = 2000;", 16512 Alignment); 16513 verifyFormat("something = 2000;\n" 16514 "int i = 1, j = 10;\n", 16515 Alignment); 16516 verifyFormat("something = 2000;\n" 16517 "another = 911;\n" 16518 "int i = 1, j = 10;\n" 16519 "oneMore = 1;\n" 16520 "i = 2;", 16521 Alignment); 16522 verifyFormat("int a = 5;\n" 16523 "int one = 1;\n" 16524 "method();\n" 16525 "int oneTwoThree = 123;\n" 16526 "int oneTwo = 12;", 16527 Alignment); 16528 verifyFormat("int oneTwoThree = 123;\n" 16529 "int oneTwo = 12;\n" 16530 "method();\n", 16531 Alignment); 16532 verifyFormat("int oneTwoThree = 123; // comment\n" 16533 "int oneTwo = 12; // comment", 16534 Alignment); 16535 16536 // Bug 25167 16537 /* Uncomment when fixed 16538 verifyFormat("#if A\n" 16539 "#else\n" 16540 "int aaaaaaaa = 12;\n" 16541 "#endif\n" 16542 "#if B\n" 16543 "#else\n" 16544 "int a = 12;\n" 16545 "#endif\n", 16546 Alignment); 16547 verifyFormat("enum foo {\n" 16548 "#if A\n" 16549 "#else\n" 16550 " aaaaaaaa = 12;\n" 16551 "#endif\n" 16552 "#if B\n" 16553 "#else\n" 16554 " a = 12;\n" 16555 "#endif\n" 16556 "};\n", 16557 Alignment); 16558 */ 16559 16560 Alignment.MaxEmptyLinesToKeep = 10; 16561 /* Test alignment across empty lines */ 16562 EXPECT_EQ("int a = 5;\n" 16563 "\n" 16564 "int oneTwoThree = 123;", 16565 format("int a = 5;\n" 16566 "\n" 16567 "int oneTwoThree= 123;", 16568 Alignment)); 16569 EXPECT_EQ("int a = 5;\n" 16570 "int one = 1;\n" 16571 "\n" 16572 "int oneTwoThree = 123;", 16573 format("int a = 5;\n" 16574 "int one = 1;\n" 16575 "\n" 16576 "int oneTwoThree = 123;", 16577 Alignment)); 16578 EXPECT_EQ("int a = 5;\n" 16579 "int one = 1;\n" 16580 "\n" 16581 "int oneTwoThree = 123;\n" 16582 "int oneTwo = 12;", 16583 format("int a = 5;\n" 16584 "int one = 1;\n" 16585 "\n" 16586 "int oneTwoThree = 123;\n" 16587 "int oneTwo = 12;", 16588 Alignment)); 16589 16590 /* Test across comments */ 16591 EXPECT_EQ("int a = 5;\n" 16592 "/* block comment */\n" 16593 "int oneTwoThree = 123;", 16594 format("int a = 5;\n" 16595 "/* block comment */\n" 16596 "int oneTwoThree=123;", 16597 Alignment)); 16598 16599 EXPECT_EQ("int a = 5;\n" 16600 "// line comment\n" 16601 "int oneTwoThree = 123;", 16602 format("int a = 5;\n" 16603 "// line comment\n" 16604 "int oneTwoThree=123;", 16605 Alignment)); 16606 16607 /* Test across comments and newlines */ 16608 EXPECT_EQ("int a = 5;\n" 16609 "\n" 16610 "/* block comment */\n" 16611 "int oneTwoThree = 123;", 16612 format("int a = 5;\n" 16613 "\n" 16614 "/* block comment */\n" 16615 "int oneTwoThree=123;", 16616 Alignment)); 16617 16618 EXPECT_EQ("int a = 5;\n" 16619 "\n" 16620 "// line comment\n" 16621 "int oneTwoThree = 123;", 16622 format("int a = 5;\n" 16623 "\n" 16624 "// line comment\n" 16625 "int oneTwoThree=123;", 16626 Alignment)); 16627 16628 EXPECT_EQ("int a = 5;\n" 16629 "//\n" 16630 "// multi-line line comment\n" 16631 "//\n" 16632 "int oneTwoThree = 123;", 16633 format("int a = 5;\n" 16634 "//\n" 16635 "// multi-line line comment\n" 16636 "//\n" 16637 "int oneTwoThree=123;", 16638 Alignment)); 16639 16640 EXPECT_EQ("int a = 5;\n" 16641 "/*\n" 16642 " * multi-line block comment\n" 16643 " */\n" 16644 "int oneTwoThree = 123;", 16645 format("int a = 5;\n" 16646 "/*\n" 16647 " * multi-line block comment\n" 16648 " */\n" 16649 "int oneTwoThree=123;", 16650 Alignment)); 16651 16652 EXPECT_EQ("int a = 5;\n" 16653 "\n" 16654 "/* block comment */\n" 16655 "\n" 16656 "\n" 16657 "\n" 16658 "int oneTwoThree = 123;", 16659 format("int a = 5;\n" 16660 "\n" 16661 "/* block comment */\n" 16662 "\n" 16663 "\n" 16664 "\n" 16665 "int oneTwoThree=123;", 16666 Alignment)); 16667 16668 EXPECT_EQ("int a = 5;\n" 16669 "\n" 16670 "// line comment\n" 16671 "\n" 16672 "\n" 16673 "\n" 16674 "int oneTwoThree = 123;", 16675 format("int a = 5;\n" 16676 "\n" 16677 "// line comment\n" 16678 "\n" 16679 "\n" 16680 "\n" 16681 "int oneTwoThree=123;", 16682 Alignment)); 16683 16684 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16685 verifyFormat("#define A \\\n" 16686 " int aaaa = 12; \\\n" 16687 " int b = 23; \\\n" 16688 " int ccc = 234; \\\n" 16689 " int dddddddddd = 2345;", 16690 Alignment); 16691 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16692 verifyFormat("#define A \\\n" 16693 " int aaaa = 12; \\\n" 16694 " int b = 23; \\\n" 16695 " int ccc = 234; \\\n" 16696 " int dddddddddd = 2345;", 16697 Alignment); 16698 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16699 verifyFormat("#define A " 16700 " \\\n" 16701 " int aaaa = 12; " 16702 " \\\n" 16703 " int b = 23; " 16704 " \\\n" 16705 " int ccc = 234; " 16706 " \\\n" 16707 " int dddddddddd = 2345;", 16708 Alignment); 16709 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16710 "k = 4, int l = 5,\n" 16711 " int m = 6) {\n" 16712 " int j = 10;\n" 16713 " otherThing = 1;\n" 16714 "}", 16715 Alignment); 16716 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16717 " int i = 1;\n" 16718 " int j = 2;\n" 16719 " int big = 10000;\n" 16720 "}", 16721 Alignment); 16722 verifyFormat("class C {\n" 16723 "public:\n" 16724 " int i = 1;\n" 16725 " virtual void f() = 0;\n" 16726 "};", 16727 Alignment); 16728 verifyFormat("int i = 1;\n" 16729 "if (SomeType t = getSomething()) {\n" 16730 "}\n" 16731 "int j = 2;\n" 16732 "int big = 10000;", 16733 Alignment); 16734 verifyFormat("int j = 7;\n" 16735 "for (int k = 0; k < N; ++k) {\n" 16736 "}\n" 16737 "int j = 2;\n" 16738 "int big = 10000;\n" 16739 "}", 16740 Alignment); 16741 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16742 verifyFormat("int i = 1;\n" 16743 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16744 " = someLooooooooooooooooongFunction();\n" 16745 "int j = 2;", 16746 Alignment); 16747 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16748 verifyFormat("int i = 1;\n" 16749 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16750 " someLooooooooooooooooongFunction();\n" 16751 "int j = 2;", 16752 Alignment); 16753 16754 verifyFormat("auto lambda = []() {\n" 16755 " auto i = 0;\n" 16756 " return 0;\n" 16757 "};\n" 16758 "int i = 0;\n" 16759 "auto v = type{\n" 16760 " i = 1, //\n" 16761 " (i = 2), //\n" 16762 " i = 3 //\n" 16763 "};", 16764 Alignment); 16765 16766 verifyFormat( 16767 "int i = 1;\n" 16768 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16769 " loooooooooooooooooooooongParameterB);\n" 16770 "int j = 2;", 16771 Alignment); 16772 16773 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16774 " typename B = very_long_type_name_1,\n" 16775 " typename T_2 = very_long_type_name_2>\n" 16776 "auto foo() {}\n", 16777 Alignment); 16778 verifyFormat("int a, b = 1;\n" 16779 "int c = 2;\n" 16780 "int dd = 3;\n", 16781 Alignment); 16782 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16783 "float b[1][] = {{3.f}};\n", 16784 Alignment); 16785 verifyFormat("for (int i = 0; i < 1; i++)\n" 16786 " int x = 1;\n", 16787 Alignment); 16788 verifyFormat("for (i = 0; i < 1; i++)\n" 16789 " x = 1;\n" 16790 "y = 1;\n", 16791 Alignment); 16792 16793 Alignment.ReflowComments = true; 16794 Alignment.ColumnLimit = 50; 16795 EXPECT_EQ("int x = 0;\n" 16796 "int yy = 1; /// specificlennospace\n" 16797 "int zzz = 2;\n", 16798 format("int x = 0;\n" 16799 "int yy = 1; ///specificlennospace\n" 16800 "int zzz = 2;\n", 16801 Alignment)); 16802 } 16803 16804 TEST_F(FormatTest, AlignCompoundAssignments) { 16805 FormatStyle Alignment = getLLVMStyle(); 16806 Alignment.AlignConsecutiveAssignments.Enabled = true; 16807 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 16808 Alignment.AlignConsecutiveAssignments.PadOperators = false; 16809 verifyFormat("sfdbddfbdfbb = 5;\n" 16810 "dvsdsv = 5;\n" 16811 "int dsvvdvsdvvv = 123;", 16812 Alignment); 16813 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16814 "dvsdsv |= 5;\n" 16815 "int dsvvdvsdvvv = 123;", 16816 Alignment); 16817 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16818 "dvsdsv <<= 5;\n" 16819 "int dsvvdvsdvvv = 123;", 16820 Alignment); 16821 // Test that `<=` is not treated as a compound assignment. 16822 verifyFormat("aa &= 5;\n" 16823 "b <= 10;\n" 16824 "c = 15;", 16825 Alignment); 16826 Alignment.AlignConsecutiveAssignments.PadOperators = true; 16827 verifyFormat("sfdbddfbdfbb = 5;\n" 16828 "dvsdsv = 5;\n" 16829 "int dsvvdvsdvvv = 123;", 16830 Alignment); 16831 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16832 "dvsdsv |= 5;\n" 16833 "int dsvvdvsdvvv = 123;", 16834 Alignment); 16835 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16836 "dvsdsv <<= 5;\n" 16837 "int dsvvdvsdvvv = 123;", 16838 Alignment); 16839 EXPECT_EQ("a += 5;\n" 16840 "one = 1;\n" 16841 "\n" 16842 "oneTwoThree = 123;\n", 16843 format("a += 5;\n" 16844 "one = 1;\n" 16845 "\n" 16846 "oneTwoThree = 123;\n", 16847 Alignment)); 16848 EXPECT_EQ("a += 5;\n" 16849 "one = 1;\n" 16850 "//\n" 16851 "oneTwoThree = 123;\n", 16852 format("a += 5;\n" 16853 "one = 1;\n" 16854 "//\n" 16855 "oneTwoThree = 123;\n", 16856 Alignment)); 16857 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16858 EXPECT_EQ("a += 5;\n" 16859 "one = 1;\n" 16860 "\n" 16861 "oneTwoThree = 123;\n", 16862 format("a += 5;\n" 16863 "one = 1;\n" 16864 "\n" 16865 "oneTwoThree = 123;\n", 16866 Alignment)); 16867 EXPECT_EQ("a += 5;\n" 16868 "one = 1;\n" 16869 "//\n" 16870 "oneTwoThree = 123;\n", 16871 format("a += 5;\n" 16872 "one = 1;\n" 16873 "//\n" 16874 "oneTwoThree = 123;\n", 16875 Alignment)); 16876 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 16877 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16878 EXPECT_EQ("a += 5;\n" 16879 "one = 1;\n" 16880 "\n" 16881 "oneTwoThree = 123;\n", 16882 format("a += 5;\n" 16883 "one = 1;\n" 16884 "\n" 16885 "oneTwoThree = 123;\n", 16886 Alignment)); 16887 EXPECT_EQ("a += 5;\n" 16888 "one = 1;\n" 16889 "//\n" 16890 "oneTwoThree = 123;\n", 16891 format("a += 5;\n" 16892 "one = 1;\n" 16893 "//\n" 16894 "oneTwoThree = 123;\n", 16895 Alignment)); 16896 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16897 EXPECT_EQ("a += 5;\n" 16898 "one >>= 1;\n" 16899 "\n" 16900 "oneTwoThree = 123;\n", 16901 format("a += 5;\n" 16902 "one >>= 1;\n" 16903 "\n" 16904 "oneTwoThree = 123;\n", 16905 Alignment)); 16906 EXPECT_EQ("a += 5;\n" 16907 "one = 1;\n" 16908 "//\n" 16909 "oneTwoThree <<= 123;\n", 16910 format("a += 5;\n" 16911 "one = 1;\n" 16912 "//\n" 16913 "oneTwoThree <<= 123;\n", 16914 Alignment)); 16915 } 16916 16917 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16918 FormatStyle Alignment = getLLVMStyle(); 16919 Alignment.AlignConsecutiveMacros.Enabled = true; 16920 verifyFormat("int a = 5;\n" 16921 "int oneTwoThree = 123;", 16922 Alignment); 16923 verifyFormat("int a = 5;\n" 16924 "int oneTwoThree = 123;", 16925 Alignment); 16926 16927 Alignment.AlignConsecutiveAssignments.Enabled = true; 16928 verifyFormat("int a = 5;\n" 16929 "int oneTwoThree = 123;", 16930 Alignment); 16931 verifyFormat("int a = method();\n" 16932 "int oneTwoThree = 133;", 16933 Alignment); 16934 verifyFormat("aa <= 5;\n" 16935 "a &= 5;\n" 16936 "bcd *= 5;\n" 16937 "ghtyf += 5;\n" 16938 "dvfvdb -= 5;\n" 16939 "a /= 5;\n" 16940 "vdsvsv %= 5;\n" 16941 "sfdbddfbdfbb ^= 5;\n" 16942 "dvsdsv |= 5;\n" 16943 "int dsvvdvsdvvv = 123;", 16944 Alignment); 16945 verifyFormat("int i = 1, j = 10;\n" 16946 "something = 2000;", 16947 Alignment); 16948 verifyFormat("something = 2000;\n" 16949 "int i = 1, j = 10;\n", 16950 Alignment); 16951 verifyFormat("something = 2000;\n" 16952 "another = 911;\n" 16953 "int i = 1, j = 10;\n" 16954 "oneMore = 1;\n" 16955 "i = 2;", 16956 Alignment); 16957 verifyFormat("int a = 5;\n" 16958 "int one = 1;\n" 16959 "method();\n" 16960 "int oneTwoThree = 123;\n" 16961 "int oneTwo = 12;", 16962 Alignment); 16963 verifyFormat("int oneTwoThree = 123;\n" 16964 "int oneTwo = 12;\n" 16965 "method();\n", 16966 Alignment); 16967 verifyFormat("int oneTwoThree = 123; // comment\n" 16968 "int oneTwo = 12; // comment", 16969 Alignment); 16970 verifyFormat("int f() = default;\n" 16971 "int &operator() = default;\n" 16972 "int &operator=() {", 16973 Alignment); 16974 verifyFormat("int f() = delete;\n" 16975 "int &operator() = delete;\n" 16976 "int &operator=() {", 16977 Alignment); 16978 verifyFormat("int f() = default; // comment\n" 16979 "int &operator() = default; // comment\n" 16980 "int &operator=() {", 16981 Alignment); 16982 verifyFormat("int f() = default;\n" 16983 "int &operator() = default;\n" 16984 "int &operator==() {", 16985 Alignment); 16986 verifyFormat("int f() = default;\n" 16987 "int &operator() = default;\n" 16988 "int &operator<=() {", 16989 Alignment); 16990 verifyFormat("int f() = default;\n" 16991 "int &operator() = default;\n" 16992 "int &operator!=() {", 16993 Alignment); 16994 verifyFormat("int f() = default;\n" 16995 "int &operator() = default;\n" 16996 "int &operator=();", 16997 Alignment); 16998 verifyFormat("int f() = delete;\n" 16999 "int &operator() = delete;\n" 17000 "int &operator=();", 17001 Alignment); 17002 verifyFormat("/* long long padding */ int f() = default;\n" 17003 "int &operator() = default;\n" 17004 "int &operator/**/ =();", 17005 Alignment); 17006 // https://llvm.org/PR33697 17007 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17008 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17009 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17010 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17011 " void f() = delete;\n" 17012 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17013 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17014 "};\n", 17015 AlignmentWithPenalty); 17016 17017 // Bug 25167 17018 /* Uncomment when fixed 17019 verifyFormat("#if A\n" 17020 "#else\n" 17021 "int aaaaaaaa = 12;\n" 17022 "#endif\n" 17023 "#if B\n" 17024 "#else\n" 17025 "int a = 12;\n" 17026 "#endif\n", 17027 Alignment); 17028 verifyFormat("enum foo {\n" 17029 "#if A\n" 17030 "#else\n" 17031 " aaaaaaaa = 12;\n" 17032 "#endif\n" 17033 "#if B\n" 17034 "#else\n" 17035 " a = 12;\n" 17036 "#endif\n" 17037 "};\n", 17038 Alignment); 17039 */ 17040 17041 EXPECT_EQ("int a = 5;\n" 17042 "\n" 17043 "int oneTwoThree = 123;", 17044 format("int a = 5;\n" 17045 "\n" 17046 "int oneTwoThree= 123;", 17047 Alignment)); 17048 EXPECT_EQ("int a = 5;\n" 17049 "int one = 1;\n" 17050 "\n" 17051 "int oneTwoThree = 123;", 17052 format("int a = 5;\n" 17053 "int one = 1;\n" 17054 "\n" 17055 "int oneTwoThree = 123;", 17056 Alignment)); 17057 EXPECT_EQ("int a = 5;\n" 17058 "int one = 1;\n" 17059 "\n" 17060 "int oneTwoThree = 123;\n" 17061 "int oneTwo = 12;", 17062 format("int a = 5;\n" 17063 "int one = 1;\n" 17064 "\n" 17065 "int oneTwoThree = 123;\n" 17066 "int oneTwo = 12;", 17067 Alignment)); 17068 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17069 verifyFormat("#define A \\\n" 17070 " int aaaa = 12; \\\n" 17071 " int b = 23; \\\n" 17072 " int ccc = 234; \\\n" 17073 " int dddddddddd = 2345;", 17074 Alignment); 17075 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17076 verifyFormat("#define A \\\n" 17077 " int aaaa = 12; \\\n" 17078 " int b = 23; \\\n" 17079 " int ccc = 234; \\\n" 17080 " int dddddddddd = 2345;", 17081 Alignment); 17082 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17083 verifyFormat("#define A " 17084 " \\\n" 17085 " int aaaa = 12; " 17086 " \\\n" 17087 " int b = 23; " 17088 " \\\n" 17089 " int ccc = 234; " 17090 " \\\n" 17091 " int dddddddddd = 2345;", 17092 Alignment); 17093 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17094 "k = 4, int l = 5,\n" 17095 " int m = 6) {\n" 17096 " int j = 10;\n" 17097 " otherThing = 1;\n" 17098 "}", 17099 Alignment); 17100 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17101 " int i = 1;\n" 17102 " int j = 2;\n" 17103 " int big = 10000;\n" 17104 "}", 17105 Alignment); 17106 verifyFormat("class C {\n" 17107 "public:\n" 17108 " int i = 1;\n" 17109 " virtual void f() = 0;\n" 17110 "};", 17111 Alignment); 17112 verifyFormat("int i = 1;\n" 17113 "if (SomeType t = getSomething()) {\n" 17114 "}\n" 17115 "int j = 2;\n" 17116 "int big = 10000;", 17117 Alignment); 17118 verifyFormat("int j = 7;\n" 17119 "for (int k = 0; k < N; ++k) {\n" 17120 "}\n" 17121 "int j = 2;\n" 17122 "int big = 10000;\n" 17123 "}", 17124 Alignment); 17125 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17126 verifyFormat("int i = 1;\n" 17127 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17128 " = someLooooooooooooooooongFunction();\n" 17129 "int j = 2;", 17130 Alignment); 17131 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17132 verifyFormat("int i = 1;\n" 17133 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17134 " someLooooooooooooooooongFunction();\n" 17135 "int j = 2;", 17136 Alignment); 17137 17138 verifyFormat("auto lambda = []() {\n" 17139 " auto i = 0;\n" 17140 " return 0;\n" 17141 "};\n" 17142 "int i = 0;\n" 17143 "auto v = type{\n" 17144 " i = 1, //\n" 17145 " (i = 2), //\n" 17146 " i = 3 //\n" 17147 "};", 17148 Alignment); 17149 17150 verifyFormat( 17151 "int i = 1;\n" 17152 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17153 " loooooooooooooooooooooongParameterB);\n" 17154 "int j = 2;", 17155 Alignment); 17156 17157 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17158 " typename B = very_long_type_name_1,\n" 17159 " typename T_2 = very_long_type_name_2>\n" 17160 "auto foo() {}\n", 17161 Alignment); 17162 verifyFormat("int a, b = 1;\n" 17163 "int c = 2;\n" 17164 "int dd = 3;\n", 17165 Alignment); 17166 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17167 "float b[1][] = {{3.f}};\n", 17168 Alignment); 17169 verifyFormat("for (int i = 0; i < 1; i++)\n" 17170 " int x = 1;\n", 17171 Alignment); 17172 verifyFormat("for (i = 0; i < 1; i++)\n" 17173 " x = 1;\n" 17174 "y = 1;\n", 17175 Alignment); 17176 17177 EXPECT_EQ(Alignment.ReflowComments, true); 17178 Alignment.ColumnLimit = 50; 17179 EXPECT_EQ("int x = 0;\n" 17180 "int yy = 1; /// specificlennospace\n" 17181 "int zzz = 2;\n", 17182 format("int x = 0;\n" 17183 "int yy = 1; ///specificlennospace\n" 17184 "int zzz = 2;\n", 17185 Alignment)); 17186 17187 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17188 "auto b = [] {\n" 17189 " f();\n" 17190 " return;\n" 17191 "};", 17192 Alignment); 17193 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17194 "auto b = g([] {\n" 17195 " f();\n" 17196 " return;\n" 17197 "});", 17198 Alignment); 17199 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17200 "auto b = g(param, [] {\n" 17201 " f();\n" 17202 " return;\n" 17203 "});", 17204 Alignment); 17205 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17206 "auto b = [] {\n" 17207 " if (condition) {\n" 17208 " return;\n" 17209 " }\n" 17210 "};", 17211 Alignment); 17212 17213 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17214 " ccc ? aaaaa : bbbbb,\n" 17215 " dddddddddddddddddddddddddd);", 17216 Alignment); 17217 // FIXME: https://llvm.org/PR53497 17218 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17219 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17220 // " ccc ? aaaaa : bbbbb,\n" 17221 // " dddddddddddddddddddddddddd);", 17222 // Alignment); 17223 } 17224 17225 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17226 FormatStyle Alignment = getLLVMStyle(); 17227 Alignment.AlignConsecutiveBitFields.Enabled = true; 17228 verifyFormat("int const a : 5;\n" 17229 "int oneTwoThree : 23;", 17230 Alignment); 17231 17232 // Initializers are allowed starting with c++2a 17233 verifyFormat("int const a : 5 = 1;\n" 17234 "int oneTwoThree : 23 = 0;", 17235 Alignment); 17236 17237 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17238 verifyFormat("int const a : 5;\n" 17239 "int oneTwoThree : 23;", 17240 Alignment); 17241 17242 verifyFormat("int const a : 5; // comment\n" 17243 "int oneTwoThree : 23; // comment", 17244 Alignment); 17245 17246 verifyFormat("int const a : 5 = 1;\n" 17247 "int oneTwoThree : 23 = 0;", 17248 Alignment); 17249 17250 Alignment.AlignConsecutiveAssignments.Enabled = true; 17251 verifyFormat("int const a : 5 = 1;\n" 17252 "int oneTwoThree : 23 = 0;", 17253 Alignment); 17254 verifyFormat("int const a : 5 = {1};\n" 17255 "int oneTwoThree : 23 = 0;", 17256 Alignment); 17257 17258 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17259 verifyFormat("int const a :5;\n" 17260 "int oneTwoThree:23;", 17261 Alignment); 17262 17263 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17264 verifyFormat("int const a :5;\n" 17265 "int oneTwoThree :23;", 17266 Alignment); 17267 17268 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17269 verifyFormat("int const a : 5;\n" 17270 "int oneTwoThree: 23;", 17271 Alignment); 17272 17273 // Known limitations: ':' is only recognized as a bitfield colon when 17274 // followed by a number. 17275 /* 17276 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17277 "int a : 5;", 17278 Alignment); 17279 */ 17280 } 17281 17282 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17283 FormatStyle Alignment = getLLVMStyle(); 17284 Alignment.AlignConsecutiveMacros.Enabled = true; 17285 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17286 verifyFormat("float const a = 5;\n" 17287 "int oneTwoThree = 123;", 17288 Alignment); 17289 verifyFormat("int a = 5;\n" 17290 "float const oneTwoThree = 123;", 17291 Alignment); 17292 17293 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17294 verifyFormat("float const a = 5;\n" 17295 "int oneTwoThree = 123;", 17296 Alignment); 17297 verifyFormat("int a = method();\n" 17298 "float const oneTwoThree = 133;", 17299 Alignment); 17300 verifyFormat("int i = 1, j = 10;\n" 17301 "something = 2000;", 17302 Alignment); 17303 verifyFormat("something = 2000;\n" 17304 "int i = 1, j = 10;\n", 17305 Alignment); 17306 verifyFormat("float something = 2000;\n" 17307 "double another = 911;\n" 17308 "int i = 1, j = 10;\n" 17309 "const int *oneMore = 1;\n" 17310 "unsigned i = 2;", 17311 Alignment); 17312 verifyFormat("float a = 5;\n" 17313 "int one = 1;\n" 17314 "method();\n" 17315 "const double oneTwoThree = 123;\n" 17316 "const unsigned int oneTwo = 12;", 17317 Alignment); 17318 verifyFormat("int oneTwoThree{0}; // comment\n" 17319 "unsigned oneTwo; // comment", 17320 Alignment); 17321 verifyFormat("unsigned int *a;\n" 17322 "int *b;\n" 17323 "unsigned int Const *c;\n" 17324 "unsigned int const *d;\n" 17325 "unsigned int Const &e;\n" 17326 "unsigned int const &f;", 17327 Alignment); 17328 verifyFormat("Const unsigned int *c;\n" 17329 "const unsigned int *d;\n" 17330 "Const unsigned int &e;\n" 17331 "const unsigned int &f;\n" 17332 "const unsigned g;\n" 17333 "Const unsigned h;", 17334 Alignment); 17335 EXPECT_EQ("float const a = 5;\n" 17336 "\n" 17337 "int oneTwoThree = 123;", 17338 format("float const a = 5;\n" 17339 "\n" 17340 "int oneTwoThree= 123;", 17341 Alignment)); 17342 EXPECT_EQ("float a = 5;\n" 17343 "int one = 1;\n" 17344 "\n" 17345 "unsigned oneTwoThree = 123;", 17346 format("float a = 5;\n" 17347 "int one = 1;\n" 17348 "\n" 17349 "unsigned oneTwoThree = 123;", 17350 Alignment)); 17351 EXPECT_EQ("float a = 5;\n" 17352 "int one = 1;\n" 17353 "\n" 17354 "unsigned oneTwoThree = 123;\n" 17355 "int oneTwo = 12;", 17356 format("float a = 5;\n" 17357 "int one = 1;\n" 17358 "\n" 17359 "unsigned oneTwoThree = 123;\n" 17360 "int oneTwo = 12;", 17361 Alignment)); 17362 // Function prototype alignment 17363 verifyFormat("int a();\n" 17364 "double b();", 17365 Alignment); 17366 verifyFormat("int a(int x);\n" 17367 "double b();", 17368 Alignment); 17369 unsigned OldColumnLimit = Alignment.ColumnLimit; 17370 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17371 // otherwise the function parameters will be re-flowed onto a single line. 17372 Alignment.ColumnLimit = 0; 17373 EXPECT_EQ("int a(int x,\n" 17374 " float y);\n" 17375 "double b(int x,\n" 17376 " double y);", 17377 format("int a(int x,\n" 17378 " float y);\n" 17379 "double b(int x,\n" 17380 " double y);", 17381 Alignment)); 17382 // This ensures that function parameters of function declarations are 17383 // correctly indented when their owning functions are indented. 17384 // The failure case here is for 'double y' to not be indented enough. 17385 EXPECT_EQ("double a(int x);\n" 17386 "int b(int y,\n" 17387 " double z);", 17388 format("double a(int x);\n" 17389 "int b(int y,\n" 17390 " double z);", 17391 Alignment)); 17392 // Set ColumnLimit low so that we induce wrapping immediately after 17393 // the function name and opening paren. 17394 Alignment.ColumnLimit = 13; 17395 verifyFormat("int function(\n" 17396 " int x,\n" 17397 " bool y);", 17398 Alignment); 17399 Alignment.ColumnLimit = OldColumnLimit; 17400 // Ensure function pointers don't screw up recursive alignment 17401 verifyFormat("int a(int x, void (*fp)(int y));\n" 17402 "double b();", 17403 Alignment); 17404 Alignment.AlignConsecutiveAssignments.Enabled = true; 17405 // Ensure recursive alignment is broken by function braces, so that the 17406 // "a = 1" does not align with subsequent assignments inside the function 17407 // body. 17408 verifyFormat("int func(int a = 1) {\n" 17409 " int b = 2;\n" 17410 " int cc = 3;\n" 17411 "}", 17412 Alignment); 17413 verifyFormat("float something = 2000;\n" 17414 "double another = 911;\n" 17415 "int i = 1, j = 10;\n" 17416 "const int *oneMore = 1;\n" 17417 "unsigned i = 2;", 17418 Alignment); 17419 verifyFormat("int oneTwoThree = {0}; // comment\n" 17420 "unsigned oneTwo = 0; // comment", 17421 Alignment); 17422 // Make sure that scope is correctly tracked, in the absence of braces 17423 verifyFormat("for (int i = 0; i < n; i++)\n" 17424 " j = i;\n" 17425 "double x = 1;\n", 17426 Alignment); 17427 verifyFormat("if (int i = 0)\n" 17428 " j = i;\n" 17429 "double x = 1;\n", 17430 Alignment); 17431 // Ensure operator[] and operator() are comprehended 17432 verifyFormat("struct test {\n" 17433 " long long int foo();\n" 17434 " int operator[](int a);\n" 17435 " double bar();\n" 17436 "};\n", 17437 Alignment); 17438 verifyFormat("struct test {\n" 17439 " long long int foo();\n" 17440 " int operator()(int a);\n" 17441 " double bar();\n" 17442 "};\n", 17443 Alignment); 17444 // http://llvm.org/PR52914 17445 verifyFormat("char *a[] = {\"a\", // comment\n" 17446 " \"bb\"};\n" 17447 "int bbbbbbb = 0;", 17448 Alignment); 17449 17450 // PAS_Right 17451 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17452 " int const i = 1;\n" 17453 " int *j = 2;\n" 17454 " int big = 10000;\n" 17455 "\n" 17456 " unsigned oneTwoThree = 123;\n" 17457 " int oneTwo = 12;\n" 17458 " method();\n" 17459 " float k = 2;\n" 17460 " int ll = 10000;\n" 17461 "}", 17462 format("void SomeFunction(int parameter= 0) {\n" 17463 " int const i= 1;\n" 17464 " int *j=2;\n" 17465 " int big = 10000;\n" 17466 "\n" 17467 "unsigned oneTwoThree =123;\n" 17468 "int oneTwo = 12;\n" 17469 " method();\n" 17470 "float k= 2;\n" 17471 "int ll=10000;\n" 17472 "}", 17473 Alignment)); 17474 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17475 " int const i = 1;\n" 17476 " int **j = 2, ***k;\n" 17477 " int &k = i;\n" 17478 " int &&l = i + j;\n" 17479 " int big = 10000;\n" 17480 "\n" 17481 " unsigned oneTwoThree = 123;\n" 17482 " int oneTwo = 12;\n" 17483 " method();\n" 17484 " float k = 2;\n" 17485 " int ll = 10000;\n" 17486 "}", 17487 format("void SomeFunction(int parameter= 0) {\n" 17488 " int const i= 1;\n" 17489 " int **j=2,***k;\n" 17490 "int &k=i;\n" 17491 "int &&l=i+j;\n" 17492 " int big = 10000;\n" 17493 "\n" 17494 "unsigned oneTwoThree =123;\n" 17495 "int oneTwo = 12;\n" 17496 " method();\n" 17497 "float k= 2;\n" 17498 "int ll=10000;\n" 17499 "}", 17500 Alignment)); 17501 // variables are aligned at their name, pointers are at the right most 17502 // position 17503 verifyFormat("int *a;\n" 17504 "int **b;\n" 17505 "int ***c;\n" 17506 "int foobar;\n", 17507 Alignment); 17508 17509 // PAS_Left 17510 FormatStyle AlignmentLeft = Alignment; 17511 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17512 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17513 " int const i = 1;\n" 17514 " int* j = 2;\n" 17515 " int big = 10000;\n" 17516 "\n" 17517 " unsigned oneTwoThree = 123;\n" 17518 " int oneTwo = 12;\n" 17519 " method();\n" 17520 " float k = 2;\n" 17521 " int ll = 10000;\n" 17522 "}", 17523 format("void SomeFunction(int parameter= 0) {\n" 17524 " int const i= 1;\n" 17525 " int *j=2;\n" 17526 " int big = 10000;\n" 17527 "\n" 17528 "unsigned oneTwoThree =123;\n" 17529 "int oneTwo = 12;\n" 17530 " method();\n" 17531 "float k= 2;\n" 17532 "int ll=10000;\n" 17533 "}", 17534 AlignmentLeft)); 17535 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17536 " int const i = 1;\n" 17537 " int** j = 2;\n" 17538 " int& k = i;\n" 17539 " int&& l = i + j;\n" 17540 " int big = 10000;\n" 17541 "\n" 17542 " unsigned oneTwoThree = 123;\n" 17543 " int oneTwo = 12;\n" 17544 " method();\n" 17545 " float k = 2;\n" 17546 " int ll = 10000;\n" 17547 "}", 17548 format("void SomeFunction(int parameter= 0) {\n" 17549 " int const i= 1;\n" 17550 " int **j=2;\n" 17551 "int &k=i;\n" 17552 "int &&l=i+j;\n" 17553 " int big = 10000;\n" 17554 "\n" 17555 "unsigned oneTwoThree =123;\n" 17556 "int oneTwo = 12;\n" 17557 " method();\n" 17558 "float k= 2;\n" 17559 "int ll=10000;\n" 17560 "}", 17561 AlignmentLeft)); 17562 // variables are aligned at their name, pointers are at the left most position 17563 verifyFormat("int* a;\n" 17564 "int** b;\n" 17565 "int*** c;\n" 17566 "int foobar;\n", 17567 AlignmentLeft); 17568 17569 // PAS_Middle 17570 FormatStyle AlignmentMiddle = Alignment; 17571 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17572 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17573 " int const i = 1;\n" 17574 " int * j = 2;\n" 17575 " int big = 10000;\n" 17576 "\n" 17577 " unsigned oneTwoThree = 123;\n" 17578 " int oneTwo = 12;\n" 17579 " method();\n" 17580 " float k = 2;\n" 17581 " int ll = 10000;\n" 17582 "}", 17583 format("void SomeFunction(int parameter= 0) {\n" 17584 " int const i= 1;\n" 17585 " int *j=2;\n" 17586 " int big = 10000;\n" 17587 "\n" 17588 "unsigned oneTwoThree =123;\n" 17589 "int oneTwo = 12;\n" 17590 " method();\n" 17591 "float k= 2;\n" 17592 "int ll=10000;\n" 17593 "}", 17594 AlignmentMiddle)); 17595 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17596 " int const i = 1;\n" 17597 " int ** j = 2, ***k;\n" 17598 " int & k = i;\n" 17599 " int && l = i + j;\n" 17600 " int big = 10000;\n" 17601 "\n" 17602 " unsigned oneTwoThree = 123;\n" 17603 " int oneTwo = 12;\n" 17604 " method();\n" 17605 " float k = 2;\n" 17606 " int ll = 10000;\n" 17607 "}", 17608 format("void SomeFunction(int parameter= 0) {\n" 17609 " int const i= 1;\n" 17610 " int **j=2,***k;\n" 17611 "int &k=i;\n" 17612 "int &&l=i+j;\n" 17613 " int big = 10000;\n" 17614 "\n" 17615 "unsigned oneTwoThree =123;\n" 17616 "int oneTwo = 12;\n" 17617 " method();\n" 17618 "float k= 2;\n" 17619 "int ll=10000;\n" 17620 "}", 17621 AlignmentMiddle)); 17622 // variables are aligned at their name, pointers are in the middle 17623 verifyFormat("int * a;\n" 17624 "int * b;\n" 17625 "int *** c;\n" 17626 "int foobar;\n", 17627 AlignmentMiddle); 17628 17629 Alignment.AlignConsecutiveAssignments.Enabled = false; 17630 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17631 verifyFormat("#define A \\\n" 17632 " int aaaa = 12; \\\n" 17633 " float b = 23; \\\n" 17634 " const int ccc = 234; \\\n" 17635 " unsigned dddddddddd = 2345;", 17636 Alignment); 17637 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17638 verifyFormat("#define A \\\n" 17639 " int aaaa = 12; \\\n" 17640 " float b = 23; \\\n" 17641 " const int ccc = 234; \\\n" 17642 " unsigned dddddddddd = 2345;", 17643 Alignment); 17644 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17645 Alignment.ColumnLimit = 30; 17646 verifyFormat("#define A \\\n" 17647 " int aaaa = 12; \\\n" 17648 " float b = 23; \\\n" 17649 " const int ccc = 234; \\\n" 17650 " int dddddddddd = 2345;", 17651 Alignment); 17652 Alignment.ColumnLimit = 80; 17653 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17654 "k = 4, int l = 5,\n" 17655 " int m = 6) {\n" 17656 " const int j = 10;\n" 17657 " otherThing = 1;\n" 17658 "}", 17659 Alignment); 17660 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17661 " int const i = 1;\n" 17662 " int *j = 2;\n" 17663 " int big = 10000;\n" 17664 "}", 17665 Alignment); 17666 verifyFormat("class C {\n" 17667 "public:\n" 17668 " int i = 1;\n" 17669 " virtual void f() = 0;\n" 17670 "};", 17671 Alignment); 17672 verifyFormat("float i = 1;\n" 17673 "if (SomeType t = getSomething()) {\n" 17674 "}\n" 17675 "const unsigned j = 2;\n" 17676 "int big = 10000;", 17677 Alignment); 17678 verifyFormat("float j = 7;\n" 17679 "for (int k = 0; k < N; ++k) {\n" 17680 "}\n" 17681 "unsigned j = 2;\n" 17682 "int big = 10000;\n" 17683 "}", 17684 Alignment); 17685 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17686 verifyFormat("float i = 1;\n" 17687 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17688 " = someLooooooooooooooooongFunction();\n" 17689 "int j = 2;", 17690 Alignment); 17691 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17692 verifyFormat("int i = 1;\n" 17693 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17694 " someLooooooooooooooooongFunction();\n" 17695 "int j = 2;", 17696 Alignment); 17697 17698 Alignment.AlignConsecutiveAssignments.Enabled = true; 17699 verifyFormat("auto lambda = []() {\n" 17700 " auto ii = 0;\n" 17701 " float j = 0;\n" 17702 " return 0;\n" 17703 "};\n" 17704 "int i = 0;\n" 17705 "float i2 = 0;\n" 17706 "auto v = type{\n" 17707 " i = 1, //\n" 17708 " (i = 2), //\n" 17709 " i = 3 //\n" 17710 "};", 17711 Alignment); 17712 Alignment.AlignConsecutiveAssignments.Enabled = false; 17713 17714 verifyFormat( 17715 "int i = 1;\n" 17716 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17717 " loooooooooooooooooooooongParameterB);\n" 17718 "int j = 2;", 17719 Alignment); 17720 17721 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17722 // We expect declarations and assignments to align, as long as it doesn't 17723 // exceed the column limit, starting a new alignment sequence whenever it 17724 // happens. 17725 Alignment.AlignConsecutiveAssignments.Enabled = true; 17726 Alignment.ColumnLimit = 30; 17727 verifyFormat("float ii = 1;\n" 17728 "unsigned j = 2;\n" 17729 "int someVerylongVariable = 1;\n" 17730 "AnotherLongType ll = 123456;\n" 17731 "VeryVeryLongType k = 2;\n" 17732 "int myvar = 1;", 17733 Alignment); 17734 Alignment.ColumnLimit = 80; 17735 Alignment.AlignConsecutiveAssignments.Enabled = false; 17736 17737 verifyFormat( 17738 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17739 " typename LongType, typename B>\n" 17740 "auto foo() {}\n", 17741 Alignment); 17742 verifyFormat("float a, b = 1;\n" 17743 "int c = 2;\n" 17744 "int dd = 3;\n", 17745 Alignment); 17746 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17747 "float b[1][] = {{3.f}};\n", 17748 Alignment); 17749 Alignment.AlignConsecutiveAssignments.Enabled = true; 17750 verifyFormat("float a, b = 1;\n" 17751 "int c = 2;\n" 17752 "int dd = 3;\n", 17753 Alignment); 17754 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17755 "float b[1][] = {{3.f}};\n", 17756 Alignment); 17757 Alignment.AlignConsecutiveAssignments.Enabled = false; 17758 17759 Alignment.ColumnLimit = 30; 17760 Alignment.BinPackParameters = false; 17761 verifyFormat("void foo(float a,\n" 17762 " float b,\n" 17763 " int c,\n" 17764 " uint32_t *d) {\n" 17765 " int *e = 0;\n" 17766 " float f = 0;\n" 17767 " double g = 0;\n" 17768 "}\n" 17769 "void bar(ino_t a,\n" 17770 " int b,\n" 17771 " uint32_t *c,\n" 17772 " bool d) {}\n", 17773 Alignment); 17774 Alignment.BinPackParameters = true; 17775 Alignment.ColumnLimit = 80; 17776 17777 // Bug 33507 17778 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17779 verifyFormat( 17780 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17781 " static const Version verVs2017;\n" 17782 " return true;\n" 17783 "});\n", 17784 Alignment); 17785 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17786 17787 // See llvm.org/PR35641 17788 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17789 verifyFormat("int func() { //\n" 17790 " int b;\n" 17791 " unsigned c;\n" 17792 "}", 17793 Alignment); 17794 17795 // See PR37175 17796 FormatStyle Style = getMozillaStyle(); 17797 Style.AlignConsecutiveDeclarations.Enabled = true; 17798 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17799 "foo(int a);", 17800 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17801 17802 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17803 verifyFormat("unsigned int* a;\n" 17804 "int* b;\n" 17805 "unsigned int Const* c;\n" 17806 "unsigned int const* d;\n" 17807 "unsigned int Const& e;\n" 17808 "unsigned int const& f;", 17809 Alignment); 17810 verifyFormat("Const unsigned int* c;\n" 17811 "const unsigned int* d;\n" 17812 "Const unsigned int& e;\n" 17813 "const unsigned int& f;\n" 17814 "const unsigned g;\n" 17815 "Const unsigned h;", 17816 Alignment); 17817 17818 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17819 verifyFormat("unsigned int * a;\n" 17820 "int * b;\n" 17821 "unsigned int Const * c;\n" 17822 "unsigned int const * d;\n" 17823 "unsigned int Const & e;\n" 17824 "unsigned int const & f;", 17825 Alignment); 17826 verifyFormat("Const unsigned int * c;\n" 17827 "const unsigned int * d;\n" 17828 "Const unsigned int & e;\n" 17829 "const unsigned int & f;\n" 17830 "const unsigned g;\n" 17831 "Const unsigned h;", 17832 Alignment); 17833 17834 // See PR46529 17835 FormatStyle BracedAlign = getLLVMStyle(); 17836 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 17837 verifyFormat("const auto result{[]() {\n" 17838 " const auto something = 1;\n" 17839 " return 2;\n" 17840 "}};", 17841 BracedAlign); 17842 verifyFormat("int foo{[]() {\n" 17843 " int bar{0};\n" 17844 " return 0;\n" 17845 "}()};", 17846 BracedAlign); 17847 BracedAlign.Cpp11BracedListStyle = false; 17848 verifyFormat("const auto result{ []() {\n" 17849 " const auto something = 1;\n" 17850 " return 2;\n" 17851 "} };", 17852 BracedAlign); 17853 verifyFormat("int foo{ []() {\n" 17854 " int bar{ 0 };\n" 17855 " return 0;\n" 17856 "}() };", 17857 BracedAlign); 17858 } 17859 17860 TEST_F(FormatTest, AlignWithLineBreaks) { 17861 auto Style = getLLVMStyleWithColumns(120); 17862 17863 EXPECT_EQ(Style.AlignConsecutiveAssignments, 17864 FormatStyle::AlignConsecutiveStyle( 17865 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 17866 /*AcrossComments=*/false, /*AlignCompound=*/false, 17867 /*PadOperators=*/true})); 17868 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 17869 FormatStyle::AlignConsecutiveStyle({})); 17870 verifyFormat("void foo() {\n" 17871 " int myVar = 5;\n" 17872 " double x = 3.14;\n" 17873 " auto str = \"Hello \"\n" 17874 " \"World\";\n" 17875 " auto s = \"Hello \"\n" 17876 " \"Again\";\n" 17877 "}", 17878 Style); 17879 17880 // clang-format off 17881 verifyFormat("void foo() {\n" 17882 " const int capacityBefore = Entries.capacity();\n" 17883 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17884 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17885 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17886 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17887 "}", 17888 Style); 17889 // clang-format on 17890 17891 Style.AlignConsecutiveAssignments.Enabled = true; 17892 verifyFormat("void foo() {\n" 17893 " int myVar = 5;\n" 17894 " double x = 3.14;\n" 17895 " auto str = \"Hello \"\n" 17896 " \"World\";\n" 17897 " auto s = \"Hello \"\n" 17898 " \"Again\";\n" 17899 "}", 17900 Style); 17901 17902 // clang-format off 17903 verifyFormat("void foo() {\n" 17904 " const int capacityBefore = Entries.capacity();\n" 17905 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17906 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17907 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17908 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17909 "}", 17910 Style); 17911 // clang-format on 17912 17913 Style.AlignConsecutiveAssignments.Enabled = false; 17914 Style.AlignConsecutiveDeclarations.Enabled = true; 17915 verifyFormat("void foo() {\n" 17916 " int myVar = 5;\n" 17917 " double x = 3.14;\n" 17918 " auto str = \"Hello \"\n" 17919 " \"World\";\n" 17920 " auto s = \"Hello \"\n" 17921 " \"Again\";\n" 17922 "}", 17923 Style); 17924 17925 // clang-format off 17926 verifyFormat("void foo() {\n" 17927 " const int capacityBefore = Entries.capacity();\n" 17928 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17929 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17930 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17931 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17932 "}", 17933 Style); 17934 // clang-format on 17935 17936 Style.AlignConsecutiveAssignments.Enabled = true; 17937 Style.AlignConsecutiveDeclarations.Enabled = true; 17938 17939 verifyFormat("void foo() {\n" 17940 " int myVar = 5;\n" 17941 " double x = 3.14;\n" 17942 " auto str = \"Hello \"\n" 17943 " \"World\";\n" 17944 " auto s = \"Hello \"\n" 17945 " \"Again\";\n" 17946 "}", 17947 Style); 17948 17949 // clang-format off 17950 verifyFormat("void foo() {\n" 17951 " const int capacityBefore = Entries.capacity();\n" 17952 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17953 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17954 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17955 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17956 "}", 17957 Style); 17958 // clang-format on 17959 17960 Style = getLLVMStyleWithColumns(120); 17961 Style.AlignConsecutiveAssignments.Enabled = true; 17962 Style.ContinuationIndentWidth = 4; 17963 Style.IndentWidth = 4; 17964 17965 // clang-format off 17966 verifyFormat("void SomeFunc() {\n" 17967 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17968 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17969 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17970 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17971 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17972 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17973 "}", 17974 Style); 17975 // clang-format on 17976 17977 Style.BinPackArguments = false; 17978 17979 // clang-format off 17980 verifyFormat("void SomeFunc() {\n" 17981 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17982 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17983 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17984 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17985 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17986 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17987 "}", 17988 Style); 17989 // clang-format on 17990 } 17991 17992 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17993 auto Style = getLLVMStyleWithColumns(60); 17994 17995 verifyFormat("void foo1(void) {\n" 17996 " BYTE p[1] = 1;\n" 17997 " A B = {.one_foooooooooooooooo = 2,\n" 17998 " .two_fooooooooooooo = 3,\n" 17999 " .three_fooooooooooooo = 4};\n" 18000 " BYTE payload = 2;\n" 18001 "}", 18002 Style); 18003 18004 Style.AlignConsecutiveAssignments.Enabled = true; 18005 Style.AlignConsecutiveDeclarations.Enabled = false; 18006 verifyFormat("void foo2(void) {\n" 18007 " BYTE p[1] = 1;\n" 18008 " A B = {.one_foooooooooooooooo = 2,\n" 18009 " .two_fooooooooooooo = 3,\n" 18010 " .three_fooooooooooooo = 4};\n" 18011 " BYTE payload = 2;\n" 18012 "}", 18013 Style); 18014 18015 Style.AlignConsecutiveAssignments.Enabled = false; 18016 Style.AlignConsecutiveDeclarations.Enabled = true; 18017 verifyFormat("void foo3(void) {\n" 18018 " BYTE p[1] = 1;\n" 18019 " A B = {.one_foooooooooooooooo = 2,\n" 18020 " .two_fooooooooooooo = 3,\n" 18021 " .three_fooooooooooooo = 4};\n" 18022 " BYTE payload = 2;\n" 18023 "}", 18024 Style); 18025 18026 Style.AlignConsecutiveAssignments.Enabled = true; 18027 Style.AlignConsecutiveDeclarations.Enabled = true; 18028 verifyFormat("void foo4(void) {\n" 18029 " BYTE p[1] = 1;\n" 18030 " A B = {.one_foooooooooooooooo = 2,\n" 18031 " .two_fooooooooooooo = 3,\n" 18032 " .three_fooooooooooooo = 4};\n" 18033 " BYTE payload = 2;\n" 18034 "}", 18035 Style); 18036 } 18037 18038 TEST_F(FormatTest, LinuxBraceBreaking) { 18039 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18040 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18041 verifyFormat("namespace a\n" 18042 "{\n" 18043 "class A\n" 18044 "{\n" 18045 " void f()\n" 18046 " {\n" 18047 " if (true) {\n" 18048 " a();\n" 18049 " b();\n" 18050 " } else {\n" 18051 " a();\n" 18052 " }\n" 18053 " }\n" 18054 " void g() { return; }\n" 18055 "};\n" 18056 "struct B {\n" 18057 " int x;\n" 18058 "};\n" 18059 "} // namespace a\n", 18060 LinuxBraceStyle); 18061 verifyFormat("enum X {\n" 18062 " Y = 0,\n" 18063 "}\n", 18064 LinuxBraceStyle); 18065 verifyFormat("struct S {\n" 18066 " int Type;\n" 18067 " union {\n" 18068 " int x;\n" 18069 " double y;\n" 18070 " } Value;\n" 18071 " class C\n" 18072 " {\n" 18073 " MyFavoriteType Value;\n" 18074 " } Class;\n" 18075 "}\n", 18076 LinuxBraceStyle); 18077 } 18078 18079 TEST_F(FormatTest, MozillaBraceBreaking) { 18080 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18081 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18082 MozillaBraceStyle.FixNamespaceComments = false; 18083 verifyFormat("namespace a {\n" 18084 "class A\n" 18085 "{\n" 18086 " void f()\n" 18087 " {\n" 18088 " if (true) {\n" 18089 " a();\n" 18090 " b();\n" 18091 " }\n" 18092 " }\n" 18093 " void g() { return; }\n" 18094 "};\n" 18095 "enum E\n" 18096 "{\n" 18097 " A,\n" 18098 " // foo\n" 18099 " B,\n" 18100 " C\n" 18101 "};\n" 18102 "struct B\n" 18103 "{\n" 18104 " int x;\n" 18105 "};\n" 18106 "}\n", 18107 MozillaBraceStyle); 18108 verifyFormat("struct S\n" 18109 "{\n" 18110 " int Type;\n" 18111 " union\n" 18112 " {\n" 18113 " int x;\n" 18114 " double y;\n" 18115 " } Value;\n" 18116 " class C\n" 18117 " {\n" 18118 " MyFavoriteType Value;\n" 18119 " } Class;\n" 18120 "}\n", 18121 MozillaBraceStyle); 18122 } 18123 18124 TEST_F(FormatTest, StroustrupBraceBreaking) { 18125 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18126 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18127 verifyFormat("namespace a {\n" 18128 "class A {\n" 18129 " void f()\n" 18130 " {\n" 18131 " if (true) {\n" 18132 " a();\n" 18133 " b();\n" 18134 " }\n" 18135 " }\n" 18136 " void g() { return; }\n" 18137 "};\n" 18138 "struct B {\n" 18139 " int x;\n" 18140 "};\n" 18141 "} // namespace a\n", 18142 StroustrupBraceStyle); 18143 18144 verifyFormat("void foo()\n" 18145 "{\n" 18146 " if (a) {\n" 18147 " a();\n" 18148 " }\n" 18149 " else {\n" 18150 " b();\n" 18151 " }\n" 18152 "}\n", 18153 StroustrupBraceStyle); 18154 18155 verifyFormat("#ifdef _DEBUG\n" 18156 "int foo(int i = 0)\n" 18157 "#else\n" 18158 "int foo(int i = 5)\n" 18159 "#endif\n" 18160 "{\n" 18161 " return i;\n" 18162 "}", 18163 StroustrupBraceStyle); 18164 18165 verifyFormat("void foo() {}\n" 18166 "void bar()\n" 18167 "#ifdef _DEBUG\n" 18168 "{\n" 18169 " foo();\n" 18170 "}\n" 18171 "#else\n" 18172 "{\n" 18173 "}\n" 18174 "#endif", 18175 StroustrupBraceStyle); 18176 18177 verifyFormat("void foobar() { int i = 5; }\n" 18178 "#ifdef _DEBUG\n" 18179 "void bar() {}\n" 18180 "#else\n" 18181 "void bar() { foobar(); }\n" 18182 "#endif", 18183 StroustrupBraceStyle); 18184 } 18185 18186 TEST_F(FormatTest, AllmanBraceBreaking) { 18187 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18188 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18189 18190 EXPECT_EQ("namespace a\n" 18191 "{\n" 18192 "void f();\n" 18193 "void g();\n" 18194 "} // namespace a\n", 18195 format("namespace a\n" 18196 "{\n" 18197 "void f();\n" 18198 "void g();\n" 18199 "}\n", 18200 AllmanBraceStyle)); 18201 18202 verifyFormat("namespace a\n" 18203 "{\n" 18204 "class A\n" 18205 "{\n" 18206 " void f()\n" 18207 " {\n" 18208 " if (true)\n" 18209 " {\n" 18210 " a();\n" 18211 " b();\n" 18212 " }\n" 18213 " }\n" 18214 " void g() { return; }\n" 18215 "};\n" 18216 "struct B\n" 18217 "{\n" 18218 " int x;\n" 18219 "};\n" 18220 "union C\n" 18221 "{\n" 18222 "};\n" 18223 "} // namespace a", 18224 AllmanBraceStyle); 18225 18226 verifyFormat("void f()\n" 18227 "{\n" 18228 " if (true)\n" 18229 " {\n" 18230 " a();\n" 18231 " }\n" 18232 " else if (false)\n" 18233 " {\n" 18234 " b();\n" 18235 " }\n" 18236 " else\n" 18237 " {\n" 18238 " c();\n" 18239 " }\n" 18240 "}\n", 18241 AllmanBraceStyle); 18242 18243 verifyFormat("void f()\n" 18244 "{\n" 18245 " for (int i = 0; i < 10; ++i)\n" 18246 " {\n" 18247 " a();\n" 18248 " }\n" 18249 " while (false)\n" 18250 " {\n" 18251 " b();\n" 18252 " }\n" 18253 " do\n" 18254 " {\n" 18255 " c();\n" 18256 " } while (false)\n" 18257 "}\n", 18258 AllmanBraceStyle); 18259 18260 verifyFormat("void f(int a)\n" 18261 "{\n" 18262 " switch (a)\n" 18263 " {\n" 18264 " case 0:\n" 18265 " break;\n" 18266 " case 1:\n" 18267 " {\n" 18268 " break;\n" 18269 " }\n" 18270 " case 2:\n" 18271 " {\n" 18272 " }\n" 18273 " break;\n" 18274 " default:\n" 18275 " break;\n" 18276 " }\n" 18277 "}\n", 18278 AllmanBraceStyle); 18279 18280 verifyFormat("enum X\n" 18281 "{\n" 18282 " Y = 0,\n" 18283 "}\n", 18284 AllmanBraceStyle); 18285 verifyFormat("enum X\n" 18286 "{\n" 18287 " Y = 0\n" 18288 "}\n", 18289 AllmanBraceStyle); 18290 18291 verifyFormat("@interface BSApplicationController ()\n" 18292 "{\n" 18293 "@private\n" 18294 " id _extraIvar;\n" 18295 "}\n" 18296 "@end\n", 18297 AllmanBraceStyle); 18298 18299 verifyFormat("#ifdef _DEBUG\n" 18300 "int foo(int i = 0)\n" 18301 "#else\n" 18302 "int foo(int i = 5)\n" 18303 "#endif\n" 18304 "{\n" 18305 " return i;\n" 18306 "}", 18307 AllmanBraceStyle); 18308 18309 verifyFormat("void foo() {}\n" 18310 "void bar()\n" 18311 "#ifdef _DEBUG\n" 18312 "{\n" 18313 " foo();\n" 18314 "}\n" 18315 "#else\n" 18316 "{\n" 18317 "}\n" 18318 "#endif", 18319 AllmanBraceStyle); 18320 18321 verifyFormat("void foobar() { int i = 5; }\n" 18322 "#ifdef _DEBUG\n" 18323 "void bar() {}\n" 18324 "#else\n" 18325 "void bar() { foobar(); }\n" 18326 "#endif", 18327 AllmanBraceStyle); 18328 18329 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18330 FormatStyle::SLS_All); 18331 18332 verifyFormat("[](int i) { return i + 2; };\n" 18333 "[](int i, int j)\n" 18334 "{\n" 18335 " auto x = i + j;\n" 18336 " auto y = i * j;\n" 18337 " return x ^ y;\n" 18338 "};\n" 18339 "void foo()\n" 18340 "{\n" 18341 " auto shortLambda = [](int i) { return i + 2; };\n" 18342 " auto longLambda = [](int i, int j)\n" 18343 " {\n" 18344 " auto x = i + j;\n" 18345 " auto y = i * j;\n" 18346 " return x ^ y;\n" 18347 " };\n" 18348 "}", 18349 AllmanBraceStyle); 18350 18351 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18352 18353 verifyFormat("[](int i)\n" 18354 "{\n" 18355 " return i + 2;\n" 18356 "};\n" 18357 "[](int i, int j)\n" 18358 "{\n" 18359 " auto x = i + j;\n" 18360 " auto y = i * j;\n" 18361 " return x ^ y;\n" 18362 "};\n" 18363 "void foo()\n" 18364 "{\n" 18365 " auto shortLambda = [](int i)\n" 18366 " {\n" 18367 " return i + 2;\n" 18368 " };\n" 18369 " auto longLambda = [](int i, int j)\n" 18370 " {\n" 18371 " auto x = i + j;\n" 18372 " auto y = i * j;\n" 18373 " return x ^ y;\n" 18374 " };\n" 18375 "}", 18376 AllmanBraceStyle); 18377 18378 // Reset 18379 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18380 18381 // This shouldn't affect ObjC blocks.. 18382 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18383 " // ...\n" 18384 " int i;\n" 18385 "}];", 18386 AllmanBraceStyle); 18387 verifyFormat("void (^block)(void) = ^{\n" 18388 " // ...\n" 18389 " int i;\n" 18390 "};", 18391 AllmanBraceStyle); 18392 // .. or dict literals. 18393 verifyFormat("void f()\n" 18394 "{\n" 18395 " // ...\n" 18396 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18397 "}", 18398 AllmanBraceStyle); 18399 verifyFormat("void f()\n" 18400 "{\n" 18401 " // ...\n" 18402 " [object someMethod:@{a : @\"b\"}];\n" 18403 "}", 18404 AllmanBraceStyle); 18405 verifyFormat("int f()\n" 18406 "{ // comment\n" 18407 " return 42;\n" 18408 "}", 18409 AllmanBraceStyle); 18410 18411 AllmanBraceStyle.ColumnLimit = 19; 18412 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18413 AllmanBraceStyle.ColumnLimit = 18; 18414 verifyFormat("void f()\n" 18415 "{\n" 18416 " int i;\n" 18417 "}", 18418 AllmanBraceStyle); 18419 AllmanBraceStyle.ColumnLimit = 80; 18420 18421 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18422 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18423 FormatStyle::SIS_WithoutElse; 18424 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18425 verifyFormat("void f(bool b)\n" 18426 "{\n" 18427 " if (b)\n" 18428 " {\n" 18429 " return;\n" 18430 " }\n" 18431 "}\n", 18432 BreakBeforeBraceShortIfs); 18433 verifyFormat("void f(bool b)\n" 18434 "{\n" 18435 " if constexpr (b)\n" 18436 " {\n" 18437 " return;\n" 18438 " }\n" 18439 "}\n", 18440 BreakBeforeBraceShortIfs); 18441 verifyFormat("void f(bool b)\n" 18442 "{\n" 18443 " if CONSTEXPR (b)\n" 18444 " {\n" 18445 " return;\n" 18446 " }\n" 18447 "}\n", 18448 BreakBeforeBraceShortIfs); 18449 verifyFormat("void f(bool b)\n" 18450 "{\n" 18451 " if (b) return;\n" 18452 "}\n", 18453 BreakBeforeBraceShortIfs); 18454 verifyFormat("void f(bool b)\n" 18455 "{\n" 18456 " if constexpr (b) return;\n" 18457 "}\n", 18458 BreakBeforeBraceShortIfs); 18459 verifyFormat("void f(bool b)\n" 18460 "{\n" 18461 " if CONSTEXPR (b) return;\n" 18462 "}\n", 18463 BreakBeforeBraceShortIfs); 18464 verifyFormat("void f(bool b)\n" 18465 "{\n" 18466 " while (b)\n" 18467 " {\n" 18468 " return;\n" 18469 " }\n" 18470 "}\n", 18471 BreakBeforeBraceShortIfs); 18472 } 18473 18474 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18475 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18476 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18477 18478 // Make a few changes to the style for testing purposes 18479 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18480 FormatStyle::SFS_Empty; 18481 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18482 18483 // FIXME: this test case can't decide whether there should be a blank line 18484 // after the ~D() line or not. It adds one if one doesn't exist in the test 18485 // and it removes the line if one exists. 18486 /* 18487 verifyFormat("class A;\n" 18488 "namespace B\n" 18489 " {\n" 18490 "class C;\n" 18491 "// Comment\n" 18492 "class D\n" 18493 " {\n" 18494 "public:\n" 18495 " D();\n" 18496 " ~D() {}\n" 18497 "private:\n" 18498 " enum E\n" 18499 " {\n" 18500 " F\n" 18501 " }\n" 18502 " };\n" 18503 " } // namespace B\n", 18504 WhitesmithsBraceStyle); 18505 */ 18506 18507 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18508 verifyFormat("namespace a\n" 18509 " {\n" 18510 "class A\n" 18511 " {\n" 18512 " void f()\n" 18513 " {\n" 18514 " if (true)\n" 18515 " {\n" 18516 " a();\n" 18517 " b();\n" 18518 " }\n" 18519 " }\n" 18520 " void g()\n" 18521 " {\n" 18522 " return;\n" 18523 " }\n" 18524 " };\n" 18525 "struct B\n" 18526 " {\n" 18527 " int x;\n" 18528 " };\n" 18529 " } // namespace a", 18530 WhitesmithsBraceStyle); 18531 18532 verifyFormat("namespace a\n" 18533 " {\n" 18534 "namespace b\n" 18535 " {\n" 18536 "class A\n" 18537 " {\n" 18538 " void f()\n" 18539 " {\n" 18540 " if (true)\n" 18541 " {\n" 18542 " a();\n" 18543 " b();\n" 18544 " }\n" 18545 " }\n" 18546 " void g()\n" 18547 " {\n" 18548 " return;\n" 18549 " }\n" 18550 " };\n" 18551 "struct B\n" 18552 " {\n" 18553 " int x;\n" 18554 " };\n" 18555 " } // namespace b\n" 18556 " } // namespace a", 18557 WhitesmithsBraceStyle); 18558 18559 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18560 verifyFormat("namespace a\n" 18561 " {\n" 18562 "namespace b\n" 18563 " {\n" 18564 " class A\n" 18565 " {\n" 18566 " void f()\n" 18567 " {\n" 18568 " if (true)\n" 18569 " {\n" 18570 " a();\n" 18571 " b();\n" 18572 " }\n" 18573 " }\n" 18574 " void g()\n" 18575 " {\n" 18576 " return;\n" 18577 " }\n" 18578 " };\n" 18579 " struct B\n" 18580 " {\n" 18581 " int x;\n" 18582 " };\n" 18583 " } // namespace b\n" 18584 " } // namespace a", 18585 WhitesmithsBraceStyle); 18586 18587 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18588 verifyFormat("namespace a\n" 18589 " {\n" 18590 " namespace b\n" 18591 " {\n" 18592 " class A\n" 18593 " {\n" 18594 " void f()\n" 18595 " {\n" 18596 " if (true)\n" 18597 " {\n" 18598 " a();\n" 18599 " b();\n" 18600 " }\n" 18601 " }\n" 18602 " void g()\n" 18603 " {\n" 18604 " return;\n" 18605 " }\n" 18606 " };\n" 18607 " struct B\n" 18608 " {\n" 18609 " int x;\n" 18610 " };\n" 18611 " } // namespace b\n" 18612 " } // namespace a", 18613 WhitesmithsBraceStyle); 18614 18615 verifyFormat("void f()\n" 18616 " {\n" 18617 " if (true)\n" 18618 " {\n" 18619 " a();\n" 18620 " }\n" 18621 " else if (false)\n" 18622 " {\n" 18623 " b();\n" 18624 " }\n" 18625 " else\n" 18626 " {\n" 18627 " c();\n" 18628 " }\n" 18629 " }\n", 18630 WhitesmithsBraceStyle); 18631 18632 verifyFormat("void f()\n" 18633 " {\n" 18634 " for (int i = 0; i < 10; ++i)\n" 18635 " {\n" 18636 " a();\n" 18637 " }\n" 18638 " while (false)\n" 18639 " {\n" 18640 " b();\n" 18641 " }\n" 18642 " do\n" 18643 " {\n" 18644 " c();\n" 18645 " } while (false)\n" 18646 " }\n", 18647 WhitesmithsBraceStyle); 18648 18649 WhitesmithsBraceStyle.IndentCaseLabels = true; 18650 verifyFormat("void switchTest1(int a)\n" 18651 " {\n" 18652 " switch (a)\n" 18653 " {\n" 18654 " case 2:\n" 18655 " {\n" 18656 " }\n" 18657 " break;\n" 18658 " }\n" 18659 " }\n", 18660 WhitesmithsBraceStyle); 18661 18662 verifyFormat("void switchTest2(int a)\n" 18663 " {\n" 18664 " switch (a)\n" 18665 " {\n" 18666 " case 0:\n" 18667 " break;\n" 18668 " case 1:\n" 18669 " {\n" 18670 " break;\n" 18671 " }\n" 18672 " case 2:\n" 18673 " {\n" 18674 " }\n" 18675 " break;\n" 18676 " default:\n" 18677 " break;\n" 18678 " }\n" 18679 " }\n", 18680 WhitesmithsBraceStyle); 18681 18682 verifyFormat("void switchTest3(int a)\n" 18683 " {\n" 18684 " switch (a)\n" 18685 " {\n" 18686 " case 0:\n" 18687 " {\n" 18688 " foo(x);\n" 18689 " }\n" 18690 " break;\n" 18691 " default:\n" 18692 " {\n" 18693 " foo(1);\n" 18694 " }\n" 18695 " break;\n" 18696 " }\n" 18697 " }\n", 18698 WhitesmithsBraceStyle); 18699 18700 WhitesmithsBraceStyle.IndentCaseLabels = false; 18701 18702 verifyFormat("void switchTest4(int a)\n" 18703 " {\n" 18704 " switch (a)\n" 18705 " {\n" 18706 " case 2:\n" 18707 " {\n" 18708 " }\n" 18709 " break;\n" 18710 " }\n" 18711 " }\n", 18712 WhitesmithsBraceStyle); 18713 18714 verifyFormat("void switchTest5(int a)\n" 18715 " {\n" 18716 " switch (a)\n" 18717 " {\n" 18718 " case 0:\n" 18719 " break;\n" 18720 " case 1:\n" 18721 " {\n" 18722 " foo();\n" 18723 " break;\n" 18724 " }\n" 18725 " case 2:\n" 18726 " {\n" 18727 " }\n" 18728 " break;\n" 18729 " default:\n" 18730 " break;\n" 18731 " }\n" 18732 " }\n", 18733 WhitesmithsBraceStyle); 18734 18735 verifyFormat("void switchTest6(int a)\n" 18736 " {\n" 18737 " switch (a)\n" 18738 " {\n" 18739 " case 0:\n" 18740 " {\n" 18741 " foo(x);\n" 18742 " }\n" 18743 " break;\n" 18744 " default:\n" 18745 " {\n" 18746 " foo(1);\n" 18747 " }\n" 18748 " break;\n" 18749 " }\n" 18750 " }\n", 18751 WhitesmithsBraceStyle); 18752 18753 verifyFormat("enum X\n" 18754 " {\n" 18755 " Y = 0, // testing\n" 18756 " }\n", 18757 WhitesmithsBraceStyle); 18758 18759 verifyFormat("enum X\n" 18760 " {\n" 18761 " Y = 0\n" 18762 " }\n", 18763 WhitesmithsBraceStyle); 18764 verifyFormat("enum X\n" 18765 " {\n" 18766 " Y = 0,\n" 18767 " Z = 1\n" 18768 " };\n", 18769 WhitesmithsBraceStyle); 18770 18771 verifyFormat("@interface BSApplicationController ()\n" 18772 " {\n" 18773 "@private\n" 18774 " id _extraIvar;\n" 18775 " }\n" 18776 "@end\n", 18777 WhitesmithsBraceStyle); 18778 18779 verifyFormat("#ifdef _DEBUG\n" 18780 "int foo(int i = 0)\n" 18781 "#else\n" 18782 "int foo(int i = 5)\n" 18783 "#endif\n" 18784 " {\n" 18785 " return i;\n" 18786 " }", 18787 WhitesmithsBraceStyle); 18788 18789 verifyFormat("void foo() {}\n" 18790 "void bar()\n" 18791 "#ifdef _DEBUG\n" 18792 " {\n" 18793 " foo();\n" 18794 " }\n" 18795 "#else\n" 18796 " {\n" 18797 " }\n" 18798 "#endif", 18799 WhitesmithsBraceStyle); 18800 18801 verifyFormat("void foobar()\n" 18802 " {\n" 18803 " int i = 5;\n" 18804 " }\n" 18805 "#ifdef _DEBUG\n" 18806 "void bar()\n" 18807 " {\n" 18808 " }\n" 18809 "#else\n" 18810 "void bar()\n" 18811 " {\n" 18812 " foobar();\n" 18813 " }\n" 18814 "#endif", 18815 WhitesmithsBraceStyle); 18816 18817 // This shouldn't affect ObjC blocks.. 18818 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18819 " // ...\n" 18820 " int i;\n" 18821 "}];", 18822 WhitesmithsBraceStyle); 18823 verifyFormat("void (^block)(void) = ^{\n" 18824 " // ...\n" 18825 " int i;\n" 18826 "};", 18827 WhitesmithsBraceStyle); 18828 // .. or dict literals. 18829 verifyFormat("void f()\n" 18830 " {\n" 18831 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18832 " }", 18833 WhitesmithsBraceStyle); 18834 18835 verifyFormat("int f()\n" 18836 " { // comment\n" 18837 " return 42;\n" 18838 " }", 18839 WhitesmithsBraceStyle); 18840 18841 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18842 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18843 FormatStyle::SIS_OnlyFirstIf; 18844 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18845 verifyFormat("void f(bool b)\n" 18846 " {\n" 18847 " if (b)\n" 18848 " {\n" 18849 " return;\n" 18850 " }\n" 18851 " }\n", 18852 BreakBeforeBraceShortIfs); 18853 verifyFormat("void f(bool b)\n" 18854 " {\n" 18855 " if (b) return;\n" 18856 " }\n", 18857 BreakBeforeBraceShortIfs); 18858 verifyFormat("void f(bool b)\n" 18859 " {\n" 18860 " while (b)\n" 18861 " {\n" 18862 " return;\n" 18863 " }\n" 18864 " }\n", 18865 BreakBeforeBraceShortIfs); 18866 } 18867 18868 TEST_F(FormatTest, GNUBraceBreaking) { 18869 FormatStyle GNUBraceStyle = getLLVMStyle(); 18870 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18871 verifyFormat("namespace a\n" 18872 "{\n" 18873 "class A\n" 18874 "{\n" 18875 " void f()\n" 18876 " {\n" 18877 " int a;\n" 18878 " {\n" 18879 " int b;\n" 18880 " }\n" 18881 " if (true)\n" 18882 " {\n" 18883 " a();\n" 18884 " b();\n" 18885 " }\n" 18886 " }\n" 18887 " void g() { return; }\n" 18888 "}\n" 18889 "} // namespace a", 18890 GNUBraceStyle); 18891 18892 verifyFormat("void f()\n" 18893 "{\n" 18894 " if (true)\n" 18895 " {\n" 18896 " a();\n" 18897 " }\n" 18898 " else if (false)\n" 18899 " {\n" 18900 " b();\n" 18901 " }\n" 18902 " else\n" 18903 " {\n" 18904 " c();\n" 18905 " }\n" 18906 "}\n", 18907 GNUBraceStyle); 18908 18909 verifyFormat("void f()\n" 18910 "{\n" 18911 " for (int i = 0; i < 10; ++i)\n" 18912 " {\n" 18913 " a();\n" 18914 " }\n" 18915 " while (false)\n" 18916 " {\n" 18917 " b();\n" 18918 " }\n" 18919 " do\n" 18920 " {\n" 18921 " c();\n" 18922 " }\n" 18923 " while (false);\n" 18924 "}\n", 18925 GNUBraceStyle); 18926 18927 verifyFormat("void f(int a)\n" 18928 "{\n" 18929 " switch (a)\n" 18930 " {\n" 18931 " case 0:\n" 18932 " break;\n" 18933 " case 1:\n" 18934 " {\n" 18935 " break;\n" 18936 " }\n" 18937 " case 2:\n" 18938 " {\n" 18939 " }\n" 18940 " break;\n" 18941 " default:\n" 18942 " break;\n" 18943 " }\n" 18944 "}\n", 18945 GNUBraceStyle); 18946 18947 verifyFormat("enum X\n" 18948 "{\n" 18949 " Y = 0,\n" 18950 "}\n", 18951 GNUBraceStyle); 18952 18953 verifyFormat("@interface BSApplicationController ()\n" 18954 "{\n" 18955 "@private\n" 18956 " id _extraIvar;\n" 18957 "}\n" 18958 "@end\n", 18959 GNUBraceStyle); 18960 18961 verifyFormat("#ifdef _DEBUG\n" 18962 "int foo(int i = 0)\n" 18963 "#else\n" 18964 "int foo(int i = 5)\n" 18965 "#endif\n" 18966 "{\n" 18967 " return i;\n" 18968 "}", 18969 GNUBraceStyle); 18970 18971 verifyFormat("void foo() {}\n" 18972 "void bar()\n" 18973 "#ifdef _DEBUG\n" 18974 "{\n" 18975 " foo();\n" 18976 "}\n" 18977 "#else\n" 18978 "{\n" 18979 "}\n" 18980 "#endif", 18981 GNUBraceStyle); 18982 18983 verifyFormat("void foobar() { int i = 5; }\n" 18984 "#ifdef _DEBUG\n" 18985 "void bar() {}\n" 18986 "#else\n" 18987 "void bar() { foobar(); }\n" 18988 "#endif", 18989 GNUBraceStyle); 18990 } 18991 18992 TEST_F(FormatTest, WebKitBraceBreaking) { 18993 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18994 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18995 WebKitBraceStyle.FixNamespaceComments = false; 18996 verifyFormat("namespace a {\n" 18997 "class A {\n" 18998 " void f()\n" 18999 " {\n" 19000 " if (true) {\n" 19001 " a();\n" 19002 " b();\n" 19003 " }\n" 19004 " }\n" 19005 " void g() { return; }\n" 19006 "};\n" 19007 "enum E {\n" 19008 " A,\n" 19009 " // foo\n" 19010 " B,\n" 19011 " C\n" 19012 "};\n" 19013 "struct B {\n" 19014 " int x;\n" 19015 "};\n" 19016 "}\n", 19017 WebKitBraceStyle); 19018 verifyFormat("struct S {\n" 19019 " int Type;\n" 19020 " union {\n" 19021 " int x;\n" 19022 " double y;\n" 19023 " } Value;\n" 19024 " class C {\n" 19025 " MyFavoriteType Value;\n" 19026 " } Class;\n" 19027 "};\n", 19028 WebKitBraceStyle); 19029 } 19030 19031 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19032 verifyFormat("void f() {\n" 19033 " try {\n" 19034 " } catch (const Exception &e) {\n" 19035 " }\n" 19036 "}\n", 19037 getLLVMStyle()); 19038 } 19039 19040 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19041 auto Style = getLLVMStyle(); 19042 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19043 Style.AlignConsecutiveAssignments.Enabled = true; 19044 Style.AlignConsecutiveDeclarations.Enabled = true; 19045 verifyFormat("struct test demo[] = {\n" 19046 " {56, 23, \"hello\"},\n" 19047 " {-1, 93463, \"world\"},\n" 19048 " { 7, 5, \"!!\"}\n" 19049 "};\n", 19050 Style); 19051 19052 verifyFormat("struct test demo[] = {\n" 19053 " {56, 23, \"hello\"}, // first line\n" 19054 " {-1, 93463, \"world\"}, // second line\n" 19055 " { 7, 5, \"!!\"} // third line\n" 19056 "};\n", 19057 Style); 19058 19059 verifyFormat("struct test demo[4] = {\n" 19060 " { 56, 23, 21, \"oh\"}, // first line\n" 19061 " { -1, 93463, 22, \"my\"}, // second line\n" 19062 " { 7, 5, 1, \"goodness\"} // third line\n" 19063 " {234, 5, 1, \"gracious\"} // fourth line\n" 19064 "};\n", 19065 Style); 19066 19067 verifyFormat("struct test demo[3] = {\n" 19068 " {56, 23, \"hello\"},\n" 19069 " {-1, 93463, \"world\"},\n" 19070 " { 7, 5, \"!!\"}\n" 19071 "};\n", 19072 Style); 19073 19074 verifyFormat("struct test demo[3] = {\n" 19075 " {int{56}, 23, \"hello\"},\n" 19076 " {int{-1}, 93463, \"world\"},\n" 19077 " { int{7}, 5, \"!!\"}\n" 19078 "};\n", 19079 Style); 19080 19081 verifyFormat("struct test demo[] = {\n" 19082 " {56, 23, \"hello\"},\n" 19083 " {-1, 93463, \"world\"},\n" 19084 " { 7, 5, \"!!\"},\n" 19085 "};\n", 19086 Style); 19087 19088 verifyFormat("test demo[] = {\n" 19089 " {56, 23, \"hello\"},\n" 19090 " {-1, 93463, \"world\"},\n" 19091 " { 7, 5, \"!!\"},\n" 19092 "};\n", 19093 Style); 19094 19095 verifyFormat("demo = std::array<struct test, 3>{\n" 19096 " test{56, 23, \"hello\"},\n" 19097 " test{-1, 93463, \"world\"},\n" 19098 " test{ 7, 5, \"!!\"},\n" 19099 "};\n", 19100 Style); 19101 19102 verifyFormat("test demo[] = {\n" 19103 " {56, 23, \"hello\"},\n" 19104 "#if X\n" 19105 " {-1, 93463, \"world\"},\n" 19106 "#endif\n" 19107 " { 7, 5, \"!!\"}\n" 19108 "};\n", 19109 Style); 19110 19111 verifyFormat( 19112 "test demo[] = {\n" 19113 " { 7, 23,\n" 19114 " \"hello world i am a very long line that really, in any\"\n" 19115 " \"just world, ought to be split over multiple lines\"},\n" 19116 " {-1, 93463, \"world\"},\n" 19117 " {56, 5, \"!!\"}\n" 19118 "};\n", 19119 Style); 19120 19121 verifyFormat("return GradForUnaryCwise(g, {\n" 19122 " {{\"sign\"}, \"Sign\", " 19123 " {\"x\", \"dy\"}},\n" 19124 " { {\"dx\"}, \"Mul\", {\"dy\"" 19125 ", \"sign\"}},\n" 19126 "});\n", 19127 Style); 19128 19129 Style.ColumnLimit = 0; 19130 EXPECT_EQ( 19131 "test demo[] = {\n" 19132 " {56, 23, \"hello world i am a very long line that really, " 19133 "in any just world, ought to be split over multiple lines\"},\n" 19134 " {-1, 93463, " 19135 " \"world\"},\n" 19136 " { 7, 5, " 19137 " \"!!\"},\n" 19138 "};", 19139 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19140 "that really, in any just world, ought to be split over multiple " 19141 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19142 Style)); 19143 19144 Style.ColumnLimit = 80; 19145 verifyFormat("test demo[] = {\n" 19146 " {56, 23, /* a comment */ \"hello\"},\n" 19147 " {-1, 93463, \"world\"},\n" 19148 " { 7, 5, \"!!\"}\n" 19149 "};\n", 19150 Style); 19151 19152 verifyFormat("test demo[] = {\n" 19153 " {56, 23, \"hello\"},\n" 19154 " {-1, 93463, \"world\" /* comment here */},\n" 19155 " { 7, 5, \"!!\"}\n" 19156 "};\n", 19157 Style); 19158 19159 verifyFormat("test demo[] = {\n" 19160 " {56, /* a comment */ 23, \"hello\"},\n" 19161 " {-1, 93463, \"world\"},\n" 19162 " { 7, 5, \"!!\"}\n" 19163 "};\n", 19164 Style); 19165 19166 Style.ColumnLimit = 20; 19167 EXPECT_EQ( 19168 "demo = std::array<\n" 19169 " struct test, 3>{\n" 19170 " test{\n" 19171 " 56, 23,\n" 19172 " \"hello \"\n" 19173 " \"world i \"\n" 19174 " \"am a very \"\n" 19175 " \"long line \"\n" 19176 " \"that \"\n" 19177 " \"really, \"\n" 19178 " \"in any \"\n" 19179 " \"just \"\n" 19180 " \"world, \"\n" 19181 " \"ought to \"\n" 19182 " \"be split \"\n" 19183 " \"over \"\n" 19184 " \"multiple \"\n" 19185 " \"lines\"},\n" 19186 " test{-1, 93463,\n" 19187 " \"world\"},\n" 19188 " test{ 7, 5,\n" 19189 " \"!!\" },\n" 19190 "};", 19191 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19192 "i am a very long line that really, in any just world, ought " 19193 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19194 "test{7, 5, \"!!\"},};", 19195 Style)); 19196 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19197 Style = getLLVMStyleWithColumns(50); 19198 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19199 verifyFormat("static A x = {\n" 19200 " {{init1, init2, init3, init4},\n" 19201 " {init1, init2, init3, init4}}\n" 19202 "};", 19203 Style); 19204 // TODO: Fix the indentations below when this option is fully functional. 19205 verifyFormat("int a[][] = {\n" 19206 " {\n" 19207 " {0, 2}, //\n" 19208 " {1, 2} //\n" 19209 " }\n" 19210 "};", 19211 Style); 19212 Style.ColumnLimit = 100; 19213 EXPECT_EQ( 19214 "test demo[] = {\n" 19215 " {56, 23,\n" 19216 " \"hello world i am a very long line that really, in any just world" 19217 ", ought to be split over \"\n" 19218 " \"multiple lines\" },\n" 19219 " {-1, 93463, \"world\"},\n" 19220 " { 7, 5, \"!!\"},\n" 19221 "};", 19222 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19223 "that really, in any just world, ought to be split over multiple " 19224 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19225 Style)); 19226 19227 Style = getLLVMStyleWithColumns(50); 19228 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19229 verifyFormat("struct test demo[] = {\n" 19230 " {56, 23, \"hello\"},\n" 19231 " {-1, 93463, \"world\"},\n" 19232 " { 7, 5, \"!!\"}\n" 19233 "};\n" 19234 "static A x = {\n" 19235 " {{init1, init2, init3, init4},\n" 19236 " {init1, init2, init3, init4}}\n" 19237 "};", 19238 Style); 19239 Style.ColumnLimit = 100; 19240 Style.AlignConsecutiveAssignments.AcrossComments = true; 19241 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19242 verifyFormat("struct test demo[] = {\n" 19243 " {56, 23, \"hello\"},\n" 19244 " {-1, 93463, \"world\"},\n" 19245 " { 7, 5, \"!!\"}\n" 19246 "};\n" 19247 "struct test demo[4] = {\n" 19248 " { 56, 23, 21, \"oh\"}, // first line\n" 19249 " { -1, 93463, 22, \"my\"}, // second line\n" 19250 " { 7, 5, 1, \"goodness\"} // third line\n" 19251 " {234, 5, 1, \"gracious\"} // fourth line\n" 19252 "};\n", 19253 Style); 19254 EXPECT_EQ( 19255 "test demo[] = {\n" 19256 " {56,\n" 19257 " \"hello world i am a very long line that really, in any just world" 19258 ", ought to be split over \"\n" 19259 " \"multiple lines\", 23},\n" 19260 " {-1, \"world\", 93463},\n" 19261 " { 7, \"!!\", 5},\n" 19262 "};", 19263 format("test demo[] = {{56, \"hello world i am a very long line " 19264 "that really, in any just world, ought to be split over multiple " 19265 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19266 Style)); 19267 } 19268 19269 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19270 auto Style = getLLVMStyle(); 19271 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19272 /* FIXME: This case gets misformatted. 19273 verifyFormat("auto foo = Items{\n" 19274 " Section{0, bar(), },\n" 19275 " Section{1, boo() }\n" 19276 "};\n", 19277 Style); 19278 */ 19279 verifyFormat("auto foo = Items{\n" 19280 " Section{\n" 19281 " 0, bar(),\n" 19282 " }\n" 19283 "};\n", 19284 Style); 19285 verifyFormat("struct test demo[] = {\n" 19286 " {56, 23, \"hello\"},\n" 19287 " {-1, 93463, \"world\"},\n" 19288 " {7, 5, \"!!\" }\n" 19289 "};\n", 19290 Style); 19291 verifyFormat("struct test demo[] = {\n" 19292 " {56, 23, \"hello\"}, // first line\n" 19293 " {-1, 93463, \"world\"}, // second line\n" 19294 " {7, 5, \"!!\" } // third line\n" 19295 "};\n", 19296 Style); 19297 verifyFormat("struct test demo[4] = {\n" 19298 " {56, 23, 21, \"oh\" }, // first line\n" 19299 " {-1, 93463, 22, \"my\" }, // second line\n" 19300 " {7, 5, 1, \"goodness\"} // third line\n" 19301 " {234, 5, 1, \"gracious\"} // fourth line\n" 19302 "};\n", 19303 Style); 19304 verifyFormat("struct test demo[3] = {\n" 19305 " {56, 23, \"hello\"},\n" 19306 " {-1, 93463, \"world\"},\n" 19307 " {7, 5, \"!!\" }\n" 19308 "};\n", 19309 Style); 19310 19311 verifyFormat("struct test demo[3] = {\n" 19312 " {int{56}, 23, \"hello\"},\n" 19313 " {int{-1}, 93463, \"world\"},\n" 19314 " {int{7}, 5, \"!!\" }\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("test demo[] = {\n" 19324 " {56, 23, \"hello\"},\n" 19325 " {-1, 93463, \"world\"},\n" 19326 " {7, 5, \"!!\" },\n" 19327 "};\n", 19328 Style); 19329 verifyFormat("demo = std::array<struct test, 3>{\n" 19330 " test{56, 23, \"hello\"},\n" 19331 " test{-1, 93463, \"world\"},\n" 19332 " test{7, 5, \"!!\" },\n" 19333 "};\n", 19334 Style); 19335 verifyFormat("test demo[] = {\n" 19336 " {56, 23, \"hello\"},\n" 19337 "#if X\n" 19338 " {-1, 93463, \"world\"},\n" 19339 "#endif\n" 19340 " {7, 5, \"!!\" }\n" 19341 "};\n", 19342 Style); 19343 verifyFormat( 19344 "test demo[] = {\n" 19345 " {7, 23,\n" 19346 " \"hello world i am a very long line that really, in any\"\n" 19347 " \"just world, ought to be split over multiple lines\"},\n" 19348 " {-1, 93463, \"world\" },\n" 19349 " {56, 5, \"!!\" }\n" 19350 "};\n", 19351 Style); 19352 19353 verifyFormat("return GradForUnaryCwise(g, {\n" 19354 " {{\"sign\"}, \"Sign\", {\"x\", " 19355 "\"dy\"} },\n" 19356 " {{\"dx\"}, \"Mul\", " 19357 "{\"dy\", \"sign\"}},\n" 19358 "});\n", 19359 Style); 19360 19361 Style.ColumnLimit = 0; 19362 EXPECT_EQ( 19363 "test demo[] = {\n" 19364 " {56, 23, \"hello world i am a very long line that really, in any " 19365 "just world, ought to be split over multiple lines\"},\n" 19366 " {-1, 93463, \"world\" " 19367 " },\n" 19368 " {7, 5, \"!!\" " 19369 " },\n" 19370 "};", 19371 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19372 "that really, in any just world, ought to be split over multiple " 19373 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19374 Style)); 19375 19376 Style.ColumnLimit = 80; 19377 verifyFormat("test demo[] = {\n" 19378 " {56, 23, /* a comment */ \"hello\"},\n" 19379 " {-1, 93463, \"world\" },\n" 19380 " {7, 5, \"!!\" }\n" 19381 "};\n", 19382 Style); 19383 19384 verifyFormat("test demo[] = {\n" 19385 " {56, 23, \"hello\" },\n" 19386 " {-1, 93463, \"world\" /* comment here */},\n" 19387 " {7, 5, \"!!\" }\n" 19388 "};\n", 19389 Style); 19390 19391 verifyFormat("test demo[] = {\n" 19392 " {56, /* a comment */ 23, \"hello\"},\n" 19393 " {-1, 93463, \"world\"},\n" 19394 " {7, 5, \"!!\" }\n" 19395 "};\n", 19396 Style); 19397 19398 Style.ColumnLimit = 20; 19399 EXPECT_EQ( 19400 "demo = std::array<\n" 19401 " struct test, 3>{\n" 19402 " test{\n" 19403 " 56, 23,\n" 19404 " \"hello \"\n" 19405 " \"world i \"\n" 19406 " \"am a very \"\n" 19407 " \"long line \"\n" 19408 " \"that \"\n" 19409 " \"really, \"\n" 19410 " \"in any \"\n" 19411 " \"just \"\n" 19412 " \"world, \"\n" 19413 " \"ought to \"\n" 19414 " \"be split \"\n" 19415 " \"over \"\n" 19416 " \"multiple \"\n" 19417 " \"lines\"},\n" 19418 " test{-1, 93463,\n" 19419 " \"world\"},\n" 19420 " test{7, 5,\n" 19421 " \"!!\" },\n" 19422 "};", 19423 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19424 "i am a very long line that really, in any just world, ought " 19425 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19426 "test{7, 5, \"!!\"},};", 19427 Style)); 19428 19429 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19430 Style = getLLVMStyleWithColumns(50); 19431 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19432 verifyFormat("static A x = {\n" 19433 " {{init1, init2, init3, init4},\n" 19434 " {init1, init2, init3, init4}}\n" 19435 "};", 19436 Style); 19437 Style.ColumnLimit = 100; 19438 EXPECT_EQ( 19439 "test demo[] = {\n" 19440 " {56, 23,\n" 19441 " \"hello world i am a very long line that really, in any just world" 19442 ", ought to be split over \"\n" 19443 " \"multiple lines\" },\n" 19444 " {-1, 93463, \"world\"},\n" 19445 " {7, 5, \"!!\" },\n" 19446 "};", 19447 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19448 "that really, in any just world, ought to be split over multiple " 19449 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19450 Style)); 19451 } 19452 19453 TEST_F(FormatTest, UnderstandsPragmas) { 19454 verifyFormat("#pragma omp reduction(| : var)"); 19455 verifyFormat("#pragma omp reduction(+ : var)"); 19456 19457 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19458 "(including parentheses).", 19459 format("#pragma mark Any non-hyphenated or hyphenated string " 19460 "(including parentheses).")); 19461 } 19462 19463 TEST_F(FormatTest, UnderstandPragmaOption) { 19464 verifyFormat("#pragma option -C -A"); 19465 19466 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19467 } 19468 19469 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19470 FormatStyle Style = getLLVMStyleWithColumns(20); 19471 19472 // See PR41213 19473 EXPECT_EQ("/*\n" 19474 " *\t9012345\n" 19475 " * /8901\n" 19476 " */", 19477 format("/*\n" 19478 " *\t9012345 /8901\n" 19479 " */", 19480 Style)); 19481 EXPECT_EQ("/*\n" 19482 " *345678\n" 19483 " *\t/8901\n" 19484 " */", 19485 format("/*\n" 19486 " *345678\t/8901\n" 19487 " */", 19488 Style)); 19489 19490 verifyFormat("int a; // the\n" 19491 " // comment", 19492 Style); 19493 EXPECT_EQ("int a; /* first line\n" 19494 " * second\n" 19495 " * line third\n" 19496 " * line\n" 19497 " */", 19498 format("int a; /* first line\n" 19499 " * second\n" 19500 " * line third\n" 19501 " * line\n" 19502 " */", 19503 Style)); 19504 EXPECT_EQ("int a; // first line\n" 19505 " // second\n" 19506 " // line third\n" 19507 " // line", 19508 format("int a; // first line\n" 19509 " // second line\n" 19510 " // third line", 19511 Style)); 19512 19513 Style.PenaltyExcessCharacter = 90; 19514 verifyFormat("int a; // the comment", Style); 19515 EXPECT_EQ("int a; // the comment\n" 19516 " // aaa", 19517 format("int a; // the comment aaa", Style)); 19518 EXPECT_EQ("int a; /* first line\n" 19519 " * second line\n" 19520 " * third line\n" 19521 " */", 19522 format("int a; /* first line\n" 19523 " * second line\n" 19524 " * third line\n" 19525 " */", 19526 Style)); 19527 EXPECT_EQ("int a; // first line\n" 19528 " // second line\n" 19529 " // third line", 19530 format("int a; // first line\n" 19531 " // second line\n" 19532 " // third line", 19533 Style)); 19534 // FIXME: Investigate why this is not getting the same layout as the test 19535 // above. 19536 EXPECT_EQ("int a; /* first line\n" 19537 " * second line\n" 19538 " * third line\n" 19539 " */", 19540 format("int a; /* first line second line third line" 19541 "\n*/", 19542 Style)); 19543 19544 EXPECT_EQ("// foo bar baz bazfoo\n" 19545 "// foo bar foo bar\n", 19546 format("// foo bar baz bazfoo\n" 19547 "// foo bar foo bar\n", 19548 Style)); 19549 EXPECT_EQ("// foo bar baz bazfoo\n" 19550 "// foo bar foo bar\n", 19551 format("// foo bar baz bazfoo\n" 19552 "// foo bar foo bar\n", 19553 Style)); 19554 19555 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19556 // next one. 19557 EXPECT_EQ("// foo bar baz bazfoo\n" 19558 "// bar foo bar\n", 19559 format("// foo bar baz bazfoo bar\n" 19560 "// foo bar\n", 19561 Style)); 19562 19563 EXPECT_EQ("// foo bar baz bazfoo\n" 19564 "// foo bar baz bazfoo\n" 19565 "// bar foo bar\n", 19566 format("// foo bar baz bazfoo\n" 19567 "// foo bar baz bazfoo bar\n" 19568 "// foo bar\n", 19569 Style)); 19570 19571 EXPECT_EQ("// foo bar baz bazfoo\n" 19572 "// foo bar baz bazfoo\n" 19573 "// bar foo bar\n", 19574 format("// foo bar baz bazfoo\n" 19575 "// foo bar baz bazfoo bar\n" 19576 "// foo bar\n", 19577 Style)); 19578 19579 // Make sure we do not keep protruding characters if strict mode reflow is 19580 // cheaper than keeping protruding characters. 19581 Style.ColumnLimit = 21; 19582 EXPECT_EQ( 19583 "// foo foo foo foo\n" 19584 "// foo foo foo foo\n" 19585 "// foo foo foo foo\n", 19586 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19587 19588 EXPECT_EQ("int a = /* long block\n" 19589 " comment */\n" 19590 " 42;", 19591 format("int a = /* long block comment */ 42;", Style)); 19592 } 19593 19594 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19595 FormatStyle Style = getLLVMStyle(); 19596 Style.ColumnLimit = 8; 19597 Style.PenaltyExcessCharacter = 15; 19598 verifyFormat("int foo(\n" 19599 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19600 Style); 19601 Style.PenaltyBreakOpenParenthesis = 200; 19602 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19603 format("int foo(\n" 19604 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19605 Style)); 19606 } 19607 19608 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19609 FormatStyle Style = getLLVMStyle(); 19610 Style.ColumnLimit = 5; 19611 Style.PenaltyExcessCharacter = 150; 19612 verifyFormat("foo((\n" 19613 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19614 19615 Style); 19616 Style.PenaltyBreakOpenParenthesis = 100000; 19617 EXPECT_EQ("foo((int)\n" 19618 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19619 format("foo((\n" 19620 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19621 Style)); 19622 } 19623 19624 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19625 FormatStyle Style = getLLVMStyle(); 19626 Style.ColumnLimit = 4; 19627 Style.PenaltyExcessCharacter = 100; 19628 verifyFormat("for (\n" 19629 " int iiiiiiiiiiiiiiiii =\n" 19630 " 0;\n" 19631 " iiiiiiiiiiiiiiiii <\n" 19632 " 2;\n" 19633 " iiiiiiiiiiiiiiiii++) {\n" 19634 "}", 19635 19636 Style); 19637 Style.PenaltyBreakOpenParenthesis = 1250; 19638 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19639 " 0;\n" 19640 " iiiiiiiiiiiiiiiii <\n" 19641 " 2;\n" 19642 " iiiiiiiiiiiiiiiii++) {\n" 19643 "}", 19644 format("for (\n" 19645 " int iiiiiiiiiiiiiiiii =\n" 19646 " 0;\n" 19647 " iiiiiiiiiiiiiiiii <\n" 19648 " 2;\n" 19649 " iiiiiiiiiiiiiiiii++) {\n" 19650 "}", 19651 Style)); 19652 } 19653 19654 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19655 for (size_t i = 1; i < Styles.size(); ++i) \ 19656 EXPECT_EQ(Styles[0], Styles[i]) \ 19657 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19658 19659 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19660 SmallVector<FormatStyle, 3> Styles; 19661 Styles.resize(3); 19662 19663 Styles[0] = getLLVMStyle(); 19664 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19665 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19666 EXPECT_ALL_STYLES_EQUAL(Styles); 19667 19668 Styles[0] = getGoogleStyle(); 19669 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19670 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19671 EXPECT_ALL_STYLES_EQUAL(Styles); 19672 19673 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19674 EXPECT_TRUE( 19675 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19676 EXPECT_TRUE( 19677 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19678 EXPECT_ALL_STYLES_EQUAL(Styles); 19679 19680 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19681 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19682 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19683 EXPECT_ALL_STYLES_EQUAL(Styles); 19684 19685 Styles[0] = getMozillaStyle(); 19686 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19687 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19688 EXPECT_ALL_STYLES_EQUAL(Styles); 19689 19690 Styles[0] = getWebKitStyle(); 19691 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19692 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19693 EXPECT_ALL_STYLES_EQUAL(Styles); 19694 19695 Styles[0] = getGNUStyle(); 19696 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19697 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19698 EXPECT_ALL_STYLES_EQUAL(Styles); 19699 19700 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19701 } 19702 19703 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19704 SmallVector<FormatStyle, 8> Styles; 19705 Styles.resize(2); 19706 19707 Styles[0] = getGoogleStyle(); 19708 Styles[1] = getLLVMStyle(); 19709 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19710 EXPECT_ALL_STYLES_EQUAL(Styles); 19711 19712 Styles.resize(5); 19713 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19714 Styles[1] = getLLVMStyle(); 19715 Styles[1].Language = FormatStyle::LK_JavaScript; 19716 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19717 19718 Styles[2] = getLLVMStyle(); 19719 Styles[2].Language = FormatStyle::LK_JavaScript; 19720 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19721 "BasedOnStyle: Google", 19722 &Styles[2]) 19723 .value()); 19724 19725 Styles[3] = getLLVMStyle(); 19726 Styles[3].Language = FormatStyle::LK_JavaScript; 19727 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19728 "Language: JavaScript", 19729 &Styles[3]) 19730 .value()); 19731 19732 Styles[4] = getLLVMStyle(); 19733 Styles[4].Language = FormatStyle::LK_JavaScript; 19734 EXPECT_EQ(0, parseConfiguration("---\n" 19735 "BasedOnStyle: LLVM\n" 19736 "IndentWidth: 123\n" 19737 "---\n" 19738 "BasedOnStyle: Google\n" 19739 "Language: JavaScript", 19740 &Styles[4]) 19741 .value()); 19742 EXPECT_ALL_STYLES_EQUAL(Styles); 19743 } 19744 19745 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19746 Style.FIELD = false; \ 19747 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19748 EXPECT_TRUE(Style.FIELD); \ 19749 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19750 EXPECT_FALSE(Style.FIELD); 19751 19752 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19753 19754 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19755 Style.STRUCT.FIELD = false; \ 19756 EXPECT_EQ(0, \ 19757 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19758 .value()); \ 19759 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19760 EXPECT_EQ(0, \ 19761 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19762 .value()); \ 19763 EXPECT_FALSE(Style.STRUCT.FIELD); 19764 19765 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19766 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19767 19768 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19769 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19770 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19771 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19772 19773 TEST_F(FormatTest, ParsesConfigurationBools) { 19774 FormatStyle Style = {}; 19775 Style.Language = FormatStyle::LK_Cpp; 19776 CHECK_PARSE_BOOL(AlignTrailingComments); 19777 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19778 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19779 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19780 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19781 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19782 CHECK_PARSE_BOOL(BinPackArguments); 19783 CHECK_PARSE_BOOL(BinPackParameters); 19784 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19785 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19786 CHECK_PARSE_BOOL(BreakStringLiterals); 19787 CHECK_PARSE_BOOL(CompactNamespaces); 19788 CHECK_PARSE_BOOL(DeriveLineEnding); 19789 CHECK_PARSE_BOOL(DerivePointerAlignment); 19790 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19791 CHECK_PARSE_BOOL(DisableFormat); 19792 CHECK_PARSE_BOOL(IndentAccessModifiers); 19793 CHECK_PARSE_BOOL(IndentCaseLabels); 19794 CHECK_PARSE_BOOL(IndentCaseBlocks); 19795 CHECK_PARSE_BOOL(IndentGotoLabels); 19796 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19797 CHECK_PARSE_BOOL(IndentRequiresClause); 19798 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19799 CHECK_PARSE_BOOL(InsertBraces); 19800 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19801 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19802 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19803 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19804 CHECK_PARSE_BOOL(ReflowComments); 19805 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19806 CHECK_PARSE_BOOL(SortUsingDeclarations); 19807 CHECK_PARSE_BOOL(SpacesInParentheses); 19808 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19809 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19810 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19811 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19812 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19813 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19814 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19815 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19816 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19817 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19818 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19819 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19820 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19821 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19822 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19823 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19824 CHECK_PARSE_BOOL(UseCRLF); 19825 19826 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19827 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19828 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19829 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19830 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19831 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19832 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19833 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19834 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19835 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19836 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19837 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19838 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19839 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19840 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19841 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19842 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19843 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19844 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19845 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19846 AfterFunctionDeclarationName); 19847 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19848 AfterFunctionDefinitionName); 19849 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19850 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19851 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19852 } 19853 19854 #undef CHECK_PARSE_BOOL 19855 19856 TEST_F(FormatTest, ParsesConfiguration) { 19857 FormatStyle Style = {}; 19858 Style.Language = FormatStyle::LK_Cpp; 19859 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19860 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19861 ConstructorInitializerIndentWidth, 1234u); 19862 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19863 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19864 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19865 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19866 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19867 PenaltyBreakBeforeFirstCallParameter, 1234u); 19868 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19869 PenaltyBreakTemplateDeclaration, 1234u); 19870 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19871 1234u); 19872 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19873 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19874 PenaltyReturnTypeOnItsOwnLine, 1234u); 19875 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19876 SpacesBeforeTrailingComments, 1234u); 19877 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19878 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19879 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19880 19881 Style.QualifierAlignment = FormatStyle::QAS_Right; 19882 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19883 FormatStyle::QAS_Leave); 19884 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19885 FormatStyle::QAS_Right); 19886 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19887 FormatStyle::QAS_Left); 19888 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19889 FormatStyle::QAS_Custom); 19890 19891 Style.QualifierOrder.clear(); 19892 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19893 std::vector<std::string>({"const", "volatile", "type"})); 19894 Style.QualifierOrder.clear(); 19895 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19896 std::vector<std::string>({"const", "type"})); 19897 Style.QualifierOrder.clear(); 19898 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19899 std::vector<std::string>({"volatile", "type"})); 19900 19901 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 19902 do { \ 19903 Style.FIELD.Enabled = true; \ 19904 CHECK_PARSE(#FIELD ": None", FIELD, \ 19905 FormatStyle::AlignConsecutiveStyle( \ 19906 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19907 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19908 /*PadOperators=*/true})); \ 19909 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 19910 FormatStyle::AlignConsecutiveStyle( \ 19911 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19912 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19913 /*PadOperators=*/true})); \ 19914 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 19915 FormatStyle::AlignConsecutiveStyle( \ 19916 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19917 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19918 /*PadOperators=*/true})); \ 19919 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 19920 FormatStyle::AlignConsecutiveStyle( \ 19921 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19922 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 19923 /*PadOperators=*/true})); \ 19924 /* For backwards compability, false / true should still parse */ \ 19925 CHECK_PARSE(#FIELD ": false", FIELD, \ 19926 FormatStyle::AlignConsecutiveStyle( \ 19927 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19928 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19929 /*PadOperators=*/true})); \ 19930 CHECK_PARSE(#FIELD ": true", FIELD, \ 19931 FormatStyle::AlignConsecutiveStyle( \ 19932 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19933 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19934 /*PadOperators=*/true})); \ 19935 \ 19936 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 19937 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 19938 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 19939 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 19940 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 19941 } while (false) 19942 19943 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 19944 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 19945 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 19946 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 19947 19948 #undef CHECK_ALIGN_CONSECUTIVE 19949 19950 Style.PointerAlignment = FormatStyle::PAS_Middle; 19951 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19952 FormatStyle::PAS_Left); 19953 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19954 FormatStyle::PAS_Right); 19955 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19956 FormatStyle::PAS_Middle); 19957 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19958 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19959 FormatStyle::RAS_Pointer); 19960 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19961 FormatStyle::RAS_Left); 19962 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19963 FormatStyle::RAS_Right); 19964 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19965 FormatStyle::RAS_Middle); 19966 // For backward compatibility: 19967 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19968 FormatStyle::PAS_Left); 19969 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19970 FormatStyle::PAS_Right); 19971 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19972 FormatStyle::PAS_Middle); 19973 19974 Style.Standard = FormatStyle::LS_Auto; 19975 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19976 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19977 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19978 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19979 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19980 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19981 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19982 // Legacy aliases: 19983 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19984 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19985 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19986 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19987 19988 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19989 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19990 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19991 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19992 FormatStyle::BOS_None); 19993 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19994 FormatStyle::BOS_All); 19995 // For backward compatibility: 19996 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19997 FormatStyle::BOS_None); 19998 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19999 FormatStyle::BOS_All); 20000 20001 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20002 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20003 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20004 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20005 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20006 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20007 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20008 // For backward compatibility: 20009 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20010 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20011 20012 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20013 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20014 FormatStyle::BILS_AfterComma); 20015 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20016 FormatStyle::BILS_BeforeComma); 20017 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20018 FormatStyle::BILS_AfterColon); 20019 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20020 FormatStyle::BILS_BeforeColon); 20021 // For backward compatibility: 20022 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20023 FormatStyle::BILS_BeforeComma); 20024 20025 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20026 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20027 FormatStyle::PCIS_Never); 20028 CHECK_PARSE("PackConstructorInitializers: BinPack", 20029 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20030 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20031 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20032 CHECK_PARSE("PackConstructorInitializers: NextLine", 20033 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20034 // For backward compatibility: 20035 CHECK_PARSE("BasedOnStyle: Google\n" 20036 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20037 "AllowAllConstructorInitializersOnNextLine: false", 20038 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20039 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20040 CHECK_PARSE("BasedOnStyle: Google\n" 20041 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20042 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20043 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20044 "AllowAllConstructorInitializersOnNextLine: true", 20045 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20046 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20047 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20048 "AllowAllConstructorInitializersOnNextLine: false", 20049 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20050 20051 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20052 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20053 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20054 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20055 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20056 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20057 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20058 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20059 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20060 20061 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20062 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20063 FormatStyle::BAS_Align); 20064 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20065 FormatStyle::BAS_DontAlign); 20066 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20067 FormatStyle::BAS_AlwaysBreak); 20068 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20069 FormatStyle::BAS_BlockIndent); 20070 // For backward compatibility: 20071 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20072 FormatStyle::BAS_DontAlign); 20073 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20074 FormatStyle::BAS_Align); 20075 20076 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20077 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20078 FormatStyle::ENAS_DontAlign); 20079 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20080 FormatStyle::ENAS_Left); 20081 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20082 FormatStyle::ENAS_Right); 20083 // For backward compatibility: 20084 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20085 FormatStyle::ENAS_Left); 20086 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20087 FormatStyle::ENAS_Right); 20088 20089 Style.AlignOperands = FormatStyle::OAS_Align; 20090 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20091 FormatStyle::OAS_DontAlign); 20092 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20093 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20094 FormatStyle::OAS_AlignAfterOperator); 20095 // For backward compatibility: 20096 CHECK_PARSE("AlignOperands: false", AlignOperands, 20097 FormatStyle::OAS_DontAlign); 20098 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20099 20100 Style.UseTab = FormatStyle::UT_ForIndentation; 20101 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20102 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20103 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20104 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20105 FormatStyle::UT_ForContinuationAndIndentation); 20106 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20107 FormatStyle::UT_AlignWithSpaces); 20108 // For backward compatibility: 20109 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20110 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20111 20112 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20113 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20114 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20115 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20116 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20117 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20118 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20119 // For backward compatibility: 20120 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20121 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20122 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20123 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20124 20125 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20126 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20127 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20128 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20129 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20130 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20131 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20132 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20133 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20134 // For backward compatibility: 20135 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20136 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20137 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20138 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20139 20140 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20141 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20142 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20143 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20144 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20145 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20146 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20147 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20148 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20149 20150 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20151 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20152 FormatStyle::SBPO_Never); 20153 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20154 FormatStyle::SBPO_Always); 20155 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20156 FormatStyle::SBPO_ControlStatements); 20157 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20158 SpaceBeforeParens, 20159 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20160 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20161 FormatStyle::SBPO_NonEmptyParentheses); 20162 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20163 FormatStyle::SBPO_Custom); 20164 // For backward compatibility: 20165 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20166 FormatStyle::SBPO_Never); 20167 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20168 FormatStyle::SBPO_ControlStatements); 20169 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20170 SpaceBeforeParens, 20171 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20172 20173 Style.ColumnLimit = 123; 20174 FormatStyle BaseStyle = getLLVMStyle(); 20175 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20176 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20177 20178 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20179 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20180 FormatStyle::BS_Attach); 20181 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20182 FormatStyle::BS_Linux); 20183 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20184 FormatStyle::BS_Mozilla); 20185 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20186 FormatStyle::BS_Stroustrup); 20187 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20188 FormatStyle::BS_Allman); 20189 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20190 FormatStyle::BS_Whitesmiths); 20191 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20192 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20193 FormatStyle::BS_WebKit); 20194 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20195 FormatStyle::BS_Custom); 20196 20197 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20198 CHECK_PARSE("BraceWrapping:\n" 20199 " AfterControlStatement: MultiLine", 20200 BraceWrapping.AfterControlStatement, 20201 FormatStyle::BWACS_MultiLine); 20202 CHECK_PARSE("BraceWrapping:\n" 20203 " AfterControlStatement: Always", 20204 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20205 CHECK_PARSE("BraceWrapping:\n" 20206 " AfterControlStatement: Never", 20207 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20208 // For backward compatibility: 20209 CHECK_PARSE("BraceWrapping:\n" 20210 " AfterControlStatement: true", 20211 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20212 CHECK_PARSE("BraceWrapping:\n" 20213 " AfterControlStatement: false", 20214 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20215 20216 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20217 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20218 FormatStyle::RTBS_None); 20219 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20220 FormatStyle::RTBS_All); 20221 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20222 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20223 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20224 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20225 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20226 AlwaysBreakAfterReturnType, 20227 FormatStyle::RTBS_TopLevelDefinitions); 20228 20229 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20230 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20231 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20232 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20233 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20234 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20235 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20236 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20237 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20238 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20239 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20240 20241 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20242 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20243 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20244 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20245 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20246 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20247 AlwaysBreakAfterDefinitionReturnType, 20248 FormatStyle::DRTBS_TopLevel); 20249 20250 Style.NamespaceIndentation = FormatStyle::NI_All; 20251 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20252 FormatStyle::NI_None); 20253 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20254 FormatStyle::NI_Inner); 20255 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20256 FormatStyle::NI_All); 20257 20258 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20259 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20260 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20261 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20262 AllowShortIfStatementsOnASingleLine, 20263 FormatStyle::SIS_WithoutElse); 20264 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20265 AllowShortIfStatementsOnASingleLine, 20266 FormatStyle::SIS_OnlyFirstIf); 20267 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20268 AllowShortIfStatementsOnASingleLine, 20269 FormatStyle::SIS_AllIfsAndElse); 20270 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20271 AllowShortIfStatementsOnASingleLine, 20272 FormatStyle::SIS_OnlyFirstIf); 20273 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20274 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20275 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20276 AllowShortIfStatementsOnASingleLine, 20277 FormatStyle::SIS_WithoutElse); 20278 20279 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20280 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20281 FormatStyle::IEBS_AfterExternBlock); 20282 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20283 FormatStyle::IEBS_Indent); 20284 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20285 FormatStyle::IEBS_NoIndent); 20286 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20287 FormatStyle::IEBS_Indent); 20288 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20289 FormatStyle::IEBS_NoIndent); 20290 20291 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20292 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20293 FormatStyle::BFCS_Both); 20294 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20295 FormatStyle::BFCS_None); 20296 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20297 FormatStyle::BFCS_Before); 20298 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20299 FormatStyle::BFCS_After); 20300 20301 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20302 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20303 FormatStyle::SJSIO_After); 20304 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20305 FormatStyle::SJSIO_Before); 20306 20307 // FIXME: This is required because parsing a configuration simply overwrites 20308 // the first N elements of the list instead of resetting it. 20309 Style.ForEachMacros.clear(); 20310 std::vector<std::string> BoostForeach; 20311 BoostForeach.push_back("BOOST_FOREACH"); 20312 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20313 std::vector<std::string> BoostAndQForeach; 20314 BoostAndQForeach.push_back("BOOST_FOREACH"); 20315 BoostAndQForeach.push_back("Q_FOREACH"); 20316 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20317 BoostAndQForeach); 20318 20319 Style.IfMacros.clear(); 20320 std::vector<std::string> CustomIfs; 20321 CustomIfs.push_back("MYIF"); 20322 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20323 20324 Style.AttributeMacros.clear(); 20325 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20326 std::vector<std::string>{"__capability"}); 20327 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20328 std::vector<std::string>({"attr1", "attr2"})); 20329 20330 Style.StatementAttributeLikeMacros.clear(); 20331 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20332 StatementAttributeLikeMacros, 20333 std::vector<std::string>({"emit", "Q_EMIT"})); 20334 20335 Style.StatementMacros.clear(); 20336 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20337 std::vector<std::string>{"QUNUSED"}); 20338 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20339 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20340 20341 Style.NamespaceMacros.clear(); 20342 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20343 std::vector<std::string>{"TESTSUITE"}); 20344 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20345 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20346 20347 Style.WhitespaceSensitiveMacros.clear(); 20348 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20349 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20350 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20351 WhitespaceSensitiveMacros, 20352 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20353 Style.WhitespaceSensitiveMacros.clear(); 20354 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20355 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20356 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20357 WhitespaceSensitiveMacros, 20358 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20359 20360 Style.IncludeStyle.IncludeCategories.clear(); 20361 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20362 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20363 CHECK_PARSE("IncludeCategories:\n" 20364 " - Regex: abc/.*\n" 20365 " Priority: 2\n" 20366 " - Regex: .*\n" 20367 " Priority: 1\n" 20368 " CaseSensitive: true\n", 20369 IncludeStyle.IncludeCategories, ExpectedCategories); 20370 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20371 "abc$"); 20372 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20373 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20374 20375 Style.SortIncludes = FormatStyle::SI_Never; 20376 CHECK_PARSE("SortIncludes: true", SortIncludes, 20377 FormatStyle::SI_CaseSensitive); 20378 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20379 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20380 FormatStyle::SI_CaseInsensitive); 20381 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20382 FormatStyle::SI_CaseSensitive); 20383 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20384 20385 Style.RawStringFormats.clear(); 20386 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20387 { 20388 FormatStyle::LK_TextProto, 20389 {"pb", "proto"}, 20390 {"PARSE_TEXT_PROTO"}, 20391 /*CanonicalDelimiter=*/"", 20392 "llvm", 20393 }, 20394 { 20395 FormatStyle::LK_Cpp, 20396 {"cc", "cpp"}, 20397 {"C_CODEBLOCK", "CPPEVAL"}, 20398 /*CanonicalDelimiter=*/"cc", 20399 /*BasedOnStyle=*/"", 20400 }, 20401 }; 20402 20403 CHECK_PARSE("RawStringFormats:\n" 20404 " - Language: TextProto\n" 20405 " Delimiters:\n" 20406 " - 'pb'\n" 20407 " - 'proto'\n" 20408 " EnclosingFunctions:\n" 20409 " - 'PARSE_TEXT_PROTO'\n" 20410 " BasedOnStyle: llvm\n" 20411 " - Language: Cpp\n" 20412 " Delimiters:\n" 20413 " - 'cc'\n" 20414 " - 'cpp'\n" 20415 " EnclosingFunctions:\n" 20416 " - 'C_CODEBLOCK'\n" 20417 " - 'CPPEVAL'\n" 20418 " CanonicalDelimiter: 'cc'", 20419 RawStringFormats, ExpectedRawStringFormats); 20420 20421 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20422 " Minimum: 0\n" 20423 " Maximum: 0", 20424 SpacesInLineCommentPrefix.Minimum, 0u); 20425 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20426 Style.SpacesInLineCommentPrefix.Minimum = 1; 20427 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20428 " Minimum: 2", 20429 SpacesInLineCommentPrefix.Minimum, 0u); 20430 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20431 " Maximum: -1", 20432 SpacesInLineCommentPrefix.Maximum, -1u); 20433 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20434 " Minimum: 2", 20435 SpacesInLineCommentPrefix.Minimum, 2u); 20436 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20437 " Maximum: 1", 20438 SpacesInLineCommentPrefix.Maximum, 1u); 20439 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20440 20441 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20442 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20443 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20444 FormatStyle::SIAS_Always); 20445 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20446 // For backward compatibility: 20447 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20448 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20449 20450 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20451 FormatStyle::RCPS_WithPreceding); 20452 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20453 FormatStyle::RCPS_WithFollowing); 20454 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20455 FormatStyle::RCPS_SingleLine); 20456 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20457 FormatStyle::RCPS_OwnLine); 20458 20459 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20460 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20461 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20462 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20463 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20464 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20465 // For backward compatibility: 20466 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20467 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20468 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20469 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20470 } 20471 20472 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20473 FormatStyle Style = {}; 20474 Style.Language = FormatStyle::LK_Cpp; 20475 CHECK_PARSE("Language: Cpp\n" 20476 "IndentWidth: 12", 20477 IndentWidth, 12u); 20478 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20479 "IndentWidth: 34", 20480 &Style), 20481 ParseError::Unsuitable); 20482 FormatStyle BinPackedTCS = {}; 20483 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20484 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20485 "InsertTrailingCommas: Wrapped", 20486 &BinPackedTCS), 20487 ParseError::BinPackTrailingCommaConflict); 20488 EXPECT_EQ(12u, Style.IndentWidth); 20489 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20490 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20491 20492 Style.Language = FormatStyle::LK_JavaScript; 20493 CHECK_PARSE("Language: JavaScript\n" 20494 "IndentWidth: 12", 20495 IndentWidth, 12u); 20496 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20497 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20498 "IndentWidth: 34", 20499 &Style), 20500 ParseError::Unsuitable); 20501 EXPECT_EQ(23u, Style.IndentWidth); 20502 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20503 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20504 20505 CHECK_PARSE("BasedOnStyle: LLVM\n" 20506 "IndentWidth: 67", 20507 IndentWidth, 67u); 20508 20509 CHECK_PARSE("---\n" 20510 "Language: JavaScript\n" 20511 "IndentWidth: 12\n" 20512 "---\n" 20513 "Language: Cpp\n" 20514 "IndentWidth: 34\n" 20515 "...\n", 20516 IndentWidth, 12u); 20517 20518 Style.Language = FormatStyle::LK_Cpp; 20519 CHECK_PARSE("---\n" 20520 "Language: JavaScript\n" 20521 "IndentWidth: 12\n" 20522 "---\n" 20523 "Language: Cpp\n" 20524 "IndentWidth: 34\n" 20525 "...\n", 20526 IndentWidth, 34u); 20527 CHECK_PARSE("---\n" 20528 "IndentWidth: 78\n" 20529 "---\n" 20530 "Language: JavaScript\n" 20531 "IndentWidth: 56\n" 20532 "...\n", 20533 IndentWidth, 78u); 20534 20535 Style.ColumnLimit = 123; 20536 Style.IndentWidth = 234; 20537 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20538 Style.TabWidth = 345; 20539 EXPECT_FALSE(parseConfiguration("---\n" 20540 "IndentWidth: 456\n" 20541 "BreakBeforeBraces: Allman\n" 20542 "---\n" 20543 "Language: JavaScript\n" 20544 "IndentWidth: 111\n" 20545 "TabWidth: 111\n" 20546 "---\n" 20547 "Language: Cpp\n" 20548 "BreakBeforeBraces: Stroustrup\n" 20549 "TabWidth: 789\n" 20550 "...\n", 20551 &Style)); 20552 EXPECT_EQ(123u, Style.ColumnLimit); 20553 EXPECT_EQ(456u, Style.IndentWidth); 20554 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20555 EXPECT_EQ(789u, Style.TabWidth); 20556 20557 EXPECT_EQ(parseConfiguration("---\n" 20558 "Language: JavaScript\n" 20559 "IndentWidth: 56\n" 20560 "---\n" 20561 "IndentWidth: 78\n" 20562 "...\n", 20563 &Style), 20564 ParseError::Error); 20565 EXPECT_EQ(parseConfiguration("---\n" 20566 "Language: JavaScript\n" 20567 "IndentWidth: 56\n" 20568 "---\n" 20569 "Language: JavaScript\n" 20570 "IndentWidth: 78\n" 20571 "...\n", 20572 &Style), 20573 ParseError::Error); 20574 20575 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20576 } 20577 20578 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20579 FormatStyle Style = {}; 20580 Style.Language = FormatStyle::LK_JavaScript; 20581 Style.BreakBeforeTernaryOperators = true; 20582 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20583 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20584 20585 Style.BreakBeforeTernaryOperators = true; 20586 EXPECT_EQ(0, parseConfiguration("---\n" 20587 "BasedOnStyle: Google\n" 20588 "---\n" 20589 "Language: JavaScript\n" 20590 "IndentWidth: 76\n" 20591 "...\n", 20592 &Style) 20593 .value()); 20594 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20595 EXPECT_EQ(76u, Style.IndentWidth); 20596 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20597 } 20598 20599 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20600 FormatStyle Style = getLLVMStyle(); 20601 std::string YAML = configurationAsText(Style); 20602 FormatStyle ParsedStyle = {}; 20603 ParsedStyle.Language = FormatStyle::LK_Cpp; 20604 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20605 EXPECT_EQ(Style, ParsedStyle); 20606 } 20607 20608 TEST_F(FormatTest, WorksFor8bitEncodings) { 20609 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20610 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20611 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20612 "\"\xef\xee\xf0\xf3...\"", 20613 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20614 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20615 "\xef\xee\xf0\xf3...\"", 20616 getLLVMStyleWithColumns(12))); 20617 } 20618 20619 TEST_F(FormatTest, HandlesUTF8BOM) { 20620 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20621 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20622 format("\xef\xbb\xbf#include <iostream>")); 20623 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20624 format("\xef\xbb\xbf\n#include <iostream>")); 20625 } 20626 20627 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20628 #if !defined(_MSC_VER) 20629 20630 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20631 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20632 getLLVMStyleWithColumns(35)); 20633 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20634 getLLVMStyleWithColumns(31)); 20635 verifyFormat("// Однажды в студёную зимнюю пору...", 20636 getLLVMStyleWithColumns(36)); 20637 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20638 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20639 getLLVMStyleWithColumns(39)); 20640 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20641 getLLVMStyleWithColumns(35)); 20642 } 20643 20644 TEST_F(FormatTest, SplitsUTF8Strings) { 20645 // Non-printable characters' width is currently considered to be the length in 20646 // bytes in UTF8. The characters can be displayed in very different manner 20647 // (zero-width, single width with a substitution glyph, expanded to their code 20648 // (e.g. "<8d>"), so there's no single correct way to handle them. 20649 EXPECT_EQ("\"aaaaÄ\"\n" 20650 "\"\xc2\x8d\";", 20651 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20652 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20653 "\"\xc2\x8d\";", 20654 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20655 EXPECT_EQ("\"Однажды, в \"\n" 20656 "\"студёную \"\n" 20657 "\"зимнюю \"\n" 20658 "\"пору,\"", 20659 format("\"Однажды, в студёную зимнюю пору,\"", 20660 getLLVMStyleWithColumns(13))); 20661 EXPECT_EQ( 20662 "\"一 二 三 \"\n" 20663 "\"四 五六 \"\n" 20664 "\"七 八 九 \"\n" 20665 "\"十\"", 20666 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20667 EXPECT_EQ("\"一\t\"\n" 20668 "\"二 \t\"\n" 20669 "\"三 四 \"\n" 20670 "\"五\t\"\n" 20671 "\"六 \t\"\n" 20672 "\"七 \"\n" 20673 "\"八九十\tqq\"", 20674 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20675 getLLVMStyleWithColumns(11))); 20676 20677 // UTF8 character in an escape sequence. 20678 EXPECT_EQ("\"aaaaaa\"\n" 20679 "\"\\\xC2\x8D\"", 20680 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20681 } 20682 20683 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20684 EXPECT_EQ("const char *sssss =\n" 20685 " \"一二三四五六七八\\\n" 20686 " 九 十\";", 20687 format("const char *sssss = \"一二三四五六七八\\\n" 20688 " 九 十\";", 20689 getLLVMStyleWithColumns(30))); 20690 } 20691 20692 TEST_F(FormatTest, SplitsUTF8LineComments) { 20693 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20694 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20695 EXPECT_EQ("// Я из лесу\n" 20696 "// вышел; был\n" 20697 "// сильный\n" 20698 "// мороз.", 20699 format("// Я из лесу вышел; был сильный мороз.", 20700 getLLVMStyleWithColumns(13))); 20701 EXPECT_EQ("// 一二三\n" 20702 "// 四五六七\n" 20703 "// 八 九\n" 20704 "// 十", 20705 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20706 } 20707 20708 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20709 EXPECT_EQ("/* Гляжу,\n" 20710 " * поднимается\n" 20711 " * медленно в\n" 20712 " * гору\n" 20713 " * Лошадка,\n" 20714 " * везущая\n" 20715 " * хворосту\n" 20716 " * воз. */", 20717 format("/* Гляжу, поднимается медленно в гору\n" 20718 " * Лошадка, везущая хворосту воз. */", 20719 getLLVMStyleWithColumns(13))); 20720 EXPECT_EQ( 20721 "/* 一二三\n" 20722 " * 四五六七\n" 20723 " * 八 九\n" 20724 " * 十 */", 20725 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20726 EXPECT_EQ("/* \n" 20727 " * \n" 20728 " * - */", 20729 format("/* - */", getLLVMStyleWithColumns(12))); 20730 } 20731 20732 #endif // _MSC_VER 20733 20734 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20735 FormatStyle Style = getLLVMStyle(); 20736 20737 Style.ConstructorInitializerIndentWidth = 4; 20738 verifyFormat( 20739 "SomeClass::Constructor()\n" 20740 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20741 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20742 Style); 20743 20744 Style.ConstructorInitializerIndentWidth = 2; 20745 verifyFormat( 20746 "SomeClass::Constructor()\n" 20747 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20748 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20749 Style); 20750 20751 Style.ConstructorInitializerIndentWidth = 0; 20752 verifyFormat( 20753 "SomeClass::Constructor()\n" 20754 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20755 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20756 Style); 20757 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20758 verifyFormat( 20759 "SomeLongTemplateVariableName<\n" 20760 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20761 Style); 20762 verifyFormat("bool smaller = 1 < " 20763 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20764 " " 20765 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20766 Style); 20767 20768 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20769 verifyFormat("SomeClass::Constructor() :\n" 20770 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20771 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20772 Style); 20773 } 20774 20775 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20776 FormatStyle Style = getLLVMStyle(); 20777 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20778 Style.ConstructorInitializerIndentWidth = 4; 20779 verifyFormat("SomeClass::Constructor()\n" 20780 " : a(a)\n" 20781 " , b(b)\n" 20782 " , c(c) {}", 20783 Style); 20784 verifyFormat("SomeClass::Constructor()\n" 20785 " : a(a) {}", 20786 Style); 20787 20788 Style.ColumnLimit = 0; 20789 verifyFormat("SomeClass::Constructor()\n" 20790 " : a(a) {}", 20791 Style); 20792 verifyFormat("SomeClass::Constructor() noexcept\n" 20793 " : a(a) {}", 20794 Style); 20795 verifyFormat("SomeClass::Constructor()\n" 20796 " : a(a)\n" 20797 " , b(b)\n" 20798 " , c(c) {}", 20799 Style); 20800 verifyFormat("SomeClass::Constructor()\n" 20801 " : a(a) {\n" 20802 " foo();\n" 20803 " bar();\n" 20804 "}", 20805 Style); 20806 20807 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20808 verifyFormat("SomeClass::Constructor()\n" 20809 " : a(a)\n" 20810 " , b(b)\n" 20811 " , c(c) {\n}", 20812 Style); 20813 verifyFormat("SomeClass::Constructor()\n" 20814 " : a(a) {\n}", 20815 Style); 20816 20817 Style.ColumnLimit = 80; 20818 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20819 Style.ConstructorInitializerIndentWidth = 2; 20820 verifyFormat("SomeClass::Constructor()\n" 20821 " : a(a)\n" 20822 " , b(b)\n" 20823 " , c(c) {}", 20824 Style); 20825 20826 Style.ConstructorInitializerIndentWidth = 0; 20827 verifyFormat("SomeClass::Constructor()\n" 20828 ": a(a)\n" 20829 ", b(b)\n" 20830 ", c(c) {}", 20831 Style); 20832 20833 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20834 Style.ConstructorInitializerIndentWidth = 4; 20835 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20836 verifyFormat( 20837 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20838 Style); 20839 verifyFormat( 20840 "SomeClass::Constructor()\n" 20841 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20842 Style); 20843 Style.ConstructorInitializerIndentWidth = 4; 20844 Style.ColumnLimit = 60; 20845 verifyFormat("SomeClass::Constructor()\n" 20846 " : aaaaaaaa(aaaaaaaa)\n" 20847 " , aaaaaaaa(aaaaaaaa)\n" 20848 " , aaaaaaaa(aaaaaaaa) {}", 20849 Style); 20850 } 20851 20852 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20853 FormatStyle Style = getLLVMStyle(); 20854 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20855 Style.ConstructorInitializerIndentWidth = 4; 20856 verifyFormat("SomeClass::Constructor()\n" 20857 " : a{a}\n" 20858 " , b{b} {}", 20859 Style); 20860 verifyFormat("SomeClass::Constructor()\n" 20861 " : a{a}\n" 20862 "#if CONDITION\n" 20863 " , b{b}\n" 20864 "#endif\n" 20865 "{\n}", 20866 Style); 20867 Style.ConstructorInitializerIndentWidth = 2; 20868 verifyFormat("SomeClass::Constructor()\n" 20869 "#if CONDITION\n" 20870 " : a{a}\n" 20871 "#endif\n" 20872 " , b{b}\n" 20873 " , c{c} {\n}", 20874 Style); 20875 Style.ConstructorInitializerIndentWidth = 0; 20876 verifyFormat("SomeClass::Constructor()\n" 20877 ": a{a}\n" 20878 "#ifdef CONDITION\n" 20879 ", b{b}\n" 20880 "#else\n" 20881 ", c{c}\n" 20882 "#endif\n" 20883 ", d{d} {\n}", 20884 Style); 20885 Style.ConstructorInitializerIndentWidth = 4; 20886 verifyFormat("SomeClass::Constructor()\n" 20887 " : a{a}\n" 20888 "#if WINDOWS\n" 20889 "#if DEBUG\n" 20890 " , b{0}\n" 20891 "#else\n" 20892 " , b{1}\n" 20893 "#endif\n" 20894 "#else\n" 20895 "#if DEBUG\n" 20896 " , b{2}\n" 20897 "#else\n" 20898 " , b{3}\n" 20899 "#endif\n" 20900 "#endif\n" 20901 "{\n}", 20902 Style); 20903 verifyFormat("SomeClass::Constructor()\n" 20904 " : a{a}\n" 20905 "#if WINDOWS\n" 20906 " , b{0}\n" 20907 "#if DEBUG\n" 20908 " , c{0}\n" 20909 "#else\n" 20910 " , c{1}\n" 20911 "#endif\n" 20912 "#else\n" 20913 "#if DEBUG\n" 20914 " , c{2}\n" 20915 "#else\n" 20916 " , c{3}\n" 20917 "#endif\n" 20918 " , b{1}\n" 20919 "#endif\n" 20920 "{\n}", 20921 Style); 20922 } 20923 20924 TEST_F(FormatTest, Destructors) { 20925 verifyFormat("void F(int &i) { i.~int(); }"); 20926 verifyFormat("void F(int &i) { i->~int(); }"); 20927 } 20928 20929 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20930 FormatStyle Style = getWebKitStyle(); 20931 20932 // Don't indent in outer namespaces. 20933 verifyFormat("namespace outer {\n" 20934 "int i;\n" 20935 "namespace inner {\n" 20936 " int i;\n" 20937 "} // namespace inner\n" 20938 "} // namespace outer\n" 20939 "namespace other_outer {\n" 20940 "int i;\n" 20941 "}", 20942 Style); 20943 20944 // Don't indent case labels. 20945 verifyFormat("switch (variable) {\n" 20946 "case 1:\n" 20947 "case 2:\n" 20948 " doSomething();\n" 20949 " break;\n" 20950 "default:\n" 20951 " ++variable;\n" 20952 "}", 20953 Style); 20954 20955 // Wrap before binary operators. 20956 EXPECT_EQ("void f()\n" 20957 "{\n" 20958 " if (aaaaaaaaaaaaaaaa\n" 20959 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20960 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20961 " return;\n" 20962 "}", 20963 format("void f() {\n" 20964 "if (aaaaaaaaaaaaaaaa\n" 20965 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20966 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20967 "return;\n" 20968 "}", 20969 Style)); 20970 20971 // Allow functions on a single line. 20972 verifyFormat("void f() { return; }", Style); 20973 20974 // Allow empty blocks on a single line and insert a space in empty blocks. 20975 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20976 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20977 // However, don't merge non-empty short loops. 20978 EXPECT_EQ("while (true) {\n" 20979 " continue;\n" 20980 "}", 20981 format("while (true) { continue; }", Style)); 20982 20983 // Constructor initializers are formatted one per line with the "," on the 20984 // new line. 20985 verifyFormat("Constructor()\n" 20986 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20987 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20988 " aaaaaaaaaaaaaa)\n" 20989 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20990 "{\n" 20991 "}", 20992 Style); 20993 verifyFormat("SomeClass::Constructor()\n" 20994 " : a(a)\n" 20995 "{\n" 20996 "}", 20997 Style); 20998 EXPECT_EQ("SomeClass::Constructor()\n" 20999 " : a(a)\n" 21000 "{\n" 21001 "}", 21002 format("SomeClass::Constructor():a(a){}", Style)); 21003 verifyFormat("SomeClass::Constructor()\n" 21004 " : a(a)\n" 21005 " , b(b)\n" 21006 " , c(c)\n" 21007 "{\n" 21008 "}", 21009 Style); 21010 verifyFormat("SomeClass::Constructor()\n" 21011 " : a(a)\n" 21012 "{\n" 21013 " foo();\n" 21014 " bar();\n" 21015 "}", 21016 Style); 21017 21018 // Access specifiers should be aligned left. 21019 verifyFormat("class C {\n" 21020 "public:\n" 21021 " int i;\n" 21022 "};", 21023 Style); 21024 21025 // Do not align comments. 21026 verifyFormat("int a; // Do not\n" 21027 "double b; // align comments.", 21028 Style); 21029 21030 // Do not align operands. 21031 EXPECT_EQ("ASSERT(aaaa\n" 21032 " || bbbb);", 21033 format("ASSERT ( aaaa\n||bbbb);", Style)); 21034 21035 // Accept input's line breaks. 21036 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21037 " || bbbbbbbbbbbbbbb) {\n" 21038 " i++;\n" 21039 "}", 21040 format("if (aaaaaaaaaaaaaaa\n" 21041 "|| bbbbbbbbbbbbbbb) { i++; }", 21042 Style)); 21043 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21044 " i++;\n" 21045 "}", 21046 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21047 21048 // Don't automatically break all macro definitions (llvm.org/PR17842). 21049 verifyFormat("#define aNumber 10", Style); 21050 // However, generally keep the line breaks that the user authored. 21051 EXPECT_EQ("#define aNumber \\\n" 21052 " 10", 21053 format("#define aNumber \\\n" 21054 " 10", 21055 Style)); 21056 21057 // Keep empty and one-element array literals on a single line. 21058 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21059 " copyItems:YES];", 21060 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21061 "copyItems:YES];", 21062 Style)); 21063 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21064 " copyItems:YES];", 21065 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21066 " copyItems:YES];", 21067 Style)); 21068 // FIXME: This does not seem right, there should be more indentation before 21069 // the array literal's entries. Nested blocks have the same problem. 21070 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21071 " @\"a\",\n" 21072 " @\"a\"\n" 21073 "]\n" 21074 " copyItems:YES];", 21075 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21076 " @\"a\",\n" 21077 " @\"a\"\n" 21078 " ]\n" 21079 " copyItems:YES];", 21080 Style)); 21081 EXPECT_EQ( 21082 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21083 " copyItems:YES];", 21084 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21085 " copyItems:YES];", 21086 Style)); 21087 21088 verifyFormat("[self.a b:c c:d];", Style); 21089 EXPECT_EQ("[self.a b:c\n" 21090 " c:d];", 21091 format("[self.a b:c\n" 21092 "c:d];", 21093 Style)); 21094 } 21095 21096 TEST_F(FormatTest, FormatsLambdas) { 21097 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21098 verifyFormat( 21099 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21100 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21101 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21102 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21103 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21104 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21105 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21106 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21107 verifyFormat("int x = f(*+[] {});"); 21108 verifyFormat("void f() {\n" 21109 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21110 "}\n"); 21111 verifyFormat("void f() {\n" 21112 " other(x.begin(), //\n" 21113 " x.end(), //\n" 21114 " [&](int, int) { return 1; });\n" 21115 "}\n"); 21116 verifyFormat("void f() {\n" 21117 " other.other.other.other.other(\n" 21118 " x.begin(), x.end(),\n" 21119 " [something, rather](int, int, int, int, int, int, int) { " 21120 "return 1; });\n" 21121 "}\n"); 21122 verifyFormat( 21123 "void f() {\n" 21124 " other.other.other.other.other(\n" 21125 " x.begin(), x.end(),\n" 21126 " [something, rather](int, int, int, int, int, int, int) {\n" 21127 " //\n" 21128 " });\n" 21129 "}\n"); 21130 verifyFormat("SomeFunction([]() { // A cool function...\n" 21131 " return 43;\n" 21132 "});"); 21133 EXPECT_EQ("SomeFunction([]() {\n" 21134 "#define A a\n" 21135 " return 43;\n" 21136 "});", 21137 format("SomeFunction([](){\n" 21138 "#define A a\n" 21139 "return 43;\n" 21140 "});")); 21141 verifyFormat("void f() {\n" 21142 " SomeFunction([](decltype(x), A *a) {});\n" 21143 " SomeFunction([](typeof(x), A *a) {});\n" 21144 " SomeFunction([](_Atomic(x), A *a) {});\n" 21145 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21146 "}"); 21147 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21148 " [](const aaaaaaaaaa &a) { return a; });"); 21149 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21150 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21151 "});"); 21152 verifyFormat("Constructor()\n" 21153 " : Field([] { // comment\n" 21154 " int i;\n" 21155 " }) {}"); 21156 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21157 " return some_parameter.size();\n" 21158 "};"); 21159 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21160 " [](const string &s) { return s; };"); 21161 verifyFormat("int i = aaaaaa ? 1 //\n" 21162 " : [] {\n" 21163 " return 2; //\n" 21164 " }();"); 21165 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21166 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21167 " return x == 2; // force break\n" 21168 " });"); 21169 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21170 " [=](int iiiiiiiiiiii) {\n" 21171 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21172 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21173 " });", 21174 getLLVMStyleWithColumns(60)); 21175 21176 verifyFormat("SomeFunction({[&] {\n" 21177 " // comment\n" 21178 " },\n" 21179 " [&] {\n" 21180 " // comment\n" 21181 " }});"); 21182 verifyFormat("SomeFunction({[&] {\n" 21183 " // comment\n" 21184 "}});"); 21185 verifyFormat( 21186 "virtual aaaaaaaaaaaaaaaa(\n" 21187 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21188 " aaaaa aaaaaaaaa);"); 21189 21190 // Lambdas with return types. 21191 verifyFormat("int c = []() -> int { return 2; }();\n"); 21192 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21193 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21194 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21195 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21196 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21197 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21198 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21199 verifyFormat("[a, a]() -> a<1> {};"); 21200 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21201 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21202 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21203 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21204 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21205 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21206 verifyFormat("[]() -> foo<!5> { return {}; };"); 21207 verifyFormat("[]() -> foo<~5> { return {}; };"); 21208 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21209 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21210 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21211 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21212 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21213 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21214 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21215 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21216 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21217 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21218 verifyFormat("namespace bar {\n" 21219 "// broken:\n" 21220 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21221 "} // namespace bar"); 21222 verifyFormat("namespace bar {\n" 21223 "// broken:\n" 21224 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21225 "} // namespace bar"); 21226 verifyFormat("namespace bar {\n" 21227 "// broken:\n" 21228 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21229 "} // namespace bar"); 21230 verifyFormat("namespace bar {\n" 21231 "// broken:\n" 21232 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21233 "} // namespace bar"); 21234 verifyFormat("namespace bar {\n" 21235 "// broken:\n" 21236 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21237 "} // namespace bar"); 21238 verifyFormat("namespace bar {\n" 21239 "// broken:\n" 21240 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21241 "} // namespace bar"); 21242 verifyFormat("namespace bar {\n" 21243 "// broken:\n" 21244 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21245 "} // namespace bar"); 21246 verifyFormat("namespace bar {\n" 21247 "// broken:\n" 21248 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21249 "} // namespace bar"); 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 >= 2> { return {}; }};\n" 21277 "} // namespace bar"); 21278 verifyFormat("namespace bar {\n" 21279 "// broken:\n" 21280 "auto foo{[]() -> foo<5 <= 2> { 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<2 ? 1 : 0> { return {}; }};\n" 21289 "} // namespace bar"); 21290 verifyFormat("[]() -> a<1> {};"); 21291 verifyFormat("[]() -> a<1> { ; };"); 21292 verifyFormat("[]() -> a<1> { ; }();"); 21293 verifyFormat("[a, a]() -> a<true> {};"); 21294 verifyFormat("[]() -> a<true> {};"); 21295 verifyFormat("[]() -> a<true> { ; };"); 21296 verifyFormat("[]() -> a<true> { ; }();"); 21297 verifyFormat("[a, a]() -> a<false> {};"); 21298 verifyFormat("[]() -> a<false> {};"); 21299 verifyFormat("[]() -> a<false> { ; };"); 21300 verifyFormat("[]() -> a<false> { ; }();"); 21301 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21302 verifyFormat("namespace bar {\n" 21303 "auto foo{[]() -> foo<false> { ; }};\n" 21304 "} // namespace bar"); 21305 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21306 " int j) -> int {\n" 21307 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21308 "};"); 21309 verifyFormat( 21310 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21311 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21312 " return aaaaaaaaaaaaaaaaa;\n" 21313 " });", 21314 getLLVMStyleWithColumns(70)); 21315 verifyFormat("[]() //\n" 21316 " -> int {\n" 21317 " return 1; //\n" 21318 "};"); 21319 verifyFormat("[]() -> Void<T...> {};"); 21320 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21321 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21322 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21323 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21324 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21325 verifyFormat("return int{[x = x]() { return x; }()};"); 21326 21327 // Lambdas with explicit template argument lists. 21328 verifyFormat( 21329 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21330 verifyFormat("auto L = []<class T>(T) {\n" 21331 " {\n" 21332 " f();\n" 21333 " g();\n" 21334 " }\n" 21335 "};\n"); 21336 verifyFormat("auto L = []<class... T>(T...) {\n" 21337 " {\n" 21338 " f();\n" 21339 " g();\n" 21340 " }\n" 21341 "};\n"); 21342 verifyFormat("auto L = []<typename... T>(T...) {\n" 21343 " {\n" 21344 " f();\n" 21345 " g();\n" 21346 " }\n" 21347 "};\n"); 21348 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21349 " {\n" 21350 " f();\n" 21351 " g();\n" 21352 " }\n" 21353 "};\n"); 21354 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21355 " {\n" 21356 " f();\n" 21357 " g();\n" 21358 " }\n" 21359 "};\n"); 21360 21361 // Multiple lambdas in the same parentheses change indentation rules. These 21362 // lambdas are forced to start on new lines. 21363 verifyFormat("SomeFunction(\n" 21364 " []() {\n" 21365 " //\n" 21366 " },\n" 21367 " []() {\n" 21368 " //\n" 21369 " });"); 21370 21371 // A lambda passed as arg0 is always pushed to the next line. 21372 verifyFormat("SomeFunction(\n" 21373 " [this] {\n" 21374 " //\n" 21375 " },\n" 21376 " 1);\n"); 21377 21378 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21379 // the arg0 case above. 21380 auto Style = getGoogleStyle(); 21381 Style.BinPackArguments = false; 21382 verifyFormat("SomeFunction(\n" 21383 " a,\n" 21384 " [this] {\n" 21385 " //\n" 21386 " },\n" 21387 " b);\n", 21388 Style); 21389 verifyFormat("SomeFunction(\n" 21390 " a,\n" 21391 " [this] {\n" 21392 " //\n" 21393 " },\n" 21394 " b);\n"); 21395 21396 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21397 // the BinPackArguments value (as long as the code is wide enough). 21398 verifyFormat( 21399 "something->SomeFunction(\n" 21400 " a,\n" 21401 " [this] {\n" 21402 " " 21403 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21404 " },\n" 21405 " b);\n"); 21406 21407 // A multi-line lambda is pulled up as long as the introducer fits on the 21408 // previous line and there are no further args. 21409 verifyFormat("function(1, [this, that] {\n" 21410 " //\n" 21411 "});\n"); 21412 verifyFormat("function([this, that] {\n" 21413 " //\n" 21414 "});\n"); 21415 // FIXME: this format is not ideal and we should consider forcing the first 21416 // arg onto its own line. 21417 verifyFormat("function(a, b, c, //\n" 21418 " d, [this, that] {\n" 21419 " //\n" 21420 " });\n"); 21421 21422 // Multiple lambdas are treated correctly even when there is a short arg0. 21423 verifyFormat("SomeFunction(\n" 21424 " 1,\n" 21425 " [this] {\n" 21426 " //\n" 21427 " },\n" 21428 " [this] {\n" 21429 " //\n" 21430 " },\n" 21431 " 1);\n"); 21432 21433 // More complex introducers. 21434 verifyFormat("return [i, args...] {};"); 21435 21436 // Not lambdas. 21437 verifyFormat("constexpr char hello[]{\"hello\"};"); 21438 verifyFormat("double &operator[](int i) { return 0; }\n" 21439 "int i;"); 21440 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21441 verifyFormat("int i = a[a][a]->f();"); 21442 verifyFormat("int i = (*b)[a]->f();"); 21443 21444 // Other corner cases. 21445 verifyFormat("void f() {\n" 21446 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21447 " );\n" 21448 "}"); 21449 21450 // Lambdas created through weird macros. 21451 verifyFormat("void f() {\n" 21452 " MACRO((const AA &a) { return 1; });\n" 21453 " MACRO((AA &a) { return 1; });\n" 21454 "}"); 21455 21456 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21457 " doo_dah();\n" 21458 " doo_dah();\n" 21459 " })) {\n" 21460 "}"); 21461 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21462 " doo_dah();\n" 21463 " doo_dah();\n" 21464 " })) {\n" 21465 "}"); 21466 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21467 " doo_dah();\n" 21468 " doo_dah();\n" 21469 " })) {\n" 21470 "}"); 21471 verifyFormat("auto lambda = []() {\n" 21472 " int a = 2\n" 21473 "#if A\n" 21474 " + 2\n" 21475 "#endif\n" 21476 " ;\n" 21477 "};"); 21478 21479 // Lambdas with complex multiline introducers. 21480 verifyFormat( 21481 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21482 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21483 " -> ::std::unordered_set<\n" 21484 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21485 " //\n" 21486 " });"); 21487 21488 FormatStyle DoNotMerge = getLLVMStyle(); 21489 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21490 verifyFormat("auto c = []() {\n" 21491 " return b;\n" 21492 "};", 21493 "auto c = []() { return b; };", DoNotMerge); 21494 verifyFormat("auto c = []() {\n" 21495 "};", 21496 " auto c = []() {};", DoNotMerge); 21497 21498 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21499 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21500 verifyFormat("auto c = []() {\n" 21501 " return b;\n" 21502 "};", 21503 "auto c = []() {\n" 21504 " return b;\n" 21505 " };", 21506 MergeEmptyOnly); 21507 verifyFormat("auto c = []() {};", 21508 "auto c = []() {\n" 21509 "};", 21510 MergeEmptyOnly); 21511 21512 FormatStyle MergeInline = getLLVMStyle(); 21513 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21514 verifyFormat("auto c = []() {\n" 21515 " return b;\n" 21516 "};", 21517 "auto c = []() { return b; };", MergeInline); 21518 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21519 MergeInline); 21520 verifyFormat("function([]() { return b; }, a)", 21521 "function([]() { return b; }, a)", MergeInline); 21522 verifyFormat("function(a, []() { return b; })", 21523 "function(a, []() { return b; })", MergeInline); 21524 21525 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21526 // AllowShortLambdasOnASingleLine 21527 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21528 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21529 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21530 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21531 FormatStyle::ShortLambdaStyle::SLS_None; 21532 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21533 " []()\n" 21534 " {\n" 21535 " return 17;\n" 21536 " });", 21537 LLVMWithBeforeLambdaBody); 21538 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21539 " []()\n" 21540 " {\n" 21541 " });", 21542 LLVMWithBeforeLambdaBody); 21543 verifyFormat("auto fct_SLS_None = []()\n" 21544 "{\n" 21545 " return 17;\n" 21546 "};", 21547 LLVMWithBeforeLambdaBody); 21548 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21549 " []()\n" 21550 " {\n" 21551 " return Call(\n" 21552 " []()\n" 21553 " {\n" 21554 " return 17;\n" 21555 " });\n" 21556 " });", 21557 LLVMWithBeforeLambdaBody); 21558 verifyFormat("void Fct() {\n" 21559 " return {[]()\n" 21560 " {\n" 21561 " return 17;\n" 21562 " }};\n" 21563 "}", 21564 LLVMWithBeforeLambdaBody); 21565 21566 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21567 FormatStyle::ShortLambdaStyle::SLS_Empty; 21568 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21569 " []()\n" 21570 " {\n" 21571 " return 17;\n" 21572 " });", 21573 LLVMWithBeforeLambdaBody); 21574 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21575 LLVMWithBeforeLambdaBody); 21576 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21577 "ongFunctionName_SLS_Empty(\n" 21578 " []() {});", 21579 LLVMWithBeforeLambdaBody); 21580 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21581 " []()\n" 21582 " {\n" 21583 " return 17;\n" 21584 " });", 21585 LLVMWithBeforeLambdaBody); 21586 verifyFormat("auto fct_SLS_Empty = []()\n" 21587 "{\n" 21588 " return 17;\n" 21589 "};", 21590 LLVMWithBeforeLambdaBody); 21591 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21592 " []()\n" 21593 " {\n" 21594 " return Call([]() {});\n" 21595 " });", 21596 LLVMWithBeforeLambdaBody); 21597 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21598 " []()\n" 21599 " {\n" 21600 " return Call([]() {});\n" 21601 " });", 21602 LLVMWithBeforeLambdaBody); 21603 verifyFormat( 21604 "FctWithLongLineInLambda_SLS_Empty(\n" 21605 " []()\n" 21606 " {\n" 21607 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21608 " AndShouldNotBeConsiderAsInline,\n" 21609 " LambdaBodyMustBeBreak);\n" 21610 " });", 21611 LLVMWithBeforeLambdaBody); 21612 21613 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21614 FormatStyle::ShortLambdaStyle::SLS_Inline; 21615 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21616 LLVMWithBeforeLambdaBody); 21617 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21618 LLVMWithBeforeLambdaBody); 21619 verifyFormat("auto fct_SLS_Inline = []()\n" 21620 "{\n" 21621 " return 17;\n" 21622 "};", 21623 LLVMWithBeforeLambdaBody); 21624 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21625 "17; }); });", 21626 LLVMWithBeforeLambdaBody); 21627 verifyFormat( 21628 "FctWithLongLineInLambda_SLS_Inline(\n" 21629 " []()\n" 21630 " {\n" 21631 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21632 " AndShouldNotBeConsiderAsInline,\n" 21633 " LambdaBodyMustBeBreak);\n" 21634 " });", 21635 LLVMWithBeforeLambdaBody); 21636 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21637 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21638 " []() { return 17; });", 21639 LLVMWithBeforeLambdaBody); 21640 verifyFormat( 21641 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21642 LLVMWithBeforeLambdaBody); 21643 21644 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21645 FormatStyle::ShortLambdaStyle::SLS_All; 21646 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21647 LLVMWithBeforeLambdaBody); 21648 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21649 LLVMWithBeforeLambdaBody); 21650 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21651 LLVMWithBeforeLambdaBody); 21652 verifyFormat("FctWithOneParam_SLS_All(\n" 21653 " []()\n" 21654 " {\n" 21655 " // A cool function...\n" 21656 " return 43;\n" 21657 " });", 21658 LLVMWithBeforeLambdaBody); 21659 verifyFormat("FctWithMultipleParams_SLS_All(" 21660 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21661 " []() { return 17; });", 21662 LLVMWithBeforeLambdaBody); 21663 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21664 LLVMWithBeforeLambdaBody); 21665 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21666 LLVMWithBeforeLambdaBody); 21667 verifyFormat( 21668 "FctWithLongLineInLambda_SLS_All(\n" 21669 " []()\n" 21670 " {\n" 21671 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21672 " AndShouldNotBeConsiderAsInline,\n" 21673 " LambdaBodyMustBeBreak);\n" 21674 " });", 21675 LLVMWithBeforeLambdaBody); 21676 verifyFormat( 21677 "auto fct_SLS_All = []()\n" 21678 "{\n" 21679 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21680 " AndShouldNotBeConsiderAsInline,\n" 21681 " LambdaBodyMustBeBreak);\n" 21682 "};", 21683 LLVMWithBeforeLambdaBody); 21684 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21685 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21686 LLVMWithBeforeLambdaBody); 21687 verifyFormat( 21688 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21689 " FirstParam,\n" 21690 " SecondParam,\n" 21691 " ThirdParam,\n" 21692 " FourthParam);", 21693 LLVMWithBeforeLambdaBody); 21694 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21695 " []() { return " 21696 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21697 " FirstParam,\n" 21698 " SecondParam,\n" 21699 " ThirdParam,\n" 21700 " FourthParam);", 21701 LLVMWithBeforeLambdaBody); 21702 verifyFormat( 21703 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21704 " SecondParam,\n" 21705 " ThirdParam,\n" 21706 " FourthParam,\n" 21707 " []() { return SomeValueNotSoLong; });", 21708 LLVMWithBeforeLambdaBody); 21709 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21710 " []()\n" 21711 " {\n" 21712 " return " 21713 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21714 "eConsiderAsInline;\n" 21715 " });", 21716 LLVMWithBeforeLambdaBody); 21717 verifyFormat( 21718 "FctWithLongLineInLambda_SLS_All(\n" 21719 " []()\n" 21720 " {\n" 21721 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21722 " AndShouldNotBeConsiderAsInline,\n" 21723 " LambdaBodyMustBeBreak);\n" 21724 " });", 21725 LLVMWithBeforeLambdaBody); 21726 verifyFormat("FctWithTwoParams_SLS_All(\n" 21727 " []()\n" 21728 " {\n" 21729 " // A cool function...\n" 21730 " return 43;\n" 21731 " },\n" 21732 " 87);", 21733 LLVMWithBeforeLambdaBody); 21734 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21735 LLVMWithBeforeLambdaBody); 21736 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21737 LLVMWithBeforeLambdaBody); 21738 verifyFormat( 21739 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21740 LLVMWithBeforeLambdaBody); 21741 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21742 "}); }, x);", 21743 LLVMWithBeforeLambdaBody); 21744 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21745 " []()\n" 21746 " {\n" 21747 " // A cool function...\n" 21748 " return Call([]() { return 17; });\n" 21749 " });", 21750 LLVMWithBeforeLambdaBody); 21751 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21752 " []()\n" 21753 " {\n" 21754 " return Call(\n" 21755 " []()\n" 21756 " {\n" 21757 " // A cool function...\n" 21758 " return 17;\n" 21759 " });\n" 21760 " });", 21761 LLVMWithBeforeLambdaBody); 21762 21763 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21764 FormatStyle::ShortLambdaStyle::SLS_None; 21765 21766 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21767 "{\n" 21768 " return MyAssignment::SelectFromList(this);\n" 21769 "};\n", 21770 LLVMWithBeforeLambdaBody); 21771 21772 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21773 "{\n" 21774 " return MyAssignment::SelectFromList(this);\n" 21775 "};\n", 21776 LLVMWithBeforeLambdaBody); 21777 21778 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21779 "{\n" 21780 " return MyAssignment::SelectFromList(this);\n" 21781 "};\n", 21782 LLVMWithBeforeLambdaBody); 21783 21784 verifyFormat("namespace test {\n" 21785 "class Test {\n" 21786 "public:\n" 21787 " Test() = default;\n" 21788 "};\n" 21789 "} // namespace test", 21790 LLVMWithBeforeLambdaBody); 21791 21792 // Lambdas with different indentation styles. 21793 Style = getLLVMStyleWithColumns(100); 21794 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21795 " return promise.then(\n" 21796 " [this, &someVariable, someObject = " 21797 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21798 " return someObject.startAsyncAction().then(\n" 21799 " [this, &someVariable](AsyncActionResult result) " 21800 "mutable { result.processMore(); });\n" 21801 " });\n" 21802 "}\n", 21803 format("SomeResult doSomething(SomeObject promise) {\n" 21804 " return promise.then([this, &someVariable, someObject = " 21805 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21806 " return someObject.startAsyncAction().then([this, " 21807 "&someVariable](AsyncActionResult result) mutable {\n" 21808 " result.processMore();\n" 21809 " });\n" 21810 " });\n" 21811 "}\n", 21812 Style)); 21813 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21814 verifyFormat("test() {\n" 21815 " ([]() -> {\n" 21816 " int b = 32;\n" 21817 " return 3;\n" 21818 " }).foo();\n" 21819 "}", 21820 Style); 21821 verifyFormat("test() {\n" 21822 " []() -> {\n" 21823 " int b = 32;\n" 21824 " return 3;\n" 21825 " }\n" 21826 "}", 21827 Style); 21828 verifyFormat("std::sort(v.begin(), v.end(),\n" 21829 " [](const auto &someLongArgumentName, const auto " 21830 "&someOtherLongArgumentName) {\n" 21831 " return someLongArgumentName.someMemberVariable < " 21832 "someOtherLongArgumentName.someMemberVariable;\n" 21833 "});", 21834 Style); 21835 verifyFormat("test() {\n" 21836 " (\n" 21837 " []() -> {\n" 21838 " int b = 32;\n" 21839 " return 3;\n" 21840 " },\n" 21841 " foo, bar)\n" 21842 " .foo();\n" 21843 "}", 21844 Style); 21845 verifyFormat("test() {\n" 21846 " ([]() -> {\n" 21847 " int b = 32;\n" 21848 " return 3;\n" 21849 " })\n" 21850 " .foo()\n" 21851 " .bar();\n" 21852 "}", 21853 Style); 21854 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21855 " return promise.then(\n" 21856 " [this, &someVariable, someObject = " 21857 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21858 " return someObject.startAsyncAction().then(\n" 21859 " [this, &someVariable](AsyncActionResult result) mutable { " 21860 "result.processMore(); });\n" 21861 " });\n" 21862 "}\n", 21863 format("SomeResult doSomething(SomeObject promise) {\n" 21864 " return promise.then([this, &someVariable, someObject = " 21865 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21866 " return someObject.startAsyncAction().then([this, " 21867 "&someVariable](AsyncActionResult result) mutable {\n" 21868 " result.processMore();\n" 21869 " });\n" 21870 " });\n" 21871 "}\n", 21872 Style)); 21873 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21874 " return promise.then([this, &someVariable] {\n" 21875 " return someObject.startAsyncAction().then(\n" 21876 " [this, &someVariable](AsyncActionResult result) mutable { " 21877 "result.processMore(); });\n" 21878 " });\n" 21879 "}\n", 21880 format("SomeResult doSomething(SomeObject promise) {\n" 21881 " return promise.then([this, &someVariable] {\n" 21882 " return someObject.startAsyncAction().then([this, " 21883 "&someVariable](AsyncActionResult result) mutable {\n" 21884 " result.processMore();\n" 21885 " });\n" 21886 " });\n" 21887 "}\n", 21888 Style)); 21889 Style = getGoogleStyle(); 21890 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21891 EXPECT_EQ("#define A \\\n" 21892 " [] { \\\n" 21893 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21894 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21895 " }", 21896 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21897 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21898 Style)); 21899 // TODO: The current formatting has a minor issue that's not worth fixing 21900 // right now whereby the closing brace is indented relative to the signature 21901 // instead of being aligned. This only happens with macros. 21902 } 21903 21904 TEST_F(FormatTest, LambdaWithLineComments) { 21905 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21906 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21907 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21908 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21909 FormatStyle::ShortLambdaStyle::SLS_All; 21910 21911 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21912 verifyFormat("auto k = []() // comment\n" 21913 "{ return; }", 21914 LLVMWithBeforeLambdaBody); 21915 verifyFormat("auto k = []() /* comment */ { return; }", 21916 LLVMWithBeforeLambdaBody); 21917 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21918 LLVMWithBeforeLambdaBody); 21919 verifyFormat("auto k = []() // X\n" 21920 "{ return; }", 21921 LLVMWithBeforeLambdaBody); 21922 verifyFormat( 21923 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21924 "{ return; }", 21925 LLVMWithBeforeLambdaBody); 21926 } 21927 21928 TEST_F(FormatTest, EmptyLinesInLambdas) { 21929 verifyFormat("auto lambda = []() {\n" 21930 " x(); //\n" 21931 "};", 21932 "auto lambda = []() {\n" 21933 "\n" 21934 " x(); //\n" 21935 "\n" 21936 "};"); 21937 } 21938 21939 TEST_F(FormatTest, FormatsBlocks) { 21940 FormatStyle ShortBlocks = getLLVMStyle(); 21941 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21942 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21943 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21944 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21945 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21946 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21947 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21948 21949 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21950 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21951 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21952 21953 verifyFormat("[operation setCompletionBlock:^{\n" 21954 " [self onOperationDone];\n" 21955 "}];"); 21956 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21957 " [self onOperationDone];\n" 21958 "}]};"); 21959 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21960 " f();\n" 21961 "}];"); 21962 verifyFormat("int a = [operation block:^int(int *i) {\n" 21963 " return 1;\n" 21964 "}];"); 21965 verifyFormat("[myObject doSomethingWith:arg1\n" 21966 " aaa:^int(int *a) {\n" 21967 " return 1;\n" 21968 " }\n" 21969 " bbb:f(a * bbbbbbbb)];"); 21970 21971 verifyFormat("[operation setCompletionBlock:^{\n" 21972 " [self.delegate newDataAvailable];\n" 21973 "}];", 21974 getLLVMStyleWithColumns(60)); 21975 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21976 " NSString *path = [self sessionFilePath];\n" 21977 " if (path) {\n" 21978 " // ...\n" 21979 " }\n" 21980 "});"); 21981 verifyFormat("[[SessionService sharedService]\n" 21982 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21983 " if (window) {\n" 21984 " [self windowDidLoad:window];\n" 21985 " } else {\n" 21986 " [self errorLoadingWindow];\n" 21987 " }\n" 21988 " }];"); 21989 verifyFormat("void (^largeBlock)(void) = ^{\n" 21990 " // ...\n" 21991 "};\n", 21992 getLLVMStyleWithColumns(40)); 21993 verifyFormat("[[SessionService sharedService]\n" 21994 " loadWindowWithCompletionBlock: //\n" 21995 " ^(SessionWindow *window) {\n" 21996 " if (window) {\n" 21997 " [self windowDidLoad:window];\n" 21998 " } else {\n" 21999 " [self errorLoadingWindow];\n" 22000 " }\n" 22001 " }];", 22002 getLLVMStyleWithColumns(60)); 22003 verifyFormat("[myObject doSomethingWith:arg1\n" 22004 " firstBlock:^(Foo *a) {\n" 22005 " // ...\n" 22006 " int i;\n" 22007 " }\n" 22008 " secondBlock:^(Bar *b) {\n" 22009 " // ...\n" 22010 " int i;\n" 22011 " }\n" 22012 " thirdBlock:^Foo(Bar *b) {\n" 22013 " // ...\n" 22014 " int i;\n" 22015 " }];"); 22016 verifyFormat("[myObject doSomethingWith:arg1\n" 22017 " firstBlock:-1\n" 22018 " secondBlock:^(Bar *b) {\n" 22019 " // ...\n" 22020 " int i;\n" 22021 " }];"); 22022 22023 verifyFormat("f(^{\n" 22024 " @autoreleasepool {\n" 22025 " if (a) {\n" 22026 " g();\n" 22027 " }\n" 22028 " }\n" 22029 "});"); 22030 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22031 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22032 "};"); 22033 22034 FormatStyle FourIndent = getLLVMStyle(); 22035 FourIndent.ObjCBlockIndentWidth = 4; 22036 verifyFormat("[operation setCompletionBlock:^{\n" 22037 " [self onOperationDone];\n" 22038 "}];", 22039 FourIndent); 22040 } 22041 22042 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22043 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22044 22045 verifyFormat("[[SessionService sharedService] " 22046 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22047 " if (window) {\n" 22048 " [self windowDidLoad:window];\n" 22049 " } else {\n" 22050 " [self errorLoadingWindow];\n" 22051 " }\n" 22052 "}];", 22053 ZeroColumn); 22054 EXPECT_EQ("[[SessionService sharedService]\n" 22055 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22056 " if (window) {\n" 22057 " [self windowDidLoad:window];\n" 22058 " } else {\n" 22059 " [self errorLoadingWindow];\n" 22060 " }\n" 22061 " }];", 22062 format("[[SessionService sharedService]\n" 22063 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22064 " if (window) {\n" 22065 " [self windowDidLoad:window];\n" 22066 " } else {\n" 22067 " [self errorLoadingWindow];\n" 22068 " }\n" 22069 "}];", 22070 ZeroColumn)); 22071 verifyFormat("[myObject doSomethingWith:arg1\n" 22072 " firstBlock:^(Foo *a) {\n" 22073 " // ...\n" 22074 " int i;\n" 22075 " }\n" 22076 " secondBlock:^(Bar *b) {\n" 22077 " // ...\n" 22078 " int i;\n" 22079 " }\n" 22080 " thirdBlock:^Foo(Bar *b) {\n" 22081 " // ...\n" 22082 " int i;\n" 22083 " }];", 22084 ZeroColumn); 22085 verifyFormat("f(^{\n" 22086 " @autoreleasepool {\n" 22087 " if (a) {\n" 22088 " g();\n" 22089 " }\n" 22090 " }\n" 22091 "});", 22092 ZeroColumn); 22093 verifyFormat("void (^largeBlock)(void) = ^{\n" 22094 " // ...\n" 22095 "};", 22096 ZeroColumn); 22097 22098 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22099 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22100 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22101 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22102 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22103 " int i;\n" 22104 "};", 22105 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22106 } 22107 22108 TEST_F(FormatTest, SupportsCRLF) { 22109 EXPECT_EQ("int a;\r\n" 22110 "int b;\r\n" 22111 "int c;\r\n", 22112 format("int a;\r\n" 22113 " int b;\r\n" 22114 " int c;\r\n", 22115 getLLVMStyle())); 22116 EXPECT_EQ("int a;\r\n" 22117 "int b;\r\n" 22118 "int c;\r\n", 22119 format("int a;\r\n" 22120 " int b;\n" 22121 " int c;\r\n", 22122 getLLVMStyle())); 22123 EXPECT_EQ("int a;\n" 22124 "int b;\n" 22125 "int c;\n", 22126 format("int a;\r\n" 22127 " int b;\n" 22128 " int c;\n", 22129 getLLVMStyle())); 22130 EXPECT_EQ("\"aaaaaaa \"\r\n" 22131 "\"bbbbbbb\";\r\n", 22132 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22133 EXPECT_EQ("#define A \\\r\n" 22134 " b; \\\r\n" 22135 " c; \\\r\n" 22136 " d;\r\n", 22137 format("#define A \\\r\n" 22138 " b; \\\r\n" 22139 " c; d; \r\n", 22140 getGoogleStyle())); 22141 22142 EXPECT_EQ("/*\r\n" 22143 "multi line block comments\r\n" 22144 "should not introduce\r\n" 22145 "an extra carriage return\r\n" 22146 "*/\r\n", 22147 format("/*\r\n" 22148 "multi line block comments\r\n" 22149 "should not introduce\r\n" 22150 "an extra carriage return\r\n" 22151 "*/\r\n")); 22152 EXPECT_EQ("/*\r\n" 22153 "\r\n" 22154 "*/", 22155 format("/*\r\n" 22156 " \r\r\r\n" 22157 "*/")); 22158 22159 FormatStyle style = getLLVMStyle(); 22160 22161 style.DeriveLineEnding = true; 22162 style.UseCRLF = false; 22163 EXPECT_EQ("union FooBarBazQux {\n" 22164 " int foo;\n" 22165 " int bar;\n" 22166 " int baz;\n" 22167 "};", 22168 format("union FooBarBazQux {\r\n" 22169 " int foo;\n" 22170 " int bar;\r\n" 22171 " int baz;\n" 22172 "};", 22173 style)); 22174 style.UseCRLF = true; 22175 EXPECT_EQ("union FooBarBazQux {\r\n" 22176 " int foo;\r\n" 22177 " int bar;\r\n" 22178 " int baz;\r\n" 22179 "};", 22180 format("union FooBarBazQux {\r\n" 22181 " int foo;\n" 22182 " int bar;\r\n" 22183 " int baz;\n" 22184 "};", 22185 style)); 22186 22187 style.DeriveLineEnding = false; 22188 style.UseCRLF = false; 22189 EXPECT_EQ("union FooBarBazQux {\n" 22190 " int foo;\n" 22191 " int bar;\n" 22192 " int baz;\n" 22193 " int qux;\n" 22194 "};", 22195 format("union FooBarBazQux {\r\n" 22196 " int foo;\n" 22197 " int bar;\r\n" 22198 " int baz;\n" 22199 " int qux;\r\n" 22200 "};", 22201 style)); 22202 style.UseCRLF = true; 22203 EXPECT_EQ("union FooBarBazQux {\r\n" 22204 " int foo;\r\n" 22205 " int bar;\r\n" 22206 " int baz;\r\n" 22207 " int qux;\r\n" 22208 "};", 22209 format("union FooBarBazQux {\r\n" 22210 " int foo;\n" 22211 " int bar;\r\n" 22212 " int baz;\n" 22213 " int qux;\n" 22214 "};", 22215 style)); 22216 22217 style.DeriveLineEnding = true; 22218 style.UseCRLF = false; 22219 EXPECT_EQ("union FooBarBazQux {\r\n" 22220 " int foo;\r\n" 22221 " int bar;\r\n" 22222 " int baz;\r\n" 22223 " int qux;\r\n" 22224 "};", 22225 format("union FooBarBazQux {\r\n" 22226 " int foo;\n" 22227 " int bar;\r\n" 22228 " int baz;\n" 22229 " int qux;\r\n" 22230 "};", 22231 style)); 22232 style.UseCRLF = true; 22233 EXPECT_EQ("union FooBarBazQux {\n" 22234 " int foo;\n" 22235 " int bar;\n" 22236 " int baz;\n" 22237 " int qux;\n" 22238 "};", 22239 format("union FooBarBazQux {\r\n" 22240 " int foo;\n" 22241 " int bar;\r\n" 22242 " int baz;\n" 22243 " int qux;\n" 22244 "};", 22245 style)); 22246 } 22247 22248 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22249 verifyFormat("MY_CLASS(C) {\n" 22250 " int i;\n" 22251 " int j;\n" 22252 "};"); 22253 } 22254 22255 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22256 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22257 TwoIndent.ContinuationIndentWidth = 2; 22258 22259 EXPECT_EQ("int i =\n" 22260 " longFunction(\n" 22261 " arg);", 22262 format("int i = longFunction(arg);", TwoIndent)); 22263 22264 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22265 SixIndent.ContinuationIndentWidth = 6; 22266 22267 EXPECT_EQ("int i =\n" 22268 " longFunction(\n" 22269 " arg);", 22270 format("int i = longFunction(arg);", SixIndent)); 22271 } 22272 22273 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22274 FormatStyle Style = getLLVMStyle(); 22275 verifyFormat("int Foo::getter(\n" 22276 " //\n" 22277 ") const {\n" 22278 " return foo;\n" 22279 "}", 22280 Style); 22281 verifyFormat("void Foo::setter(\n" 22282 " //\n" 22283 ") {\n" 22284 " foo = 1;\n" 22285 "}", 22286 Style); 22287 } 22288 22289 TEST_F(FormatTest, SpacesInAngles) { 22290 FormatStyle Spaces = getLLVMStyle(); 22291 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22292 22293 verifyFormat("vector< ::std::string > x1;", Spaces); 22294 verifyFormat("Foo< int, Bar > x2;", Spaces); 22295 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22296 22297 verifyFormat("static_cast< int >(arg);", Spaces); 22298 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22299 verifyFormat("f< int, float >();", Spaces); 22300 verifyFormat("template <> g() {}", Spaces); 22301 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22302 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22303 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22304 Spaces); 22305 22306 Spaces.Standard = FormatStyle::LS_Cpp03; 22307 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22308 verifyFormat("A< A< int > >();", Spaces); 22309 22310 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22311 verifyFormat("A<A<int> >();", Spaces); 22312 22313 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22314 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22315 Spaces); 22316 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22317 Spaces); 22318 22319 verifyFormat("A<A<int> >();", Spaces); 22320 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22321 verifyFormat("A< A< int > >();", Spaces); 22322 22323 Spaces.Standard = FormatStyle::LS_Cpp11; 22324 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22325 verifyFormat("A< A< int > >();", Spaces); 22326 22327 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22328 verifyFormat("vector<::std::string> x4;", Spaces); 22329 verifyFormat("vector<int> x5;", Spaces); 22330 verifyFormat("Foo<int, Bar> x6;", Spaces); 22331 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22332 22333 verifyFormat("A<A<int>>();", Spaces); 22334 22335 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22336 verifyFormat("vector<::std::string> x4;", Spaces); 22337 verifyFormat("vector< ::std::string > x4;", Spaces); 22338 verifyFormat("vector<int> x5;", Spaces); 22339 verifyFormat("vector< int > x5;", Spaces); 22340 verifyFormat("Foo<int, Bar> x6;", Spaces); 22341 verifyFormat("Foo< int, Bar > x6;", Spaces); 22342 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22343 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22344 22345 verifyFormat("A<A<int>>();", Spaces); 22346 verifyFormat("A< A< int > >();", Spaces); 22347 verifyFormat("A<A<int > >();", Spaces); 22348 verifyFormat("A< A< int>>();", Spaces); 22349 22350 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22351 verifyFormat("// clang-format off\n" 22352 "foo<<<1, 1>>>();\n" 22353 "// clang-format on\n", 22354 Spaces); 22355 verifyFormat("// clang-format off\n" 22356 "foo< < <1, 1> > >();\n" 22357 "// clang-format on\n", 22358 Spaces); 22359 } 22360 22361 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22362 FormatStyle Style = getLLVMStyle(); 22363 Style.SpaceAfterTemplateKeyword = false; 22364 verifyFormat("template<int> void foo();", Style); 22365 } 22366 22367 TEST_F(FormatTest, TripleAngleBrackets) { 22368 verifyFormat("f<<<1, 1>>>();"); 22369 verifyFormat("f<<<1, 1, 1, s>>>();"); 22370 verifyFormat("f<<<a, b, c, d>>>();"); 22371 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22372 verifyFormat("f<param><<<1, 1>>>();"); 22373 verifyFormat("f<1><<<1, 1>>>();"); 22374 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22375 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22376 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22377 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22378 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22379 } 22380 22381 TEST_F(FormatTest, MergeLessLessAtEnd) { 22382 verifyFormat("<<"); 22383 EXPECT_EQ("< < <", format("\\\n<<<")); 22384 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22385 "aaallvm::outs() <<"); 22386 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22387 "aaaallvm::outs()\n <<"); 22388 } 22389 22390 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22391 std::string code = "#if A\n" 22392 "#if B\n" 22393 "a.\n" 22394 "#endif\n" 22395 " a = 1;\n" 22396 "#else\n" 22397 "#endif\n" 22398 "#if C\n" 22399 "#else\n" 22400 "#endif\n"; 22401 EXPECT_EQ(code, format(code)); 22402 } 22403 22404 TEST_F(FormatTest, HandleConflictMarkers) { 22405 // Git/SVN conflict markers. 22406 EXPECT_EQ("int a;\n" 22407 "void f() {\n" 22408 " callme(some(parameter1,\n" 22409 "<<<<<<< text by the vcs\n" 22410 " parameter2),\n" 22411 "||||||| text by the vcs\n" 22412 " parameter2),\n" 22413 " parameter3,\n" 22414 "======= text by the vcs\n" 22415 " parameter2, parameter3),\n" 22416 ">>>>>>> text by the vcs\n" 22417 " otherparameter);\n", 22418 format("int a;\n" 22419 "void f() {\n" 22420 " callme(some(parameter1,\n" 22421 "<<<<<<< text by the vcs\n" 22422 " parameter2),\n" 22423 "||||||| text by the vcs\n" 22424 " parameter2),\n" 22425 " parameter3,\n" 22426 "======= text by the vcs\n" 22427 " parameter2,\n" 22428 " parameter3),\n" 22429 ">>>>>>> text by the vcs\n" 22430 " otherparameter);\n")); 22431 22432 // Perforce markers. 22433 EXPECT_EQ("void f() {\n" 22434 " function(\n" 22435 ">>>> text by the vcs\n" 22436 " parameter,\n" 22437 "==== text by the vcs\n" 22438 " parameter,\n" 22439 "==== text by the vcs\n" 22440 " parameter,\n" 22441 "<<<< text by the vcs\n" 22442 " parameter);\n", 22443 format("void f() {\n" 22444 " function(\n" 22445 ">>>> text by the vcs\n" 22446 " parameter,\n" 22447 "==== text by the vcs\n" 22448 " parameter,\n" 22449 "==== text by the vcs\n" 22450 " parameter,\n" 22451 "<<<< text by the vcs\n" 22452 " parameter);\n")); 22453 22454 EXPECT_EQ("<<<<<<<\n" 22455 "|||||||\n" 22456 "=======\n" 22457 ">>>>>>>", 22458 format("<<<<<<<\n" 22459 "|||||||\n" 22460 "=======\n" 22461 ">>>>>>>")); 22462 22463 EXPECT_EQ("<<<<<<<\n" 22464 "|||||||\n" 22465 "int i;\n" 22466 "=======\n" 22467 ">>>>>>>", 22468 format("<<<<<<<\n" 22469 "|||||||\n" 22470 "int i;\n" 22471 "=======\n" 22472 ">>>>>>>")); 22473 22474 // FIXME: Handle parsing of macros around conflict markers correctly: 22475 EXPECT_EQ("#define Macro \\\n" 22476 "<<<<<<<\n" 22477 "Something \\\n" 22478 "|||||||\n" 22479 "Else \\\n" 22480 "=======\n" 22481 "Other \\\n" 22482 ">>>>>>>\n" 22483 " End int i;\n", 22484 format("#define Macro \\\n" 22485 "<<<<<<<\n" 22486 " Something \\\n" 22487 "|||||||\n" 22488 " Else \\\n" 22489 "=======\n" 22490 " Other \\\n" 22491 ">>>>>>>\n" 22492 " End\n" 22493 "int i;\n")); 22494 22495 verifyFormat(R"(==== 22496 #ifdef A 22497 a 22498 #else 22499 b 22500 #endif 22501 )"); 22502 } 22503 22504 TEST_F(FormatTest, DisableRegions) { 22505 EXPECT_EQ("int i;\n" 22506 "// clang-format off\n" 22507 " int j;\n" 22508 "// clang-format on\n" 22509 "int k;", 22510 format(" int i;\n" 22511 " // clang-format off\n" 22512 " int j;\n" 22513 " // clang-format on\n" 22514 " int k;")); 22515 EXPECT_EQ("int i;\n" 22516 "/* clang-format off */\n" 22517 " int j;\n" 22518 "/* clang-format on */\n" 22519 "int k;", 22520 format(" int i;\n" 22521 " /* clang-format off */\n" 22522 " int j;\n" 22523 " /* clang-format on */\n" 22524 " int k;")); 22525 22526 // Don't reflow comments within disabled regions. 22527 EXPECT_EQ("// clang-format off\n" 22528 "// long long long long long long line\n" 22529 "/* clang-format on */\n" 22530 "/* long long long\n" 22531 " * long long long\n" 22532 " * line */\n" 22533 "int i;\n" 22534 "/* clang-format off */\n" 22535 "/* long long long long long long line */\n", 22536 format("// clang-format off\n" 22537 "// long long long long long long line\n" 22538 "/* clang-format on */\n" 22539 "/* long long long long long long line */\n" 22540 "int i;\n" 22541 "/* clang-format off */\n" 22542 "/* long long long long long long line */\n", 22543 getLLVMStyleWithColumns(20))); 22544 } 22545 22546 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22547 format("? ) ="); 22548 verifyNoCrash("#define a\\\n /**/}"); 22549 } 22550 22551 TEST_F(FormatTest, FormatsTableGenCode) { 22552 FormatStyle Style = getLLVMStyle(); 22553 Style.Language = FormatStyle::LK_TableGen; 22554 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22555 } 22556 22557 TEST_F(FormatTest, ArrayOfTemplates) { 22558 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22559 format("auto a = new unique_ptr<int > [ 10];")); 22560 22561 FormatStyle Spaces = getLLVMStyle(); 22562 Spaces.SpacesInSquareBrackets = true; 22563 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22564 format("auto a = new unique_ptr<int > [10];", Spaces)); 22565 } 22566 22567 TEST_F(FormatTest, ArrayAsTemplateType) { 22568 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22569 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22570 22571 FormatStyle Spaces = getLLVMStyle(); 22572 Spaces.SpacesInSquareBrackets = true; 22573 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22574 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22575 } 22576 22577 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22578 22579 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22580 llvm::vfs::InMemoryFileSystem FS; 22581 auto Style1 = getStyle("file", "", "Google", "", &FS); 22582 ASSERT_TRUE((bool)Style1); 22583 ASSERT_EQ(*Style1, getGoogleStyle()); 22584 } 22585 22586 TEST(FormatStyle, GetStyleOfFile) { 22587 llvm::vfs::InMemoryFileSystem FS; 22588 // Test 1: format file in the same directory. 22589 ASSERT_TRUE( 22590 FS.addFile("/a/.clang-format", 0, 22591 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22592 ASSERT_TRUE( 22593 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22594 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22595 ASSERT_TRUE((bool)Style1); 22596 ASSERT_EQ(*Style1, getLLVMStyle()); 22597 22598 // Test 2.1: fallback to default. 22599 ASSERT_TRUE( 22600 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22601 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22602 ASSERT_TRUE((bool)Style2); 22603 ASSERT_EQ(*Style2, getMozillaStyle()); 22604 22605 // Test 2.2: no format on 'none' fallback style. 22606 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22607 ASSERT_TRUE((bool)Style2); 22608 ASSERT_EQ(*Style2, getNoStyle()); 22609 22610 // Test 2.3: format if config is found with no based style while fallback is 22611 // 'none'. 22612 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22613 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22614 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22615 ASSERT_TRUE((bool)Style2); 22616 ASSERT_EQ(*Style2, getLLVMStyle()); 22617 22618 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22619 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22620 ASSERT_TRUE((bool)Style2); 22621 ASSERT_EQ(*Style2, getLLVMStyle()); 22622 22623 // Test 3: format file in parent directory. 22624 ASSERT_TRUE( 22625 FS.addFile("/c/.clang-format", 0, 22626 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22627 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22628 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22629 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22630 ASSERT_TRUE((bool)Style3); 22631 ASSERT_EQ(*Style3, getGoogleStyle()); 22632 22633 // Test 4: error on invalid fallback style 22634 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22635 ASSERT_FALSE((bool)Style4); 22636 llvm::consumeError(Style4.takeError()); 22637 22638 // Test 5: error on invalid yaml on command line 22639 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22640 ASSERT_FALSE((bool)Style5); 22641 llvm::consumeError(Style5.takeError()); 22642 22643 // Test 6: error on invalid style 22644 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22645 ASSERT_FALSE((bool)Style6); 22646 llvm::consumeError(Style6.takeError()); 22647 22648 // Test 7: found config file, error on parsing it 22649 ASSERT_TRUE( 22650 FS.addFile("/d/.clang-format", 0, 22651 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22652 "InvalidKey: InvalidValue"))); 22653 ASSERT_TRUE( 22654 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22655 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22656 ASSERT_FALSE((bool)Style7a); 22657 llvm::consumeError(Style7a.takeError()); 22658 22659 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22660 ASSERT_TRUE((bool)Style7b); 22661 22662 // Test 8: inferred per-language defaults apply. 22663 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22664 ASSERT_TRUE((bool)StyleTd); 22665 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22666 22667 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22668 // fallback style. 22669 ASSERT_TRUE(FS.addFile( 22670 "/e/sub/.clang-format", 0, 22671 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22672 "ColumnLimit: 20"))); 22673 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22674 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22675 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22676 ASSERT_TRUE(static_cast<bool>(Style9)); 22677 ASSERT_EQ(*Style9, [] { 22678 auto Style = getNoStyle(); 22679 Style.ColumnLimit = 20; 22680 return Style; 22681 }()); 22682 22683 // Test 9.1.2: propagate more than one level with no parent file. 22684 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22685 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22686 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22687 llvm::MemoryBuffer::getMemBuffer( 22688 "BasedOnStyle: InheritParentConfig\n" 22689 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22690 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22691 22692 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22693 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22694 ASSERT_TRUE(static_cast<bool>(Style9)); 22695 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22696 auto Style = getNoStyle(); 22697 Style.ColumnLimit = 20; 22698 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22699 return Style; 22700 }()); 22701 22702 // Test 9.2: with LLVM fallback style 22703 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22704 ASSERT_TRUE(static_cast<bool>(Style9)); 22705 ASSERT_EQ(*Style9, [] { 22706 auto Style = getLLVMStyle(); 22707 Style.ColumnLimit = 20; 22708 return Style; 22709 }()); 22710 22711 // Test 9.3: with a parent file 22712 ASSERT_TRUE( 22713 FS.addFile("/e/.clang-format", 0, 22714 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22715 "UseTab: Always"))); 22716 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22717 ASSERT_TRUE(static_cast<bool>(Style9)); 22718 ASSERT_EQ(*Style9, [] { 22719 auto Style = getGoogleStyle(); 22720 Style.ColumnLimit = 20; 22721 Style.UseTab = FormatStyle::UT_Always; 22722 return Style; 22723 }()); 22724 22725 // Test 9.4: propagate more than one level with a parent file. 22726 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22727 auto Style = getGoogleStyle(); 22728 Style.ColumnLimit = 20; 22729 Style.UseTab = FormatStyle::UT_Always; 22730 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22731 return Style; 22732 }(); 22733 22734 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22735 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22736 ASSERT_TRUE(static_cast<bool>(Style9)); 22737 ASSERT_EQ(*Style9, SubSubStyle); 22738 22739 // Test 9.5: use InheritParentConfig as style name 22740 Style9 = 22741 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22742 ASSERT_TRUE(static_cast<bool>(Style9)); 22743 ASSERT_EQ(*Style9, SubSubStyle); 22744 22745 // Test 9.6: use command line style with inheritance 22746 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22747 "none", "", &FS); 22748 ASSERT_TRUE(static_cast<bool>(Style9)); 22749 ASSERT_EQ(*Style9, SubSubStyle); 22750 22751 // Test 9.7: use command line style with inheritance and own config 22752 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22753 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22754 "/e/sub/code.cpp", "none", "", &FS); 22755 ASSERT_TRUE(static_cast<bool>(Style9)); 22756 ASSERT_EQ(*Style9, SubSubStyle); 22757 22758 // Test 9.8: use inheritance from a file without BasedOnStyle 22759 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22760 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22761 ASSERT_TRUE( 22762 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22763 llvm::MemoryBuffer::getMemBuffer( 22764 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22765 // Make sure we do not use the fallback style 22766 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22767 ASSERT_TRUE(static_cast<bool>(Style9)); 22768 ASSERT_EQ(*Style9, [] { 22769 auto Style = getLLVMStyle(); 22770 Style.ColumnLimit = 123; 22771 return Style; 22772 }()); 22773 22774 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22775 ASSERT_TRUE(static_cast<bool>(Style9)); 22776 ASSERT_EQ(*Style9, [] { 22777 auto Style = getLLVMStyle(); 22778 Style.ColumnLimit = 123; 22779 Style.IndentWidth = 7; 22780 return Style; 22781 }()); 22782 22783 // Test 9.9: use inheritance from a specific config file. 22784 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22785 "none", "", &FS); 22786 ASSERT_TRUE(static_cast<bool>(Style9)); 22787 ASSERT_EQ(*Style9, SubSubStyle); 22788 } 22789 22790 TEST(FormatStyle, GetStyleOfSpecificFile) { 22791 llvm::vfs::InMemoryFileSystem FS; 22792 // Specify absolute path to a format file in a parent directory. 22793 ASSERT_TRUE( 22794 FS.addFile("/e/.clang-format", 0, 22795 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22796 ASSERT_TRUE( 22797 FS.addFile("/e/explicit.clang-format", 0, 22798 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22799 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22800 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22801 auto Style = getStyle("file:/e/explicit.clang-format", 22802 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22803 ASSERT_TRUE(static_cast<bool>(Style)); 22804 ASSERT_EQ(*Style, getGoogleStyle()); 22805 22806 // Specify relative path to a format file. 22807 ASSERT_TRUE( 22808 FS.addFile("../../e/explicit.clang-format", 0, 22809 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22810 Style = getStyle("file:../../e/explicit.clang-format", 22811 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22812 ASSERT_TRUE(static_cast<bool>(Style)); 22813 ASSERT_EQ(*Style, getGoogleStyle()); 22814 22815 // Specify path to a format file that does not exist. 22816 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22817 "LLVM", "", &FS); 22818 ASSERT_FALSE(static_cast<bool>(Style)); 22819 llvm::consumeError(Style.takeError()); 22820 22821 // Specify path to a file on the filesystem. 22822 SmallString<128> FormatFilePath; 22823 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22824 "FormatFileTest", "tpl", FormatFilePath); 22825 EXPECT_FALSE((bool)ECF); 22826 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22827 EXPECT_FALSE((bool)ECF); 22828 FormatFileTest << "BasedOnStyle: Google\n"; 22829 FormatFileTest.close(); 22830 22831 SmallString<128> TestFilePath; 22832 std::error_code ECT = 22833 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22834 EXPECT_FALSE((bool)ECT); 22835 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22836 CodeFileTest << "int i;\n"; 22837 CodeFileTest.close(); 22838 22839 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22840 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22841 22842 llvm::sys::fs::remove(FormatFilePath.c_str()); 22843 llvm::sys::fs::remove(TestFilePath.c_str()); 22844 ASSERT_TRUE(static_cast<bool>(Style)); 22845 ASSERT_EQ(*Style, getGoogleStyle()); 22846 } 22847 22848 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22849 // Column limit is 20. 22850 std::string Code = "Type *a =\n" 22851 " new Type();\n" 22852 "g(iiiii, 0, jjjjj,\n" 22853 " 0, kkkkk, 0, mm);\n" 22854 "int bad = format ;"; 22855 std::string Expected = "auto a = new Type();\n" 22856 "g(iiiii, nullptr,\n" 22857 " jjjjj, nullptr,\n" 22858 " kkkkk, nullptr,\n" 22859 " mm);\n" 22860 "int bad = format ;"; 22861 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22862 tooling::Replacements Replaces = toReplacements( 22863 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22864 "auto "), 22865 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22866 "nullptr"), 22867 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22868 "nullptr"), 22869 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22870 "nullptr")}); 22871 22872 FormatStyle Style = getLLVMStyle(); 22873 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22874 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22875 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22876 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22877 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22878 EXPECT_TRUE(static_cast<bool>(Result)); 22879 EXPECT_EQ(Expected, *Result); 22880 } 22881 22882 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22883 std::string Code = "#include \"a.h\"\n" 22884 "#include \"c.h\"\n" 22885 "\n" 22886 "int main() {\n" 22887 " return 0;\n" 22888 "}"; 22889 std::string Expected = "#include \"a.h\"\n" 22890 "#include \"b.h\"\n" 22891 "#include \"c.h\"\n" 22892 "\n" 22893 "int main() {\n" 22894 " return 0;\n" 22895 "}"; 22896 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22897 tooling::Replacements Replaces = toReplacements( 22898 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22899 "#include \"b.h\"\n")}); 22900 22901 FormatStyle Style = getLLVMStyle(); 22902 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22903 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22904 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22905 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22906 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22907 EXPECT_TRUE(static_cast<bool>(Result)); 22908 EXPECT_EQ(Expected, *Result); 22909 } 22910 22911 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22912 EXPECT_EQ("using std::cin;\n" 22913 "using std::cout;", 22914 format("using std::cout;\n" 22915 "using std::cin;", 22916 getGoogleStyle())); 22917 } 22918 22919 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22920 FormatStyle Style = getLLVMStyle(); 22921 Style.Standard = FormatStyle::LS_Cpp03; 22922 // cpp03 recognize this string as identifier u8 and literal character 'a' 22923 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22924 } 22925 22926 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22927 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22928 // all modes, including C++11, C++14 and C++17 22929 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22930 } 22931 22932 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22933 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22934 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22935 } 22936 22937 TEST_F(FormatTest, StructuredBindings) { 22938 // Structured bindings is a C++17 feature. 22939 // all modes, including C++11, C++14 and C++17 22940 verifyFormat("auto [a, b] = f();"); 22941 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22942 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22943 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22944 EXPECT_EQ("auto const volatile [a, b] = f();", 22945 format("auto const volatile[a, b] = f();")); 22946 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22947 EXPECT_EQ("auto &[a, b, c] = f();", 22948 format("auto &[ a , b,c ] = f();")); 22949 EXPECT_EQ("auto &&[a, b, c] = f();", 22950 format("auto &&[ a , b,c ] = f();")); 22951 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22952 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22953 format("auto const volatile &&[a, b] = f();")); 22954 EXPECT_EQ("auto const &&[a, b] = f();", 22955 format("auto const && [a, b] = f();")); 22956 EXPECT_EQ("const auto &[a, b] = f();", 22957 format("const auto & [a, b] = f();")); 22958 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22959 format("const auto volatile &&[a, b] = f();")); 22960 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22961 format("volatile const auto &&[a, b] = f();")); 22962 EXPECT_EQ("const auto &&[a, b] = f();", 22963 format("const auto && [a, b] = f();")); 22964 22965 // Make sure we don't mistake structured bindings for lambdas. 22966 FormatStyle PointerMiddle = getLLVMStyle(); 22967 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22968 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22969 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22970 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22971 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22972 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22973 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22974 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22975 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22976 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22977 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22978 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22979 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22980 22981 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22982 format("for (const auto && [a, b] : some_range) {\n}")); 22983 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22984 format("for (const auto & [a, b] : some_range) {\n}")); 22985 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22986 format("for (const auto[a, b] : some_range) {\n}")); 22987 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22988 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22989 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22990 EXPECT_EQ("auto const &[x, y](expr);", 22991 format("auto const & [x,y] (expr);")); 22992 EXPECT_EQ("auto const &&[x, y](expr);", 22993 format("auto const && [x,y] (expr);")); 22994 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22995 EXPECT_EQ("auto const &[x, y]{expr};", 22996 format("auto const & [x,y] {expr};")); 22997 EXPECT_EQ("auto const &&[x, y]{expr};", 22998 format("auto const && [x,y] {expr};")); 22999 23000 FormatStyle Spaces = getLLVMStyle(); 23001 Spaces.SpacesInSquareBrackets = true; 23002 verifyFormat("auto [ a, b ] = f();", Spaces); 23003 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23004 verifyFormat("auto &[ a, b ] = f();", Spaces); 23005 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23006 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23007 } 23008 23009 TEST_F(FormatTest, FileAndCode) { 23010 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23011 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23012 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23013 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23014 EXPECT_EQ(FormatStyle::LK_ObjC, 23015 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23016 EXPECT_EQ( 23017 FormatStyle::LK_ObjC, 23018 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23019 EXPECT_EQ(FormatStyle::LK_ObjC, 23020 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23021 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23022 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23023 EXPECT_EQ(FormatStyle::LK_ObjC, 23024 guessLanguage("foo", "@interface Foo\n@end\n")); 23025 EXPECT_EQ(FormatStyle::LK_ObjC, 23026 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23027 EXPECT_EQ( 23028 FormatStyle::LK_ObjC, 23029 guessLanguage("foo.h", 23030 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23031 EXPECT_EQ( 23032 FormatStyle::LK_Cpp, 23033 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23034 // Only one of the two preprocessor regions has ObjC-like code. 23035 EXPECT_EQ(FormatStyle::LK_ObjC, 23036 guessLanguage("foo.h", "#if A\n" 23037 "#define B() C\n" 23038 "#else\n" 23039 "#define B() [NSString a:@\"\"]\n" 23040 "#endif\n")); 23041 } 23042 23043 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23044 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23045 EXPECT_EQ(FormatStyle::LK_ObjC, 23046 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23047 EXPECT_EQ(FormatStyle::LK_Cpp, 23048 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23049 EXPECT_EQ( 23050 FormatStyle::LK_Cpp, 23051 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23052 EXPECT_EQ(FormatStyle::LK_ObjC, 23053 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23054 EXPECT_EQ(FormatStyle::LK_Cpp, 23055 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23056 EXPECT_EQ(FormatStyle::LK_ObjC, 23057 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23058 EXPECT_EQ(FormatStyle::LK_Cpp, 23059 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23060 EXPECT_EQ(FormatStyle::LK_Cpp, 23061 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23062 EXPECT_EQ(FormatStyle::LK_ObjC, 23063 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23064 EXPECT_EQ(FormatStyle::LK_Cpp, 23065 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23066 EXPECT_EQ( 23067 FormatStyle::LK_Cpp, 23068 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23069 EXPECT_EQ( 23070 FormatStyle::LK_Cpp, 23071 guessLanguage("foo.h", 23072 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23073 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23074 } 23075 23076 TEST_F(FormatTest, GuessLanguageWithCaret) { 23077 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23078 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23079 EXPECT_EQ(FormatStyle::LK_ObjC, 23080 guessLanguage("foo.h", "int(^)(char, float);")); 23081 EXPECT_EQ(FormatStyle::LK_ObjC, 23082 guessLanguage("foo.h", "int(^foo)(char, float);")); 23083 EXPECT_EQ(FormatStyle::LK_ObjC, 23084 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23085 EXPECT_EQ(FormatStyle::LK_ObjC, 23086 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23087 EXPECT_EQ( 23088 FormatStyle::LK_ObjC, 23089 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23090 } 23091 23092 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23093 EXPECT_EQ(FormatStyle::LK_Cpp, 23094 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23095 EXPECT_EQ(FormatStyle::LK_Cpp, 23096 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23097 EXPECT_EQ(FormatStyle::LK_Cpp, 23098 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23099 } 23100 23101 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23102 // ASM symbolic names are identifiers that must be surrounded by [] without 23103 // space in between: 23104 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23105 23106 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23107 verifyFormat(R"(// 23108 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23109 )"); 23110 23111 // A list of several ASM symbolic names. 23112 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23113 23114 // ASM symbolic names in inline ASM with inputs and outputs. 23115 verifyFormat(R"(// 23116 asm("cmoveq %1, %2, %[result]" 23117 : [result] "=r"(result) 23118 : "r"(test), "r"(new), "[result]"(old)); 23119 )"); 23120 23121 // ASM symbolic names in inline ASM with no outputs. 23122 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23123 } 23124 23125 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23126 EXPECT_EQ(FormatStyle::LK_Cpp, 23127 guessLanguage("foo.h", "void f() {\n" 23128 " asm (\"mov %[e], %[d]\"\n" 23129 " : [d] \"=rm\" (d)\n" 23130 " [e] \"rm\" (*e));\n" 23131 "}")); 23132 EXPECT_EQ(FormatStyle::LK_Cpp, 23133 guessLanguage("foo.h", "void f() {\n" 23134 " _asm (\"mov %[e], %[d]\"\n" 23135 " : [d] \"=rm\" (d)\n" 23136 " [e] \"rm\" (*e));\n" 23137 "}")); 23138 EXPECT_EQ(FormatStyle::LK_Cpp, 23139 guessLanguage("foo.h", "void f() {\n" 23140 " __asm (\"mov %[e], %[d]\"\n" 23141 " : [d] \"=rm\" (d)\n" 23142 " [e] \"rm\" (*e));\n" 23143 "}")); 23144 EXPECT_EQ(FormatStyle::LK_Cpp, 23145 guessLanguage("foo.h", "void f() {\n" 23146 " __asm__ (\"mov %[e], %[d]\"\n" 23147 " : [d] \"=rm\" (d)\n" 23148 " [e] \"rm\" (*e));\n" 23149 "}")); 23150 EXPECT_EQ(FormatStyle::LK_Cpp, 23151 guessLanguage("foo.h", "void f() {\n" 23152 " asm (\"mov %[e], %[d]\"\n" 23153 " : [d] \"=rm\" (d),\n" 23154 " [e] \"rm\" (*e));\n" 23155 "}")); 23156 EXPECT_EQ(FormatStyle::LK_Cpp, 23157 guessLanguage("foo.h", "void f() {\n" 23158 " asm volatile (\"mov %[e], %[d]\"\n" 23159 " : [d] \"=rm\" (d)\n" 23160 " [e] \"rm\" (*e));\n" 23161 "}")); 23162 } 23163 23164 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23165 EXPECT_EQ(FormatStyle::LK_Cpp, 23166 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23167 EXPECT_EQ(FormatStyle::LK_ObjC, 23168 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23169 EXPECT_EQ( 23170 FormatStyle::LK_Cpp, 23171 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23172 EXPECT_EQ( 23173 FormatStyle::LK_ObjC, 23174 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23175 } 23176 23177 TEST_F(FormatTest, TypenameMacros) { 23178 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23179 23180 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23181 FormatStyle Google = getGoogleStyleWithColumns(0); 23182 Google.TypenameMacros = TypenameMacros; 23183 verifyFormat("struct foo {\n" 23184 " int bar;\n" 23185 " TAILQ_ENTRY(a) bleh;\n" 23186 "};", 23187 Google); 23188 23189 FormatStyle Macros = getLLVMStyle(); 23190 Macros.TypenameMacros = TypenameMacros; 23191 23192 verifyFormat("STACK_OF(int) a;", Macros); 23193 verifyFormat("STACK_OF(int) *a;", Macros); 23194 verifyFormat("STACK_OF(int const *) *a;", Macros); 23195 verifyFormat("STACK_OF(int *const) *a;", Macros); 23196 verifyFormat("STACK_OF(int, string) a;", Macros); 23197 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23198 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23199 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23200 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23201 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23202 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23203 23204 Macros.PointerAlignment = FormatStyle::PAS_Left; 23205 verifyFormat("STACK_OF(int)* a;", Macros); 23206 verifyFormat("STACK_OF(int*)* a;", Macros); 23207 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23208 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23209 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23210 } 23211 23212 TEST_F(FormatTest, AtomicQualifier) { 23213 // Check that we treate _Atomic as a type and not a function call 23214 FormatStyle Google = getGoogleStyleWithColumns(0); 23215 verifyFormat("struct foo {\n" 23216 " int a1;\n" 23217 " _Atomic(a) a2;\n" 23218 " _Atomic(_Atomic(int) *const) a3;\n" 23219 "};", 23220 Google); 23221 verifyFormat("_Atomic(uint64_t) a;"); 23222 verifyFormat("_Atomic(uint64_t) *a;"); 23223 verifyFormat("_Atomic(uint64_t const *) *a;"); 23224 verifyFormat("_Atomic(uint64_t *const) *a;"); 23225 verifyFormat("_Atomic(const uint64_t *) *a;"); 23226 verifyFormat("_Atomic(uint64_t) a;"); 23227 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23228 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23229 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23230 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23231 23232 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23233 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23234 FormatStyle Style = getLLVMStyle(); 23235 Style.PointerAlignment = FormatStyle::PAS_Left; 23236 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23237 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23238 verifyFormat("_Atomic(int)* a;", Style); 23239 verifyFormat("_Atomic(int*)* a;", Style); 23240 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23241 23242 Style.SpacesInCStyleCastParentheses = true; 23243 Style.SpacesInParentheses = false; 23244 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23245 Style.SpacesInCStyleCastParentheses = false; 23246 Style.SpacesInParentheses = true; 23247 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23248 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23249 } 23250 23251 TEST_F(FormatTest, AmbersandInLamda) { 23252 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23253 FormatStyle AlignStyle = getLLVMStyle(); 23254 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23255 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23256 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23257 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23258 } 23259 23260 TEST_F(FormatTest, SpacesInConditionalStatement) { 23261 FormatStyle Spaces = getLLVMStyle(); 23262 Spaces.IfMacros.clear(); 23263 Spaces.IfMacros.push_back("MYIF"); 23264 Spaces.SpacesInConditionalStatement = true; 23265 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23266 verifyFormat("if ( !a )\n return;", Spaces); 23267 verifyFormat("if ( a )\n return;", Spaces); 23268 verifyFormat("if constexpr ( a )\n return;", Spaces); 23269 verifyFormat("MYIF ( a )\n return;", Spaces); 23270 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23271 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23272 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23273 verifyFormat("while ( a )\n return;", Spaces); 23274 verifyFormat("while ( (a && b) )\n return;", Spaces); 23275 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23276 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23277 // Check that space on the left of "::" is inserted as expected at beginning 23278 // of condition. 23279 verifyFormat("while ( ::func() )\n return;", Spaces); 23280 23281 // Check impact of ControlStatementsExceptControlMacros is honored. 23282 Spaces.SpaceBeforeParens = 23283 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23284 verifyFormat("MYIF( a )\n return;", Spaces); 23285 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23286 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23287 } 23288 23289 TEST_F(FormatTest, AlternativeOperators) { 23290 // Test case for ensuring alternate operators are not 23291 // combined with their right most neighbour. 23292 verifyFormat("int a and b;"); 23293 verifyFormat("int a and_eq b;"); 23294 verifyFormat("int a bitand b;"); 23295 verifyFormat("int a bitor b;"); 23296 verifyFormat("int a compl b;"); 23297 verifyFormat("int a not b;"); 23298 verifyFormat("int a not_eq b;"); 23299 verifyFormat("int a or b;"); 23300 verifyFormat("int a xor b;"); 23301 verifyFormat("int a xor_eq b;"); 23302 verifyFormat("return this not_eq bitand other;"); 23303 verifyFormat("bool operator not_eq(const X bitand other)"); 23304 23305 verifyFormat("int a and 5;"); 23306 verifyFormat("int a and_eq 5;"); 23307 verifyFormat("int a bitand 5;"); 23308 verifyFormat("int a bitor 5;"); 23309 verifyFormat("int a compl 5;"); 23310 verifyFormat("int a not 5;"); 23311 verifyFormat("int a not_eq 5;"); 23312 verifyFormat("int a or 5;"); 23313 verifyFormat("int a xor 5;"); 23314 verifyFormat("int a xor_eq 5;"); 23315 23316 verifyFormat("int a compl(5);"); 23317 verifyFormat("int a not(5);"); 23318 23319 /* FIXME handle alternate tokens 23320 * https://en.cppreference.com/w/cpp/language/operator_alternative 23321 // alternative tokens 23322 verifyFormat("compl foo();"); // ~foo(); 23323 verifyFormat("foo() <%%>;"); // foo(); 23324 verifyFormat("void foo() <%%>;"); // void foo(){} 23325 verifyFormat("int a <:1:>;"); // int a[1];[ 23326 verifyFormat("%:define ABC abc"); // #define ABC abc 23327 verifyFormat("%:%:"); // ## 23328 */ 23329 } 23330 23331 TEST_F(FormatTest, STLWhileNotDefineChed) { 23332 verifyFormat("#if defined(while)\n" 23333 "#define while EMIT WARNING C4005\n" 23334 "#endif // while"); 23335 } 23336 23337 TEST_F(FormatTest, OperatorSpacing) { 23338 FormatStyle Style = getLLVMStyle(); 23339 Style.PointerAlignment = FormatStyle::PAS_Right; 23340 verifyFormat("Foo::operator*();", Style); 23341 verifyFormat("Foo::operator void *();", Style); 23342 verifyFormat("Foo::operator void **();", Style); 23343 verifyFormat("Foo::operator void *&();", Style); 23344 verifyFormat("Foo::operator void *&&();", Style); 23345 verifyFormat("Foo::operator void const *();", Style); 23346 verifyFormat("Foo::operator void const **();", Style); 23347 verifyFormat("Foo::operator void const *&();", Style); 23348 verifyFormat("Foo::operator void const *&&();", Style); 23349 verifyFormat("Foo::operator()(void *);", Style); 23350 verifyFormat("Foo::operator*(void *);", Style); 23351 verifyFormat("Foo::operator*();", Style); 23352 verifyFormat("Foo::operator**();", Style); 23353 verifyFormat("Foo::operator&();", Style); 23354 verifyFormat("Foo::operator<int> *();", Style); 23355 verifyFormat("Foo::operator<Foo> *();", Style); 23356 verifyFormat("Foo::operator<int> **();", Style); 23357 verifyFormat("Foo::operator<Foo> **();", Style); 23358 verifyFormat("Foo::operator<int> &();", Style); 23359 verifyFormat("Foo::operator<Foo> &();", Style); 23360 verifyFormat("Foo::operator<int> &&();", Style); 23361 verifyFormat("Foo::operator<Foo> &&();", Style); 23362 verifyFormat("Foo::operator<int> *&();", Style); 23363 verifyFormat("Foo::operator<Foo> *&();", Style); 23364 verifyFormat("Foo::operator<int> *&&();", Style); 23365 verifyFormat("Foo::operator<Foo> *&&();", Style); 23366 verifyFormat("operator*(int (*)(), class Foo);", Style); 23367 23368 verifyFormat("Foo::operator&();", Style); 23369 verifyFormat("Foo::operator void &();", Style); 23370 verifyFormat("Foo::operator void const &();", Style); 23371 verifyFormat("Foo::operator()(void &);", Style); 23372 verifyFormat("Foo::operator&(void &);", Style); 23373 verifyFormat("Foo::operator&();", Style); 23374 verifyFormat("operator&(int (&)(), class Foo);", Style); 23375 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23376 23377 verifyFormat("Foo::operator&&();", Style); 23378 verifyFormat("Foo::operator**();", Style); 23379 verifyFormat("Foo::operator void &&();", Style); 23380 verifyFormat("Foo::operator void const &&();", Style); 23381 verifyFormat("Foo::operator()(void &&);", Style); 23382 verifyFormat("Foo::operator&&(void &&);", Style); 23383 verifyFormat("Foo::operator&&();", Style); 23384 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23385 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23386 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23387 Style); 23388 verifyFormat("operator void **()", Style); 23389 verifyFormat("operator const FooRight<Object> &()", Style); 23390 verifyFormat("operator const FooRight<Object> *()", Style); 23391 verifyFormat("operator const FooRight<Object> **()", Style); 23392 verifyFormat("operator const FooRight<Object> *&()", Style); 23393 verifyFormat("operator const FooRight<Object> *&&()", Style); 23394 23395 Style.PointerAlignment = FormatStyle::PAS_Left; 23396 verifyFormat("Foo::operator*();", Style); 23397 verifyFormat("Foo::operator**();", Style); 23398 verifyFormat("Foo::operator void*();", Style); 23399 verifyFormat("Foo::operator void**();", Style); 23400 verifyFormat("Foo::operator void*&();", Style); 23401 verifyFormat("Foo::operator void*&&();", 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 const*&&();", Style); 23406 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23407 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23408 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23409 verifyFormat("Foo::operator()(void*);", Style); 23410 verifyFormat("Foo::operator*(void*);", Style); 23411 verifyFormat("Foo::operator*();", 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<Foo>*&();", Style); 23417 verifyFormat("Foo::operator<int>&();", Style); 23418 verifyFormat("Foo::operator<Foo>&();", Style); 23419 verifyFormat("Foo::operator<int>&&();", Style); 23420 verifyFormat("Foo::operator<Foo>&&();", Style); 23421 verifyFormat("Foo::operator<int>*&();", Style); 23422 verifyFormat("Foo::operator<Foo>*&();", Style); 23423 verifyFormat("operator*(int (*)(), class Foo);", Style); 23424 23425 verifyFormat("Foo::operator&();", Style); 23426 verifyFormat("Foo::operator void&();", Style); 23427 verifyFormat("Foo::operator void const&();", Style); 23428 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23429 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23430 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23431 verifyFormat("Foo::operator()(void&);", Style); 23432 verifyFormat("Foo::operator&(void&);", Style); 23433 verifyFormat("Foo::operator&();", Style); 23434 verifyFormat("operator&(int (&)(), class Foo);", Style); 23435 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23436 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23437 23438 verifyFormat("Foo::operator&&();", Style); 23439 verifyFormat("Foo::operator void&&();", Style); 23440 verifyFormat("Foo::operator void const&&();", Style); 23441 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23442 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23443 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23444 verifyFormat("Foo::operator()(void&&);", Style); 23445 verifyFormat("Foo::operator&&(void&&);", Style); 23446 verifyFormat("Foo::operator&&();", Style); 23447 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23448 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23449 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23450 Style); 23451 verifyFormat("operator void**()", Style); 23452 verifyFormat("operator const FooLeft<Object>&()", Style); 23453 verifyFormat("operator const FooLeft<Object>*()", Style); 23454 verifyFormat("operator const FooLeft<Object>**()", Style); 23455 verifyFormat("operator const FooLeft<Object>*&()", Style); 23456 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23457 23458 // PR45107 23459 verifyFormat("operator Vector<String>&();", Style); 23460 verifyFormat("operator const Vector<String>&();", Style); 23461 verifyFormat("operator foo::Bar*();", Style); 23462 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23463 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23464 Style); 23465 23466 Style.PointerAlignment = FormatStyle::PAS_Middle; 23467 verifyFormat("Foo::operator*();", Style); 23468 verifyFormat("Foo::operator void *();", Style); 23469 verifyFormat("Foo::operator()(void *);", Style); 23470 verifyFormat("Foo::operator*(void *);", Style); 23471 verifyFormat("Foo::operator*();", Style); 23472 verifyFormat("operator*(int (*)(), class Foo);", Style); 23473 23474 verifyFormat("Foo::operator&();", Style); 23475 verifyFormat("Foo::operator void &();", Style); 23476 verifyFormat("Foo::operator void const &();", Style); 23477 verifyFormat("Foo::operator()(void &);", Style); 23478 verifyFormat("Foo::operator&(void &);", Style); 23479 verifyFormat("Foo::operator&();", Style); 23480 verifyFormat("operator&(int (&)(), class Foo);", Style); 23481 23482 verifyFormat("Foo::operator&&();", Style); 23483 verifyFormat("Foo::operator void &&();", Style); 23484 verifyFormat("Foo::operator void const &&();", Style); 23485 verifyFormat("Foo::operator()(void &&);", Style); 23486 verifyFormat("Foo::operator&&(void &&);", Style); 23487 verifyFormat("Foo::operator&&();", Style); 23488 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23489 } 23490 23491 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23492 FormatStyle Style = getLLVMStyle(); 23493 // PR46157 23494 verifyFormat("foo(operator+, -42);", Style); 23495 verifyFormat("foo(operator++, -42);", Style); 23496 verifyFormat("foo(operator--, -42);", Style); 23497 verifyFormat("foo(-42, operator--);", Style); 23498 verifyFormat("foo(-42, operator, );", Style); 23499 verifyFormat("foo(operator, , -42);", Style); 23500 } 23501 23502 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23503 FormatStyle Style = getLLVMStyle(); 23504 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23505 23506 // Don't use the helpers here, since 'mess up' will change the whitespace 23507 // and these are all whitespace sensitive by definition 23508 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23509 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23510 EXPECT_EQ( 23511 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23512 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23513 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23514 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23515 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23516 " Still=Intentional);", 23517 format("FOO(String-ized&Messy+But,: :\n" 23518 " Still=Intentional);", 23519 Style)); 23520 Style.AlignConsecutiveAssignments.Enabled = true; 23521 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23522 " Still=Intentional);", 23523 format("FOO(String-ized=&Messy+But,: :\n" 23524 " Still=Intentional);", 23525 Style)); 23526 23527 Style.ColumnLimit = 21; 23528 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23529 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23530 } 23531 23532 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23533 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23534 // test its interaction with line wrapping 23535 FormatStyle Style = getLLVMStyleWithColumns(80); 23536 verifyFormat("namespace {\n" 23537 "int i;\n" 23538 "int j;\n" 23539 "} // namespace", 23540 Style); 23541 23542 verifyFormat("namespace AAA {\n" 23543 "int i;\n" 23544 "int j;\n" 23545 "} // namespace AAA", 23546 Style); 23547 23548 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23549 "int i;\n" 23550 "int j;\n" 23551 "} // namespace Averyveryveryverylongnamespace", 23552 format("namespace Averyveryveryverylongnamespace {\n" 23553 "int i;\n" 23554 "int j;\n" 23555 "}", 23556 Style)); 23557 23558 EXPECT_EQ( 23559 "namespace " 23560 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23561 " went::mad::now {\n" 23562 "int i;\n" 23563 "int j;\n" 23564 "} // namespace\n" 23565 " // " 23566 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23567 "went::mad::now", 23568 format("namespace " 23569 "would::it::save::you::a::lot::of::time::if_::i::" 23570 "just::gave::up::and_::went::mad::now {\n" 23571 "int i;\n" 23572 "int j;\n" 23573 "}", 23574 Style)); 23575 23576 // This used to duplicate the comment again and again on subsequent runs 23577 EXPECT_EQ( 23578 "namespace " 23579 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23580 " went::mad::now {\n" 23581 "int i;\n" 23582 "int j;\n" 23583 "} // namespace\n" 23584 " // " 23585 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23586 "went::mad::now", 23587 format("namespace " 23588 "would::it::save::you::a::lot::of::time::if_::i::" 23589 "just::gave::up::and_::went::mad::now {\n" 23590 "int i;\n" 23591 "int j;\n" 23592 "} // namespace\n" 23593 " // " 23594 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23595 "and_::went::mad::now", 23596 Style)); 23597 } 23598 23599 TEST_F(FormatTest, LikelyUnlikely) { 23600 FormatStyle Style = getLLVMStyle(); 23601 23602 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23603 " return 29;\n" 23604 "}", 23605 Style); 23606 23607 verifyFormat("if (argc > 5) [[likely]] {\n" 23608 " return 29;\n" 23609 "}", 23610 Style); 23611 23612 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23613 " return 29;\n" 23614 "} else [[likely]] {\n" 23615 " return 42;\n" 23616 "}\n", 23617 Style); 23618 23619 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23620 " return 29;\n" 23621 "} else if (argc > 10) [[likely]] {\n" 23622 " return 99;\n" 23623 "} else {\n" 23624 " return 42;\n" 23625 "}\n", 23626 Style); 23627 23628 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23629 " return 29;\n" 23630 "}", 23631 Style); 23632 23633 verifyFormat("if (argc > 5) [[unlikely]]\n" 23634 " return 29;\n", 23635 Style); 23636 verifyFormat("if (argc > 5) [[likely]]\n" 23637 " return 29;\n", 23638 Style); 23639 23640 Style.AttributeMacros.push_back("UNLIKELY"); 23641 Style.AttributeMacros.push_back("LIKELY"); 23642 verifyFormat("if (argc > 5) UNLIKELY\n" 23643 " return 29;\n", 23644 Style); 23645 23646 verifyFormat("if (argc > 5) UNLIKELY {\n" 23647 " return 29;\n" 23648 "}", 23649 Style); 23650 verifyFormat("if (argc > 5) UNLIKELY {\n" 23651 " return 29;\n" 23652 "} else [[likely]] {\n" 23653 " return 42;\n" 23654 "}\n", 23655 Style); 23656 verifyFormat("if (argc > 5) UNLIKELY {\n" 23657 " return 29;\n" 23658 "} else LIKELY {\n" 23659 " return 42;\n" 23660 "}\n", 23661 Style); 23662 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23663 " return 29;\n" 23664 "} else LIKELY {\n" 23665 " return 42;\n" 23666 "}\n", 23667 Style); 23668 } 23669 23670 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23671 verifyFormat("Constructor()\n" 23672 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23673 " aaaa(aaaaaaaaaaaaaaaaaa, " 23674 "aaaaaaaaaaaaaaaaaat))"); 23675 verifyFormat("Constructor()\n" 23676 " : aaaaaaaaaaaaa(aaaaaa), " 23677 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23678 23679 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23680 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23681 verifyFormat("Constructor()\n" 23682 " : aaaaaa(aaaaaa),\n" 23683 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23684 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23685 StyleWithWhitespacePenalty); 23686 verifyFormat("Constructor()\n" 23687 " : aaaaaaaaaaaaa(aaaaaa), " 23688 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23689 StyleWithWhitespacePenalty); 23690 } 23691 23692 TEST_F(FormatTest, LLVMDefaultStyle) { 23693 FormatStyle Style = getLLVMStyle(); 23694 verifyFormat("extern \"C\" {\n" 23695 "int foo();\n" 23696 "}", 23697 Style); 23698 } 23699 TEST_F(FormatTest, GNUDefaultStyle) { 23700 FormatStyle Style = getGNUStyle(); 23701 verifyFormat("extern \"C\"\n" 23702 "{\n" 23703 " int foo ();\n" 23704 "}", 23705 Style); 23706 } 23707 TEST_F(FormatTest, MozillaDefaultStyle) { 23708 FormatStyle Style = getMozillaStyle(); 23709 verifyFormat("extern \"C\"\n" 23710 "{\n" 23711 " int foo();\n" 23712 "}", 23713 Style); 23714 } 23715 TEST_F(FormatTest, GoogleDefaultStyle) { 23716 FormatStyle Style = getGoogleStyle(); 23717 verifyFormat("extern \"C\" {\n" 23718 "int foo();\n" 23719 "}", 23720 Style); 23721 } 23722 TEST_F(FormatTest, ChromiumDefaultStyle) { 23723 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23724 verifyFormat("extern \"C\" {\n" 23725 "int foo();\n" 23726 "}", 23727 Style); 23728 } 23729 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23730 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23731 verifyFormat("extern \"C\"\n" 23732 "{\n" 23733 " int foo();\n" 23734 "}", 23735 Style); 23736 } 23737 TEST_F(FormatTest, WebKitDefaultStyle) { 23738 FormatStyle Style = getWebKitStyle(); 23739 verifyFormat("extern \"C\" {\n" 23740 "int foo();\n" 23741 "}", 23742 Style); 23743 } 23744 23745 TEST_F(FormatTest, Concepts) { 23746 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23747 FormatStyle::BBCDS_Always); 23748 verifyFormat("template <typename T>\n" 23749 "concept True = true;"); 23750 23751 verifyFormat("template <typename T>\n" 23752 "concept C = ((false || foo()) && C2<T>) ||\n" 23753 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23754 getLLVMStyleWithColumns(60)); 23755 23756 verifyFormat("template <typename T>\n" 23757 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23758 "sizeof(T) <= 8;"); 23759 23760 verifyFormat("template <typename T>\n" 23761 "concept DelayedCheck = true && requires(T t) {\n" 23762 " t.bar();\n" 23763 " t.baz();\n" 23764 " } && sizeof(T) <= 8;"); 23765 23766 verifyFormat("template <typename T>\n" 23767 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23768 " t.bar();\n" 23769 " t.baz();\n" 23770 " } && sizeof(T) <= 8;"); 23771 23772 verifyFormat("template <typename T>\n" 23773 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23774 "sizeof(T) <= 8;"); 23775 23776 verifyFormat("template <typename T>\n" 23777 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23778 "&& sizeof(T) <= 8;"); 23779 23780 verifyFormat( 23781 "template <typename T>\n" 23782 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23783 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23784 23785 verifyFormat("template <typename T>\n" 23786 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23787 "&& sizeof(T) <= 8;"); 23788 23789 verifyFormat( 23790 "template <typename T>\n" 23791 "concept DelayedCheck = (bool)(0) ||\n" 23792 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23793 23794 verifyFormat("template <typename T>\n" 23795 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23796 "&& sizeof(T) <= 8;"); 23797 23798 verifyFormat("template <typename T>\n" 23799 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23800 "sizeof(T) <= 8;"); 23801 23802 verifyFormat("template <typename T>\n" 23803 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23804 " requires(T t) {\n" 23805 " t.bar();\n" 23806 " t.baz();\n" 23807 " } && sizeof(T) <= 8 && !(4 < 3);", 23808 getLLVMStyleWithColumns(60)); 23809 23810 verifyFormat("template <typename T>\n" 23811 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23812 23813 verifyFormat("template <typename T>\n" 23814 "concept C = foo();"); 23815 23816 verifyFormat("template <typename T>\n" 23817 "concept C = foo(T());"); 23818 23819 verifyFormat("template <typename T>\n" 23820 "concept C = foo(T{});"); 23821 23822 verifyFormat("template <typename T>\n" 23823 "concept Size = V<sizeof(T)>::Value > 5;"); 23824 23825 verifyFormat("template <typename T>\n" 23826 "concept True = S<T>::Value;"); 23827 23828 verifyFormat( 23829 "template <typename T>\n" 23830 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23831 " sizeof(T) <= 8;"); 23832 23833 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23834 // the lambda l square. 23835 verifyFormat("template <typename T>\n" 23836 "concept C = [] -> bool { return true; }() && requires(T t) { " 23837 "t.bar(); } &&\n" 23838 " sizeof(T) <= 8;"); 23839 23840 verifyFormat( 23841 "template <typename T>\n" 23842 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23843 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23844 23845 verifyFormat("template <typename T>\n" 23846 "concept C = decltype([]() { return std::true_type{}; " 23847 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23848 getLLVMStyleWithColumns(120)); 23849 23850 verifyFormat("template <typename T>\n" 23851 "concept C = decltype([]() -> std::true_type { return {}; " 23852 "}())::value &&\n" 23853 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23854 23855 verifyFormat("template <typename T>\n" 23856 "concept C = true;\n" 23857 "Foo Bar;"); 23858 23859 verifyFormat("template <typename T>\n" 23860 "concept Hashable = requires(T a) {\n" 23861 " { std::hash<T>{}(a) } -> " 23862 "std::convertible_to<std::size_t>;\n" 23863 " };"); 23864 23865 verifyFormat( 23866 "template <typename T>\n" 23867 "concept EqualityComparable = requires(T a, T b) {\n" 23868 " { a == b } -> std::same_as<bool>;\n" 23869 " };"); 23870 23871 verifyFormat( 23872 "template <typename T>\n" 23873 "concept EqualityComparable = requires(T a, T b) {\n" 23874 " { a == b } -> std::same_as<bool>;\n" 23875 " { a != b } -> std::same_as<bool>;\n" 23876 " };"); 23877 23878 verifyFormat("template <typename T>\n" 23879 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23880 " { a == b };\n" 23881 " { a != b };\n" 23882 " };"); 23883 23884 verifyFormat("template <typename T>\n" 23885 "concept HasSizeT = requires { typename T::size_t; };"); 23886 23887 verifyFormat("template <typename T>\n" 23888 "concept Semiregular =\n" 23889 " DefaultConstructible<T> && CopyConstructible<T> && " 23890 "CopyAssignable<T> &&\n" 23891 " requires(T a, std::size_t n) {\n" 23892 " requires Same<T *, decltype(&a)>;\n" 23893 " { a.~T() } noexcept;\n" 23894 " requires Same<T *, decltype(new T)>;\n" 23895 " requires Same<T *, decltype(new T[n])>;\n" 23896 " { delete new T; };\n" 23897 " { delete new T[n]; };\n" 23898 " };"); 23899 23900 verifyFormat("template <typename T>\n" 23901 "concept Semiregular =\n" 23902 " requires(T a, std::size_t n) {\n" 23903 " requires Same<T *, decltype(&a)>;\n" 23904 " { a.~T() } noexcept;\n" 23905 " requires Same<T *, decltype(new T)>;\n" 23906 " requires Same<T *, decltype(new T[n])>;\n" 23907 " { delete new T; };\n" 23908 " { delete new T[n]; };\n" 23909 " { new T } -> std::same_as<T *>;\n" 23910 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23911 "CopyAssignable<T>;"); 23912 23913 verifyFormat( 23914 "template <typename T>\n" 23915 "concept Semiregular =\n" 23916 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23917 " requires Same<T *, decltype(&a)>;\n" 23918 " { a.~T() } noexcept;\n" 23919 " requires Same<T *, decltype(new T)>;\n" 23920 " requires Same<T *, decltype(new " 23921 "T[n])>;\n" 23922 " { delete new T; };\n" 23923 " { delete new T[n]; };\n" 23924 " } && CopyConstructible<T> && " 23925 "CopyAssignable<T>;"); 23926 23927 verifyFormat("template <typename T>\n" 23928 "concept Two = requires(T t) {\n" 23929 " { t.foo() } -> std::same_as<Bar>;\n" 23930 " } && requires(T &&t) {\n" 23931 " { t.foo() } -> std::same_as<Bar &&>;\n" 23932 " };"); 23933 23934 verifyFormat( 23935 "template <typename T>\n" 23936 "concept C = requires(T x) {\n" 23937 " { *x } -> std::convertible_to<typename T::inner>;\n" 23938 " { x + 1 } noexcept -> std::same_as<int>;\n" 23939 " { x * 1 } -> std::convertible_to<T>;\n" 23940 " };"); 23941 23942 verifyFormat( 23943 "template <typename T, typename U = T>\n" 23944 "concept Swappable = requires(T &&t, U &&u) {\n" 23945 " swap(std::forward<T>(t), std::forward<U>(u));\n" 23946 " swap(std::forward<U>(u), std::forward<T>(t));\n" 23947 " };"); 23948 23949 verifyFormat("template <typename T, typename U>\n" 23950 "concept Common = requires(T &&t, U &&u) {\n" 23951 " typename CommonType<T, U>;\n" 23952 " { CommonType<T, U>(std::forward<T>(t)) };\n" 23953 " };"); 23954 23955 verifyFormat("template <typename T, typename U>\n" 23956 "concept Common = requires(T &&t, U &&u) {\n" 23957 " typename CommonType<T, U>;\n" 23958 " { CommonType<T, U>{std::forward<T>(t)} };\n" 23959 " };"); 23960 23961 verifyFormat( 23962 "template <typename T>\n" 23963 "concept C = requires(T t) {\n" 23964 " requires Bar<T> && Foo<T>;\n" 23965 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23966 " };"); 23967 23968 verifyFormat("template <typename T>\n" 23969 "concept HasFoo = requires(T t) {\n" 23970 " { t.foo() };\n" 23971 " t.foo();\n" 23972 " };\n" 23973 "template <typename T>\n" 23974 "concept HasBar = requires(T t) {\n" 23975 " { t.bar() };\n" 23976 " t.bar();\n" 23977 " };"); 23978 23979 verifyFormat("template <typename T>\n" 23980 "concept Large = sizeof(T) > 10;"); 23981 23982 verifyFormat("template <typename T, typename U>\n" 23983 "concept FooableWith = requires(T t, U u) {\n" 23984 " typename T::foo_type;\n" 23985 " { t.foo(u) } -> typename T::foo_type;\n" 23986 " t++;\n" 23987 " };\n" 23988 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 23989 23990 verifyFormat("template <typename T>\n" 23991 "concept Context = is_specialization_of_v<context, T>;"); 23992 23993 verifyFormat("template <typename T>\n" 23994 "concept Node = std::is_object_v<T>;"); 23995 23996 verifyFormat("template <class T>\n" 23997 "concept integral = __is_integral(T);"); 23998 23999 verifyFormat("template <class T>\n" 24000 "concept is2D = __array_extent(T, 1) == 2;"); 24001 24002 verifyFormat("template <class T>\n" 24003 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24004 24005 verifyFormat("template <class T, class T2>\n" 24006 "concept Same = __is_same_as<T, T2>;"); 24007 24008 auto Style = getLLVMStyle(); 24009 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24010 24011 verifyFormat( 24012 "template <typename T>\n" 24013 "concept C = requires(T t) {\n" 24014 " requires Bar<T> && Foo<T>;\n" 24015 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24016 " };", 24017 Style); 24018 24019 verifyFormat("template <typename T>\n" 24020 "concept HasFoo = requires(T t) {\n" 24021 " { t.foo() };\n" 24022 " t.foo();\n" 24023 " };\n" 24024 "template <typename T>\n" 24025 "concept HasBar = requires(T t) {\n" 24026 " { t.bar() };\n" 24027 " t.bar();\n" 24028 " };", 24029 Style); 24030 24031 verifyFormat("template <typename T> concept True = true;", Style); 24032 24033 verifyFormat("template <typename T>\n" 24034 "concept C = decltype([]() -> std::true_type { return {}; " 24035 "}())::value &&\n" 24036 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24037 Style); 24038 24039 verifyFormat("template <typename T>\n" 24040 "concept Semiregular =\n" 24041 " DefaultConstructible<T> && CopyConstructible<T> && " 24042 "CopyAssignable<T> &&\n" 24043 " requires(T a, std::size_t n) {\n" 24044 " requires Same<T *, decltype(&a)>;\n" 24045 " { a.~T() } noexcept;\n" 24046 " requires Same<T *, decltype(new T)>;\n" 24047 " requires Same<T *, decltype(new T[n])>;\n" 24048 " { delete new T; };\n" 24049 " { delete new T[n]; };\n" 24050 " };", 24051 Style); 24052 24053 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24054 24055 verifyFormat("template <typename T> concept C =\n" 24056 " requires(T t) {\n" 24057 " requires Bar<T> && Foo<T>;\n" 24058 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24059 " };", 24060 Style); 24061 24062 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24063 " { t.foo() };\n" 24064 " t.foo();\n" 24065 " };\n" 24066 "template <typename T> concept HasBar = requires(T t) {\n" 24067 " { t.bar() };\n" 24068 " t.bar();\n" 24069 " };", 24070 Style); 24071 24072 verifyFormat("template <typename T> concept True = true;", Style); 24073 24074 verifyFormat( 24075 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24076 " return {};\n" 24077 " }())::value &&\n" 24078 " requires(T t) { t.bar(); } && " 24079 "sizeof(T) <= 8;", 24080 Style); 24081 24082 verifyFormat("template <typename T> concept Semiregular =\n" 24083 " DefaultConstructible<T> && CopyConstructible<T> && " 24084 "CopyAssignable<T> &&\n" 24085 " requires(T a, std::size_t n) {\n" 24086 " requires Same<T *, decltype(&a)>;\n" 24087 " { a.~T() } noexcept;\n" 24088 " requires Same<T *, decltype(new T)>;\n" 24089 " requires Same<T *, decltype(new T[n])>;\n" 24090 " { delete new T; };\n" 24091 " { delete new T[n]; };\n" 24092 " };", 24093 Style); 24094 24095 // The following tests are invalid C++, we just want to make sure we don't 24096 // assert. 24097 verifyFormat("template <typename T>\n" 24098 "concept C = requires C2<T>;"); 24099 24100 verifyFormat("template <typename T>\n" 24101 "concept C = 5 + 4;"); 24102 24103 verifyFormat("template <typename T>\n" 24104 "concept C =\n" 24105 "class X;"); 24106 24107 verifyFormat("template <typename T>\n" 24108 "concept C = [] && true;"); 24109 24110 verifyFormat("template <typename T>\n" 24111 "concept C = [] && requires(T t) { typename T::size_type; };"); 24112 } 24113 24114 TEST_F(FormatTest, RequiresClausesPositions) { 24115 auto Style = getLLVMStyle(); 24116 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24117 EXPECT_EQ(Style.IndentRequiresClause, true); 24118 24119 verifyFormat("template <typename T>\n" 24120 " requires(Foo<T> && std::trait<T>)\n" 24121 "struct Bar;", 24122 Style); 24123 24124 verifyFormat("template <typename T>\n" 24125 " requires(Foo<T> && std::trait<T>)\n" 24126 "class Bar {\n" 24127 "public:\n" 24128 " Bar(T t);\n" 24129 " bool baz();\n" 24130 "};", 24131 Style); 24132 24133 verifyFormat( 24134 "template <typename T>\n" 24135 " requires requires(T &&t) {\n" 24136 " typename T::I;\n" 24137 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24138 " }\n" 24139 "Bar(T) -> Bar<typename T::I>;", 24140 Style); 24141 24142 verifyFormat("template <typename T>\n" 24143 " requires(Foo<T> && std::trait<T>)\n" 24144 "constexpr T MyGlobal;", 24145 Style); 24146 24147 verifyFormat("template <typename T>\n" 24148 " requires Foo<T> && requires(T t) {\n" 24149 " { t.baz() } -> std::same_as<bool>;\n" 24150 " requires std::same_as<T::Factor, int>;\n" 24151 " }\n" 24152 "inline int bar(T t) {\n" 24153 " return t.baz() ? T::Factor : 5;\n" 24154 "}", 24155 Style); 24156 24157 verifyFormat("template <typename T>\n" 24158 "inline int bar(T t)\n" 24159 " requires Foo<T> && requires(T t) {\n" 24160 " { t.baz() } -> std::same_as<bool>;\n" 24161 " requires std::same_as<T::Factor, int>;\n" 24162 " }\n" 24163 "{\n" 24164 " return t.baz() ? T::Factor : 5;\n" 24165 "}", 24166 Style); 24167 24168 verifyFormat("template <typename T>\n" 24169 " requires F<T>\n" 24170 "int bar(T t) {\n" 24171 " return 5;\n" 24172 "}", 24173 Style); 24174 24175 verifyFormat("template <typename T>\n" 24176 "int bar(T t)\n" 24177 " requires F<T>\n" 24178 "{\n" 24179 " return 5;\n" 24180 "}", 24181 Style); 24182 24183 verifyFormat("template <typename T>\n" 24184 "int bar(T t)\n" 24185 " requires F<T>;", 24186 Style); 24187 24188 Style.IndentRequiresClause = false; 24189 verifyFormat("template <typename T>\n" 24190 "requires F<T>\n" 24191 "int bar(T t) {\n" 24192 " return 5;\n" 24193 "}", 24194 Style); 24195 24196 verifyFormat("template <typename T>\n" 24197 "int bar(T t)\n" 24198 "requires F<T>\n" 24199 "{\n" 24200 " return 5;\n" 24201 "}", 24202 Style); 24203 24204 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24205 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24206 "template <typename T> requires Foo<T> void bar() {}\n" 24207 "template <typename T> void bar() requires Foo<T> {}\n" 24208 "template <typename T> void bar() requires Foo<T>;\n" 24209 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24210 Style); 24211 24212 auto ColumnStyle = Style; 24213 ColumnStyle.ColumnLimit = 40; 24214 verifyFormat("template <typename AAAAAAA>\n" 24215 "requires Foo<T> struct Bar {};\n" 24216 "template <typename AAAAAAA>\n" 24217 "requires Foo<T> void bar() {}\n" 24218 "template <typename AAAAAAA>\n" 24219 "void bar() requires Foo<T> {}\n" 24220 "template <typename AAAAAAA>\n" 24221 "requires Foo<T> Baz(T) -> Baz<T>;", 24222 ColumnStyle); 24223 24224 verifyFormat("template <typename T>\n" 24225 "requires Foo<AAAAAAA> struct Bar {};\n" 24226 "template <typename T>\n" 24227 "requires Foo<AAAAAAA> void bar() {}\n" 24228 "template <typename T>\n" 24229 "void bar() requires Foo<AAAAAAA> {}\n" 24230 "template <typename T>\n" 24231 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24232 ColumnStyle); 24233 24234 verifyFormat("template <typename AAAAAAA>\n" 24235 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24236 "struct Bar {};\n" 24237 "template <typename AAAAAAA>\n" 24238 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24239 "void bar() {}\n" 24240 "template <typename AAAAAAA>\n" 24241 "void bar()\n" 24242 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24243 "template <typename AAAAAAA>\n" 24244 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24245 "template <typename AAAAAAA>\n" 24246 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24247 "Bar(T) -> Bar<T>;", 24248 ColumnStyle); 24249 24250 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24251 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24252 24253 verifyFormat("template <typename T>\n" 24254 "requires Foo<T> struct Bar {};\n" 24255 "template <typename T>\n" 24256 "requires Foo<T> void bar() {}\n" 24257 "template <typename T>\n" 24258 "void bar()\n" 24259 "requires Foo<T> {}\n" 24260 "template <typename T>\n" 24261 "void bar()\n" 24262 "requires Foo<T>;\n" 24263 "template <typename T>\n" 24264 "requires Foo<T> Bar(T) -> Bar<T>;", 24265 Style); 24266 24267 verifyFormat("template <typename AAAAAAA>\n" 24268 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24269 "struct Bar {};\n" 24270 "template <typename AAAAAAA>\n" 24271 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24272 "void bar() {}\n" 24273 "template <typename AAAAAAA>\n" 24274 "void bar()\n" 24275 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24276 "template <typename AAAAAAA>\n" 24277 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24278 "template <typename AAAAAAA>\n" 24279 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24280 "Bar(T) -> Bar<T>;", 24281 ColumnStyle); 24282 24283 Style.IndentRequiresClause = true; 24284 ColumnStyle.IndentRequiresClause = true; 24285 24286 verifyFormat("template <typename T>\n" 24287 " requires Foo<T> struct Bar {};\n" 24288 "template <typename T>\n" 24289 " requires Foo<T> void bar() {}\n" 24290 "template <typename T>\n" 24291 "void bar()\n" 24292 " requires Foo<T> {}\n" 24293 "template <typename T>\n" 24294 " requires Foo<T> Bar(T) -> Bar<T>;", 24295 Style); 24296 24297 verifyFormat("template <typename AAAAAAA>\n" 24298 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24299 "struct Bar {};\n" 24300 "template <typename AAAAAAA>\n" 24301 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24302 "void bar() {}\n" 24303 "template <typename AAAAAAA>\n" 24304 "void bar()\n" 24305 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24306 "template <typename AAAAAAA>\n" 24307 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24308 "template <typename AAAAAAA>\n" 24309 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24310 "Bar(T) -> Bar<T>;", 24311 ColumnStyle); 24312 24313 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24314 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24315 24316 verifyFormat("template <typename T> requires Foo<T>\n" 24317 "struct Bar {};\n" 24318 "template <typename T> requires Foo<T>\n" 24319 "void bar() {}\n" 24320 "template <typename T>\n" 24321 "void bar() requires Foo<T>\n" 24322 "{}\n" 24323 "template <typename T> void bar() requires Foo<T>;\n" 24324 "template <typename T> requires Foo<T>\n" 24325 "Bar(T) -> Bar<T>;", 24326 Style); 24327 24328 verifyFormat("template <typename AAAAAAA>\n" 24329 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24330 "struct Bar {};\n" 24331 "template <typename AAAAAAA>\n" 24332 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24333 "void bar() {}\n" 24334 "template <typename AAAAAAA>\n" 24335 "void bar()\n" 24336 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24337 "{}\n" 24338 "template <typename AAAAAAA>\n" 24339 "requires Foo<AAAAAAAA>\n" 24340 "Bar(T) -> Bar<T>;\n" 24341 "template <typename AAAAAAA>\n" 24342 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24343 "Bar(T) -> Bar<T>;", 24344 ColumnStyle); 24345 } 24346 24347 TEST_F(FormatTest, RequiresClauses) { 24348 verifyFormat("struct [[nodiscard]] zero_t {\n" 24349 " template <class T>\n" 24350 " requires requires { number_zero_v<T>; }\n" 24351 " [[nodiscard]] constexpr operator T() const {\n" 24352 " return number_zero_v<T>;\n" 24353 " }\n" 24354 "};"); 24355 24356 auto Style = getLLVMStyle(); 24357 24358 verifyFormat( 24359 "template <typename T>\n" 24360 " requires is_default_constructible_v<hash<T>> and\n" 24361 " is_copy_constructible_v<hash<T>> and\n" 24362 " is_move_constructible_v<hash<T>> and\n" 24363 " is_copy_assignable_v<hash<T>> and " 24364 "is_move_assignable_v<hash<T>> and\n" 24365 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24366 " is_callable_v<hash<T>(T)> and\n" 24367 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24368 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24369 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24370 "struct S {};", 24371 Style); 24372 24373 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24374 verifyFormat( 24375 "template <typename T>\n" 24376 " requires is_default_constructible_v<hash<T>>\n" 24377 " and is_copy_constructible_v<hash<T>>\n" 24378 " and is_move_constructible_v<hash<T>>\n" 24379 " and is_copy_assignable_v<hash<T>> and " 24380 "is_move_assignable_v<hash<T>>\n" 24381 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24382 " and is_callable_v<hash<T>(T)>\n" 24383 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24384 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24385 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24386 "&>()))>\n" 24387 "struct S {};", 24388 Style); 24389 24390 // Not a clause, but we once hit an assert. 24391 verifyFormat("#if 0\n" 24392 "#else\n" 24393 "foo();\n" 24394 "#endif\n" 24395 "bar(requires);"); 24396 } 24397 24398 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24399 FormatStyle Style = getLLVMStyle(); 24400 StringRef Source = "void Foo::slot() {\n" 24401 " unsigned char MyChar = 'x';\n" 24402 " emit signal(MyChar);\n" 24403 " Q_EMIT signal(MyChar);\n" 24404 "}"; 24405 24406 EXPECT_EQ(Source, format(Source, Style)); 24407 24408 Style.AlignConsecutiveDeclarations.Enabled = true; 24409 EXPECT_EQ("void Foo::slot() {\n" 24410 " unsigned char MyChar = 'x';\n" 24411 " emit signal(MyChar);\n" 24412 " Q_EMIT signal(MyChar);\n" 24413 "}", 24414 format(Source, Style)); 24415 24416 Style.StatementAttributeLikeMacros.push_back("emit"); 24417 EXPECT_EQ(Source, format(Source, Style)); 24418 24419 Style.StatementAttributeLikeMacros = {}; 24420 EXPECT_EQ("void Foo::slot() {\n" 24421 " unsigned char MyChar = 'x';\n" 24422 " emit signal(MyChar);\n" 24423 " Q_EMIT signal(MyChar);\n" 24424 "}", 24425 format(Source, Style)); 24426 } 24427 24428 TEST_F(FormatTest, IndentAccessModifiers) { 24429 FormatStyle Style = getLLVMStyle(); 24430 Style.IndentAccessModifiers = true; 24431 // Members are *two* levels below the record; 24432 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24433 verifyFormat("class C {\n" 24434 " int i;\n" 24435 "};\n", 24436 Style); 24437 verifyFormat("union C {\n" 24438 " int i;\n" 24439 " unsigned u;\n" 24440 "};\n", 24441 Style); 24442 // Access modifiers should be indented one level below the record. 24443 verifyFormat("class C {\n" 24444 " public:\n" 24445 " int i;\n" 24446 "};\n", 24447 Style); 24448 verifyFormat("struct S {\n" 24449 " private:\n" 24450 " class C {\n" 24451 " int j;\n" 24452 "\n" 24453 " public:\n" 24454 " C();\n" 24455 " };\n" 24456 "\n" 24457 " public:\n" 24458 " int i;\n" 24459 "};\n", 24460 Style); 24461 // Enumerations are not records and should be unaffected. 24462 Style.AllowShortEnumsOnASingleLine = false; 24463 verifyFormat("enum class E {\n" 24464 " A,\n" 24465 " B\n" 24466 "};\n", 24467 Style); 24468 // Test with a different indentation width; 24469 // also proves that the result is Style.AccessModifierOffset agnostic. 24470 Style.IndentWidth = 3; 24471 verifyFormat("class C {\n" 24472 " public:\n" 24473 " int i;\n" 24474 "};\n", 24475 Style); 24476 } 24477 24478 TEST_F(FormatTest, LimitlessStringsAndComments) { 24479 auto Style = getLLVMStyleWithColumns(0); 24480 constexpr StringRef Code = 24481 "/**\n" 24482 " * This is a multiline comment with quite some long lines, at least for " 24483 "the LLVM Style.\n" 24484 " * We will redo this with strings and line comments. Just to check if " 24485 "everything is working.\n" 24486 " */\n" 24487 "bool foo() {\n" 24488 " /* Single line multi line comment. */\n" 24489 " const std::string String = \"This is a multiline string with quite " 24490 "some long lines, at least for the LLVM Style.\"\n" 24491 " \"We already did it with multi line " 24492 "comments, and we will do it with line comments. Just to check if " 24493 "everything is working.\";\n" 24494 " // This is a line comment (block) with quite some long lines, at " 24495 "least for the LLVM Style.\n" 24496 " // We already did this with multi line comments and strings. Just to " 24497 "check if everything is working.\n" 24498 " const std::string SmallString = \"Hello World\";\n" 24499 " // Small line comment\n" 24500 " return String.size() > SmallString.size();\n" 24501 "}"; 24502 EXPECT_EQ(Code, format(Code, Style)); 24503 } 24504 24505 TEST_F(FormatTest, FormatDecayCopy) { 24506 // error cases from unit tests 24507 verifyFormat("foo(auto())"); 24508 verifyFormat("foo(auto{})"); 24509 verifyFormat("foo(auto({}))"); 24510 verifyFormat("foo(auto{{}})"); 24511 24512 verifyFormat("foo(auto(1))"); 24513 verifyFormat("foo(auto{1})"); 24514 verifyFormat("foo(new auto(1))"); 24515 verifyFormat("foo(new auto{1})"); 24516 verifyFormat("decltype(auto(1)) x;"); 24517 verifyFormat("decltype(auto{1}) x;"); 24518 verifyFormat("auto(x);"); 24519 verifyFormat("auto{x};"); 24520 verifyFormat("new auto{x};"); 24521 verifyFormat("auto{x} = y;"); 24522 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24523 // the user's own fault 24524 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24525 // clearly the user's own fault 24526 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24527 } 24528 24529 TEST_F(FormatTest, Cpp20ModulesSupport) { 24530 FormatStyle Style = getLLVMStyle(); 24531 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24532 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24533 24534 verifyFormat("export import foo;", Style); 24535 verifyFormat("export import foo:bar;", Style); 24536 verifyFormat("export import foo.bar;", Style); 24537 verifyFormat("export import foo.bar:baz;", Style); 24538 verifyFormat("export import :bar;", Style); 24539 verifyFormat("export module foo:bar;", Style); 24540 verifyFormat("export module foo;", Style); 24541 verifyFormat("export module foo.bar;", Style); 24542 verifyFormat("export module foo.bar:baz;", Style); 24543 verifyFormat("export import <string_view>;", Style); 24544 24545 verifyFormat("export type_name var;", Style); 24546 verifyFormat("template <class T> export using A = B<T>;", Style); 24547 verifyFormat("export using A = B;", Style); 24548 verifyFormat("export int func() {\n" 24549 " foo();\n" 24550 "}", 24551 Style); 24552 verifyFormat("export struct {\n" 24553 " int foo;\n" 24554 "};", 24555 Style); 24556 verifyFormat("export {\n" 24557 " int foo;\n" 24558 "};", 24559 Style); 24560 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24561 24562 verifyFormat("import bar;", Style); 24563 verifyFormat("import foo.bar;", Style); 24564 verifyFormat("import foo:bar;", Style); 24565 verifyFormat("import :bar;", Style); 24566 verifyFormat("import <ctime>;", Style); 24567 verifyFormat("import \"header\";", Style); 24568 24569 verifyFormat("module foo;", Style); 24570 verifyFormat("module foo:bar;", Style); 24571 verifyFormat("module foo.bar;", Style); 24572 verifyFormat("module;", Style); 24573 24574 verifyFormat("export namespace hi {\n" 24575 "const char *sayhi();\n" 24576 "}", 24577 Style); 24578 24579 verifyFormat("module :private;", Style); 24580 verifyFormat("import <foo/bar.h>;", Style); 24581 verifyFormat("import foo...bar;", Style); 24582 verifyFormat("import ..........;", Style); 24583 verifyFormat("module foo:private;", Style); 24584 verifyFormat("import a", Style); 24585 verifyFormat("module a", Style); 24586 verifyFormat("export import a", Style); 24587 verifyFormat("export module a", Style); 24588 24589 verifyFormat("import", Style); 24590 verifyFormat("module", Style); 24591 verifyFormat("export", Style); 24592 } 24593 24594 TEST_F(FormatTest, CoroutineForCoawait) { 24595 FormatStyle Style = getLLVMStyle(); 24596 verifyFormat("for co_await (auto x : range())\n ;"); 24597 verifyFormat("for (auto i : arr) {\n" 24598 "}", 24599 Style); 24600 verifyFormat("for co_await (auto i : arr) {\n" 24601 "}", 24602 Style); 24603 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24604 "}", 24605 Style); 24606 } 24607 24608 TEST_F(FormatTest, CoroutineCoAwait) { 24609 verifyFormat("int x = co_await foo();"); 24610 verifyFormat("int x = (co_await foo());"); 24611 verifyFormat("co_await (42);"); 24612 verifyFormat("void operator co_await(int);"); 24613 verifyFormat("void operator co_await(a);"); 24614 verifyFormat("co_await a;"); 24615 verifyFormat("co_await missing_await_resume{};"); 24616 verifyFormat("co_await a; // comment"); 24617 verifyFormat("void test0() { co_await a; }"); 24618 verifyFormat("co_await co_await co_await foo();"); 24619 verifyFormat("co_await foo().bar();"); 24620 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24621 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24622 "foo(); }(x, y);"); 24623 24624 FormatStyle Style = getLLVMStyleWithColumns(40); 24625 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24626 " co_return co_await foo();\n" 24627 "}(x, y);", 24628 Style); 24629 verifyFormat("co_await;"); 24630 } 24631 24632 TEST_F(FormatTest, CoroutineCoYield) { 24633 verifyFormat("int x = co_yield foo();"); 24634 verifyFormat("int x = (co_yield foo());"); 24635 verifyFormat("co_yield (42);"); 24636 verifyFormat("co_yield {42};"); 24637 verifyFormat("co_yield 42;"); 24638 verifyFormat("co_yield n++;"); 24639 verifyFormat("co_yield ++n;"); 24640 verifyFormat("co_yield;"); 24641 } 24642 24643 TEST_F(FormatTest, CoroutineCoReturn) { 24644 verifyFormat("co_return (42);"); 24645 verifyFormat("co_return;"); 24646 verifyFormat("co_return {};"); 24647 verifyFormat("co_return x;"); 24648 verifyFormat("co_return co_await foo();"); 24649 verifyFormat("co_return co_yield foo();"); 24650 } 24651 24652 TEST_F(FormatTest, EmptyShortBlock) { 24653 auto Style = getLLVMStyle(); 24654 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24655 24656 verifyFormat("try {\n" 24657 " doA();\n" 24658 "} catch (Exception &e) {\n" 24659 " e.printStackTrace();\n" 24660 "}\n", 24661 Style); 24662 24663 verifyFormat("try {\n" 24664 " doA();\n" 24665 "} catch (Exception &e) {}\n", 24666 Style); 24667 } 24668 24669 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24670 auto Style = getLLVMStyle(); 24671 24672 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24673 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24674 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24675 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24676 24677 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24678 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24679 } 24680 24681 TEST_F(FormatTest, InsertBraces) { 24682 FormatStyle Style = getLLVMStyle(); 24683 Style.InsertBraces = true; 24684 24685 verifyFormat("// clang-format off\n" 24686 "// comment\n" 24687 "if (a) f();\n" 24688 "// clang-format on\n" 24689 "if (b) {\n" 24690 " g();\n" 24691 "}", 24692 "// clang-format off\n" 24693 "// comment\n" 24694 "if (a) f();\n" 24695 "// clang-format on\n" 24696 "if (b) g();", 24697 Style); 24698 24699 verifyFormat("if (a) {\n" 24700 " switch (b) {\n" 24701 " case 1:\n" 24702 " c = 0;\n" 24703 " break;\n" 24704 " default:\n" 24705 " c = 1;\n" 24706 " }\n" 24707 "}", 24708 "if (a)\n" 24709 " switch (b) {\n" 24710 " case 1:\n" 24711 " c = 0;\n" 24712 " break;\n" 24713 " default:\n" 24714 " c = 1;\n" 24715 " }", 24716 Style); 24717 24718 verifyFormat("for (auto node : nodes) {\n" 24719 " if (node) {\n" 24720 " break;\n" 24721 " }\n" 24722 "}", 24723 "for (auto node : nodes)\n" 24724 " if (node)\n" 24725 " break;", 24726 Style); 24727 24728 verifyFormat("for (auto node : nodes) {\n" 24729 " if (node)\n" 24730 "}", 24731 "for (auto node : nodes)\n" 24732 " if (node)", 24733 Style); 24734 24735 verifyFormat("do {\n" 24736 " --a;\n" 24737 "} while (a);", 24738 "do\n" 24739 " --a;\n" 24740 "while (a);", 24741 Style); 24742 24743 verifyFormat("if (i) {\n" 24744 " ++i;\n" 24745 "} else {\n" 24746 " --i;\n" 24747 "}", 24748 "if (i)\n" 24749 " ++i;\n" 24750 "else {\n" 24751 " --i;\n" 24752 "}", 24753 Style); 24754 24755 verifyFormat("void f() {\n" 24756 " while (j--) {\n" 24757 " while (i) {\n" 24758 " --i;\n" 24759 " }\n" 24760 " }\n" 24761 "}", 24762 "void f() {\n" 24763 " while (j--)\n" 24764 " while (i)\n" 24765 " --i;\n" 24766 "}", 24767 Style); 24768 24769 verifyFormat("f({\n" 24770 " if (a) {\n" 24771 " g();\n" 24772 " }\n" 24773 "});", 24774 "f({\n" 24775 " if (a)\n" 24776 " g();\n" 24777 "});", 24778 Style); 24779 24780 verifyFormat("if (a) {\n" 24781 " f();\n" 24782 "} else if (b) {\n" 24783 " g();\n" 24784 "} else {\n" 24785 " h();\n" 24786 "}", 24787 "if (a)\n" 24788 " f();\n" 24789 "else if (b)\n" 24790 " g();\n" 24791 "else\n" 24792 " h();", 24793 Style); 24794 24795 verifyFormat("if (a) {\n" 24796 " f();\n" 24797 "}\n" 24798 "// comment\n" 24799 "/* comment */", 24800 "if (a)\n" 24801 " f();\n" 24802 "// comment\n" 24803 "/* comment */", 24804 Style); 24805 24806 verifyFormat("if (a) {\n" 24807 " // foo\n" 24808 " // bar\n" 24809 " f();\n" 24810 "}", 24811 "if (a)\n" 24812 " // foo\n" 24813 " // bar\n" 24814 " f();", 24815 Style); 24816 24817 verifyFormat("if (a) { // comment\n" 24818 " // comment\n" 24819 " f();\n" 24820 "}", 24821 "if (a) // comment\n" 24822 " // comment\n" 24823 " f();", 24824 Style); 24825 24826 verifyFormat("if (a) {\n" 24827 " f(); // comment\n" 24828 "}", 24829 "if (a)\n" 24830 " f(); // comment", 24831 Style); 24832 24833 verifyFormat("if (a) {\n" 24834 " f();\n" 24835 "}\n" 24836 "#undef A\n" 24837 "#undef B", 24838 "if (a)\n" 24839 " f();\n" 24840 "#undef A\n" 24841 "#undef B", 24842 Style); 24843 24844 verifyFormat("if (a)\n" 24845 "#ifdef A\n" 24846 " f();\n" 24847 "#else\n" 24848 " g();\n" 24849 "#endif", 24850 Style); 24851 24852 verifyFormat("#if 0\n" 24853 "#elif 1\n" 24854 "#endif\n" 24855 "void f() {\n" 24856 " if (a) {\n" 24857 " g();\n" 24858 " }\n" 24859 "}", 24860 "#if 0\n" 24861 "#elif 1\n" 24862 "#endif\n" 24863 "void f() {\n" 24864 " if (a) g();\n" 24865 "}", 24866 Style); 24867 24868 Style.ColumnLimit = 15; 24869 24870 verifyFormat("#define A \\\n" 24871 " if (a) \\\n" 24872 " f();", 24873 Style); 24874 24875 verifyFormat("if (a + b >\n" 24876 " c) {\n" 24877 " f();\n" 24878 "}", 24879 "if (a + b > c)\n" 24880 " f();", 24881 Style); 24882 } 24883 24884 TEST_F(FormatTest, RemoveBraces) { 24885 FormatStyle Style = getLLVMStyle(); 24886 Style.RemoveBracesLLVM = true; 24887 24888 // The following eight test cases are fully-braced versions of the examples at 24889 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24890 // statement-bodies-of-if-else-loop-statements". 24891 24892 // 1. Omit the braces, since the body is simple and clearly associated with 24893 // the if. 24894 verifyFormat("if (isa<FunctionDecl>(D))\n" 24895 " handleFunctionDecl(D);\n" 24896 "else if (isa<VarDecl>(D))\n" 24897 " handleVarDecl(D);", 24898 "if (isa<FunctionDecl>(D)) {\n" 24899 " handleFunctionDecl(D);\n" 24900 "} else if (isa<VarDecl>(D)) {\n" 24901 " handleVarDecl(D);\n" 24902 "}", 24903 Style); 24904 24905 // 2. Here we document the condition itself and not the body. 24906 verifyFormat("if (isa<VarDecl>(D)) {\n" 24907 " // It is necessary that we explain the situation with this\n" 24908 " // surprisingly long comment, so it would be unclear\n" 24909 " // without the braces whether the following statement is in\n" 24910 " // the scope of the `if`.\n" 24911 " // Because the condition is documented, we can't really\n" 24912 " // hoist this comment that applies to the body above the\n" 24913 " // if.\n" 24914 " handleOtherDecl(D);\n" 24915 "}", 24916 Style); 24917 24918 // 3. Use braces on the outer `if` to avoid a potential dangling else 24919 // situation. 24920 verifyFormat("if (isa<VarDecl>(D)) {\n" 24921 " for (auto *A : D.attrs())\n" 24922 " if (shouldProcessAttr(A))\n" 24923 " handleAttr(A);\n" 24924 "}", 24925 "if (isa<VarDecl>(D)) {\n" 24926 " for (auto *A : D.attrs()) {\n" 24927 " if (shouldProcessAttr(A)) {\n" 24928 " handleAttr(A);\n" 24929 " }\n" 24930 " }\n" 24931 "}", 24932 Style); 24933 24934 // 4. Use braces for the `if` block to keep it uniform with the else block. 24935 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24936 " handleFunctionDecl(D);\n" 24937 "} else {\n" 24938 " // In this else case, it is necessary that we explain the\n" 24939 " // situation with this surprisingly long comment, so it\n" 24940 " // would be unclear without the braces whether the\n" 24941 " // following statement is in the scope of the `if`.\n" 24942 " handleOtherDecl(D);\n" 24943 "}", 24944 Style); 24945 24946 // 5. This should also omit braces. The `for` loop contains only a single 24947 // statement, so it shouldn't have braces. The `if` also only contains a 24948 // single simple statement (the for loop), so it also should omit braces. 24949 verifyFormat("if (isa<FunctionDecl>(D))\n" 24950 " for (auto *A : D.attrs())\n" 24951 " handleAttr(A);", 24952 "if (isa<FunctionDecl>(D)) {\n" 24953 " for (auto *A : D.attrs()) {\n" 24954 " handleAttr(A);\n" 24955 " }\n" 24956 "}", 24957 Style); 24958 24959 // 6. Use braces for the outer `if` since the nested `for` is braced. 24960 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24961 " for (auto *A : D.attrs()) {\n" 24962 " // In this for loop body, it is necessary that we explain\n" 24963 " // the situation with this surprisingly long comment,\n" 24964 " // forcing braces on the `for` block.\n" 24965 " handleAttr(A);\n" 24966 " }\n" 24967 "}", 24968 Style); 24969 24970 // 7. Use braces on the outer block because there are more than two levels of 24971 // nesting. 24972 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24973 " for (auto *A : D.attrs())\n" 24974 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 24975 " handleAttrOnDecl(D, A, i);\n" 24976 "}", 24977 "if (isa<FunctionDecl>(D)) {\n" 24978 " for (auto *A : D.attrs()) {\n" 24979 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 24980 " handleAttrOnDecl(D, A, i);\n" 24981 " }\n" 24982 " }\n" 24983 "}", 24984 Style); 24985 24986 // 8. Use braces on the outer block because of a nested `if`, otherwise the 24987 // compiler would warn: `add explicit braces to avoid dangling else` 24988 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24989 " if (shouldProcess(D))\n" 24990 " handleVarDecl(D);\n" 24991 " else\n" 24992 " markAsIgnored(D);\n" 24993 "}", 24994 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24995 " if (shouldProcess(D)) {\n" 24996 " handleVarDecl(D);\n" 24997 " } else {\n" 24998 " markAsIgnored(D);\n" 24999 " }\n" 25000 "}", 25001 Style); 25002 25003 verifyFormat("// clang-format off\n" 25004 "// comment\n" 25005 "while (i > 0) { --i; }\n" 25006 "// clang-format on\n" 25007 "while (j < 0)\n" 25008 " ++j;", 25009 "// clang-format off\n" 25010 "// comment\n" 25011 "while (i > 0) { --i; }\n" 25012 "// clang-format on\n" 25013 "while (j < 0) { ++j; }", 25014 Style); 25015 25016 verifyFormat("if (a)\n" 25017 " b; // comment\n" 25018 "else if (c)\n" 25019 " d; /* comment */\n" 25020 "else\n" 25021 " e;", 25022 "if (a) {\n" 25023 " b; // comment\n" 25024 "} else if (c) {\n" 25025 " d; /* comment */\n" 25026 "} else {\n" 25027 " e;\n" 25028 "}", 25029 Style); 25030 25031 verifyFormat("if (a) {\n" 25032 " b;\n" 25033 " c;\n" 25034 "} else if (d) {\n" 25035 " e;\n" 25036 "}", 25037 Style); 25038 25039 verifyFormat("if (a) {\n" 25040 "#undef NDEBUG\n" 25041 " b;\n" 25042 "} else {\n" 25043 " c;\n" 25044 "}", 25045 Style); 25046 25047 verifyFormat("if (a) {\n" 25048 " // comment\n" 25049 "} else if (b) {\n" 25050 " c;\n" 25051 "}", 25052 Style); 25053 25054 verifyFormat("if (a) {\n" 25055 " b;\n" 25056 "} else {\n" 25057 " { c; }\n" 25058 "}", 25059 Style); 25060 25061 verifyFormat("if (a) {\n" 25062 " if (b) // comment\n" 25063 " c;\n" 25064 "} else if (d) {\n" 25065 " e;\n" 25066 "}", 25067 "if (a) {\n" 25068 " if (b) { // comment\n" 25069 " c;\n" 25070 " }\n" 25071 "} else if (d) {\n" 25072 " e;\n" 25073 "}", 25074 Style); 25075 25076 verifyFormat("if (a) {\n" 25077 " if (b) {\n" 25078 " c;\n" 25079 " // comment\n" 25080 " } else if (d) {\n" 25081 " e;\n" 25082 " }\n" 25083 "}", 25084 Style); 25085 25086 verifyFormat("if (a) {\n" 25087 " if (b)\n" 25088 " c;\n" 25089 "}", 25090 "if (a) {\n" 25091 " if (b) {\n" 25092 " c;\n" 25093 " }\n" 25094 "}", 25095 Style); 25096 25097 verifyFormat("if (a)\n" 25098 " if (b)\n" 25099 " c;\n" 25100 " else\n" 25101 " d;\n" 25102 "else\n" 25103 " e;", 25104 "if (a) {\n" 25105 " if (b) {\n" 25106 " c;\n" 25107 " } else {\n" 25108 " d;\n" 25109 " }\n" 25110 "} else {\n" 25111 " e;\n" 25112 "}", 25113 Style); 25114 25115 verifyFormat("if (a) {\n" 25116 " // comment\n" 25117 " if (b)\n" 25118 " c;\n" 25119 " else if (d)\n" 25120 " e;\n" 25121 "} else {\n" 25122 " g;\n" 25123 "}", 25124 "if (a) {\n" 25125 " // comment\n" 25126 " if (b) {\n" 25127 " c;\n" 25128 " } else if (d) {\n" 25129 " e;\n" 25130 " }\n" 25131 "} else {\n" 25132 " g;\n" 25133 "}", 25134 Style); 25135 25136 verifyFormat("if (a)\n" 25137 " b;\n" 25138 "else if (c)\n" 25139 " d;\n" 25140 "else\n" 25141 " e;", 25142 "if (a) {\n" 25143 " b;\n" 25144 "} else {\n" 25145 " if (c) {\n" 25146 " d;\n" 25147 " } else {\n" 25148 " e;\n" 25149 " }\n" 25150 "}", 25151 Style); 25152 25153 verifyFormat("if (a) {\n" 25154 " if (b)\n" 25155 " c;\n" 25156 " else if (d)\n" 25157 " e;\n" 25158 "} else {\n" 25159 " g;\n" 25160 "}", 25161 "if (a) {\n" 25162 " if (b)\n" 25163 " c;\n" 25164 " else {\n" 25165 " if (d)\n" 25166 " e;\n" 25167 " }\n" 25168 "} else {\n" 25169 " g;\n" 25170 "}", 25171 Style); 25172 25173 verifyFormat("if (a)\n" 25174 " b;\n" 25175 "else if (c)\n" 25176 " while (d)\n" 25177 " e;\n" 25178 "// comment", 25179 "if (a)\n" 25180 "{\n" 25181 " b;\n" 25182 "} else if (c) {\n" 25183 " while (d) {\n" 25184 " e;\n" 25185 " }\n" 25186 "}\n" 25187 "// comment", 25188 Style); 25189 25190 verifyFormat("if (a) {\n" 25191 " b;\n" 25192 "} else if (c) {\n" 25193 " d;\n" 25194 "} else {\n" 25195 " e;\n" 25196 " g;\n" 25197 "}", 25198 Style); 25199 25200 verifyFormat("if (a) {\n" 25201 " b;\n" 25202 "} else if (c) {\n" 25203 " d;\n" 25204 "} else {\n" 25205 " e;\n" 25206 "} // comment", 25207 Style); 25208 25209 verifyFormat("int abs = [](int i) {\n" 25210 " if (i >= 0)\n" 25211 " return i;\n" 25212 " return -i;\n" 25213 "};", 25214 "int abs = [](int i) {\n" 25215 " if (i >= 0) {\n" 25216 " return i;\n" 25217 " }\n" 25218 " return -i;\n" 25219 "};", 25220 Style); 25221 25222 verifyFormat("if (a)\n" 25223 " foo();\n" 25224 "else\n" 25225 " bar();", 25226 "if (a)\n" 25227 "{\n" 25228 " foo();\n" 25229 "}\n" 25230 "else\n" 25231 "{\n" 25232 " bar();\n" 25233 "}", 25234 Style); 25235 25236 verifyFormat("if (a) {\n" 25237 "Label:\n" 25238 "}", 25239 Style); 25240 25241 verifyFormat("if (a) {\n" 25242 "Label:\n" 25243 " f();\n" 25244 "}", 25245 Style); 25246 25247 verifyFormat("if (a) {\n" 25248 " f();\n" 25249 "Label:\n" 25250 "}", 25251 Style); 25252 25253 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 25254 #if 0 25255 Style.ColumnLimit = 65; 25256 25257 verifyFormat("if (condition) {\n" 25258 " ff(Indices,\n" 25259 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25260 "} else {\n" 25261 " ff(Indices,\n" 25262 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25263 "}", 25264 Style); 25265 25266 Style.ColumnLimit = 20; 25267 25268 verifyFormat("if (a) {\n" 25269 " b = c + // 1 -\n" 25270 " d;\n" 25271 "}", 25272 Style); 25273 25274 verifyFormat("if (a) {\n" 25275 " b = c >= 0 ? d\n" 25276 " : e;\n" 25277 "}", 25278 "if (a) {\n" 25279 " b = c >= 0 ? d : e;\n" 25280 "}", 25281 Style); 25282 #endif 25283 25284 Style.ColumnLimit = 20; 25285 25286 verifyFormat("if (a)\n" 25287 " b = c > 0 ? d : e;", 25288 "if (a) {\n" 25289 " b = c > 0 ? d : e;\n" 25290 "}", 25291 Style); 25292 25293 Style.ColumnLimit = 0; 25294 25295 verifyFormat("if (a)\n" 25296 " b234567890223456789032345678904234567890 = " 25297 "c234567890223456789032345678904234567890;", 25298 "if (a) {\n" 25299 " b234567890223456789032345678904234567890 = " 25300 "c234567890223456789032345678904234567890;\n" 25301 "}", 25302 Style); 25303 } 25304 25305 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25306 auto Style = getLLVMStyle(); 25307 25308 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25309 "void functionDecl(int a, int b, int c);"; 25310 25311 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25312 "paramF, paramG, paramH, paramI);\n" 25313 "void functionDecl(int argumentA, int argumentB, int " 25314 "argumentC, int argumentD, int argumentE);"; 25315 25316 verifyFormat(Short, Style); 25317 25318 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25319 "paramF, paramG, paramH,\n" 25320 " paramI);\n" 25321 "void functionDecl(int argumentA, int argumentB, int " 25322 "argumentC, int argumentD,\n" 25323 " int argumentE);"; 25324 25325 verifyFormat(NoBreak, Medium, Style); 25326 verifyFormat(NoBreak, 25327 "functionCall(\n" 25328 " paramA,\n" 25329 " paramB,\n" 25330 " paramC,\n" 25331 " paramD,\n" 25332 " paramE,\n" 25333 " paramF,\n" 25334 " paramG,\n" 25335 " paramH,\n" 25336 " paramI\n" 25337 ");\n" 25338 "void functionDecl(\n" 25339 " int argumentA,\n" 25340 " int argumentB,\n" 25341 " int argumentC,\n" 25342 " int argumentD,\n" 25343 " int argumentE\n" 25344 ");", 25345 Style); 25346 25347 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25348 " nestedLongFunctionCall(argument1, " 25349 "argument2, argument3,\n" 25350 " argument4, " 25351 "argument5));", 25352 Style); 25353 25354 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25355 25356 verifyFormat(Short, Style); 25357 verifyFormat( 25358 "functionCall(\n" 25359 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25360 "paramI\n" 25361 ");\n" 25362 "void functionDecl(\n" 25363 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25364 "argumentE\n" 25365 ");", 25366 Medium, Style); 25367 25368 Style.AllowAllArgumentsOnNextLine = false; 25369 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25370 25371 verifyFormat(Short, Style); 25372 verifyFormat( 25373 "functionCall(\n" 25374 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25375 "paramI\n" 25376 ");\n" 25377 "void functionDecl(\n" 25378 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25379 "argumentE\n" 25380 ");", 25381 Medium, Style); 25382 25383 Style.BinPackArguments = false; 25384 Style.BinPackParameters = false; 25385 25386 verifyFormat(Short, Style); 25387 25388 verifyFormat("functionCall(\n" 25389 " paramA,\n" 25390 " paramB,\n" 25391 " paramC,\n" 25392 " paramD,\n" 25393 " paramE,\n" 25394 " paramF,\n" 25395 " paramG,\n" 25396 " paramH,\n" 25397 " paramI\n" 25398 ");\n" 25399 "void functionDecl(\n" 25400 " int argumentA,\n" 25401 " int argumentB,\n" 25402 " int argumentC,\n" 25403 " int argumentD,\n" 25404 " int argumentE\n" 25405 ");", 25406 Medium, Style); 25407 25408 verifyFormat("outerFunctionCall(\n" 25409 " nestedFunctionCall(argument1),\n" 25410 " nestedLongFunctionCall(\n" 25411 " argument1,\n" 25412 " argument2,\n" 25413 " argument3,\n" 25414 " argument4,\n" 25415 " argument5\n" 25416 " )\n" 25417 ");", 25418 Style); 25419 25420 verifyFormat("int a = (int)b;", Style); 25421 verifyFormat("int a = (int)b;", 25422 "int a = (\n" 25423 " int\n" 25424 ") b;", 25425 Style); 25426 25427 verifyFormat("return (true);", Style); 25428 verifyFormat("return (true);", 25429 "return (\n" 25430 " true\n" 25431 ");", 25432 Style); 25433 25434 verifyFormat("void foo();", Style); 25435 verifyFormat("void foo();", 25436 "void foo(\n" 25437 ");", 25438 Style); 25439 25440 verifyFormat("void foo() {}", Style); 25441 verifyFormat("void foo() {}", 25442 "void foo(\n" 25443 ") {\n" 25444 "}", 25445 Style); 25446 25447 verifyFormat("auto string = std::string();", Style); 25448 verifyFormat("auto string = std::string();", 25449 "auto string = std::string(\n" 25450 ");", 25451 Style); 25452 25453 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25454 verifyFormat("void (*functionPointer)() = nullptr;", 25455 "void (\n" 25456 " *functionPointer\n" 25457 ")\n" 25458 "(\n" 25459 ") = nullptr;", 25460 Style); 25461 } 25462 25463 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25464 auto Style = getLLVMStyle(); 25465 25466 verifyFormat("if (foo()) {\n" 25467 " return;\n" 25468 "}", 25469 Style); 25470 25471 verifyFormat("if (quitelongarg !=\n" 25472 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25473 "comment\n" 25474 " return;\n" 25475 "}", 25476 Style); 25477 25478 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25479 25480 verifyFormat("if (foo()) {\n" 25481 " return;\n" 25482 "}", 25483 Style); 25484 25485 verifyFormat("if (quitelongarg !=\n" 25486 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25487 "comment\n" 25488 " return;\n" 25489 "}", 25490 Style); 25491 } 25492 25493 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25494 auto Style = getLLVMStyle(); 25495 25496 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25497 " doSomething();\n" 25498 "}", 25499 Style); 25500 25501 verifyFormat("for (int myReallyLongCountVariable = 0; " 25502 "myReallyLongCountVariable < count;\n" 25503 " myReallyLongCountVariable++) {\n" 25504 " doSomething();\n" 25505 "}", 25506 Style); 25507 25508 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25509 25510 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25511 " doSomething();\n" 25512 "}", 25513 Style); 25514 25515 verifyFormat("for (int myReallyLongCountVariable = 0; " 25516 "myReallyLongCountVariable < count;\n" 25517 " myReallyLongCountVariable++) {\n" 25518 " doSomething();\n" 25519 "}", 25520 Style); 25521 } 25522 25523 TEST_F(FormatTest, UnderstandsDigraphs) { 25524 verifyFormat("int arr<:5:> = {};"); 25525 verifyFormat("int arr[5] = <%%>;"); 25526 verifyFormat("int arr<:::qualified_variable:> = {};"); 25527 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25528 verifyFormat("%:include <header>"); 25529 verifyFormat("%:define A x##y"); 25530 verifyFormat("#define A x%:%:y"); 25531 } 25532 25533 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 25534 auto Style = getLLVMStyle(); 25535 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 25536 Style.AlignConsecutiveAssignments.Enabled = true; 25537 Style.AlignConsecutiveDeclarations.Enabled = true; 25538 25539 // The AlignArray code is incorrect for non square Arrays and can cause 25540 // crashes, these tests assert that the array is not changed but will 25541 // also act as regression tests for when it is properly fixed 25542 verifyFormat("struct test demo[] = {\n" 25543 " {1, 2},\n" 25544 " {3, 4, 5},\n" 25545 " {6, 7, 8}\n" 25546 "};", 25547 Style); 25548 verifyFormat("struct test demo[] = {\n" 25549 " {1, 2, 3, 4, 5},\n" 25550 " {3, 4, 5},\n" 25551 " {6, 7, 8}\n" 25552 "};", 25553 Style); 25554 verifyFormat("struct test demo[] = {\n" 25555 " {1, 2, 3, 4, 5},\n" 25556 " {3, 4, 5},\n" 25557 " {6, 7, 8, 9, 10, 11, 12}\n" 25558 "};", 25559 Style); 25560 verifyFormat("struct test demo[] = {\n" 25561 " {1, 2, 3},\n" 25562 " {3, 4, 5},\n" 25563 " {6, 7, 8, 9, 10, 11, 12}\n" 25564 "};", 25565 Style); 25566 25567 verifyFormat("S{\n" 25568 " {},\n" 25569 " {},\n" 25570 " {a, b}\n" 25571 "};", 25572 Style); 25573 verifyFormat("S{\n" 25574 " {},\n" 25575 " {},\n" 25576 " {a, b},\n" 25577 "};", 25578 Style); 25579 verifyFormat("void foo() {\n" 25580 " auto thing = test{\n" 25581 " {\n" 25582 " {13}, {something}, // A\n" 25583 " }\n" 25584 " };\n" 25585 "}", 25586 "void foo() {\n" 25587 " auto thing = test{\n" 25588 " {\n" 25589 " {13},\n" 25590 " {something}, // A\n" 25591 " }\n" 25592 " };\n" 25593 "}", 25594 Style); 25595 } 25596 25597 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 25598 auto Style = getLLVMStyle(); 25599 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 25600 Style.AlignConsecutiveAssignments.Enabled = true; 25601 Style.AlignConsecutiveDeclarations.Enabled = true; 25602 25603 // The AlignArray code is incorrect for non square Arrays and can cause 25604 // crashes, these tests assert that the array is not changed but will 25605 // also act as regression tests for when it is properly fixed 25606 verifyFormat("struct test demo[] = {\n" 25607 " {1, 2},\n" 25608 " {3, 4, 5},\n" 25609 " {6, 7, 8}\n" 25610 "};", 25611 Style); 25612 verifyFormat("struct test demo[] = {\n" 25613 " {1, 2, 3, 4, 5},\n" 25614 " {3, 4, 5},\n" 25615 " {6, 7, 8}\n" 25616 "};", 25617 Style); 25618 verifyFormat("struct test demo[] = {\n" 25619 " {1, 2, 3, 4, 5},\n" 25620 " {3, 4, 5},\n" 25621 " {6, 7, 8, 9, 10, 11, 12}\n" 25622 "};", 25623 Style); 25624 verifyFormat("struct test demo[] = {\n" 25625 " {1, 2, 3},\n" 25626 " {3, 4, 5},\n" 25627 " {6, 7, 8, 9, 10, 11, 12}\n" 25628 "};", 25629 Style); 25630 25631 verifyFormat("S{\n" 25632 " {},\n" 25633 " {},\n" 25634 " {a, b}\n" 25635 "};", 25636 Style); 25637 verifyFormat("S{\n" 25638 " {},\n" 25639 " {},\n" 25640 " {a, b},\n" 25641 "};", 25642 Style); 25643 verifyFormat("void foo() {\n" 25644 " auto thing = test{\n" 25645 " {\n" 25646 " {13}, {something}, // A\n" 25647 " }\n" 25648 " };\n" 25649 "}", 25650 "void foo() {\n" 25651 " auto thing = test{\n" 25652 " {\n" 25653 " {13},\n" 25654 " {something}, // A\n" 25655 " }\n" 25656 " };\n" 25657 "}", 25658 Style); 25659 } 25660 25661 TEST_F(FormatTest, FormatsVariableTemplates) { 25662 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 25663 verifyFormat("template <typename T> " 25664 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 25665 } 25666 25667 } // namespace 25668 } // namespace format 25669 } // namespace clang 25670