1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Format/Format.h" 10 11 #include "../Tooling/ReplacementTest.h" 12 #include "FormatTestUtils.h" 13 14 #include "llvm/Support/Debug.h" 15 #include "llvm/Support/MemoryBuffer.h" 16 #include "gtest/gtest.h" 17 18 #define DEBUG_TYPE "format-test" 19 20 using clang::tooling::ReplacementTest; 21 using clang::tooling::toReplacements; 22 using testing::ScopedTrace; 23 24 namespace clang { 25 namespace format { 26 namespace { 27 28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); } 29 30 class FormatTest : public ::testing::Test { 31 protected: 32 enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck }; 33 34 std::string format(llvm::StringRef Code, 35 const FormatStyle &Style = getLLVMStyle(), 36 StatusCheck CheckComplete = SC_ExpectComplete) { 37 LLVM_DEBUG(llvm::errs() << "---\n"); 38 LLVM_DEBUG(llvm::errs() << Code << "\n\n"); 39 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size())); 40 FormattingAttemptStatus Status; 41 tooling::Replacements Replaces = 42 reformat(Style, Code, Ranges, "<stdin>", &Status); 43 if (CheckComplete != SC_DoNotCheck) { 44 bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete; 45 EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete) 46 << Code << "\n\n"; 47 } 48 ReplacementCount = Replaces.size(); 49 auto Result = applyAllReplacements(Code, Replaces); 50 EXPECT_TRUE(static_cast<bool>(Result)); 51 LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); 52 return *Result; 53 } 54 55 FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) { 56 Style.ColumnLimit = ColumnLimit; 57 return Style; 58 } 59 60 FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) { 61 return getStyleWithColumns(getLLVMStyle(), ColumnLimit); 62 } 63 64 FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) { 65 return getStyleWithColumns(getGoogleStyle(), ColumnLimit); 66 } 67 68 void _verifyFormat(const char *File, int Line, llvm::StringRef Expected, 69 llvm::StringRef Code, 70 const FormatStyle &Style = getLLVMStyle()) { 71 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 72 EXPECT_EQ(Expected.str(), format(Expected, Style)) 73 << "Expected code is not stable"; 74 EXPECT_EQ(Expected.str(), format(Code, Style)); 75 if (Style.Language == FormatStyle::LK_Cpp) { 76 // Objective-C++ is a superset of C++, so everything checked for C++ 77 // needs to be checked for Objective-C++ as well. 78 FormatStyle ObjCStyle = Style; 79 ObjCStyle.Language = FormatStyle::LK_ObjC; 80 EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle)); 81 } 82 } 83 84 void _verifyFormat(const char *File, int Line, llvm::StringRef Code, 85 const FormatStyle &Style = getLLVMStyle()) { 86 _verifyFormat(File, Line, Code, test::messUp(Code), Style); 87 } 88 89 void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code, 90 const FormatStyle &Style = getLLVMStyle()) { 91 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 92 EXPECT_EQ(Code.str(), 93 format(test::messUp(Code), Style, SC_ExpectIncomplete)); 94 } 95 96 void _verifyIndependentOfContext(const char *File, int Line, 97 llvm::StringRef Text, 98 const FormatStyle &Style = getLLVMStyle()) { 99 _verifyFormat(File, Line, Text, Style); 100 _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(), 101 Style); 102 } 103 104 /// \brief Verify that clang-format does not crash on the given input. 105 void verifyNoCrash(llvm::StringRef Code, 106 const FormatStyle &Style = getLLVMStyle()) { 107 format(Code, Style, SC_DoNotCheck); 108 } 109 110 int ReplacementCount; 111 }; 112 113 #define verifyIndependentOfContext(...) \ 114 _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__) 115 #define verifyIncompleteFormat(...) \ 116 _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__) 117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__) 118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle()) 119 120 TEST_F(FormatTest, MessUp) { 121 EXPECT_EQ("1 2 3", test::messUp("1 2 3")); 122 EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n")); 123 EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc")); 124 EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc")); 125 EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne")); 126 } 127 128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) { 129 EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language); 130 } 131 132 TEST_F(FormatTest, LLVMStyleOverride) { 133 EXPECT_EQ(FormatStyle::LK_Proto, 134 getLLVMStyle(FormatStyle::LK_Proto).Language); 135 } 136 137 //===----------------------------------------------------------------------===// 138 // Basic function tests. 139 //===----------------------------------------------------------------------===// 140 141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { 142 EXPECT_EQ(";", format(";")); 143 } 144 145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) { 146 EXPECT_EQ("int i;", format(" int i;")); 147 EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;")); 148 EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); 149 EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); 150 } 151 152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { 153 EXPECT_EQ("int i;", format("int\ni;")); 154 } 155 156 TEST_F(FormatTest, FormatsNestedBlockStatements) { 157 EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); 158 } 159 160 TEST_F(FormatTest, FormatsNestedCall) { 161 verifyFormat("Method(f1, f2(f3));"); 162 verifyFormat("Method(f1(f2, f3()));"); 163 verifyFormat("Method(f1(f2, (f3())));"); 164 } 165 166 TEST_F(FormatTest, NestedNameSpecifiers) { 167 verifyFormat("vector<::Type> v;"); 168 verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); 169 verifyFormat("static constexpr bool Bar = decltype(bar())::value;"); 170 verifyFormat("static constexpr bool Bar = typeof(bar())::value;"); 171 verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;"); 172 verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;"); 173 verifyFormat("bool a = 2 < ::SomeFunction();"); 174 verifyFormat("ALWAYS_INLINE ::std::string getName();"); 175 verifyFormat("some::string getName();"); 176 } 177 178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { 179 EXPECT_EQ("if (a) {\n" 180 " f();\n" 181 "}", 182 format("if(a){f();}")); 183 EXPECT_EQ(4, ReplacementCount); 184 EXPECT_EQ("if (a) {\n" 185 " f();\n" 186 "}", 187 format("if (a) {\n" 188 " f();\n" 189 "}")); 190 EXPECT_EQ(0, ReplacementCount); 191 EXPECT_EQ("/*\r\n" 192 "\r\n" 193 "*/\r\n", 194 format("/*\r\n" 195 "\r\n" 196 "*/\r\n")); 197 EXPECT_EQ(0, ReplacementCount); 198 } 199 200 TEST_F(FormatTest, RemovesEmptyLines) { 201 EXPECT_EQ("class C {\n" 202 " int i;\n" 203 "};", 204 format("class C {\n" 205 " int i;\n" 206 "\n" 207 "};")); 208 209 // Don't remove empty lines at the start of namespaces or extern "C" blocks. 210 EXPECT_EQ("namespace N {\n" 211 "\n" 212 "int i;\n" 213 "}", 214 format("namespace N {\n" 215 "\n" 216 "int i;\n" 217 "}", 218 getGoogleStyle())); 219 EXPECT_EQ("/* something */ namespace N {\n" 220 "\n" 221 "int i;\n" 222 "}", 223 format("/* something */ namespace N {\n" 224 "\n" 225 "int i;\n" 226 "}", 227 getGoogleStyle())); 228 EXPECT_EQ("inline namespace N {\n" 229 "\n" 230 "int i;\n" 231 "}", 232 format("inline namespace N {\n" 233 "\n" 234 "int i;\n" 235 "}", 236 getGoogleStyle())); 237 EXPECT_EQ("/* something */ inline namespace N {\n" 238 "\n" 239 "int i;\n" 240 "}", 241 format("/* something */ inline namespace N {\n" 242 "\n" 243 "int i;\n" 244 "}", 245 getGoogleStyle())); 246 EXPECT_EQ("export namespace N {\n" 247 "\n" 248 "int i;\n" 249 "}", 250 format("export namespace N {\n" 251 "\n" 252 "int i;\n" 253 "}", 254 getGoogleStyle())); 255 EXPECT_EQ("extern /**/ \"C\" /**/ {\n" 256 "\n" 257 "int i;\n" 258 "}", 259 format("extern /**/ \"C\" /**/ {\n" 260 "\n" 261 "int i;\n" 262 "}", 263 getGoogleStyle())); 264 265 auto CustomStyle = getLLVMStyle(); 266 CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom; 267 CustomStyle.BraceWrapping.AfterNamespace = true; 268 CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false; 269 EXPECT_EQ("namespace N\n" 270 "{\n" 271 "\n" 272 "int i;\n" 273 "}", 274 format("namespace N\n" 275 "{\n" 276 "\n" 277 "\n" 278 "int i;\n" 279 "}", 280 CustomStyle)); 281 EXPECT_EQ("/* something */ namespace N\n" 282 "{\n" 283 "\n" 284 "int i;\n" 285 "}", 286 format("/* something */ namespace N {\n" 287 "\n" 288 "\n" 289 "int i;\n" 290 "}", 291 CustomStyle)); 292 EXPECT_EQ("inline namespace N\n" 293 "{\n" 294 "\n" 295 "int i;\n" 296 "}", 297 format("inline namespace N\n" 298 "{\n" 299 "\n" 300 "\n" 301 "int i;\n" 302 "}", 303 CustomStyle)); 304 EXPECT_EQ("/* something */ inline namespace N\n" 305 "{\n" 306 "\n" 307 "int i;\n" 308 "}", 309 format("/* something */ inline namespace N\n" 310 "{\n" 311 "\n" 312 "int i;\n" 313 "}", 314 CustomStyle)); 315 EXPECT_EQ("export namespace N\n" 316 "{\n" 317 "\n" 318 "int i;\n" 319 "}", 320 format("export namespace N\n" 321 "{\n" 322 "\n" 323 "int i;\n" 324 "}", 325 CustomStyle)); 326 EXPECT_EQ("namespace a\n" 327 "{\n" 328 "namespace b\n" 329 "{\n" 330 "\n" 331 "class AA {};\n" 332 "\n" 333 "} // namespace b\n" 334 "} // namespace a\n", 335 format("namespace a\n" 336 "{\n" 337 "namespace b\n" 338 "{\n" 339 "\n" 340 "\n" 341 "class AA {};\n" 342 "\n" 343 "\n" 344 "}\n" 345 "}\n", 346 CustomStyle)); 347 EXPECT_EQ("namespace A /* comment */\n" 348 "{\n" 349 "class B {}\n" 350 "} // namespace A", 351 format("namespace A /* comment */ { class B {} }", CustomStyle)); 352 EXPECT_EQ("namespace A\n" 353 "{ /* comment */\n" 354 "class B {}\n" 355 "} // namespace A", 356 format("namespace A {/* comment */ class B {} }", CustomStyle)); 357 EXPECT_EQ("namespace A\n" 358 "{ /* comment */\n" 359 "\n" 360 "class B {}\n" 361 "\n" 362 "" 363 "} // namespace A", 364 format("namespace A { /* comment */\n" 365 "\n" 366 "\n" 367 "class B {}\n" 368 "\n" 369 "\n" 370 "}", 371 CustomStyle)); 372 EXPECT_EQ("namespace A /* comment */\n" 373 "{\n" 374 "\n" 375 "class B {}\n" 376 "\n" 377 "} // namespace A", 378 format("namespace A/* comment */ {\n" 379 "\n" 380 "\n" 381 "class B {}\n" 382 "\n" 383 "\n" 384 "}", 385 CustomStyle)); 386 387 // ...but do keep inlining and removing empty lines for non-block extern "C" 388 // functions. 389 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); 390 EXPECT_EQ("extern \"C\" int f() {\n" 391 " int i = 42;\n" 392 " return i;\n" 393 "}", 394 format("extern \"C\" int f() {\n" 395 "\n" 396 " int i = 42;\n" 397 " return i;\n" 398 "}", 399 getGoogleStyle())); 400 401 // Remove empty lines at the beginning and end of blocks. 402 EXPECT_EQ("void f() {\n" 403 "\n" 404 " if (a) {\n" 405 "\n" 406 " f();\n" 407 " }\n" 408 "}", 409 format("void f() {\n" 410 "\n" 411 " if (a) {\n" 412 "\n" 413 " f();\n" 414 "\n" 415 " }\n" 416 "\n" 417 "}", 418 getLLVMStyle())); 419 EXPECT_EQ("void f() {\n" 420 " if (a) {\n" 421 " f();\n" 422 " }\n" 423 "}", 424 format("void f() {\n" 425 "\n" 426 " if (a) {\n" 427 "\n" 428 " f();\n" 429 "\n" 430 " }\n" 431 "\n" 432 "}", 433 getGoogleStyle())); 434 435 // Don't remove empty lines in more complex control statements. 436 EXPECT_EQ("void f() {\n" 437 " if (a) {\n" 438 " f();\n" 439 "\n" 440 " } else if (b) {\n" 441 " f();\n" 442 " }\n" 443 "}", 444 format("void f() {\n" 445 " if (a) {\n" 446 " f();\n" 447 "\n" 448 " } else if (b) {\n" 449 " f();\n" 450 "\n" 451 " }\n" 452 "\n" 453 "}")); 454 455 // Don't remove empty lines before namespace endings. 456 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 457 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 458 EXPECT_EQ("namespace {\n" 459 "int i;\n" 460 "\n" 461 "}", 462 format("namespace {\n" 463 "int i;\n" 464 "\n" 465 "}", 466 LLVMWithNoNamespaceFix)); 467 EXPECT_EQ("namespace {\n" 468 "int i;\n" 469 "}", 470 format("namespace {\n" 471 "int i;\n" 472 "}", 473 LLVMWithNoNamespaceFix)); 474 EXPECT_EQ("namespace {\n" 475 "int i;\n" 476 "\n" 477 "};", 478 format("namespace {\n" 479 "int i;\n" 480 "\n" 481 "};", 482 LLVMWithNoNamespaceFix)); 483 EXPECT_EQ("namespace {\n" 484 "int i;\n" 485 "};", 486 format("namespace {\n" 487 "int i;\n" 488 "};", 489 LLVMWithNoNamespaceFix)); 490 EXPECT_EQ("namespace {\n" 491 "int i;\n" 492 "\n" 493 "}", 494 format("namespace {\n" 495 "int i;\n" 496 "\n" 497 "}")); 498 EXPECT_EQ("namespace {\n" 499 "int i;\n" 500 "\n" 501 "} // namespace", 502 format("namespace {\n" 503 "int i;\n" 504 "\n" 505 "} // namespace")); 506 507 FormatStyle Style = getLLVMStyle(); 508 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 509 Style.MaxEmptyLinesToKeep = 2; 510 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 511 Style.BraceWrapping.AfterClass = true; 512 Style.BraceWrapping.AfterFunction = true; 513 Style.KeepEmptyLinesAtTheStartOfBlocks = false; 514 515 EXPECT_EQ("class Foo\n" 516 "{\n" 517 " Foo() {}\n" 518 "\n" 519 " void funk() {}\n" 520 "};", 521 format("class Foo\n" 522 "{\n" 523 " Foo()\n" 524 " {\n" 525 " }\n" 526 "\n" 527 " void funk() {}\n" 528 "};", 529 Style)); 530 } 531 532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { 533 verifyFormat("x = (a) and (b);"); 534 verifyFormat("x = (a) or (b);"); 535 verifyFormat("x = (a) bitand (b);"); 536 verifyFormat("x = (a) bitor (b);"); 537 verifyFormat("x = (a) not_eq (b);"); 538 verifyFormat("x = (a) and_eq (b);"); 539 verifyFormat("x = (a) or_eq (b);"); 540 verifyFormat("x = (a) xor (b);"); 541 } 542 543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { 544 verifyFormat("x = compl(a);"); 545 verifyFormat("x = not(a);"); 546 verifyFormat("x = bitand(a);"); 547 // Unary operator must not be merged with the next identifier 548 verifyFormat("x = compl a;"); 549 verifyFormat("x = not a;"); 550 verifyFormat("x = bitand a;"); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // Tests for control statements. 555 //===----------------------------------------------------------------------===// 556 557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { 558 verifyFormat("if (true)\n f();\ng();"); 559 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); 560 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); 561 verifyFormat("if constexpr (true)\n" 562 " f();\ng();"); 563 verifyFormat("if CONSTEXPR (true)\n" 564 " f();\ng();"); 565 verifyFormat("if constexpr (a)\n" 566 " if constexpr (b)\n" 567 " if constexpr (c)\n" 568 " g();\n" 569 "h();"); 570 verifyFormat("if CONSTEXPR (a)\n" 571 " if CONSTEXPR (b)\n" 572 " if CONSTEXPR (c)\n" 573 " g();\n" 574 "h();"); 575 verifyFormat("if constexpr (a)\n" 576 " if constexpr (b) {\n" 577 " f();\n" 578 " }\n" 579 "g();"); 580 verifyFormat("if CONSTEXPR (a)\n" 581 " if CONSTEXPR (b) {\n" 582 " f();\n" 583 " }\n" 584 "g();"); 585 586 verifyFormat("if consteval {\n}"); 587 verifyFormat("if !consteval {\n}"); 588 verifyFormat("if not consteval {\n}"); 589 verifyFormat("if consteval {\n} else {\n}"); 590 verifyFormat("if !consteval {\n} else {\n}"); 591 verifyFormat("if consteval {\n" 592 " f();\n" 593 "}"); 594 verifyFormat("if !consteval {\n" 595 " f();\n" 596 "}"); 597 verifyFormat("if consteval {\n" 598 " f();\n" 599 "} else {\n" 600 " g();\n" 601 "}"); 602 verifyFormat("if CONSTEVAL {\n" 603 " f();\n" 604 "}"); 605 verifyFormat("if !CONSTEVAL {\n" 606 " f();\n" 607 "}"); 608 609 verifyFormat("if (a)\n" 610 " g();"); 611 verifyFormat("if (a) {\n" 612 " g()\n" 613 "};"); 614 verifyFormat("if (a)\n" 615 " g();\n" 616 "else\n" 617 " g();"); 618 verifyFormat("if (a) {\n" 619 " g();\n" 620 "} else\n" 621 " g();"); 622 verifyFormat("if (a)\n" 623 " g();\n" 624 "else {\n" 625 " g();\n" 626 "}"); 627 verifyFormat("if (a) {\n" 628 " g();\n" 629 "} else {\n" 630 " g();\n" 631 "}"); 632 verifyFormat("if (a)\n" 633 " g();\n" 634 "else if (b)\n" 635 " g();\n" 636 "else\n" 637 " g();"); 638 verifyFormat("if (a) {\n" 639 " g();\n" 640 "} else if (b)\n" 641 " g();\n" 642 "else\n" 643 " g();"); 644 verifyFormat("if (a)\n" 645 " g();\n" 646 "else if (b) {\n" 647 " g();\n" 648 "} else\n" 649 " g();"); 650 verifyFormat("if (a)\n" 651 " g();\n" 652 "else if (b)\n" 653 " g();\n" 654 "else {\n" 655 " g();\n" 656 "}"); 657 verifyFormat("if (a)\n" 658 " g();\n" 659 "else if (b) {\n" 660 " g();\n" 661 "} else {\n" 662 " g();\n" 663 "}"); 664 verifyFormat("if (a) {\n" 665 " g();\n" 666 "} else if (b) {\n" 667 " g();\n" 668 "} else {\n" 669 " g();\n" 670 "}"); 671 672 FormatStyle AllowsMergedIf = getLLVMStyle(); 673 AllowsMergedIf.IfMacros.push_back("MYIF"); 674 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 675 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 676 FormatStyle::SIS_WithoutElse; 677 verifyFormat("if (a)\n" 678 " // comment\n" 679 " f();", 680 AllowsMergedIf); 681 verifyFormat("{\n" 682 " if (a)\n" 683 " label:\n" 684 " f();\n" 685 "}", 686 AllowsMergedIf); 687 verifyFormat("#define A \\\n" 688 " if (a) \\\n" 689 " label: \\\n" 690 " f()", 691 AllowsMergedIf); 692 verifyFormat("if (a)\n" 693 " ;", 694 AllowsMergedIf); 695 verifyFormat("if (a)\n" 696 " if (b) return;", 697 AllowsMergedIf); 698 699 verifyFormat("if (a) // Can't merge this\n" 700 " f();\n", 701 AllowsMergedIf); 702 verifyFormat("if (a) /* still don't merge */\n" 703 " f();", 704 AllowsMergedIf); 705 verifyFormat("if (a) { // Never merge this\n" 706 " f();\n" 707 "}", 708 AllowsMergedIf); 709 verifyFormat("if (a) { /* Never merge this */\n" 710 " f();\n" 711 "}", 712 AllowsMergedIf); 713 verifyFormat("MYIF (a)\n" 714 " // comment\n" 715 " f();", 716 AllowsMergedIf); 717 verifyFormat("{\n" 718 " MYIF (a)\n" 719 " label:\n" 720 " f();\n" 721 "}", 722 AllowsMergedIf); 723 verifyFormat("#define A \\\n" 724 " MYIF (a) \\\n" 725 " label: \\\n" 726 " f()", 727 AllowsMergedIf); 728 verifyFormat("MYIF (a)\n" 729 " ;", 730 AllowsMergedIf); 731 verifyFormat("MYIF (a)\n" 732 " MYIF (b) return;", 733 AllowsMergedIf); 734 735 verifyFormat("MYIF (a) // Can't merge this\n" 736 " f();\n", 737 AllowsMergedIf); 738 verifyFormat("MYIF (a) /* still don't merge */\n" 739 " f();", 740 AllowsMergedIf); 741 verifyFormat("MYIF (a) { // Never merge this\n" 742 " f();\n" 743 "}", 744 AllowsMergedIf); 745 verifyFormat("MYIF (a) { /* Never merge this */\n" 746 " f();\n" 747 "}", 748 AllowsMergedIf); 749 750 AllowsMergedIf.ColumnLimit = 14; 751 // Where line-lengths matter, a 2-letter synonym that maintains line length. 752 // Not IF to avoid any confusion that IF is somehow special. 753 AllowsMergedIf.IfMacros.push_back("FI"); 754 verifyFormat("if (a) return;", AllowsMergedIf); 755 verifyFormat("if (aaaaaaaaa)\n" 756 " return;", 757 AllowsMergedIf); 758 verifyFormat("FI (a) return;", AllowsMergedIf); 759 verifyFormat("FI (aaaaaaaaa)\n" 760 " return;", 761 AllowsMergedIf); 762 763 AllowsMergedIf.ColumnLimit = 13; 764 verifyFormat("if (a)\n return;", AllowsMergedIf); 765 verifyFormat("FI (a)\n return;", AllowsMergedIf); 766 767 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 768 AllowsMergedIfElse.IfMacros.push_back("MYIF"); 769 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 770 FormatStyle::SIS_AllIfsAndElse; 771 verifyFormat("if (a)\n" 772 " // comment\n" 773 " f();\n" 774 "else\n" 775 " // comment\n" 776 " f();", 777 AllowsMergedIfElse); 778 verifyFormat("{\n" 779 " if (a)\n" 780 " label:\n" 781 " f();\n" 782 " else\n" 783 " label:\n" 784 " f();\n" 785 "}", 786 AllowsMergedIfElse); 787 verifyFormat("if (a)\n" 788 " ;\n" 789 "else\n" 790 " ;", 791 AllowsMergedIfElse); 792 verifyFormat("if (a) {\n" 793 "} else {\n" 794 "}", 795 AllowsMergedIfElse); 796 verifyFormat("if (a) return;\n" 797 "else if (b) return;\n" 798 "else return;", 799 AllowsMergedIfElse); 800 verifyFormat("if (a) {\n" 801 "} else return;", 802 AllowsMergedIfElse); 803 verifyFormat("if (a) {\n" 804 "} else if (b) return;\n" 805 "else return;", 806 AllowsMergedIfElse); 807 verifyFormat("if (a) return;\n" 808 "else if (b) {\n" 809 "} else return;", 810 AllowsMergedIfElse); 811 verifyFormat("if (a)\n" 812 " if (b) return;\n" 813 " else return;", 814 AllowsMergedIfElse); 815 verifyFormat("if constexpr (a)\n" 816 " if constexpr (b) return;\n" 817 " else if constexpr (c) return;\n" 818 " else return;", 819 AllowsMergedIfElse); 820 verifyFormat("MYIF (a)\n" 821 " // comment\n" 822 " f();\n" 823 "else\n" 824 " // comment\n" 825 " f();", 826 AllowsMergedIfElse); 827 verifyFormat("{\n" 828 " MYIF (a)\n" 829 " label:\n" 830 " f();\n" 831 " else\n" 832 " label:\n" 833 " f();\n" 834 "}", 835 AllowsMergedIfElse); 836 verifyFormat("MYIF (a)\n" 837 " ;\n" 838 "else\n" 839 " ;", 840 AllowsMergedIfElse); 841 verifyFormat("MYIF (a) {\n" 842 "} else {\n" 843 "}", 844 AllowsMergedIfElse); 845 verifyFormat("MYIF (a) return;\n" 846 "else MYIF (b) return;\n" 847 "else return;", 848 AllowsMergedIfElse); 849 verifyFormat("MYIF (a) {\n" 850 "} else return;", 851 AllowsMergedIfElse); 852 verifyFormat("MYIF (a) {\n" 853 "} else MYIF (b) return;\n" 854 "else return;", 855 AllowsMergedIfElse); 856 verifyFormat("MYIF (a) return;\n" 857 "else MYIF (b) {\n" 858 "} else return;", 859 AllowsMergedIfElse); 860 verifyFormat("MYIF (a)\n" 861 " MYIF (b) return;\n" 862 " else return;", 863 AllowsMergedIfElse); 864 verifyFormat("MYIF constexpr (a)\n" 865 " MYIF constexpr (b) return;\n" 866 " else MYIF constexpr (c) return;\n" 867 " else return;", 868 AllowsMergedIfElse); 869 } 870 871 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 872 FormatStyle AllowsMergedIf = getLLVMStyle(); 873 AllowsMergedIf.IfMacros.push_back("MYIF"); 874 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 875 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 876 FormatStyle::SIS_WithoutElse; 877 verifyFormat("if (a)\n" 878 " f();\n" 879 "else {\n" 880 " g();\n" 881 "}", 882 AllowsMergedIf); 883 verifyFormat("if (a)\n" 884 " f();\n" 885 "else\n" 886 " g();\n", 887 AllowsMergedIf); 888 889 verifyFormat("if (a) g();", AllowsMergedIf); 890 verifyFormat("if (a) {\n" 891 " g()\n" 892 "};", 893 AllowsMergedIf); 894 verifyFormat("if (a)\n" 895 " g();\n" 896 "else\n" 897 " g();", 898 AllowsMergedIf); 899 verifyFormat("if (a) {\n" 900 " g();\n" 901 "} else\n" 902 " g();", 903 AllowsMergedIf); 904 verifyFormat("if (a)\n" 905 " g();\n" 906 "else {\n" 907 " g();\n" 908 "}", 909 AllowsMergedIf); 910 verifyFormat("if (a) {\n" 911 " g();\n" 912 "} else {\n" 913 " g();\n" 914 "}", 915 AllowsMergedIf); 916 verifyFormat("if (a)\n" 917 " g();\n" 918 "else if (b)\n" 919 " g();\n" 920 "else\n" 921 " g();", 922 AllowsMergedIf); 923 verifyFormat("if (a) {\n" 924 " g();\n" 925 "} else if (b)\n" 926 " g();\n" 927 "else\n" 928 " g();", 929 AllowsMergedIf); 930 verifyFormat("if (a)\n" 931 " g();\n" 932 "else if (b) {\n" 933 " g();\n" 934 "} else\n" 935 " g();", 936 AllowsMergedIf); 937 verifyFormat("if (a)\n" 938 " g();\n" 939 "else if (b)\n" 940 " g();\n" 941 "else {\n" 942 " g();\n" 943 "}", 944 AllowsMergedIf); 945 verifyFormat("if (a)\n" 946 " g();\n" 947 "else if (b) {\n" 948 " g();\n" 949 "} else {\n" 950 " g();\n" 951 "}", 952 AllowsMergedIf); 953 verifyFormat("if (a) {\n" 954 " g();\n" 955 "} else if (b) {\n" 956 " g();\n" 957 "} else {\n" 958 " g();\n" 959 "}", 960 AllowsMergedIf); 961 verifyFormat("MYIF (a)\n" 962 " f();\n" 963 "else {\n" 964 " g();\n" 965 "}", 966 AllowsMergedIf); 967 verifyFormat("MYIF (a)\n" 968 " f();\n" 969 "else\n" 970 " g();\n", 971 AllowsMergedIf); 972 973 verifyFormat("MYIF (a) g();", AllowsMergedIf); 974 verifyFormat("MYIF (a) {\n" 975 " g()\n" 976 "};", 977 AllowsMergedIf); 978 verifyFormat("MYIF (a)\n" 979 " g();\n" 980 "else\n" 981 " g();", 982 AllowsMergedIf); 983 verifyFormat("MYIF (a) {\n" 984 " g();\n" 985 "} else\n" 986 " g();", 987 AllowsMergedIf); 988 verifyFormat("MYIF (a)\n" 989 " g();\n" 990 "else {\n" 991 " g();\n" 992 "}", 993 AllowsMergedIf); 994 verifyFormat("MYIF (a) {\n" 995 " g();\n" 996 "} else {\n" 997 " g();\n" 998 "}", 999 AllowsMergedIf); 1000 verifyFormat("MYIF (a)\n" 1001 " g();\n" 1002 "else MYIF (b)\n" 1003 " g();\n" 1004 "else\n" 1005 " g();", 1006 AllowsMergedIf); 1007 verifyFormat("MYIF (a)\n" 1008 " g();\n" 1009 "else if (b)\n" 1010 " g();\n" 1011 "else\n" 1012 " g();", 1013 AllowsMergedIf); 1014 verifyFormat("MYIF (a) {\n" 1015 " g();\n" 1016 "} else MYIF (b)\n" 1017 " g();\n" 1018 "else\n" 1019 " g();", 1020 AllowsMergedIf); 1021 verifyFormat("MYIF (a) {\n" 1022 " g();\n" 1023 "} else if (b)\n" 1024 " g();\n" 1025 "else\n" 1026 " g();", 1027 AllowsMergedIf); 1028 verifyFormat("MYIF (a)\n" 1029 " g();\n" 1030 "else MYIF (b) {\n" 1031 " g();\n" 1032 "} else\n" 1033 " g();", 1034 AllowsMergedIf); 1035 verifyFormat("MYIF (a)\n" 1036 " g();\n" 1037 "else if (b) {\n" 1038 " g();\n" 1039 "} else\n" 1040 " g();", 1041 AllowsMergedIf); 1042 verifyFormat("MYIF (a)\n" 1043 " g();\n" 1044 "else MYIF (b)\n" 1045 " g();\n" 1046 "else {\n" 1047 " g();\n" 1048 "}", 1049 AllowsMergedIf); 1050 verifyFormat("MYIF (a)\n" 1051 " g();\n" 1052 "else if (b)\n" 1053 " g();\n" 1054 "else {\n" 1055 " g();\n" 1056 "}", 1057 AllowsMergedIf); 1058 verifyFormat("MYIF (a)\n" 1059 " g();\n" 1060 "else MYIF (b) {\n" 1061 " g();\n" 1062 "} else {\n" 1063 " g();\n" 1064 "}", 1065 AllowsMergedIf); 1066 verifyFormat("MYIF (a)\n" 1067 " g();\n" 1068 "else if (b) {\n" 1069 " g();\n" 1070 "} else {\n" 1071 " g();\n" 1072 "}", 1073 AllowsMergedIf); 1074 verifyFormat("MYIF (a) {\n" 1075 " g();\n" 1076 "} else MYIF (b) {\n" 1077 " g();\n" 1078 "} else {\n" 1079 " g();\n" 1080 "}", 1081 AllowsMergedIf); 1082 verifyFormat("MYIF (a) {\n" 1083 " g();\n" 1084 "} else if (b) {\n" 1085 " g();\n" 1086 "} else {\n" 1087 " g();\n" 1088 "}", 1089 AllowsMergedIf); 1090 1091 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1092 FormatStyle::SIS_OnlyFirstIf; 1093 1094 verifyFormat("if (a) f();\n" 1095 "else {\n" 1096 " g();\n" 1097 "}", 1098 AllowsMergedIf); 1099 verifyFormat("if (a) f();\n" 1100 "else {\n" 1101 " if (a) f();\n" 1102 " else {\n" 1103 " g();\n" 1104 " }\n" 1105 " g();\n" 1106 "}", 1107 AllowsMergedIf); 1108 1109 verifyFormat("if (a) g();", AllowsMergedIf); 1110 verifyFormat("if (a) {\n" 1111 " g()\n" 1112 "};", 1113 AllowsMergedIf); 1114 verifyFormat("if (a) g();\n" 1115 "else\n" 1116 " g();", 1117 AllowsMergedIf); 1118 verifyFormat("if (a) {\n" 1119 " g();\n" 1120 "} else\n" 1121 " g();", 1122 AllowsMergedIf); 1123 verifyFormat("if (a) g();\n" 1124 "else {\n" 1125 " g();\n" 1126 "}", 1127 AllowsMergedIf); 1128 verifyFormat("if (a) {\n" 1129 " g();\n" 1130 "} else {\n" 1131 " g();\n" 1132 "}", 1133 AllowsMergedIf); 1134 verifyFormat("if (a) g();\n" 1135 "else if (b)\n" 1136 " g();\n" 1137 "else\n" 1138 " g();", 1139 AllowsMergedIf); 1140 verifyFormat("if (a) {\n" 1141 " g();\n" 1142 "} else if (b)\n" 1143 " g();\n" 1144 "else\n" 1145 " g();", 1146 AllowsMergedIf); 1147 verifyFormat("if (a) g();\n" 1148 "else if (b) {\n" 1149 " g();\n" 1150 "} else\n" 1151 " g();", 1152 AllowsMergedIf); 1153 verifyFormat("if (a) g();\n" 1154 "else if (b)\n" 1155 " g();\n" 1156 "else {\n" 1157 " g();\n" 1158 "}", 1159 AllowsMergedIf); 1160 verifyFormat("if (a) g();\n" 1161 "else if (b) {\n" 1162 " g();\n" 1163 "} else {\n" 1164 " g();\n" 1165 "}", 1166 AllowsMergedIf); 1167 verifyFormat("if (a) {\n" 1168 " g();\n" 1169 "} else if (b) {\n" 1170 " g();\n" 1171 "} else {\n" 1172 " g();\n" 1173 "}", 1174 AllowsMergedIf); 1175 verifyFormat("MYIF (a) f();\n" 1176 "else {\n" 1177 " g();\n" 1178 "}", 1179 AllowsMergedIf); 1180 verifyFormat("MYIF (a) f();\n" 1181 "else {\n" 1182 " if (a) f();\n" 1183 " else {\n" 1184 " g();\n" 1185 " }\n" 1186 " g();\n" 1187 "}", 1188 AllowsMergedIf); 1189 1190 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1191 verifyFormat("MYIF (a) {\n" 1192 " g()\n" 1193 "};", 1194 AllowsMergedIf); 1195 verifyFormat("MYIF (a) g();\n" 1196 "else\n" 1197 " g();", 1198 AllowsMergedIf); 1199 verifyFormat("MYIF (a) {\n" 1200 " g();\n" 1201 "} else\n" 1202 " g();", 1203 AllowsMergedIf); 1204 verifyFormat("MYIF (a) g();\n" 1205 "else {\n" 1206 " g();\n" 1207 "}", 1208 AllowsMergedIf); 1209 verifyFormat("MYIF (a) {\n" 1210 " g();\n" 1211 "} else {\n" 1212 " g();\n" 1213 "}", 1214 AllowsMergedIf); 1215 verifyFormat("MYIF (a) g();\n" 1216 "else MYIF (b)\n" 1217 " g();\n" 1218 "else\n" 1219 " g();", 1220 AllowsMergedIf); 1221 verifyFormat("MYIF (a) g();\n" 1222 "else if (b)\n" 1223 " g();\n" 1224 "else\n" 1225 " g();", 1226 AllowsMergedIf); 1227 verifyFormat("MYIF (a) {\n" 1228 " g();\n" 1229 "} else MYIF (b)\n" 1230 " g();\n" 1231 "else\n" 1232 " g();", 1233 AllowsMergedIf); 1234 verifyFormat("MYIF (a) {\n" 1235 " g();\n" 1236 "} else if (b)\n" 1237 " g();\n" 1238 "else\n" 1239 " g();", 1240 AllowsMergedIf); 1241 verifyFormat("MYIF (a) g();\n" 1242 "else MYIF (b) {\n" 1243 " g();\n" 1244 "} else\n" 1245 " g();", 1246 AllowsMergedIf); 1247 verifyFormat("MYIF (a) g();\n" 1248 "else if (b) {\n" 1249 " g();\n" 1250 "} else\n" 1251 " g();", 1252 AllowsMergedIf); 1253 verifyFormat("MYIF (a) g();\n" 1254 "else MYIF (b)\n" 1255 " g();\n" 1256 "else {\n" 1257 " g();\n" 1258 "}", 1259 AllowsMergedIf); 1260 verifyFormat("MYIF (a) g();\n" 1261 "else if (b)\n" 1262 " g();\n" 1263 "else {\n" 1264 " g();\n" 1265 "}", 1266 AllowsMergedIf); 1267 verifyFormat("MYIF (a) g();\n" 1268 "else MYIF (b) {\n" 1269 " g();\n" 1270 "} else {\n" 1271 " g();\n" 1272 "}", 1273 AllowsMergedIf); 1274 verifyFormat("MYIF (a) g();\n" 1275 "else if (b) {\n" 1276 " g();\n" 1277 "} else {\n" 1278 " g();\n" 1279 "}", 1280 AllowsMergedIf); 1281 verifyFormat("MYIF (a) {\n" 1282 " g();\n" 1283 "} else MYIF (b) {\n" 1284 " g();\n" 1285 "} else {\n" 1286 " g();\n" 1287 "}", 1288 AllowsMergedIf); 1289 verifyFormat("MYIF (a) {\n" 1290 " g();\n" 1291 "} else if (b) {\n" 1292 " g();\n" 1293 "} else {\n" 1294 " g();\n" 1295 "}", 1296 AllowsMergedIf); 1297 1298 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1299 FormatStyle::SIS_AllIfsAndElse; 1300 1301 verifyFormat("if (a) f();\n" 1302 "else {\n" 1303 " g();\n" 1304 "}", 1305 AllowsMergedIf); 1306 verifyFormat("if (a) f();\n" 1307 "else {\n" 1308 " if (a) f();\n" 1309 " else {\n" 1310 " g();\n" 1311 " }\n" 1312 " g();\n" 1313 "}", 1314 AllowsMergedIf); 1315 1316 verifyFormat("if (a) g();", AllowsMergedIf); 1317 verifyFormat("if (a) {\n" 1318 " g()\n" 1319 "};", 1320 AllowsMergedIf); 1321 verifyFormat("if (a) g();\n" 1322 "else g();", 1323 AllowsMergedIf); 1324 verifyFormat("if (a) {\n" 1325 " g();\n" 1326 "} else g();", 1327 AllowsMergedIf); 1328 verifyFormat("if (a) g();\n" 1329 "else {\n" 1330 " g();\n" 1331 "}", 1332 AllowsMergedIf); 1333 verifyFormat("if (a) {\n" 1334 " g();\n" 1335 "} else {\n" 1336 " g();\n" 1337 "}", 1338 AllowsMergedIf); 1339 verifyFormat("if (a) g();\n" 1340 "else if (b) g();\n" 1341 "else g();", 1342 AllowsMergedIf); 1343 verifyFormat("if (a) {\n" 1344 " g();\n" 1345 "} else if (b) g();\n" 1346 "else g();", 1347 AllowsMergedIf); 1348 verifyFormat("if (a) g();\n" 1349 "else if (b) {\n" 1350 " g();\n" 1351 "} else g();", 1352 AllowsMergedIf); 1353 verifyFormat("if (a) g();\n" 1354 "else if (b) g();\n" 1355 "else {\n" 1356 " g();\n" 1357 "}", 1358 AllowsMergedIf); 1359 verifyFormat("if (a) g();\n" 1360 "else if (b) {\n" 1361 " g();\n" 1362 "} else {\n" 1363 " g();\n" 1364 "}", 1365 AllowsMergedIf); 1366 verifyFormat("if (a) {\n" 1367 " g();\n" 1368 "} else if (b) {\n" 1369 " g();\n" 1370 "} else {\n" 1371 " g();\n" 1372 "}", 1373 AllowsMergedIf); 1374 verifyFormat("MYIF (a) f();\n" 1375 "else {\n" 1376 " g();\n" 1377 "}", 1378 AllowsMergedIf); 1379 verifyFormat("MYIF (a) f();\n" 1380 "else {\n" 1381 " if (a) f();\n" 1382 " else {\n" 1383 " g();\n" 1384 " }\n" 1385 " g();\n" 1386 "}", 1387 AllowsMergedIf); 1388 1389 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1390 verifyFormat("MYIF (a) {\n" 1391 " g()\n" 1392 "};", 1393 AllowsMergedIf); 1394 verifyFormat("MYIF (a) g();\n" 1395 "else g();", 1396 AllowsMergedIf); 1397 verifyFormat("MYIF (a) {\n" 1398 " g();\n" 1399 "} else g();", 1400 AllowsMergedIf); 1401 verifyFormat("MYIF (a) g();\n" 1402 "else {\n" 1403 " g();\n" 1404 "}", 1405 AllowsMergedIf); 1406 verifyFormat("MYIF (a) {\n" 1407 " g();\n" 1408 "} else {\n" 1409 " g();\n" 1410 "}", 1411 AllowsMergedIf); 1412 verifyFormat("MYIF (a) g();\n" 1413 "else MYIF (b) g();\n" 1414 "else g();", 1415 AllowsMergedIf); 1416 verifyFormat("MYIF (a) g();\n" 1417 "else if (b) g();\n" 1418 "else g();", 1419 AllowsMergedIf); 1420 verifyFormat("MYIF (a) {\n" 1421 " g();\n" 1422 "} else MYIF (b) g();\n" 1423 "else g();", 1424 AllowsMergedIf); 1425 verifyFormat("MYIF (a) {\n" 1426 " g();\n" 1427 "} else if (b) g();\n" 1428 "else g();", 1429 AllowsMergedIf); 1430 verifyFormat("MYIF (a) g();\n" 1431 "else MYIF (b) {\n" 1432 " g();\n" 1433 "} else g();", 1434 AllowsMergedIf); 1435 verifyFormat("MYIF (a) g();\n" 1436 "else if (b) {\n" 1437 " g();\n" 1438 "} else g();", 1439 AllowsMergedIf); 1440 verifyFormat("MYIF (a) g();\n" 1441 "else MYIF (b) g();\n" 1442 "else {\n" 1443 " g();\n" 1444 "}", 1445 AllowsMergedIf); 1446 verifyFormat("MYIF (a) g();\n" 1447 "else if (b) g();\n" 1448 "else {\n" 1449 " g();\n" 1450 "}", 1451 AllowsMergedIf); 1452 verifyFormat("MYIF (a) g();\n" 1453 "else MYIF (b) {\n" 1454 " g();\n" 1455 "} else {\n" 1456 " g();\n" 1457 "}", 1458 AllowsMergedIf); 1459 verifyFormat("MYIF (a) g();\n" 1460 "else if (b) {\n" 1461 " g();\n" 1462 "} else {\n" 1463 " g();\n" 1464 "}", 1465 AllowsMergedIf); 1466 verifyFormat("MYIF (a) {\n" 1467 " g();\n" 1468 "} else MYIF (b) {\n" 1469 " g();\n" 1470 "} else {\n" 1471 " g();\n" 1472 "}", 1473 AllowsMergedIf); 1474 verifyFormat("MYIF (a) {\n" 1475 " g();\n" 1476 "} else if (b) {\n" 1477 " g();\n" 1478 "} else {\n" 1479 " g();\n" 1480 "}", 1481 AllowsMergedIf); 1482 } 1483 1484 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 1485 FormatStyle AllowsMergedLoops = getLLVMStyle(); 1486 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 1487 verifyFormat("while (true) continue;", AllowsMergedLoops); 1488 verifyFormat("for (;;) continue;", AllowsMergedLoops); 1489 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 1490 verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops); 1491 verifyFormat("while (true)\n" 1492 " ;", 1493 AllowsMergedLoops); 1494 verifyFormat("for (;;)\n" 1495 " ;", 1496 AllowsMergedLoops); 1497 verifyFormat("for (;;)\n" 1498 " for (;;) continue;", 1499 AllowsMergedLoops); 1500 verifyFormat("for (;;)\n" 1501 " while (true) continue;", 1502 AllowsMergedLoops); 1503 verifyFormat("while (true)\n" 1504 " for (;;) continue;", 1505 AllowsMergedLoops); 1506 verifyFormat("BOOST_FOREACH (int &v, vec)\n" 1507 " for (;;) continue;", 1508 AllowsMergedLoops); 1509 verifyFormat("for (;;)\n" 1510 " BOOST_FOREACH (int &v, vec) continue;", 1511 AllowsMergedLoops); 1512 verifyFormat("for (;;) // Can't merge this\n" 1513 " continue;", 1514 AllowsMergedLoops); 1515 verifyFormat("for (;;) /* still don't merge */\n" 1516 " continue;", 1517 AllowsMergedLoops); 1518 verifyFormat("do a++;\n" 1519 "while (true);", 1520 AllowsMergedLoops); 1521 verifyFormat("do /* Don't merge */\n" 1522 " a++;\n" 1523 "while (true);", 1524 AllowsMergedLoops); 1525 verifyFormat("do // Don't merge\n" 1526 " a++;\n" 1527 "while (true);", 1528 AllowsMergedLoops); 1529 verifyFormat("do\n" 1530 " // Don't merge\n" 1531 " a++;\n" 1532 "while (true);", 1533 AllowsMergedLoops); 1534 // Without braces labels are interpreted differently. 1535 verifyFormat("{\n" 1536 " do\n" 1537 " label:\n" 1538 " a++;\n" 1539 " while (true);\n" 1540 "}", 1541 AllowsMergedLoops); 1542 } 1543 1544 TEST_F(FormatTest, FormatShortBracedStatements) { 1545 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1546 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false); 1547 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine, 1548 FormatStyle::SIS_Never); 1549 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false); 1550 EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false); 1551 verifyFormat("for (;;) {\n" 1552 " f();\n" 1553 "}"); 1554 verifyFormat("/*comment*/ for (;;) {\n" 1555 " f();\n" 1556 "}"); 1557 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1558 " f();\n" 1559 "}"); 1560 verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n" 1561 " f();\n" 1562 "}"); 1563 verifyFormat("while (true) {\n" 1564 " f();\n" 1565 "}"); 1566 verifyFormat("/*comment*/ while (true) {\n" 1567 " f();\n" 1568 "}"); 1569 verifyFormat("if (true) {\n" 1570 " f();\n" 1571 "}"); 1572 verifyFormat("/*comment*/ if (true) {\n" 1573 " f();\n" 1574 "}"); 1575 1576 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1577 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1578 // Not IF to avoid any confusion that IF is somehow special. 1579 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1580 AllowSimpleBracedStatements.ColumnLimit = 40; 1581 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1582 FormatStyle::SBS_Always; 1583 1584 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1585 FormatStyle::SIS_WithoutElse; 1586 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1587 1588 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1589 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1590 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1591 1592 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1593 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1594 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1595 verifyFormat("if consteval {}", AllowSimpleBracedStatements); 1596 verifyFormat("if !consteval {}", AllowSimpleBracedStatements); 1597 verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements); 1598 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1599 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1600 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1601 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1602 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1603 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1604 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1605 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1606 verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements); 1607 verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1608 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1609 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1610 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1611 verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements); 1612 verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1613 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1614 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1615 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1616 AllowSimpleBracedStatements); 1617 verifyFormat("if (true) {\n" 1618 " ffffffffffffffffffffffff();\n" 1619 "}", 1620 AllowSimpleBracedStatements); 1621 verifyFormat("if (true) {\n" 1622 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1623 "}", 1624 AllowSimpleBracedStatements); 1625 verifyFormat("if (true) { //\n" 1626 " f();\n" 1627 "}", 1628 AllowSimpleBracedStatements); 1629 verifyFormat("if (true) {\n" 1630 " f();\n" 1631 " f();\n" 1632 "}", 1633 AllowSimpleBracedStatements); 1634 verifyFormat("if (true) {\n" 1635 " f();\n" 1636 "} else {\n" 1637 " f();\n" 1638 "}", 1639 AllowSimpleBracedStatements); 1640 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1641 AllowSimpleBracedStatements); 1642 verifyFormat("MYIF (true) {\n" 1643 " ffffffffffffffffffffffff();\n" 1644 "}", 1645 AllowSimpleBracedStatements); 1646 verifyFormat("MYIF (true) {\n" 1647 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1648 "}", 1649 AllowSimpleBracedStatements); 1650 verifyFormat("MYIF (true) { //\n" 1651 " f();\n" 1652 "}", 1653 AllowSimpleBracedStatements); 1654 verifyFormat("MYIF (true) {\n" 1655 " f();\n" 1656 " f();\n" 1657 "}", 1658 AllowSimpleBracedStatements); 1659 verifyFormat("MYIF (true) {\n" 1660 " f();\n" 1661 "} else {\n" 1662 " f();\n" 1663 "}", 1664 AllowSimpleBracedStatements); 1665 1666 verifyFormat("struct A2 {\n" 1667 " int X;\n" 1668 "};", 1669 AllowSimpleBracedStatements); 1670 verifyFormat("typedef struct A2 {\n" 1671 " int X;\n" 1672 "} A2_t;", 1673 AllowSimpleBracedStatements); 1674 verifyFormat("template <int> struct A2 {\n" 1675 " struct B {};\n" 1676 "};", 1677 AllowSimpleBracedStatements); 1678 1679 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1680 FormatStyle::SIS_Never; 1681 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1682 verifyFormat("if (true) {\n" 1683 " f();\n" 1684 "}", 1685 AllowSimpleBracedStatements); 1686 verifyFormat("if (true) {\n" 1687 " f();\n" 1688 "} else {\n" 1689 " f();\n" 1690 "}", 1691 AllowSimpleBracedStatements); 1692 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1693 verifyFormat("MYIF (true) {\n" 1694 " f();\n" 1695 "}", 1696 AllowSimpleBracedStatements); 1697 verifyFormat("MYIF (true) {\n" 1698 " f();\n" 1699 "} else {\n" 1700 " f();\n" 1701 "}", 1702 AllowSimpleBracedStatements); 1703 1704 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1705 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1706 verifyFormat("while (true) {\n" 1707 " f();\n" 1708 "}", 1709 AllowSimpleBracedStatements); 1710 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1711 verifyFormat("for (;;) {\n" 1712 " f();\n" 1713 "}", 1714 AllowSimpleBracedStatements); 1715 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1716 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1717 " f();\n" 1718 "}", 1719 AllowSimpleBracedStatements); 1720 1721 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1722 FormatStyle::SIS_WithoutElse; 1723 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1724 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1725 FormatStyle::BWACS_Always; 1726 1727 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1728 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1729 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1730 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1731 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1732 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1733 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1734 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1735 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1736 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1737 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1738 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1739 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1740 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1741 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1742 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1743 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1744 AllowSimpleBracedStatements); 1745 verifyFormat("if (true)\n" 1746 "{\n" 1747 " ffffffffffffffffffffffff();\n" 1748 "}", 1749 AllowSimpleBracedStatements); 1750 verifyFormat("if (true)\n" 1751 "{\n" 1752 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1753 "}", 1754 AllowSimpleBracedStatements); 1755 verifyFormat("if (true)\n" 1756 "{ //\n" 1757 " f();\n" 1758 "}", 1759 AllowSimpleBracedStatements); 1760 verifyFormat("if (true)\n" 1761 "{\n" 1762 " f();\n" 1763 " f();\n" 1764 "}", 1765 AllowSimpleBracedStatements); 1766 verifyFormat("if (true)\n" 1767 "{\n" 1768 " f();\n" 1769 "} else\n" 1770 "{\n" 1771 " f();\n" 1772 "}", 1773 AllowSimpleBracedStatements); 1774 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1775 AllowSimpleBracedStatements); 1776 verifyFormat("MYIF (true)\n" 1777 "{\n" 1778 " ffffffffffffffffffffffff();\n" 1779 "}", 1780 AllowSimpleBracedStatements); 1781 verifyFormat("MYIF (true)\n" 1782 "{\n" 1783 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1784 "}", 1785 AllowSimpleBracedStatements); 1786 verifyFormat("MYIF (true)\n" 1787 "{ //\n" 1788 " f();\n" 1789 "}", 1790 AllowSimpleBracedStatements); 1791 verifyFormat("MYIF (true)\n" 1792 "{\n" 1793 " f();\n" 1794 " f();\n" 1795 "}", 1796 AllowSimpleBracedStatements); 1797 verifyFormat("MYIF (true)\n" 1798 "{\n" 1799 " f();\n" 1800 "} else\n" 1801 "{\n" 1802 " f();\n" 1803 "}", 1804 AllowSimpleBracedStatements); 1805 1806 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1807 FormatStyle::SIS_Never; 1808 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1809 verifyFormat("if (true)\n" 1810 "{\n" 1811 " f();\n" 1812 "}", 1813 AllowSimpleBracedStatements); 1814 verifyFormat("if (true)\n" 1815 "{\n" 1816 " f();\n" 1817 "} else\n" 1818 "{\n" 1819 " f();\n" 1820 "}", 1821 AllowSimpleBracedStatements); 1822 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1823 verifyFormat("MYIF (true)\n" 1824 "{\n" 1825 " f();\n" 1826 "}", 1827 AllowSimpleBracedStatements); 1828 verifyFormat("MYIF (true)\n" 1829 "{\n" 1830 " f();\n" 1831 "} else\n" 1832 "{\n" 1833 " f();\n" 1834 "}", 1835 AllowSimpleBracedStatements); 1836 1837 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1838 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1839 verifyFormat("while (true)\n" 1840 "{\n" 1841 " f();\n" 1842 "}", 1843 AllowSimpleBracedStatements); 1844 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1845 verifyFormat("for (;;)\n" 1846 "{\n" 1847 " f();\n" 1848 "}", 1849 AllowSimpleBracedStatements); 1850 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1851 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1852 "{\n" 1853 " f();\n" 1854 "}", 1855 AllowSimpleBracedStatements); 1856 } 1857 1858 TEST_F(FormatTest, UnderstandsMacros) { 1859 verifyFormat("#define A (parentheses)"); 1860 verifyFormat("/* comment */ #define A (parentheses)"); 1861 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1862 // Even the partial code should never be merged. 1863 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1864 "#", 1865 format("/* comment */ #define A (parentheses)\n" 1866 "#")); 1867 verifyFormat("/* comment */ #define A (parentheses)\n" 1868 "#\n"); 1869 verifyFormat("/* comment */ #define A (parentheses)\n" 1870 "#define B (parentheses)"); 1871 verifyFormat("#define true ((int)1)"); 1872 verifyFormat("#define and(x)"); 1873 verifyFormat("#define if(x) x"); 1874 verifyFormat("#define return(x) (x)"); 1875 verifyFormat("#define while(x) for (; x;)"); 1876 verifyFormat("#define xor(x) (^(x))"); 1877 verifyFormat("#define __except(x)"); 1878 verifyFormat("#define __try(x)"); 1879 1880 // https://llvm.org/PR54348. 1881 verifyFormat( 1882 "#define A" 1883 " " 1884 "\\\n" 1885 " class & {}"); 1886 1887 FormatStyle Style = getLLVMStyle(); 1888 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1889 Style.BraceWrapping.AfterFunction = true; 1890 // Test that a macro definition never gets merged with the following 1891 // definition. 1892 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1893 verifyFormat("#define AAA " 1894 " \\\n" 1895 " N " 1896 " \\\n" 1897 " {\n" 1898 "#define BBB }\n", 1899 Style); 1900 // verifyFormat("#define AAA N { //\n", Style); 1901 1902 verifyFormat("MACRO(return)"); 1903 verifyFormat("MACRO(co_await)"); 1904 verifyFormat("MACRO(co_return)"); 1905 verifyFormat("MACRO(co_yield)"); 1906 verifyFormat("MACRO(return, something)"); 1907 verifyFormat("MACRO(co_return, something)"); 1908 verifyFormat("MACRO(something##something)"); 1909 verifyFormat("MACRO(return##something)"); 1910 verifyFormat("MACRO(co_return##something)"); 1911 } 1912 1913 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1914 FormatStyle Style = getLLVMStyleWithColumns(60); 1915 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1916 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1917 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1918 EXPECT_EQ("#define A \\\n" 1919 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1920 " { \\\n" 1921 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1922 " }\n" 1923 "X;", 1924 format("#define A \\\n" 1925 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1926 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1927 " }\n" 1928 "X;", 1929 Style)); 1930 } 1931 1932 TEST_F(FormatTest, ParseIfElse) { 1933 verifyFormat("if (true)\n" 1934 " if (true)\n" 1935 " if (true)\n" 1936 " f();\n" 1937 " else\n" 1938 " g();\n" 1939 " else\n" 1940 " h();\n" 1941 "else\n" 1942 " i();"); 1943 verifyFormat("if (true)\n" 1944 " if (true)\n" 1945 " if (true) {\n" 1946 " if (true)\n" 1947 " f();\n" 1948 " } else {\n" 1949 " g();\n" 1950 " }\n" 1951 " else\n" 1952 " h();\n" 1953 "else {\n" 1954 " i();\n" 1955 "}"); 1956 verifyFormat("if (true)\n" 1957 " if constexpr (true)\n" 1958 " if (true) {\n" 1959 " if constexpr (true)\n" 1960 " f();\n" 1961 " } else {\n" 1962 " g();\n" 1963 " }\n" 1964 " else\n" 1965 " h();\n" 1966 "else {\n" 1967 " i();\n" 1968 "}"); 1969 verifyFormat("if (true)\n" 1970 " if CONSTEXPR (true)\n" 1971 " if (true) {\n" 1972 " if CONSTEXPR (true)\n" 1973 " f();\n" 1974 " } else {\n" 1975 " g();\n" 1976 " }\n" 1977 " else\n" 1978 " h();\n" 1979 "else {\n" 1980 " i();\n" 1981 "}"); 1982 verifyFormat("void f() {\n" 1983 " if (a) {\n" 1984 " } else {\n" 1985 " }\n" 1986 "}"); 1987 } 1988 1989 TEST_F(FormatTest, ElseIf) { 1990 verifyFormat("if (a) {\n} else if (b) {\n}"); 1991 verifyFormat("if (a)\n" 1992 " f();\n" 1993 "else if (b)\n" 1994 " g();\n" 1995 "else\n" 1996 " h();"); 1997 verifyFormat("if (a)\n" 1998 " f();\n" 1999 "else // comment\n" 2000 " if (b) {\n" 2001 " g();\n" 2002 " h();\n" 2003 " }"); 2004 verifyFormat("if constexpr (a)\n" 2005 " f();\n" 2006 "else if constexpr (b)\n" 2007 " g();\n" 2008 "else\n" 2009 " h();"); 2010 verifyFormat("if CONSTEXPR (a)\n" 2011 " f();\n" 2012 "else if CONSTEXPR (b)\n" 2013 " g();\n" 2014 "else\n" 2015 " h();"); 2016 verifyFormat("if (a) {\n" 2017 " f();\n" 2018 "}\n" 2019 "// or else ..\n" 2020 "else {\n" 2021 " g()\n" 2022 "}"); 2023 2024 verifyFormat("if (a) {\n" 2025 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2026 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2027 "}"); 2028 verifyFormat("if (a) {\n" 2029 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2030 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2031 "}"); 2032 verifyFormat("if (a) {\n" 2033 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2034 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2035 "}"); 2036 verifyFormat("if (a) {\n" 2037 "} else if (\n" 2038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2039 "}", 2040 getLLVMStyleWithColumns(62)); 2041 verifyFormat("if (a) {\n" 2042 "} else if constexpr (\n" 2043 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2044 "}", 2045 getLLVMStyleWithColumns(62)); 2046 verifyFormat("if (a) {\n" 2047 "} else if CONSTEXPR (\n" 2048 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2049 "}", 2050 getLLVMStyleWithColumns(62)); 2051 } 2052 2053 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2054 FormatStyle Style = getLLVMStyle(); 2055 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2056 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2057 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2058 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2059 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2060 verifyFormat("int *f1(int &a) const &;", Style); 2061 verifyFormat("int *f1(int &a) const & = 0;", Style); 2062 verifyFormat("int *a = f1();", Style); 2063 verifyFormat("int &b = f2();", Style); 2064 verifyFormat("int &&c = f3();", Style); 2065 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2066 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2067 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2068 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2069 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2070 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2071 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2072 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2073 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2074 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2075 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2076 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2077 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2078 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2079 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2080 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2081 verifyFormat( 2082 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2083 " res2 = [](int &a) { return 0000000000000; };", 2084 Style); 2085 2086 Style.AlignConsecutiveDeclarations.Enabled = true; 2087 verifyFormat("Const unsigned int *c;\n" 2088 "const unsigned int *d;\n" 2089 "Const unsigned int &e;\n" 2090 "const unsigned int &f;\n" 2091 "const unsigned &&g;\n" 2092 "Const unsigned h;", 2093 Style); 2094 2095 Style.PointerAlignment = FormatStyle::PAS_Left; 2096 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2097 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2098 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2099 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2100 verifyFormat("int* f1(int& a) const& = 0;", Style); 2101 verifyFormat("int* a = f1();", Style); 2102 verifyFormat("int& b = f2();", Style); 2103 verifyFormat("int&& c = f3();", Style); 2104 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2105 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2106 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2107 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2108 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2109 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2110 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2111 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2112 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2113 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2114 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2115 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2116 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2117 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2118 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2119 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2120 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2121 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2122 verifyFormat( 2123 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2124 " res2 = [](int& a) { return 0000000000000; };", 2125 Style); 2126 2127 Style.AlignConsecutiveDeclarations.Enabled = true; 2128 verifyFormat("Const unsigned int* c;\n" 2129 "const unsigned int* d;\n" 2130 "Const unsigned int& e;\n" 2131 "const unsigned int& f;\n" 2132 "const unsigned&& g;\n" 2133 "Const unsigned h;", 2134 Style); 2135 2136 Style.PointerAlignment = FormatStyle::PAS_Right; 2137 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2138 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2139 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2140 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2141 verifyFormat("int *a = f1();", Style); 2142 verifyFormat("int& b = f2();", Style); 2143 verifyFormat("int&& c = f3();", Style); 2144 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2145 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2146 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2147 2148 Style.AlignConsecutiveDeclarations.Enabled = true; 2149 verifyFormat("Const unsigned int *c;\n" 2150 "const unsigned int *d;\n" 2151 "Const unsigned int& e;\n" 2152 "const unsigned int& f;\n" 2153 "const unsigned g;\n" 2154 "Const unsigned h;", 2155 Style); 2156 2157 Style.PointerAlignment = FormatStyle::PAS_Left; 2158 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2159 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2160 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2161 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2162 verifyFormat("int* a = f1();", Style); 2163 verifyFormat("int & b = f2();", Style); 2164 verifyFormat("int && c = f3();", Style); 2165 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2166 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2167 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2168 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2169 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2170 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2171 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2172 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2173 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2174 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2175 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2176 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2177 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2178 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2179 verifyFormat( 2180 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2181 " res2 = [](int & a) { return 0000000000000; };", 2182 Style); 2183 2184 Style.AlignConsecutiveDeclarations.Enabled = true; 2185 verifyFormat("Const unsigned int* c;\n" 2186 "const unsigned int* d;\n" 2187 "Const unsigned int & e;\n" 2188 "const unsigned int & f;\n" 2189 "const unsigned && g;\n" 2190 "Const unsigned h;", 2191 Style); 2192 2193 Style.PointerAlignment = FormatStyle::PAS_Middle; 2194 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2195 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2196 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2197 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2198 verifyFormat("int * a = f1();", Style); 2199 verifyFormat("int &b = f2();", Style); 2200 verifyFormat("int &&c = f3();", Style); 2201 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2202 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2203 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2204 2205 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2206 // specifically handled 2207 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2208 } 2209 2210 TEST_F(FormatTest, FormatsForLoop) { 2211 verifyFormat( 2212 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2213 " ++VeryVeryLongLoopVariable)\n" 2214 " ;"); 2215 verifyFormat("for (;;)\n" 2216 " f();"); 2217 verifyFormat("for (;;) {\n}"); 2218 verifyFormat("for (;;) {\n" 2219 " f();\n" 2220 "}"); 2221 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2222 2223 verifyFormat( 2224 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2225 " E = UnwrappedLines.end();\n" 2226 " I != E; ++I) {\n}"); 2227 2228 verifyFormat( 2229 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2230 " ++IIIII) {\n}"); 2231 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2232 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2233 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2234 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2235 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2236 " E = FD->getDeclsInPrototypeScope().end();\n" 2237 " I != E; ++I) {\n}"); 2238 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2239 " I = Container.begin(),\n" 2240 " E = Container.end();\n" 2241 " I != E; ++I) {\n}", 2242 getLLVMStyleWithColumns(76)); 2243 2244 verifyFormat( 2245 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2246 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2247 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2248 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2249 " ++aaaaaaaaaaa) {\n}"); 2250 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2251 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2252 " ++i) {\n}"); 2253 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2254 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2255 "}"); 2256 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2257 " aaaaaaaaaa);\n" 2258 " iter; ++iter) {\n" 2259 "}"); 2260 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2261 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2262 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2263 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2264 2265 // These should not be formatted as Objective-C for-in loops. 2266 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2267 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2268 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2269 verifyFormat( 2270 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2271 2272 FormatStyle NoBinPacking = getLLVMStyle(); 2273 NoBinPacking.BinPackParameters = false; 2274 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2275 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2276 " aaaaaaaaaaaaaaaa,\n" 2277 " aaaaaaaaaaaaaaaa,\n" 2278 " aaaaaaaaaaaaaaaa);\n" 2279 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2280 "}", 2281 NoBinPacking); 2282 verifyFormat( 2283 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2284 " E = UnwrappedLines.end();\n" 2285 " I != E;\n" 2286 " ++I) {\n}", 2287 NoBinPacking); 2288 2289 FormatStyle AlignLeft = getLLVMStyle(); 2290 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2291 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2292 } 2293 2294 TEST_F(FormatTest, RangeBasedForLoops) { 2295 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2296 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2297 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2298 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2299 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2300 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2301 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2302 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2303 } 2304 2305 TEST_F(FormatTest, ForEachLoops) { 2306 FormatStyle Style = getLLVMStyle(); 2307 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2308 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2309 verifyFormat("void f() {\n" 2310 " for (;;) {\n" 2311 " }\n" 2312 " foreach (Item *item, itemlist) {\n" 2313 " }\n" 2314 " Q_FOREACH (Item *item, itemlist) {\n" 2315 " }\n" 2316 " BOOST_FOREACH (Item *item, itemlist) {\n" 2317 " }\n" 2318 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2319 "}", 2320 Style); 2321 verifyFormat("void f() {\n" 2322 " for (;;)\n" 2323 " int j = 1;\n" 2324 " Q_FOREACH (int v, vec)\n" 2325 " v *= 2;\n" 2326 " for (;;) {\n" 2327 " int j = 1;\n" 2328 " }\n" 2329 " Q_FOREACH (int v, vec) {\n" 2330 " v *= 2;\n" 2331 " }\n" 2332 "}", 2333 Style); 2334 2335 FormatStyle ShortBlocks = getLLVMStyle(); 2336 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2337 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2338 verifyFormat("void f() {\n" 2339 " for (;;)\n" 2340 " int j = 1;\n" 2341 " Q_FOREACH (int &v, vec)\n" 2342 " v *= 2;\n" 2343 " for (;;) {\n" 2344 " int j = 1;\n" 2345 " }\n" 2346 " Q_FOREACH (int &v, vec) {\n" 2347 " int j = 1;\n" 2348 " }\n" 2349 "}", 2350 ShortBlocks); 2351 2352 FormatStyle ShortLoops = getLLVMStyle(); 2353 ShortLoops.AllowShortLoopsOnASingleLine = true; 2354 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2355 verifyFormat("void f() {\n" 2356 " for (;;) int j = 1;\n" 2357 " Q_FOREACH (int &v, vec) int j = 1;\n" 2358 " for (;;) {\n" 2359 " int j = 1;\n" 2360 " }\n" 2361 " Q_FOREACH (int &v, vec) {\n" 2362 " int j = 1;\n" 2363 " }\n" 2364 "}", 2365 ShortLoops); 2366 2367 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2368 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2369 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2370 verifyFormat("void f() {\n" 2371 " for (;;) int j = 1;\n" 2372 " Q_FOREACH (int &v, vec) int j = 1;\n" 2373 " for (;;) { int j = 1; }\n" 2374 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2375 "}", 2376 ShortBlocksAndLoops); 2377 2378 Style.SpaceBeforeParens = 2379 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2380 verifyFormat("void f() {\n" 2381 " for (;;) {\n" 2382 " }\n" 2383 " foreach(Item *item, itemlist) {\n" 2384 " }\n" 2385 " Q_FOREACH(Item *item, itemlist) {\n" 2386 " }\n" 2387 " BOOST_FOREACH(Item *item, itemlist) {\n" 2388 " }\n" 2389 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2390 "}", 2391 Style); 2392 2393 // As function-like macros. 2394 verifyFormat("#define foreach(x, y)\n" 2395 "#define Q_FOREACH(x, y)\n" 2396 "#define BOOST_FOREACH(x, y)\n" 2397 "#define UNKNOWN_FOREACH(x, y)\n"); 2398 2399 // Not as function-like macros. 2400 verifyFormat("#define foreach (x, y)\n" 2401 "#define Q_FOREACH (x, y)\n" 2402 "#define BOOST_FOREACH (x, y)\n" 2403 "#define UNKNOWN_FOREACH (x, y)\n"); 2404 2405 // handle microsoft non standard extension 2406 verifyFormat("for each (char c in x->MyStringProperty)"); 2407 } 2408 2409 TEST_F(FormatTest, FormatsWhileLoop) { 2410 verifyFormat("while (true) {\n}"); 2411 verifyFormat("while (true)\n" 2412 " f();"); 2413 verifyFormat("while () {\n}"); 2414 verifyFormat("while () {\n" 2415 " f();\n" 2416 "}"); 2417 } 2418 2419 TEST_F(FormatTest, FormatsDoWhile) { 2420 verifyFormat("do {\n" 2421 " do_something();\n" 2422 "} while (something());"); 2423 verifyFormat("do\n" 2424 " do_something();\n" 2425 "while (something());"); 2426 } 2427 2428 TEST_F(FormatTest, FormatsSwitchStatement) { 2429 verifyFormat("switch (x) {\n" 2430 "case 1:\n" 2431 " f();\n" 2432 " break;\n" 2433 "case kFoo:\n" 2434 "case ns::kBar:\n" 2435 "case kBaz:\n" 2436 " break;\n" 2437 "default:\n" 2438 " g();\n" 2439 " break;\n" 2440 "}"); 2441 verifyFormat("switch (x) {\n" 2442 "case 1: {\n" 2443 " f();\n" 2444 " break;\n" 2445 "}\n" 2446 "case 2: {\n" 2447 " break;\n" 2448 "}\n" 2449 "}"); 2450 verifyFormat("switch (x) {\n" 2451 "case 1: {\n" 2452 " f();\n" 2453 " {\n" 2454 " g();\n" 2455 " h();\n" 2456 " }\n" 2457 " break;\n" 2458 "}\n" 2459 "}"); 2460 verifyFormat("switch (x) {\n" 2461 "case 1: {\n" 2462 " f();\n" 2463 " if (foo) {\n" 2464 " g();\n" 2465 " h();\n" 2466 " }\n" 2467 " break;\n" 2468 "}\n" 2469 "}"); 2470 verifyFormat("switch (x) {\n" 2471 "case 1: {\n" 2472 " f();\n" 2473 " g();\n" 2474 "} break;\n" 2475 "}"); 2476 verifyFormat("switch (test)\n" 2477 " ;"); 2478 verifyFormat("switch (x) {\n" 2479 "default: {\n" 2480 " // Do nothing.\n" 2481 "}\n" 2482 "}"); 2483 verifyFormat("switch (x) {\n" 2484 "// comment\n" 2485 "// if 1, do f()\n" 2486 "case 1:\n" 2487 " f();\n" 2488 "}"); 2489 verifyFormat("switch (x) {\n" 2490 "case 1:\n" 2491 " // Do amazing stuff\n" 2492 " {\n" 2493 " f();\n" 2494 " g();\n" 2495 " }\n" 2496 " break;\n" 2497 "}"); 2498 verifyFormat("#define A \\\n" 2499 " switch (x) { \\\n" 2500 " case a: \\\n" 2501 " foo = b; \\\n" 2502 " }", 2503 getLLVMStyleWithColumns(20)); 2504 verifyFormat("#define OPERATION_CASE(name) \\\n" 2505 " case OP_name: \\\n" 2506 " return operations::Operation##name\n", 2507 getLLVMStyleWithColumns(40)); 2508 verifyFormat("switch (x) {\n" 2509 "case 1:;\n" 2510 "default:;\n" 2511 " int i;\n" 2512 "}"); 2513 2514 verifyGoogleFormat("switch (x) {\n" 2515 " case 1:\n" 2516 " f();\n" 2517 " break;\n" 2518 " case kFoo:\n" 2519 " case ns::kBar:\n" 2520 " case kBaz:\n" 2521 " break;\n" 2522 " default:\n" 2523 " g();\n" 2524 " break;\n" 2525 "}"); 2526 verifyGoogleFormat("switch (x) {\n" 2527 " case 1: {\n" 2528 " f();\n" 2529 " break;\n" 2530 " }\n" 2531 "}"); 2532 verifyGoogleFormat("switch (test)\n" 2533 " ;"); 2534 2535 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2536 " case OP_name: \\\n" 2537 " return operations::Operation##name\n"); 2538 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2539 " // Get the correction operation class.\n" 2540 " switch (OpCode) {\n" 2541 " CASE(Add);\n" 2542 " CASE(Subtract);\n" 2543 " default:\n" 2544 " return operations::Unknown;\n" 2545 " }\n" 2546 "#undef OPERATION_CASE\n" 2547 "}"); 2548 verifyFormat("DEBUG({\n" 2549 " switch (x) {\n" 2550 " case A:\n" 2551 " f();\n" 2552 " break;\n" 2553 " // fallthrough\n" 2554 " case B:\n" 2555 " g();\n" 2556 " break;\n" 2557 " }\n" 2558 "});"); 2559 EXPECT_EQ("DEBUG({\n" 2560 " switch (x) {\n" 2561 " case A:\n" 2562 " f();\n" 2563 " break;\n" 2564 " // On B:\n" 2565 " case B:\n" 2566 " g();\n" 2567 " break;\n" 2568 " }\n" 2569 "});", 2570 format("DEBUG({\n" 2571 " switch (x) {\n" 2572 " case A:\n" 2573 " f();\n" 2574 " break;\n" 2575 " // On B:\n" 2576 " case B:\n" 2577 " g();\n" 2578 " break;\n" 2579 " }\n" 2580 "});", 2581 getLLVMStyle())); 2582 EXPECT_EQ("switch (n) {\n" 2583 "case 0: {\n" 2584 " return false;\n" 2585 "}\n" 2586 "default: {\n" 2587 " return true;\n" 2588 "}\n" 2589 "}", 2590 format("switch (n)\n" 2591 "{\n" 2592 "case 0: {\n" 2593 " return false;\n" 2594 "}\n" 2595 "default: {\n" 2596 " return true;\n" 2597 "}\n" 2598 "}", 2599 getLLVMStyle())); 2600 verifyFormat("switch (a) {\n" 2601 "case (b):\n" 2602 " return;\n" 2603 "}"); 2604 2605 verifyFormat("switch (a) {\n" 2606 "case some_namespace::\n" 2607 " some_constant:\n" 2608 " return;\n" 2609 "}", 2610 getLLVMStyleWithColumns(34)); 2611 2612 verifyFormat("switch (a) {\n" 2613 "[[likely]] case 1:\n" 2614 " return;\n" 2615 "}"); 2616 verifyFormat("switch (a) {\n" 2617 "[[likely]] [[other::likely]] case 1:\n" 2618 " return;\n" 2619 "}"); 2620 verifyFormat("switch (x) {\n" 2621 "case 1:\n" 2622 " return;\n" 2623 "[[likely]] case 2:\n" 2624 " return;\n" 2625 "}"); 2626 verifyFormat("switch (a) {\n" 2627 "case 1:\n" 2628 "[[likely]] case 2:\n" 2629 " return;\n" 2630 "}"); 2631 FormatStyle Attributes = getLLVMStyle(); 2632 Attributes.AttributeMacros.push_back("LIKELY"); 2633 Attributes.AttributeMacros.push_back("OTHER_LIKELY"); 2634 verifyFormat("switch (a) {\n" 2635 "LIKELY case b:\n" 2636 " return;\n" 2637 "}", 2638 Attributes); 2639 verifyFormat("switch (a) {\n" 2640 "LIKELY OTHER_LIKELY() case b:\n" 2641 " return;\n" 2642 "}", 2643 Attributes); 2644 verifyFormat("switch (a) {\n" 2645 "case 1:\n" 2646 " return;\n" 2647 "LIKELY case 2:\n" 2648 " return;\n" 2649 "}", 2650 Attributes); 2651 verifyFormat("switch (a) {\n" 2652 "case 1:\n" 2653 "LIKELY case 2:\n" 2654 " return;\n" 2655 "}", 2656 Attributes); 2657 2658 FormatStyle Style = getLLVMStyle(); 2659 Style.IndentCaseLabels = true; 2660 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2661 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2662 Style.BraceWrapping.AfterCaseLabel = true; 2663 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2664 EXPECT_EQ("switch (n)\n" 2665 "{\n" 2666 " case 0:\n" 2667 " {\n" 2668 " return false;\n" 2669 " }\n" 2670 " default:\n" 2671 " {\n" 2672 " return true;\n" 2673 " }\n" 2674 "}", 2675 format("switch (n) {\n" 2676 " case 0: {\n" 2677 " return false;\n" 2678 " }\n" 2679 " default: {\n" 2680 " return true;\n" 2681 " }\n" 2682 "}", 2683 Style)); 2684 Style.BraceWrapping.AfterCaseLabel = false; 2685 EXPECT_EQ("switch (n)\n" 2686 "{\n" 2687 " case 0: {\n" 2688 " return false;\n" 2689 " }\n" 2690 " default: {\n" 2691 " return true;\n" 2692 " }\n" 2693 "}", 2694 format("switch (n) {\n" 2695 " case 0:\n" 2696 " {\n" 2697 " return false;\n" 2698 " }\n" 2699 " default:\n" 2700 " {\n" 2701 " return true;\n" 2702 " }\n" 2703 "}", 2704 Style)); 2705 Style.IndentCaseLabels = false; 2706 Style.IndentCaseBlocks = true; 2707 EXPECT_EQ("switch (n)\n" 2708 "{\n" 2709 "case 0:\n" 2710 " {\n" 2711 " return false;\n" 2712 " }\n" 2713 "case 1:\n" 2714 " break;\n" 2715 "default:\n" 2716 " {\n" 2717 " return true;\n" 2718 " }\n" 2719 "}", 2720 format("switch (n) {\n" 2721 "case 0: {\n" 2722 " return false;\n" 2723 "}\n" 2724 "case 1:\n" 2725 " break;\n" 2726 "default: {\n" 2727 " return true;\n" 2728 "}\n" 2729 "}", 2730 Style)); 2731 Style.IndentCaseLabels = true; 2732 Style.IndentCaseBlocks = true; 2733 EXPECT_EQ("switch (n)\n" 2734 "{\n" 2735 " case 0:\n" 2736 " {\n" 2737 " return false;\n" 2738 " }\n" 2739 " case 1:\n" 2740 " break;\n" 2741 " default:\n" 2742 " {\n" 2743 " return true;\n" 2744 " }\n" 2745 "}", 2746 format("switch (n) {\n" 2747 "case 0: {\n" 2748 " return false;\n" 2749 "}\n" 2750 "case 1:\n" 2751 " break;\n" 2752 "default: {\n" 2753 " return true;\n" 2754 "}\n" 2755 "}", 2756 Style)); 2757 } 2758 2759 TEST_F(FormatTest, CaseRanges) { 2760 verifyFormat("switch (x) {\n" 2761 "case 'A' ... 'Z':\n" 2762 "case 1 ... 5:\n" 2763 "case a ... b:\n" 2764 " break;\n" 2765 "}"); 2766 } 2767 2768 TEST_F(FormatTest, ShortEnums) { 2769 FormatStyle Style = getLLVMStyle(); 2770 EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine); 2771 EXPECT_FALSE(Style.BraceWrapping.AfterEnum); 2772 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2773 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2774 Style.AllowShortEnumsOnASingleLine = false; 2775 verifyFormat("enum {\n" 2776 " A,\n" 2777 " B,\n" 2778 " C\n" 2779 "} ShortEnum1, ShortEnum2;", 2780 Style); 2781 verifyFormat("typedef enum {\n" 2782 " A,\n" 2783 " B,\n" 2784 " C\n" 2785 "} ShortEnum1, ShortEnum2;", 2786 Style); 2787 verifyFormat("enum {\n" 2788 " A,\n" 2789 "} ShortEnum1, ShortEnum2;", 2790 Style); 2791 verifyFormat("typedef enum {\n" 2792 " A,\n" 2793 "} ShortEnum1, ShortEnum2;", 2794 Style); 2795 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2796 Style.BraceWrapping.AfterEnum = true; 2797 verifyFormat("enum\n" 2798 "{\n" 2799 " A,\n" 2800 " B,\n" 2801 " C\n" 2802 "} ShortEnum1, ShortEnum2;", 2803 Style); 2804 verifyFormat("typedef enum\n" 2805 "{\n" 2806 " A,\n" 2807 " B,\n" 2808 " C\n" 2809 "} ShortEnum1, ShortEnum2;", 2810 Style); 2811 } 2812 2813 TEST_F(FormatTest, ShortCaseLabels) { 2814 FormatStyle Style = getLLVMStyle(); 2815 Style.AllowShortCaseLabelsOnASingleLine = true; 2816 verifyFormat("switch (a) {\n" 2817 "case 1: x = 1; break;\n" 2818 "case 2: return;\n" 2819 "case 3:\n" 2820 "case 4:\n" 2821 "case 5: return;\n" 2822 "case 6: // comment\n" 2823 " return;\n" 2824 "case 7:\n" 2825 " // comment\n" 2826 " return;\n" 2827 "case 8:\n" 2828 " x = 8; // comment\n" 2829 " break;\n" 2830 "default: y = 1; break;\n" 2831 "}", 2832 Style); 2833 verifyFormat("switch (a) {\n" 2834 "case 0: return; // comment\n" 2835 "case 1: break; // comment\n" 2836 "case 2: return;\n" 2837 "// comment\n" 2838 "case 3: return;\n" 2839 "// comment 1\n" 2840 "// comment 2\n" 2841 "// comment 3\n" 2842 "case 4: break; /* comment */\n" 2843 "case 5:\n" 2844 " // comment\n" 2845 " break;\n" 2846 "case 6: /* comment */ x = 1; break;\n" 2847 "case 7: x = /* comment */ 1; break;\n" 2848 "case 8:\n" 2849 " x = 1; /* comment */\n" 2850 " break;\n" 2851 "case 9:\n" 2852 " break; // comment line 1\n" 2853 " // comment line 2\n" 2854 "}", 2855 Style); 2856 EXPECT_EQ("switch (a) {\n" 2857 "case 1:\n" 2858 " x = 8;\n" 2859 " // fall through\n" 2860 "case 2: x = 8;\n" 2861 "// comment\n" 2862 "case 3:\n" 2863 " return; /* comment line 1\n" 2864 " * comment line 2 */\n" 2865 "case 4: i = 8;\n" 2866 "// something else\n" 2867 "#if FOO\n" 2868 "case 5: break;\n" 2869 "#endif\n" 2870 "}", 2871 format("switch (a) {\n" 2872 "case 1: x = 8;\n" 2873 " // fall through\n" 2874 "case 2:\n" 2875 " x = 8;\n" 2876 "// comment\n" 2877 "case 3:\n" 2878 " return; /* comment line 1\n" 2879 " * comment line 2 */\n" 2880 "case 4:\n" 2881 " i = 8;\n" 2882 "// something else\n" 2883 "#if FOO\n" 2884 "case 5: break;\n" 2885 "#endif\n" 2886 "}", 2887 Style)); 2888 EXPECT_EQ("switch (a) {\n" 2889 "case 0:\n" 2890 " return; // long long long long long long long long long long " 2891 "long long comment\n" 2892 " // line\n" 2893 "}", 2894 format("switch (a) {\n" 2895 "case 0: return; // long long long long long long long long " 2896 "long long long long comment line\n" 2897 "}", 2898 Style)); 2899 EXPECT_EQ("switch (a) {\n" 2900 "case 0:\n" 2901 " return; /* long long long long long long long long long long " 2902 "long long comment\n" 2903 " line */\n" 2904 "}", 2905 format("switch (a) {\n" 2906 "case 0: return; /* long long long long long long long long " 2907 "long long long long comment line */\n" 2908 "}", 2909 Style)); 2910 verifyFormat("switch (a) {\n" 2911 "#if FOO\n" 2912 "case 0: return 0;\n" 2913 "#endif\n" 2914 "}", 2915 Style); 2916 verifyFormat("switch (a) {\n" 2917 "case 1: {\n" 2918 "}\n" 2919 "case 2: {\n" 2920 " return;\n" 2921 "}\n" 2922 "case 3: {\n" 2923 " x = 1;\n" 2924 " return;\n" 2925 "}\n" 2926 "case 4:\n" 2927 " if (x)\n" 2928 " return;\n" 2929 "}", 2930 Style); 2931 Style.ColumnLimit = 21; 2932 verifyFormat("switch (a) {\n" 2933 "case 1: x = 1; break;\n" 2934 "case 2: return;\n" 2935 "case 3:\n" 2936 "case 4:\n" 2937 "case 5: return;\n" 2938 "default:\n" 2939 " y = 1;\n" 2940 " break;\n" 2941 "}", 2942 Style); 2943 Style.ColumnLimit = 80; 2944 Style.AllowShortCaseLabelsOnASingleLine = false; 2945 Style.IndentCaseLabels = true; 2946 EXPECT_EQ("switch (n) {\n" 2947 " default /*comments*/:\n" 2948 " return true;\n" 2949 " case 0:\n" 2950 " return false;\n" 2951 "}", 2952 format("switch (n) {\n" 2953 "default/*comments*/:\n" 2954 " return true;\n" 2955 "case 0:\n" 2956 " return false;\n" 2957 "}", 2958 Style)); 2959 Style.AllowShortCaseLabelsOnASingleLine = true; 2960 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2961 Style.BraceWrapping.AfterCaseLabel = true; 2962 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2963 EXPECT_EQ("switch (n)\n" 2964 "{\n" 2965 " case 0:\n" 2966 " {\n" 2967 " return false;\n" 2968 " }\n" 2969 " default:\n" 2970 " {\n" 2971 " return true;\n" 2972 " }\n" 2973 "}", 2974 format("switch (n) {\n" 2975 " case 0: {\n" 2976 " return false;\n" 2977 " }\n" 2978 " default:\n" 2979 " {\n" 2980 " return true;\n" 2981 " }\n" 2982 "}", 2983 Style)); 2984 } 2985 2986 TEST_F(FormatTest, FormatsLabels) { 2987 verifyFormat("void f() {\n" 2988 " some_code();\n" 2989 "test_label:\n" 2990 " some_other_code();\n" 2991 " {\n" 2992 " some_more_code();\n" 2993 " another_label:\n" 2994 " some_more_code();\n" 2995 " }\n" 2996 "}"); 2997 verifyFormat("{\n" 2998 " some_code();\n" 2999 "test_label:\n" 3000 " some_other_code();\n" 3001 "}"); 3002 verifyFormat("{\n" 3003 " some_code();\n" 3004 "test_label:;\n" 3005 " int i = 0;\n" 3006 "}"); 3007 FormatStyle Style = getLLVMStyle(); 3008 Style.IndentGotoLabels = false; 3009 verifyFormat("void f() {\n" 3010 " some_code();\n" 3011 "test_label:\n" 3012 " some_other_code();\n" 3013 " {\n" 3014 " some_more_code();\n" 3015 "another_label:\n" 3016 " some_more_code();\n" 3017 " }\n" 3018 "}", 3019 Style); 3020 verifyFormat("{\n" 3021 " some_code();\n" 3022 "test_label:\n" 3023 " some_other_code();\n" 3024 "}", 3025 Style); 3026 verifyFormat("{\n" 3027 " some_code();\n" 3028 "test_label:;\n" 3029 " int i = 0;\n" 3030 "}"); 3031 } 3032 3033 TEST_F(FormatTest, MultiLineControlStatements) { 3034 FormatStyle Style = getLLVMStyleWithColumns(20); 3035 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3036 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3037 // Short lines should keep opening brace on same line. 3038 EXPECT_EQ("if (foo) {\n" 3039 " bar();\n" 3040 "}", 3041 format("if(foo){bar();}", Style)); 3042 EXPECT_EQ("if (foo) {\n" 3043 " bar();\n" 3044 "} else {\n" 3045 " baz();\n" 3046 "}", 3047 format("if(foo){bar();}else{baz();}", Style)); 3048 EXPECT_EQ("if (foo && bar) {\n" 3049 " baz();\n" 3050 "}", 3051 format("if(foo&&bar){baz();}", Style)); 3052 EXPECT_EQ("if (foo) {\n" 3053 " bar();\n" 3054 "} else if (baz) {\n" 3055 " quux();\n" 3056 "}", 3057 format("if(foo){bar();}else if(baz){quux();}", Style)); 3058 EXPECT_EQ( 3059 "if (foo) {\n" 3060 " bar();\n" 3061 "} else if (baz) {\n" 3062 " quux();\n" 3063 "} else {\n" 3064 " foobar();\n" 3065 "}", 3066 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 3067 EXPECT_EQ("for (;;) {\n" 3068 " foo();\n" 3069 "}", 3070 format("for(;;){foo();}")); 3071 EXPECT_EQ("while (1) {\n" 3072 " foo();\n" 3073 "}", 3074 format("while(1){foo();}", Style)); 3075 EXPECT_EQ("switch (foo) {\n" 3076 "case bar:\n" 3077 " return;\n" 3078 "}", 3079 format("switch(foo){case bar:return;}", Style)); 3080 EXPECT_EQ("try {\n" 3081 " foo();\n" 3082 "} catch (...) {\n" 3083 " bar();\n" 3084 "}", 3085 format("try{foo();}catch(...){bar();}", Style)); 3086 EXPECT_EQ("do {\n" 3087 " foo();\n" 3088 "} while (bar &&\n" 3089 " baz);", 3090 format("do{foo();}while(bar&&baz);", Style)); 3091 // Long lines should put opening brace on new line. 3092 EXPECT_EQ("if (foo && bar &&\n" 3093 " baz)\n" 3094 "{\n" 3095 " quux();\n" 3096 "}", 3097 format("if(foo&&bar&&baz){quux();}", Style)); 3098 EXPECT_EQ("if (foo && bar &&\n" 3099 " baz)\n" 3100 "{\n" 3101 " quux();\n" 3102 "}", 3103 format("if (foo && bar &&\n" 3104 " baz) {\n" 3105 " quux();\n" 3106 "}", 3107 Style)); 3108 EXPECT_EQ("if (foo) {\n" 3109 " bar();\n" 3110 "} else if (baz ||\n" 3111 " quux)\n" 3112 "{\n" 3113 " foobar();\n" 3114 "}", 3115 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3116 EXPECT_EQ( 3117 "if (foo) {\n" 3118 " bar();\n" 3119 "} else if (baz ||\n" 3120 " quux)\n" 3121 "{\n" 3122 " foobar();\n" 3123 "} else {\n" 3124 " barbaz();\n" 3125 "}", 3126 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3127 Style)); 3128 EXPECT_EQ("for (int i = 0;\n" 3129 " i < 10; ++i)\n" 3130 "{\n" 3131 " foo();\n" 3132 "}", 3133 format("for(int i=0;i<10;++i){foo();}", Style)); 3134 EXPECT_EQ("foreach (int i,\n" 3135 " list)\n" 3136 "{\n" 3137 " foo();\n" 3138 "}", 3139 format("foreach(int i, list){foo();}", Style)); 3140 Style.ColumnLimit = 3141 40; // to concentrate at brace wrapping, not line wrap due to column limit 3142 EXPECT_EQ("foreach (int i, list) {\n" 3143 " foo();\n" 3144 "}", 3145 format("foreach(int i, list){foo();}", Style)); 3146 Style.ColumnLimit = 3147 20; // to concentrate at brace wrapping, not line wrap due to column limit 3148 EXPECT_EQ("while (foo || bar ||\n" 3149 " baz)\n" 3150 "{\n" 3151 " quux();\n" 3152 "}", 3153 format("while(foo||bar||baz){quux();}", Style)); 3154 EXPECT_EQ("switch (\n" 3155 " foo = barbaz)\n" 3156 "{\n" 3157 "case quux:\n" 3158 " return;\n" 3159 "}", 3160 format("switch(foo=barbaz){case quux:return;}", Style)); 3161 EXPECT_EQ("try {\n" 3162 " foo();\n" 3163 "} catch (\n" 3164 " Exception &bar)\n" 3165 "{\n" 3166 " baz();\n" 3167 "}", 3168 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3169 Style.ColumnLimit = 3170 40; // to concentrate at brace wrapping, not line wrap due to column limit 3171 EXPECT_EQ("try {\n" 3172 " foo();\n" 3173 "} catch (Exception &bar) {\n" 3174 " baz();\n" 3175 "}", 3176 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3177 Style.ColumnLimit = 3178 20; // to concentrate at brace wrapping, not line wrap due to column limit 3179 3180 Style.BraceWrapping.BeforeElse = true; 3181 EXPECT_EQ( 3182 "if (foo) {\n" 3183 " bar();\n" 3184 "}\n" 3185 "else if (baz ||\n" 3186 " quux)\n" 3187 "{\n" 3188 " foobar();\n" 3189 "}\n" 3190 "else {\n" 3191 " barbaz();\n" 3192 "}", 3193 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3194 Style)); 3195 3196 Style.BraceWrapping.BeforeCatch = true; 3197 EXPECT_EQ("try {\n" 3198 " foo();\n" 3199 "}\n" 3200 "catch (...) {\n" 3201 " baz();\n" 3202 "}", 3203 format("try{foo();}catch(...){baz();}", Style)); 3204 3205 Style.BraceWrapping.AfterFunction = true; 3206 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3207 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3208 Style.ColumnLimit = 80; 3209 verifyFormat("void shortfunction() { bar(); }", Style); 3210 3211 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3212 verifyFormat("void shortfunction()\n" 3213 "{\n" 3214 " bar();\n" 3215 "}", 3216 Style); 3217 } 3218 3219 TEST_F(FormatTest, BeforeWhile) { 3220 FormatStyle Style = getLLVMStyle(); 3221 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3222 3223 verifyFormat("do {\n" 3224 " foo();\n" 3225 "} while (1);", 3226 Style); 3227 Style.BraceWrapping.BeforeWhile = true; 3228 verifyFormat("do {\n" 3229 " foo();\n" 3230 "}\n" 3231 "while (1);", 3232 Style); 3233 } 3234 3235 //===----------------------------------------------------------------------===// 3236 // Tests for classes, namespaces, etc. 3237 //===----------------------------------------------------------------------===// 3238 3239 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3240 verifyFormat("class A {};"); 3241 } 3242 3243 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3244 verifyFormat("class A {\n" 3245 "public:\n" 3246 "public: // comment\n" 3247 "protected:\n" 3248 "private:\n" 3249 " void f() {}\n" 3250 "};"); 3251 verifyFormat("export class A {\n" 3252 "public:\n" 3253 "public: // comment\n" 3254 "protected:\n" 3255 "private:\n" 3256 " void f() {}\n" 3257 "};"); 3258 verifyGoogleFormat("class A {\n" 3259 " public:\n" 3260 " protected:\n" 3261 " private:\n" 3262 " void f() {}\n" 3263 "};"); 3264 verifyGoogleFormat("export class A {\n" 3265 " public:\n" 3266 " protected:\n" 3267 " private:\n" 3268 " void f() {}\n" 3269 "};"); 3270 verifyFormat("class A {\n" 3271 "public slots:\n" 3272 " void f1() {}\n" 3273 "public Q_SLOTS:\n" 3274 " void f2() {}\n" 3275 "protected slots:\n" 3276 " void f3() {}\n" 3277 "protected Q_SLOTS:\n" 3278 " void f4() {}\n" 3279 "private slots:\n" 3280 " void f5() {}\n" 3281 "private Q_SLOTS:\n" 3282 " void f6() {}\n" 3283 "signals:\n" 3284 " void g1();\n" 3285 "Q_SIGNALS:\n" 3286 " void g2();\n" 3287 "};"); 3288 3289 // Don't interpret 'signals' the wrong way. 3290 verifyFormat("signals.set();"); 3291 verifyFormat("for (Signals signals : f()) {\n}"); 3292 verifyFormat("{\n" 3293 " signals.set(); // This needs indentation.\n" 3294 "}"); 3295 verifyFormat("void f() {\n" 3296 "label:\n" 3297 " signals.baz();\n" 3298 "}"); 3299 verifyFormat("private[1];"); 3300 verifyFormat("testArray[public] = 1;"); 3301 verifyFormat("public();"); 3302 verifyFormat("myFunc(public);"); 3303 verifyFormat("std::vector<int> testVec = {private};"); 3304 verifyFormat("private.p = 1;"); 3305 verifyFormat("void function(private...){};"); 3306 verifyFormat("if (private && public)\n"); 3307 verifyFormat("private &= true;"); 3308 verifyFormat("int x = private * public;"); 3309 verifyFormat("public *= private;"); 3310 verifyFormat("int x = public + private;"); 3311 verifyFormat("private++;"); 3312 verifyFormat("++private;"); 3313 verifyFormat("public += private;"); 3314 verifyFormat("public = public - private;"); 3315 verifyFormat("public->foo();"); 3316 verifyFormat("private--;"); 3317 verifyFormat("--private;"); 3318 verifyFormat("public -= 1;"); 3319 verifyFormat("if (!private && !public)\n"); 3320 verifyFormat("public != private;"); 3321 verifyFormat("int x = public / private;"); 3322 verifyFormat("public /= 2;"); 3323 verifyFormat("public = public % 2;"); 3324 verifyFormat("public %= 2;"); 3325 verifyFormat("if (public < private)\n"); 3326 verifyFormat("public << private;"); 3327 verifyFormat("public <<= private;"); 3328 verifyFormat("if (public > private)\n"); 3329 verifyFormat("public >> private;"); 3330 verifyFormat("public >>= private;"); 3331 verifyFormat("public ^ private;"); 3332 verifyFormat("public ^= private;"); 3333 verifyFormat("public | private;"); 3334 verifyFormat("public |= private;"); 3335 verifyFormat("auto x = private ? 1 : 2;"); 3336 verifyFormat("if (public == private)\n"); 3337 verifyFormat("void foo(public, private)"); 3338 verifyFormat("public::foo();"); 3339 } 3340 3341 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3342 EXPECT_EQ("class A {\n" 3343 "public:\n" 3344 " void f();\n" 3345 "\n" 3346 "private:\n" 3347 " void g() {}\n" 3348 " // test\n" 3349 "protected:\n" 3350 " int h;\n" 3351 "};", 3352 format("class A {\n" 3353 "public:\n" 3354 "void f();\n" 3355 "private:\n" 3356 "void g() {}\n" 3357 "// test\n" 3358 "protected:\n" 3359 "int h;\n" 3360 "};")); 3361 EXPECT_EQ("class A {\n" 3362 "protected:\n" 3363 "public:\n" 3364 " void f();\n" 3365 "};", 3366 format("class A {\n" 3367 "protected:\n" 3368 "\n" 3369 "public:\n" 3370 "\n" 3371 " void f();\n" 3372 "};")); 3373 3374 // Even ensure proper spacing inside macros. 3375 EXPECT_EQ("#define B \\\n" 3376 " class A { \\\n" 3377 " protected: \\\n" 3378 " public: \\\n" 3379 " void f(); \\\n" 3380 " };", 3381 format("#define B \\\n" 3382 " class A { \\\n" 3383 " protected: \\\n" 3384 " \\\n" 3385 " public: \\\n" 3386 " \\\n" 3387 " void f(); \\\n" 3388 " };", 3389 getGoogleStyle())); 3390 // But don't remove empty lines after macros ending in access specifiers. 3391 EXPECT_EQ("#define A private:\n" 3392 "\n" 3393 "int i;", 3394 format("#define A private:\n" 3395 "\n" 3396 "int i;")); 3397 } 3398 3399 TEST_F(FormatTest, FormatsClasses) { 3400 verifyFormat("class A : public B {};"); 3401 verifyFormat("class A : public ::B {};"); 3402 3403 verifyFormat( 3404 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3405 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3406 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3407 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3408 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3409 verifyFormat( 3410 "class A : public B, public C, public D, public E, public F {};"); 3411 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3412 " public C,\n" 3413 " public D,\n" 3414 " public E,\n" 3415 " public F,\n" 3416 " public G {};"); 3417 3418 verifyFormat("class\n" 3419 " ReallyReallyLongClassName {\n" 3420 " int i;\n" 3421 "};", 3422 getLLVMStyleWithColumns(32)); 3423 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3424 " aaaaaaaaaaaaaaaa> {};"); 3425 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3426 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3427 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3428 verifyFormat("template <class R, class C>\n" 3429 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3430 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3431 verifyFormat("class ::A::B {};"); 3432 } 3433 3434 TEST_F(FormatTest, BreakInheritanceStyle) { 3435 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3436 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3437 FormatStyle::BILS_BeforeComma; 3438 verifyFormat("class MyClass : public X {};", 3439 StyleWithInheritanceBreakBeforeComma); 3440 verifyFormat("class MyClass\n" 3441 " : public X\n" 3442 " , public Y {};", 3443 StyleWithInheritanceBreakBeforeComma); 3444 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3445 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3446 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3447 StyleWithInheritanceBreakBeforeComma); 3448 verifyFormat("struct aaaaaaaaaaaaa\n" 3449 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3450 " aaaaaaaaaaaaaaaa> {};", 3451 StyleWithInheritanceBreakBeforeComma); 3452 3453 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3454 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3455 FormatStyle::BILS_AfterColon; 3456 verifyFormat("class MyClass : public X {};", 3457 StyleWithInheritanceBreakAfterColon); 3458 verifyFormat("class MyClass : public X, public Y {};", 3459 StyleWithInheritanceBreakAfterColon); 3460 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3461 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3462 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3463 StyleWithInheritanceBreakAfterColon); 3464 verifyFormat("struct aaaaaaaaaaaaa :\n" 3465 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3466 " aaaaaaaaaaaaaaaa> {};", 3467 StyleWithInheritanceBreakAfterColon); 3468 3469 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3470 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3471 FormatStyle::BILS_AfterComma; 3472 verifyFormat("class MyClass : public X {};", 3473 StyleWithInheritanceBreakAfterComma); 3474 verifyFormat("class MyClass : public X,\n" 3475 " public Y {};", 3476 StyleWithInheritanceBreakAfterComma); 3477 verifyFormat( 3478 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3479 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3480 "{};", 3481 StyleWithInheritanceBreakAfterComma); 3482 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3483 " aaaaaaaaaaaaaaaa> {};", 3484 StyleWithInheritanceBreakAfterComma); 3485 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3486 " : public OnceBreak,\n" 3487 " public AlwaysBreak,\n" 3488 " EvenBasesFitInOneLine {};", 3489 StyleWithInheritanceBreakAfterComma); 3490 } 3491 3492 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3493 verifyFormat("class A {\n} a, b;"); 3494 verifyFormat("struct A {\n} a, b;"); 3495 verifyFormat("union A {\n} a, b;"); 3496 3497 verifyFormat("constexpr class A {\n} a, b;"); 3498 verifyFormat("constexpr struct A {\n} a, b;"); 3499 verifyFormat("constexpr union A {\n} a, b;"); 3500 3501 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3502 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3503 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3504 3505 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3506 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3507 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3508 3509 verifyFormat("namespace ns {\n" 3510 "class {\n" 3511 "} a, b;\n" 3512 "} // namespace ns"); 3513 verifyFormat("namespace ns {\n" 3514 "const class {\n" 3515 "} a, b;\n" 3516 "} // namespace ns"); 3517 verifyFormat("namespace ns {\n" 3518 "constexpr class C {\n" 3519 "} a, b;\n" 3520 "} // namespace ns"); 3521 verifyFormat("namespace ns {\n" 3522 "class { /* comment */\n" 3523 "} a, b;\n" 3524 "} // namespace ns"); 3525 verifyFormat("namespace ns {\n" 3526 "const class { /* comment */\n" 3527 "} a, b;\n" 3528 "} // namespace ns"); 3529 } 3530 3531 TEST_F(FormatTest, FormatsEnum) { 3532 verifyFormat("enum {\n" 3533 " Zero,\n" 3534 " One = 1,\n" 3535 " Two = One + 1,\n" 3536 " Three = (One + Two),\n" 3537 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3538 " Five = (One, Two, Three, Four, 5)\n" 3539 "};"); 3540 verifyGoogleFormat("enum {\n" 3541 " Zero,\n" 3542 " One = 1,\n" 3543 " Two = One + 1,\n" 3544 " Three = (One + Two),\n" 3545 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3546 " Five = (One, Two, Three, Four, 5)\n" 3547 "};"); 3548 verifyFormat("enum Enum {};"); 3549 verifyFormat("enum {};"); 3550 verifyFormat("enum X E {} d;"); 3551 verifyFormat("enum __attribute__((...)) E {} d;"); 3552 verifyFormat("enum __declspec__((...)) E {} d;"); 3553 verifyFormat("enum {\n" 3554 " Bar = Foo<int, int>::value\n" 3555 "};", 3556 getLLVMStyleWithColumns(30)); 3557 3558 verifyFormat("enum ShortEnum { A, B, C };"); 3559 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3560 3561 EXPECT_EQ("enum KeepEmptyLines {\n" 3562 " ONE,\n" 3563 "\n" 3564 " TWO,\n" 3565 "\n" 3566 " THREE\n" 3567 "}", 3568 format("enum KeepEmptyLines {\n" 3569 " ONE,\n" 3570 "\n" 3571 " TWO,\n" 3572 "\n" 3573 "\n" 3574 " THREE\n" 3575 "}")); 3576 verifyFormat("enum E { // comment\n" 3577 " ONE,\n" 3578 " TWO\n" 3579 "};\n" 3580 "int i;"); 3581 3582 FormatStyle EightIndent = getLLVMStyle(); 3583 EightIndent.IndentWidth = 8; 3584 verifyFormat("enum {\n" 3585 " VOID,\n" 3586 " CHAR,\n" 3587 " SHORT,\n" 3588 " INT,\n" 3589 " LONG,\n" 3590 " SIGNED,\n" 3591 " UNSIGNED,\n" 3592 " BOOL,\n" 3593 " FLOAT,\n" 3594 " DOUBLE,\n" 3595 " COMPLEX\n" 3596 "};", 3597 EightIndent); 3598 3599 // Not enums. 3600 verifyFormat("enum X f() {\n" 3601 " a();\n" 3602 " return 42;\n" 3603 "}"); 3604 verifyFormat("enum X Type::f() {\n" 3605 " a();\n" 3606 " return 42;\n" 3607 "}"); 3608 verifyFormat("enum ::X f() {\n" 3609 " a();\n" 3610 " return 42;\n" 3611 "}"); 3612 verifyFormat("enum ns::X f() {\n" 3613 " a();\n" 3614 " return 42;\n" 3615 "}"); 3616 } 3617 3618 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3619 verifyFormat("enum Type {\n" 3620 " One = 0; // These semicolons should be commas.\n" 3621 " Two = 1;\n" 3622 "};"); 3623 verifyFormat("namespace n {\n" 3624 "enum Type {\n" 3625 " One,\n" 3626 " Two, // missing };\n" 3627 " int i;\n" 3628 "}\n" 3629 "void g() {}"); 3630 } 3631 3632 TEST_F(FormatTest, FormatsEnumStruct) { 3633 verifyFormat("enum struct {\n" 3634 " Zero,\n" 3635 " One = 1,\n" 3636 " Two = One + 1,\n" 3637 " Three = (One + Two),\n" 3638 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3639 " Five = (One, Two, Three, Four, 5)\n" 3640 "};"); 3641 verifyFormat("enum struct Enum {};"); 3642 verifyFormat("enum struct {};"); 3643 verifyFormat("enum struct X E {} d;"); 3644 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3645 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3646 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3647 } 3648 3649 TEST_F(FormatTest, FormatsEnumClass) { 3650 verifyFormat("enum class {\n" 3651 " Zero,\n" 3652 " One = 1,\n" 3653 " Two = One + 1,\n" 3654 " Three = (One + Two),\n" 3655 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3656 " Five = (One, Two, Three, Four, 5)\n" 3657 "};"); 3658 verifyFormat("enum class Enum {};"); 3659 verifyFormat("enum class {};"); 3660 verifyFormat("enum class X E {} d;"); 3661 verifyFormat("enum class __attribute__((...)) E {} d;"); 3662 verifyFormat("enum class __declspec__((...)) E {} d;"); 3663 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3664 } 3665 3666 TEST_F(FormatTest, FormatsEnumTypes) { 3667 verifyFormat("enum X : int {\n" 3668 " A, // Force multiple lines.\n" 3669 " B\n" 3670 "};"); 3671 verifyFormat("enum X : int { A, B };"); 3672 verifyFormat("enum X : std::uint32_t { A, B };"); 3673 } 3674 3675 TEST_F(FormatTest, FormatsTypedefEnum) { 3676 FormatStyle Style = getLLVMStyleWithColumns(40); 3677 verifyFormat("typedef enum {} EmptyEnum;"); 3678 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3679 verifyFormat("typedef enum {\n" 3680 " ZERO = 0,\n" 3681 " ONE = 1,\n" 3682 " TWO = 2,\n" 3683 " THREE = 3\n" 3684 "} LongEnum;", 3685 Style); 3686 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3687 Style.BraceWrapping.AfterEnum = true; 3688 verifyFormat("typedef enum {} EmptyEnum;"); 3689 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3690 verifyFormat("typedef enum\n" 3691 "{\n" 3692 " ZERO = 0,\n" 3693 " ONE = 1,\n" 3694 " TWO = 2,\n" 3695 " THREE = 3\n" 3696 "} LongEnum;", 3697 Style); 3698 } 3699 3700 TEST_F(FormatTest, FormatsNSEnums) { 3701 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3702 verifyGoogleFormat( 3703 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3704 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3705 " // Information about someDecentlyLongValue.\n" 3706 " someDecentlyLongValue,\n" 3707 " // Information about anotherDecentlyLongValue.\n" 3708 " anotherDecentlyLongValue,\n" 3709 " // Information about aThirdDecentlyLongValue.\n" 3710 " aThirdDecentlyLongValue\n" 3711 "};"); 3712 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3713 " // Information about someDecentlyLongValue.\n" 3714 " someDecentlyLongValue,\n" 3715 " // Information about anotherDecentlyLongValue.\n" 3716 " anotherDecentlyLongValue,\n" 3717 " // Information about aThirdDecentlyLongValue.\n" 3718 " aThirdDecentlyLongValue\n" 3719 "};"); 3720 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3721 " a = 1,\n" 3722 " b = 2,\n" 3723 " c = 3,\n" 3724 "};"); 3725 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3726 " a = 1,\n" 3727 " b = 2,\n" 3728 " c = 3,\n" 3729 "};"); 3730 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3731 " a = 1,\n" 3732 " b = 2,\n" 3733 " c = 3,\n" 3734 "};"); 3735 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3736 " a = 1,\n" 3737 " b = 2,\n" 3738 " c = 3,\n" 3739 "};"); 3740 } 3741 3742 TEST_F(FormatTest, FormatsBitfields) { 3743 verifyFormat("struct Bitfields {\n" 3744 " unsigned sClass : 8;\n" 3745 " unsigned ValueKind : 2;\n" 3746 "};"); 3747 verifyFormat("struct A {\n" 3748 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3749 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3750 "};"); 3751 verifyFormat("struct MyStruct {\n" 3752 " uchar data;\n" 3753 " uchar : 8;\n" 3754 " uchar : 8;\n" 3755 " uchar other;\n" 3756 "};"); 3757 FormatStyle Style = getLLVMStyle(); 3758 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3759 verifyFormat("struct Bitfields {\n" 3760 " unsigned sClass:8;\n" 3761 " unsigned ValueKind:2;\n" 3762 " uchar other;\n" 3763 "};", 3764 Style); 3765 verifyFormat("struct A {\n" 3766 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3767 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3768 "};", 3769 Style); 3770 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3771 verifyFormat("struct Bitfields {\n" 3772 " unsigned sClass :8;\n" 3773 " unsigned ValueKind :2;\n" 3774 " uchar other;\n" 3775 "};", 3776 Style); 3777 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3778 verifyFormat("struct Bitfields {\n" 3779 " unsigned sClass: 8;\n" 3780 " unsigned ValueKind: 2;\n" 3781 " uchar other;\n" 3782 "};", 3783 Style); 3784 } 3785 3786 TEST_F(FormatTest, FormatsNamespaces) { 3787 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3788 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3789 3790 verifyFormat("namespace some_namespace {\n" 3791 "class A {};\n" 3792 "void f() { f(); }\n" 3793 "}", 3794 LLVMWithNoNamespaceFix); 3795 verifyFormat("#define M(x) x##x\n" 3796 "namespace M(x) {\n" 3797 "class A {};\n" 3798 "void f() { f(); }\n" 3799 "}", 3800 LLVMWithNoNamespaceFix); 3801 verifyFormat("#define M(x) x##x\n" 3802 "namespace N::inline M(x) {\n" 3803 "class A {};\n" 3804 "void f() { f(); }\n" 3805 "}", 3806 LLVMWithNoNamespaceFix); 3807 verifyFormat("#define M(x) x##x\n" 3808 "namespace M(x)::inline N {\n" 3809 "class A {};\n" 3810 "void f() { f(); }\n" 3811 "}", 3812 LLVMWithNoNamespaceFix); 3813 verifyFormat("#define M(x) x##x\n" 3814 "namespace N::M(x) {\n" 3815 "class A {};\n" 3816 "void f() { f(); }\n" 3817 "}", 3818 LLVMWithNoNamespaceFix); 3819 verifyFormat("#define M(x) x##x\n" 3820 "namespace M::N(x) {\n" 3821 "class A {};\n" 3822 "void f() { f(); }\n" 3823 "}", 3824 LLVMWithNoNamespaceFix); 3825 verifyFormat("namespace N::inline D {\n" 3826 "class A {};\n" 3827 "void f() { f(); }\n" 3828 "}", 3829 LLVMWithNoNamespaceFix); 3830 verifyFormat("namespace N::inline D::E {\n" 3831 "class A {};\n" 3832 "void f() { f(); }\n" 3833 "}", 3834 LLVMWithNoNamespaceFix); 3835 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3836 "class A {};\n" 3837 "void f() { f(); }\n" 3838 "}", 3839 LLVMWithNoNamespaceFix); 3840 verifyFormat("/* something */ namespace some_namespace {\n" 3841 "class A {};\n" 3842 "void f() { f(); }\n" 3843 "}", 3844 LLVMWithNoNamespaceFix); 3845 verifyFormat("namespace {\n" 3846 "class A {};\n" 3847 "void f() { f(); }\n" 3848 "}", 3849 LLVMWithNoNamespaceFix); 3850 verifyFormat("/* something */ namespace {\n" 3851 "class A {};\n" 3852 "void f() { f(); }\n" 3853 "}", 3854 LLVMWithNoNamespaceFix); 3855 verifyFormat("inline namespace X {\n" 3856 "class A {};\n" 3857 "void f() { f(); }\n" 3858 "}", 3859 LLVMWithNoNamespaceFix); 3860 verifyFormat("/* something */ inline namespace X {\n" 3861 "class A {};\n" 3862 "void f() { f(); }\n" 3863 "}", 3864 LLVMWithNoNamespaceFix); 3865 verifyFormat("export namespace X {\n" 3866 "class A {};\n" 3867 "void f() { f(); }\n" 3868 "}", 3869 LLVMWithNoNamespaceFix); 3870 verifyFormat("using namespace some_namespace;\n" 3871 "class A {};\n" 3872 "void f() { f(); }", 3873 LLVMWithNoNamespaceFix); 3874 3875 // This code is more common than we thought; if we 3876 // layout this correctly the semicolon will go into 3877 // its own line, which is undesirable. 3878 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3879 verifyFormat("namespace {\n" 3880 "class A {};\n" 3881 "};", 3882 LLVMWithNoNamespaceFix); 3883 3884 verifyFormat("namespace {\n" 3885 "int SomeVariable = 0; // comment\n" 3886 "} // namespace", 3887 LLVMWithNoNamespaceFix); 3888 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3889 "#define HEADER_GUARD\n" 3890 "namespace my_namespace {\n" 3891 "int i;\n" 3892 "} // my_namespace\n" 3893 "#endif // HEADER_GUARD", 3894 format("#ifndef HEADER_GUARD\n" 3895 " #define HEADER_GUARD\n" 3896 " namespace my_namespace {\n" 3897 "int i;\n" 3898 "} // my_namespace\n" 3899 "#endif // HEADER_GUARD", 3900 LLVMWithNoNamespaceFix)); 3901 3902 EXPECT_EQ("namespace A::B {\n" 3903 "class C {};\n" 3904 "}", 3905 format("namespace A::B {\n" 3906 "class C {};\n" 3907 "}", 3908 LLVMWithNoNamespaceFix)); 3909 3910 FormatStyle Style = getLLVMStyle(); 3911 Style.NamespaceIndentation = FormatStyle::NI_All; 3912 EXPECT_EQ("namespace out {\n" 3913 " int i;\n" 3914 " namespace in {\n" 3915 " int i;\n" 3916 " } // namespace in\n" 3917 "} // namespace out", 3918 format("namespace out {\n" 3919 "int i;\n" 3920 "namespace in {\n" 3921 "int i;\n" 3922 "} // namespace in\n" 3923 "} // namespace out", 3924 Style)); 3925 3926 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3927 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3928 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3929 FormatStyle::SFS_Inline; 3930 verifyFormat("namespace {\n" 3931 " void f() {\n" 3932 " return;\n" 3933 " }\n" 3934 "} // namespace\n", 3935 ShortInlineFunctions); 3936 verifyFormat("namespace { /* comment */\n" 3937 " void f() {\n" 3938 " return;\n" 3939 " }\n" 3940 "} // namespace\n", 3941 ShortInlineFunctions); 3942 verifyFormat("namespace { // comment\n" 3943 " void f() {\n" 3944 " return;\n" 3945 " }\n" 3946 "} // namespace\n", 3947 ShortInlineFunctions); 3948 verifyFormat("namespace {\n" 3949 " int some_int;\n" 3950 " void f() {\n" 3951 " return;\n" 3952 " }\n" 3953 "} // namespace\n", 3954 ShortInlineFunctions); 3955 verifyFormat("namespace interface {\n" 3956 " void f() {\n" 3957 " return;\n" 3958 " }\n" 3959 "} // namespace interface\n", 3960 ShortInlineFunctions); 3961 verifyFormat("namespace {\n" 3962 " class X {\n" 3963 " void f() { return; }\n" 3964 " };\n" 3965 "} // namespace\n", 3966 ShortInlineFunctions); 3967 verifyFormat("namespace {\n" 3968 " class X { /* comment */\n" 3969 " void f() { return; }\n" 3970 " };\n" 3971 "} // namespace\n", 3972 ShortInlineFunctions); 3973 verifyFormat("namespace {\n" 3974 " class X { // comment\n" 3975 " void f() { return; }\n" 3976 " };\n" 3977 "} // namespace\n", 3978 ShortInlineFunctions); 3979 verifyFormat("namespace {\n" 3980 " struct X {\n" 3981 " void f() { return; }\n" 3982 " };\n" 3983 "} // namespace\n", 3984 ShortInlineFunctions); 3985 verifyFormat("namespace {\n" 3986 " union X {\n" 3987 " void f() { return; }\n" 3988 " };\n" 3989 "} // namespace\n", 3990 ShortInlineFunctions); 3991 verifyFormat("extern \"C\" {\n" 3992 "void f() {\n" 3993 " return;\n" 3994 "}\n" 3995 "} // namespace\n", 3996 ShortInlineFunctions); 3997 verifyFormat("namespace {\n" 3998 " class X {\n" 3999 " void f() { return; }\n" 4000 " } x;\n" 4001 "} // namespace\n", 4002 ShortInlineFunctions); 4003 verifyFormat("namespace {\n" 4004 " [[nodiscard]] class X {\n" 4005 " void f() { return; }\n" 4006 " };\n" 4007 "} // namespace\n", 4008 ShortInlineFunctions); 4009 verifyFormat("namespace {\n" 4010 " static class X {\n" 4011 " void f() { return; }\n" 4012 " } x;\n" 4013 "} // namespace\n", 4014 ShortInlineFunctions); 4015 verifyFormat("namespace {\n" 4016 " constexpr class X {\n" 4017 " void f() { return; }\n" 4018 " } x;\n" 4019 "} // namespace\n", 4020 ShortInlineFunctions); 4021 4022 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4023 verifyFormat("extern \"C\" {\n" 4024 " void f() {\n" 4025 " return;\n" 4026 " }\n" 4027 "} // namespace\n", 4028 ShortInlineFunctions); 4029 4030 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4031 EXPECT_EQ("namespace out {\n" 4032 "int i;\n" 4033 "namespace in {\n" 4034 " int i;\n" 4035 "} // namespace in\n" 4036 "} // namespace out", 4037 format("namespace out {\n" 4038 "int i;\n" 4039 "namespace in {\n" 4040 "int i;\n" 4041 "} // namespace in\n" 4042 "} // namespace out", 4043 Style)); 4044 4045 Style.NamespaceIndentation = FormatStyle::NI_None; 4046 verifyFormat("template <class T>\n" 4047 "concept a_concept = X<>;\n" 4048 "namespace B {\n" 4049 "struct b_struct {};\n" 4050 "} // namespace B\n", 4051 Style); 4052 verifyFormat("template <int I>\n" 4053 "constexpr void foo()\n" 4054 " requires(I == 42)\n" 4055 "{}\n" 4056 "namespace ns {\n" 4057 "void foo() {}\n" 4058 "} // namespace ns\n", 4059 Style); 4060 } 4061 4062 TEST_F(FormatTest, NamespaceMacros) { 4063 FormatStyle Style = getLLVMStyle(); 4064 Style.NamespaceMacros.push_back("TESTSUITE"); 4065 4066 verifyFormat("TESTSUITE(A) {\n" 4067 "int foo();\n" 4068 "} // TESTSUITE(A)", 4069 Style); 4070 4071 verifyFormat("TESTSUITE(A, B) {\n" 4072 "int foo();\n" 4073 "} // TESTSUITE(A)", 4074 Style); 4075 4076 // Properly indent according to NamespaceIndentation style 4077 Style.NamespaceIndentation = FormatStyle::NI_All; 4078 verifyFormat("TESTSUITE(A) {\n" 4079 " int foo();\n" 4080 "} // TESTSUITE(A)", 4081 Style); 4082 verifyFormat("TESTSUITE(A) {\n" 4083 " namespace B {\n" 4084 " int foo();\n" 4085 " } // namespace B\n" 4086 "} // TESTSUITE(A)", 4087 Style); 4088 verifyFormat("namespace A {\n" 4089 " TESTSUITE(B) {\n" 4090 " int foo();\n" 4091 " } // TESTSUITE(B)\n" 4092 "} // namespace A", 4093 Style); 4094 4095 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4096 verifyFormat("TESTSUITE(A) {\n" 4097 "TESTSUITE(B) {\n" 4098 " int foo();\n" 4099 "} // TESTSUITE(B)\n" 4100 "} // TESTSUITE(A)", 4101 Style); 4102 verifyFormat("TESTSUITE(A) {\n" 4103 "namespace B {\n" 4104 " int foo();\n" 4105 "} // namespace B\n" 4106 "} // TESTSUITE(A)", 4107 Style); 4108 verifyFormat("namespace A {\n" 4109 "TESTSUITE(B) {\n" 4110 " int foo();\n" 4111 "} // TESTSUITE(B)\n" 4112 "} // namespace A", 4113 Style); 4114 4115 // Properly merge namespace-macros blocks in CompactNamespaces mode 4116 Style.NamespaceIndentation = FormatStyle::NI_None; 4117 Style.CompactNamespaces = true; 4118 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4119 "}} // TESTSUITE(A::B)", 4120 Style); 4121 4122 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4123 "}} // TESTSUITE(out::in)", 4124 format("TESTSUITE(out) {\n" 4125 "TESTSUITE(in) {\n" 4126 "} // TESTSUITE(in)\n" 4127 "} // TESTSUITE(out)", 4128 Style)); 4129 4130 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4131 "}} // TESTSUITE(out::in)", 4132 format("TESTSUITE(out) {\n" 4133 "TESTSUITE(in) {\n" 4134 "} // TESTSUITE(in)\n" 4135 "} // TESTSUITE(out)", 4136 Style)); 4137 4138 // Do not merge different namespaces/macros 4139 EXPECT_EQ("namespace out {\n" 4140 "TESTSUITE(in) {\n" 4141 "} // TESTSUITE(in)\n" 4142 "} // namespace out", 4143 format("namespace out {\n" 4144 "TESTSUITE(in) {\n" 4145 "} // TESTSUITE(in)\n" 4146 "} // namespace out", 4147 Style)); 4148 EXPECT_EQ("TESTSUITE(out) {\n" 4149 "namespace in {\n" 4150 "} // namespace in\n" 4151 "} // TESTSUITE(out)", 4152 format("TESTSUITE(out) {\n" 4153 "namespace in {\n" 4154 "} // namespace in\n" 4155 "} // TESTSUITE(out)", 4156 Style)); 4157 Style.NamespaceMacros.push_back("FOOBAR"); 4158 EXPECT_EQ("TESTSUITE(out) {\n" 4159 "FOOBAR(in) {\n" 4160 "} // FOOBAR(in)\n" 4161 "} // TESTSUITE(out)", 4162 format("TESTSUITE(out) {\n" 4163 "FOOBAR(in) {\n" 4164 "} // FOOBAR(in)\n" 4165 "} // TESTSUITE(out)", 4166 Style)); 4167 } 4168 4169 TEST_F(FormatTest, FormatsCompactNamespaces) { 4170 FormatStyle Style = getLLVMStyle(); 4171 Style.CompactNamespaces = true; 4172 Style.NamespaceMacros.push_back("TESTSUITE"); 4173 4174 verifyFormat("namespace A { namespace B {\n" 4175 "}} // namespace A::B", 4176 Style); 4177 4178 EXPECT_EQ("namespace out { namespace in {\n" 4179 "}} // namespace out::in", 4180 format("namespace out {\n" 4181 "namespace in {\n" 4182 "} // namespace in\n" 4183 "} // namespace out", 4184 Style)); 4185 4186 // Only namespaces which have both consecutive opening and end get compacted 4187 EXPECT_EQ("namespace out {\n" 4188 "namespace in1 {\n" 4189 "} // namespace in1\n" 4190 "namespace in2 {\n" 4191 "} // namespace in2\n" 4192 "} // namespace out", 4193 format("namespace out {\n" 4194 "namespace in1 {\n" 4195 "} // namespace in1\n" 4196 "namespace in2 {\n" 4197 "} // namespace in2\n" 4198 "} // namespace out", 4199 Style)); 4200 4201 EXPECT_EQ("namespace out {\n" 4202 "int i;\n" 4203 "namespace in {\n" 4204 "int j;\n" 4205 "} // namespace in\n" 4206 "int k;\n" 4207 "} // namespace out", 4208 format("namespace out { int i;\n" 4209 "namespace in { int j; } // namespace in\n" 4210 "int k; } // namespace out", 4211 Style)); 4212 4213 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4214 "}}} // namespace A::B::C\n", 4215 format("namespace A { namespace B {\n" 4216 "namespace C {\n" 4217 "}} // namespace B::C\n" 4218 "} // namespace A\n", 4219 Style)); 4220 4221 Style.ColumnLimit = 40; 4222 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4223 "namespace bbbbbbbbbb {\n" 4224 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4225 format("namespace aaaaaaaaaa {\n" 4226 "namespace bbbbbbbbbb {\n" 4227 "} // namespace bbbbbbbbbb\n" 4228 "} // namespace aaaaaaaaaa", 4229 Style)); 4230 4231 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4232 "namespace cccccc {\n" 4233 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4234 format("namespace aaaaaa {\n" 4235 "namespace bbbbbb {\n" 4236 "namespace cccccc {\n" 4237 "} // namespace cccccc\n" 4238 "} // namespace bbbbbb\n" 4239 "} // namespace aaaaaa", 4240 Style)); 4241 Style.ColumnLimit = 80; 4242 4243 // Extra semicolon after 'inner' closing brace prevents merging 4244 EXPECT_EQ("namespace out { namespace in {\n" 4245 "}; } // namespace out::in", 4246 format("namespace out {\n" 4247 "namespace in {\n" 4248 "}; // namespace in\n" 4249 "} // namespace out", 4250 Style)); 4251 4252 // Extra semicolon after 'outer' closing brace is conserved 4253 EXPECT_EQ("namespace out { namespace in {\n" 4254 "}}; // namespace out::in", 4255 format("namespace out {\n" 4256 "namespace in {\n" 4257 "} // namespace in\n" 4258 "}; // namespace out", 4259 Style)); 4260 4261 Style.NamespaceIndentation = FormatStyle::NI_All; 4262 EXPECT_EQ("namespace out { namespace in {\n" 4263 " int i;\n" 4264 "}} // namespace out::in", 4265 format("namespace out {\n" 4266 "namespace in {\n" 4267 "int i;\n" 4268 "} // namespace in\n" 4269 "} // namespace out", 4270 Style)); 4271 EXPECT_EQ("namespace out { namespace mid {\n" 4272 " namespace in {\n" 4273 " int j;\n" 4274 " } // namespace in\n" 4275 " int k;\n" 4276 "}} // namespace out::mid", 4277 format("namespace out { namespace mid {\n" 4278 "namespace in { int j; } // namespace in\n" 4279 "int k; }} // namespace out::mid", 4280 Style)); 4281 4282 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4283 EXPECT_EQ("namespace out { namespace in {\n" 4284 " int i;\n" 4285 "}} // namespace out::in", 4286 format("namespace out {\n" 4287 "namespace in {\n" 4288 "int i;\n" 4289 "} // namespace in\n" 4290 "} // namespace out", 4291 Style)); 4292 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4293 " int i;\n" 4294 "}}} // namespace out::mid::in", 4295 format("namespace out {\n" 4296 "namespace mid {\n" 4297 "namespace in {\n" 4298 "int i;\n" 4299 "} // namespace in\n" 4300 "} // namespace mid\n" 4301 "} // namespace out", 4302 Style)); 4303 4304 Style.CompactNamespaces = true; 4305 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4306 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4307 Style.BraceWrapping.BeforeLambdaBody = true; 4308 verifyFormat("namespace out { namespace in {\n" 4309 "}} // namespace out::in", 4310 Style); 4311 EXPECT_EQ("namespace out { namespace in {\n" 4312 "}} // namespace out::in", 4313 format("namespace out {\n" 4314 "namespace in {\n" 4315 "} // namespace in\n" 4316 "} // namespace out", 4317 Style)); 4318 } 4319 4320 TEST_F(FormatTest, FormatsExternC) { 4321 verifyFormat("extern \"C\" {\nint a;"); 4322 verifyFormat("extern \"C\" {}"); 4323 verifyFormat("extern \"C\" {\n" 4324 "int foo();\n" 4325 "}"); 4326 verifyFormat("extern \"C\" int foo() {}"); 4327 verifyFormat("extern \"C\" int foo();"); 4328 verifyFormat("extern \"C\" int foo() {\n" 4329 " int i = 42;\n" 4330 " return i;\n" 4331 "}"); 4332 4333 FormatStyle Style = getLLVMStyle(); 4334 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4335 Style.BraceWrapping.AfterFunction = true; 4336 verifyFormat("extern \"C\" int foo() {}", Style); 4337 verifyFormat("extern \"C\" int foo();", Style); 4338 verifyFormat("extern \"C\" int foo()\n" 4339 "{\n" 4340 " int i = 42;\n" 4341 " return i;\n" 4342 "}", 4343 Style); 4344 4345 Style.BraceWrapping.AfterExternBlock = true; 4346 Style.BraceWrapping.SplitEmptyRecord = false; 4347 verifyFormat("extern \"C\"\n" 4348 "{}", 4349 Style); 4350 verifyFormat("extern \"C\"\n" 4351 "{\n" 4352 " int foo();\n" 4353 "}", 4354 Style); 4355 } 4356 4357 TEST_F(FormatTest, IndentExternBlockStyle) { 4358 FormatStyle Style = getLLVMStyle(); 4359 Style.IndentWidth = 2; 4360 4361 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4362 verifyFormat("extern \"C\" { /*9*/\n" 4363 "}", 4364 Style); 4365 verifyFormat("extern \"C\" {\n" 4366 " int foo10();\n" 4367 "}", 4368 Style); 4369 4370 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4371 verifyFormat("extern \"C\" { /*11*/\n" 4372 "}", 4373 Style); 4374 verifyFormat("extern \"C\" {\n" 4375 "int foo12();\n" 4376 "}", 4377 Style); 4378 4379 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4380 Style.BraceWrapping.AfterExternBlock = true; 4381 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4382 verifyFormat("extern \"C\"\n" 4383 "{ /*13*/\n" 4384 "}", 4385 Style); 4386 verifyFormat("extern \"C\"\n{\n" 4387 " int foo14();\n" 4388 "}", 4389 Style); 4390 4391 Style.BraceWrapping.AfterExternBlock = false; 4392 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4393 verifyFormat("extern \"C\" { /*15*/\n" 4394 "}", 4395 Style); 4396 verifyFormat("extern \"C\" {\n" 4397 "int foo16();\n" 4398 "}", 4399 Style); 4400 4401 Style.BraceWrapping.AfterExternBlock = true; 4402 verifyFormat("extern \"C\"\n" 4403 "{ /*13*/\n" 4404 "}", 4405 Style); 4406 verifyFormat("extern \"C\"\n" 4407 "{\n" 4408 "int foo14();\n" 4409 "}", 4410 Style); 4411 4412 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4413 verifyFormat("extern \"C\"\n" 4414 "{ /*13*/\n" 4415 "}", 4416 Style); 4417 verifyFormat("extern \"C\"\n" 4418 "{\n" 4419 " int foo14();\n" 4420 "}", 4421 Style); 4422 } 4423 4424 TEST_F(FormatTest, FormatsInlineASM) { 4425 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4426 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4427 verifyFormat( 4428 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4429 " \"cpuid\\n\\t\"\n" 4430 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4431 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4432 " : \"a\"(value));"); 4433 EXPECT_EQ( 4434 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4435 " __asm {\n" 4436 " mov edx,[that] // vtable in edx\n" 4437 " mov eax,methodIndex\n" 4438 " call [edx][eax*4] // stdcall\n" 4439 " }\n" 4440 "}", 4441 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4442 " __asm {\n" 4443 " mov edx,[that] // vtable in edx\n" 4444 " mov eax,methodIndex\n" 4445 " call [edx][eax*4] // stdcall\n" 4446 " }\n" 4447 "}")); 4448 EXPECT_EQ("_asm {\n" 4449 " xor eax, eax;\n" 4450 " cpuid;\n" 4451 "}", 4452 format("_asm {\n" 4453 " xor eax, eax;\n" 4454 " cpuid;\n" 4455 "}")); 4456 verifyFormat("void function() {\n" 4457 " // comment\n" 4458 " asm(\"\");\n" 4459 "}"); 4460 EXPECT_EQ("__asm {\n" 4461 "}\n" 4462 "int i;", 4463 format("__asm {\n" 4464 "}\n" 4465 "int i;")); 4466 } 4467 4468 TEST_F(FormatTest, FormatTryCatch) { 4469 verifyFormat("try {\n" 4470 " throw a * b;\n" 4471 "} catch (int a) {\n" 4472 " // Do nothing.\n" 4473 "} catch (...) {\n" 4474 " exit(42);\n" 4475 "}"); 4476 4477 // Function-level try statements. 4478 verifyFormat("int f() try { return 4; } catch (...) {\n" 4479 " return 5;\n" 4480 "}"); 4481 verifyFormat("class A {\n" 4482 " int a;\n" 4483 " A() try : a(0) {\n" 4484 " } catch (...) {\n" 4485 " throw;\n" 4486 " }\n" 4487 "};\n"); 4488 verifyFormat("class A {\n" 4489 " int a;\n" 4490 " A() try : a(0), b{1} {\n" 4491 " } catch (...) {\n" 4492 " throw;\n" 4493 " }\n" 4494 "};\n"); 4495 verifyFormat("class A {\n" 4496 " int a;\n" 4497 " A() try : a(0), b{1}, c{2} {\n" 4498 " } catch (...) {\n" 4499 " throw;\n" 4500 " }\n" 4501 "};\n"); 4502 verifyFormat("class A {\n" 4503 " int a;\n" 4504 " A() try : a(0), b{1}, c{2} {\n" 4505 " { // New scope.\n" 4506 " }\n" 4507 " } catch (...) {\n" 4508 " throw;\n" 4509 " }\n" 4510 "};\n"); 4511 4512 // Incomplete try-catch blocks. 4513 verifyIncompleteFormat("try {} catch ("); 4514 } 4515 4516 TEST_F(FormatTest, FormatTryAsAVariable) { 4517 verifyFormat("int try;"); 4518 verifyFormat("int try, size;"); 4519 verifyFormat("try = foo();"); 4520 verifyFormat("if (try < size) {\n return true;\n}"); 4521 4522 verifyFormat("int catch;"); 4523 verifyFormat("int catch, size;"); 4524 verifyFormat("catch = foo();"); 4525 verifyFormat("if (catch < size) {\n return true;\n}"); 4526 4527 FormatStyle Style = getLLVMStyle(); 4528 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4529 Style.BraceWrapping.AfterFunction = true; 4530 Style.BraceWrapping.BeforeCatch = true; 4531 verifyFormat("try {\n" 4532 " int bar = 1;\n" 4533 "}\n" 4534 "catch (...) {\n" 4535 " int bar = 1;\n" 4536 "}", 4537 Style); 4538 verifyFormat("#if NO_EX\n" 4539 "try\n" 4540 "#endif\n" 4541 "{\n" 4542 "}\n" 4543 "#if NO_EX\n" 4544 "catch (...) {\n" 4545 "}", 4546 Style); 4547 verifyFormat("try /* abc */ {\n" 4548 " int bar = 1;\n" 4549 "}\n" 4550 "catch (...) {\n" 4551 " int bar = 1;\n" 4552 "}", 4553 Style); 4554 verifyFormat("try\n" 4555 "// abc\n" 4556 "{\n" 4557 " int bar = 1;\n" 4558 "}\n" 4559 "catch (...) {\n" 4560 " int bar = 1;\n" 4561 "}", 4562 Style); 4563 } 4564 4565 TEST_F(FormatTest, FormatSEHTryCatch) { 4566 verifyFormat("__try {\n" 4567 " int a = b * c;\n" 4568 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4569 " // Do nothing.\n" 4570 "}"); 4571 4572 verifyFormat("__try {\n" 4573 " int a = b * c;\n" 4574 "} __finally {\n" 4575 " // Do nothing.\n" 4576 "}"); 4577 4578 verifyFormat("DEBUG({\n" 4579 " __try {\n" 4580 " } __finally {\n" 4581 " }\n" 4582 "});\n"); 4583 } 4584 4585 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4586 verifyFormat("try {\n" 4587 " f();\n" 4588 "} catch {\n" 4589 " g();\n" 4590 "}"); 4591 verifyFormat("try {\n" 4592 " f();\n" 4593 "} catch (A a) MACRO(x) {\n" 4594 " g();\n" 4595 "} catch (B b) MACRO(x) {\n" 4596 " g();\n" 4597 "}"); 4598 } 4599 4600 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4601 FormatStyle Style = getLLVMStyle(); 4602 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4603 FormatStyle::BS_WebKit}) { 4604 Style.BreakBeforeBraces = BraceStyle; 4605 verifyFormat("try {\n" 4606 " // something\n" 4607 "} catch (...) {\n" 4608 " // something\n" 4609 "}", 4610 Style); 4611 } 4612 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4613 verifyFormat("try {\n" 4614 " // something\n" 4615 "}\n" 4616 "catch (...) {\n" 4617 " // something\n" 4618 "}", 4619 Style); 4620 verifyFormat("__try {\n" 4621 " // something\n" 4622 "}\n" 4623 "__finally {\n" 4624 " // something\n" 4625 "}", 4626 Style); 4627 verifyFormat("@try {\n" 4628 " // something\n" 4629 "}\n" 4630 "@finally {\n" 4631 " // something\n" 4632 "}", 4633 Style); 4634 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4635 verifyFormat("try\n" 4636 "{\n" 4637 " // something\n" 4638 "}\n" 4639 "catch (...)\n" 4640 "{\n" 4641 " // something\n" 4642 "}", 4643 Style); 4644 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4645 verifyFormat("try\n" 4646 " {\n" 4647 " // something white\n" 4648 " }\n" 4649 "catch (...)\n" 4650 " {\n" 4651 " // something white\n" 4652 " }", 4653 Style); 4654 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4655 verifyFormat("try\n" 4656 " {\n" 4657 " // something\n" 4658 " }\n" 4659 "catch (...)\n" 4660 " {\n" 4661 " // something\n" 4662 " }", 4663 Style); 4664 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4665 Style.BraceWrapping.BeforeCatch = true; 4666 verifyFormat("try {\n" 4667 " // something\n" 4668 "}\n" 4669 "catch (...) {\n" 4670 " // something\n" 4671 "}", 4672 Style); 4673 } 4674 4675 TEST_F(FormatTest, StaticInitializers) { 4676 verifyFormat("static SomeClass SC = {1, 'a'};"); 4677 4678 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4679 " 100000000, " 4680 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4681 4682 // Here, everything other than the "}" would fit on a line. 4683 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4684 " 10000000000000000000000000};"); 4685 EXPECT_EQ("S s = {a,\n" 4686 "\n" 4687 " b};", 4688 format("S s = {\n" 4689 " a,\n" 4690 "\n" 4691 " b\n" 4692 "};")); 4693 4694 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4695 // line. However, the formatting looks a bit off and this probably doesn't 4696 // happen often in practice. 4697 verifyFormat("static int Variable[1] = {\n" 4698 " {1000000000000000000000000000000000000}};", 4699 getLLVMStyleWithColumns(40)); 4700 } 4701 4702 TEST_F(FormatTest, DesignatedInitializers) { 4703 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4704 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4705 " .bbbbbbbbbb = 2,\n" 4706 " .cccccccccc = 3,\n" 4707 " .dddddddddd = 4,\n" 4708 " .eeeeeeeeee = 5};"); 4709 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4710 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4711 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4712 " .ccccccccccccccccccccccccccc = 3,\n" 4713 " .ddddddddddddddddddddddddddd = 4,\n" 4714 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4715 4716 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4717 4718 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4719 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4720 " [2] = bbbbbbbbbb,\n" 4721 " [3] = cccccccccc,\n" 4722 " [4] = dddddddddd,\n" 4723 " [5] = eeeeeeeeee};"); 4724 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4725 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4726 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4727 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4728 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4729 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4730 } 4731 4732 TEST_F(FormatTest, NestedStaticInitializers) { 4733 verifyFormat("static A x = {{{}}};\n"); 4734 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4735 " {init1, init2, init3, init4}}};", 4736 getLLVMStyleWithColumns(50)); 4737 4738 verifyFormat("somes Status::global_reps[3] = {\n" 4739 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4740 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4741 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4742 getLLVMStyleWithColumns(60)); 4743 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4744 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4745 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4746 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4747 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4748 " {rect.fRight - rect.fLeft, rect.fBottom - " 4749 "rect.fTop}};"); 4750 4751 verifyFormat( 4752 "SomeArrayOfSomeType a = {\n" 4753 " {{1, 2, 3},\n" 4754 " {1, 2, 3},\n" 4755 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4756 " 333333333333333333333333333333},\n" 4757 " {1, 2, 3},\n" 4758 " {1, 2, 3}}};"); 4759 verifyFormat( 4760 "SomeArrayOfSomeType a = {\n" 4761 " {{1, 2, 3}},\n" 4762 " {{1, 2, 3}},\n" 4763 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4764 " 333333333333333333333333333333}},\n" 4765 " {{1, 2, 3}},\n" 4766 " {{1, 2, 3}}};"); 4767 4768 verifyFormat("struct {\n" 4769 " unsigned bit;\n" 4770 " const char *const name;\n" 4771 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4772 " {kOsWin, \"Windows\"},\n" 4773 " {kOsLinux, \"Linux\"},\n" 4774 " {kOsCrOS, \"Chrome OS\"}};"); 4775 verifyFormat("struct {\n" 4776 " unsigned bit;\n" 4777 " const char *const name;\n" 4778 "} kBitsToOs[] = {\n" 4779 " {kOsMac, \"Mac\"},\n" 4780 " {kOsWin, \"Windows\"},\n" 4781 " {kOsLinux, \"Linux\"},\n" 4782 " {kOsCrOS, \"Chrome OS\"},\n" 4783 "};"); 4784 } 4785 4786 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4787 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4788 " \\\n" 4789 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4790 } 4791 4792 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4793 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4794 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4795 4796 // Do break defaulted and deleted functions. 4797 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4798 " default;", 4799 getLLVMStyleWithColumns(40)); 4800 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4801 " delete;", 4802 getLLVMStyleWithColumns(40)); 4803 } 4804 4805 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4806 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4807 getLLVMStyleWithColumns(40)); 4808 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4809 getLLVMStyleWithColumns(40)); 4810 EXPECT_EQ("#define Q \\\n" 4811 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4812 " \"aaaaaaaa.cpp\"", 4813 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4814 getLLVMStyleWithColumns(40))); 4815 } 4816 4817 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4818 EXPECT_EQ("# 123 \"A string literal\"", 4819 format(" # 123 \"A string literal\"")); 4820 } 4821 4822 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4823 EXPECT_EQ("#;", format("#;")); 4824 verifyFormat("#\n;\n;\n;"); 4825 } 4826 4827 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4828 EXPECT_EQ("#line 42 \"test\"\n", 4829 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4830 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4831 getLLVMStyleWithColumns(12))); 4832 } 4833 4834 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4835 EXPECT_EQ("#line 42 \"test\"", 4836 format("# \\\n line \\\n 42 \\\n \"test\"")); 4837 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4838 } 4839 4840 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4841 verifyFormat("#define A \\x20"); 4842 verifyFormat("#define A \\ x20"); 4843 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4844 verifyFormat("#define A ''"); 4845 verifyFormat("#define A ''qqq"); 4846 verifyFormat("#define A `qqq"); 4847 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4848 EXPECT_EQ("const char *c = STRINGIFY(\n" 4849 "\\na : b);", 4850 format("const char * c = STRINGIFY(\n" 4851 "\\na : b);")); 4852 4853 verifyFormat("a\r\\"); 4854 verifyFormat("a\v\\"); 4855 verifyFormat("a\f\\"); 4856 } 4857 4858 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4859 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4860 style.IndentWidth = 4; 4861 style.PPIndentWidth = 1; 4862 4863 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4864 verifyFormat("#ifdef __linux__\n" 4865 "void foo() {\n" 4866 " int x = 0;\n" 4867 "}\n" 4868 "#define FOO\n" 4869 "#endif\n" 4870 "void bar() {\n" 4871 " int y = 0;\n" 4872 "}\n", 4873 style); 4874 4875 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4876 verifyFormat("#ifdef __linux__\n" 4877 "void foo() {\n" 4878 " int x = 0;\n" 4879 "}\n" 4880 "# define FOO foo\n" 4881 "#endif\n" 4882 "void bar() {\n" 4883 " int y = 0;\n" 4884 "}\n", 4885 style); 4886 4887 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4888 verifyFormat("#ifdef __linux__\n" 4889 "void foo() {\n" 4890 " int x = 0;\n" 4891 "}\n" 4892 " #define FOO foo\n" 4893 "#endif\n" 4894 "void bar() {\n" 4895 " int y = 0;\n" 4896 "}\n", 4897 style); 4898 } 4899 4900 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4901 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4902 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4903 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4904 // FIXME: We never break before the macro name. 4905 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4906 4907 verifyFormat("#define A A\n#define A A"); 4908 verifyFormat("#define A(X) A\n#define A A"); 4909 4910 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4911 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4912 } 4913 4914 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4915 EXPECT_EQ("// somecomment\n" 4916 "#include \"a.h\"\n" 4917 "#define A( \\\n" 4918 " A, B)\n" 4919 "#include \"b.h\"\n" 4920 "// somecomment\n", 4921 format(" // somecomment\n" 4922 " #include \"a.h\"\n" 4923 "#define A(A,\\\n" 4924 " B)\n" 4925 " #include \"b.h\"\n" 4926 " // somecomment\n", 4927 getLLVMStyleWithColumns(13))); 4928 } 4929 4930 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4931 4932 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4933 EXPECT_EQ("#define A \\\n" 4934 " c; \\\n" 4935 " e;\n" 4936 "f;", 4937 format("#define A c; e;\n" 4938 "f;", 4939 getLLVMStyleWithColumns(14))); 4940 } 4941 4942 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4943 4944 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4945 EXPECT_EQ("int x,\n" 4946 "#define A\n" 4947 " y;", 4948 format("int x,\n#define A\ny;")); 4949 } 4950 4951 TEST_F(FormatTest, HashInMacroDefinition) { 4952 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4953 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4954 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4955 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4956 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4957 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4958 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4959 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4960 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4961 verifyFormat("#define A \\\n" 4962 " { \\\n" 4963 " f(#c); \\\n" 4964 " }", 4965 getLLVMStyleWithColumns(11)); 4966 4967 verifyFormat("#define A(X) \\\n" 4968 " void function##X()", 4969 getLLVMStyleWithColumns(22)); 4970 4971 verifyFormat("#define A(a, b, c) \\\n" 4972 " void a##b##c()", 4973 getLLVMStyleWithColumns(22)); 4974 4975 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4976 } 4977 4978 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4979 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4980 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4981 4982 FormatStyle Style = getLLVMStyle(); 4983 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4984 verifyFormat("#define true ((foo)1)", Style); 4985 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4986 verifyFormat("#define false((foo)0)", Style); 4987 } 4988 4989 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4990 EXPECT_EQ("#define A b;", format("#define A \\\n" 4991 " \\\n" 4992 " b;", 4993 getLLVMStyleWithColumns(25))); 4994 EXPECT_EQ("#define A \\\n" 4995 " \\\n" 4996 " a; \\\n" 4997 " b;", 4998 format("#define A \\\n" 4999 " \\\n" 5000 " a; \\\n" 5001 " b;", 5002 getLLVMStyleWithColumns(11))); 5003 EXPECT_EQ("#define A \\\n" 5004 " a; \\\n" 5005 " \\\n" 5006 " b;", 5007 format("#define A \\\n" 5008 " a; \\\n" 5009 " \\\n" 5010 " b;", 5011 getLLVMStyleWithColumns(11))); 5012 } 5013 5014 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5015 verifyIncompleteFormat("#define A :"); 5016 verifyFormat("#define SOMECASES \\\n" 5017 " case 1: \\\n" 5018 " case 2\n", 5019 getLLVMStyleWithColumns(20)); 5020 verifyFormat("#define MACRO(a) \\\n" 5021 " if (a) \\\n" 5022 " f(); \\\n" 5023 " else \\\n" 5024 " g()", 5025 getLLVMStyleWithColumns(18)); 5026 verifyFormat("#define A template <typename T>"); 5027 verifyIncompleteFormat("#define STR(x) #x\n" 5028 "f(STR(this_is_a_string_literal{));"); 5029 verifyFormat("#pragma omp threadprivate( \\\n" 5030 " y)), // expected-warning", 5031 getLLVMStyleWithColumns(28)); 5032 verifyFormat("#d, = };"); 5033 verifyFormat("#if \"a"); 5034 verifyIncompleteFormat("({\n" 5035 "#define b \\\n" 5036 " } \\\n" 5037 " a\n" 5038 "a", 5039 getLLVMStyleWithColumns(15)); 5040 verifyFormat("#define A \\\n" 5041 " { \\\n" 5042 " {\n" 5043 "#define B \\\n" 5044 " } \\\n" 5045 " }", 5046 getLLVMStyleWithColumns(15)); 5047 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5048 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5049 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5050 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5051 } 5052 5053 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5054 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5055 EXPECT_EQ("class A : public QObject {\n" 5056 " Q_OBJECT\n" 5057 "\n" 5058 " A() {}\n" 5059 "};", 5060 format("class A : public QObject {\n" 5061 " Q_OBJECT\n" 5062 "\n" 5063 " A() {\n}\n" 5064 "} ;")); 5065 EXPECT_EQ("MACRO\n" 5066 "/*static*/ int i;", 5067 format("MACRO\n" 5068 " /*static*/ int i;")); 5069 EXPECT_EQ("SOME_MACRO\n" 5070 "namespace {\n" 5071 "void f();\n" 5072 "} // namespace", 5073 format("SOME_MACRO\n" 5074 " namespace {\n" 5075 "void f( );\n" 5076 "} // namespace")); 5077 // Only if the identifier contains at least 5 characters. 5078 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5079 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5080 // Only if everything is upper case. 5081 EXPECT_EQ("class A : public QObject {\n" 5082 " Q_Object A() {}\n" 5083 "};", 5084 format("class A : public QObject {\n" 5085 " Q_Object\n" 5086 " A() {\n}\n" 5087 "} ;")); 5088 5089 // Only if the next line can actually start an unwrapped line. 5090 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5091 format("SOME_WEIRD_LOG_MACRO\n" 5092 "<< SomeThing;")); 5093 5094 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5095 "(n, buffers))\n", 5096 getChromiumStyle(FormatStyle::LK_Cpp)); 5097 5098 // See PR41483 5099 EXPECT_EQ("/**/ FOO(a)\n" 5100 "FOO(b)", 5101 format("/**/ FOO(a)\n" 5102 "FOO(b)")); 5103 } 5104 5105 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5106 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5107 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5108 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5109 "class X {};\n" 5110 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5111 "int *createScopDetectionPass() { return 0; }", 5112 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5113 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5114 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5115 " class X {};\n" 5116 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5117 " int *createScopDetectionPass() { return 0; }")); 5118 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5119 // braces, so that inner block is indented one level more. 5120 EXPECT_EQ("int q() {\n" 5121 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5122 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5123 " IPC_END_MESSAGE_MAP()\n" 5124 "}", 5125 format("int q() {\n" 5126 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5127 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5128 " IPC_END_MESSAGE_MAP()\n" 5129 "}")); 5130 5131 // Same inside macros. 5132 EXPECT_EQ("#define LIST(L) \\\n" 5133 " L(A) \\\n" 5134 " L(B) \\\n" 5135 " L(C)", 5136 format("#define LIST(L) \\\n" 5137 " L(A) \\\n" 5138 " L(B) \\\n" 5139 " L(C)", 5140 getGoogleStyle())); 5141 5142 // These must not be recognized as macros. 5143 EXPECT_EQ("int q() {\n" 5144 " f(x);\n" 5145 " f(x) {}\n" 5146 " f(x)->g();\n" 5147 " f(x)->*g();\n" 5148 " f(x).g();\n" 5149 " f(x) = x;\n" 5150 " f(x) += x;\n" 5151 " f(x) -= x;\n" 5152 " f(x) *= x;\n" 5153 " f(x) /= x;\n" 5154 " f(x) %= x;\n" 5155 " f(x) &= x;\n" 5156 " f(x) |= x;\n" 5157 " f(x) ^= x;\n" 5158 " f(x) >>= x;\n" 5159 " f(x) <<= x;\n" 5160 " f(x)[y].z();\n" 5161 " LOG(INFO) << x;\n" 5162 " ifstream(x) >> x;\n" 5163 "}\n", 5164 format("int q() {\n" 5165 " f(x)\n;\n" 5166 " f(x)\n {}\n" 5167 " f(x)\n->g();\n" 5168 " f(x)\n->*g();\n" 5169 " f(x)\n.g();\n" 5170 " f(x)\n = x;\n" 5171 " f(x)\n += x;\n" 5172 " f(x)\n -= x;\n" 5173 " f(x)\n *= x;\n" 5174 " f(x)\n /= x;\n" 5175 " f(x)\n %= x;\n" 5176 " f(x)\n &= x;\n" 5177 " f(x)\n |= x;\n" 5178 " f(x)\n ^= x;\n" 5179 " f(x)\n >>= x;\n" 5180 " f(x)\n <<= x;\n" 5181 " f(x)\n[y].z();\n" 5182 " LOG(INFO)\n << x;\n" 5183 " ifstream(x)\n >> x;\n" 5184 "}\n")); 5185 EXPECT_EQ("int q() {\n" 5186 " F(x)\n" 5187 " if (1) {\n" 5188 " }\n" 5189 " F(x)\n" 5190 " while (1) {\n" 5191 " }\n" 5192 " F(x)\n" 5193 " G(x);\n" 5194 " F(x)\n" 5195 " try {\n" 5196 " Q();\n" 5197 " } catch (...) {\n" 5198 " }\n" 5199 "}\n", 5200 format("int q() {\n" 5201 "F(x)\n" 5202 "if (1) {}\n" 5203 "F(x)\n" 5204 "while (1) {}\n" 5205 "F(x)\n" 5206 "G(x);\n" 5207 "F(x)\n" 5208 "try { Q(); } catch (...) {}\n" 5209 "}\n")); 5210 EXPECT_EQ("class A {\n" 5211 " A() : t(0) {}\n" 5212 " A(int i) noexcept() : {}\n" 5213 " A(X x)\n" // FIXME: function-level try blocks are broken. 5214 " try : t(0) {\n" 5215 " } catch (...) {\n" 5216 " }\n" 5217 "};", 5218 format("class A {\n" 5219 " A()\n : t(0) {}\n" 5220 " A(int i)\n noexcept() : {}\n" 5221 " A(X x)\n" 5222 " try : t(0) {} catch (...) {}\n" 5223 "};")); 5224 FormatStyle Style = getLLVMStyle(); 5225 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5226 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5227 Style.BraceWrapping.AfterFunction = true; 5228 EXPECT_EQ("void f()\n" 5229 "try\n" 5230 "{\n" 5231 "}", 5232 format("void f() try {\n" 5233 "}", 5234 Style)); 5235 EXPECT_EQ("class SomeClass {\n" 5236 "public:\n" 5237 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5238 "};", 5239 format("class SomeClass {\n" 5240 "public:\n" 5241 " SomeClass()\n" 5242 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5243 "};")); 5244 EXPECT_EQ("class SomeClass {\n" 5245 "public:\n" 5246 " SomeClass()\n" 5247 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5248 "};", 5249 format("class SomeClass {\n" 5250 "public:\n" 5251 " SomeClass()\n" 5252 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5253 "};", 5254 getLLVMStyleWithColumns(40))); 5255 5256 verifyFormat("MACRO(>)"); 5257 5258 // Some macros contain an implicit semicolon. 5259 Style = getLLVMStyle(); 5260 Style.StatementMacros.push_back("FOO"); 5261 verifyFormat("FOO(a) int b = 0;"); 5262 verifyFormat("FOO(a)\n" 5263 "int b = 0;", 5264 Style); 5265 verifyFormat("FOO(a);\n" 5266 "int b = 0;", 5267 Style); 5268 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5269 "int b = 0;", 5270 Style); 5271 verifyFormat("FOO()\n" 5272 "int b = 0;", 5273 Style); 5274 verifyFormat("FOO\n" 5275 "int b = 0;", 5276 Style); 5277 verifyFormat("void f() {\n" 5278 " FOO(a)\n" 5279 " return a;\n" 5280 "}", 5281 Style); 5282 verifyFormat("FOO(a)\n" 5283 "FOO(b)", 5284 Style); 5285 verifyFormat("int a = 0;\n" 5286 "FOO(b)\n" 5287 "int c = 0;", 5288 Style); 5289 verifyFormat("int a = 0;\n" 5290 "int x = FOO(a)\n" 5291 "int b = 0;", 5292 Style); 5293 verifyFormat("void foo(int a) { FOO(a) }\n" 5294 "uint32_t bar() {}", 5295 Style); 5296 } 5297 5298 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5299 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5300 5301 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5302 ZeroColumn); 5303 } 5304 5305 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5306 verifyFormat("#define A \\\n" 5307 " f({ \\\n" 5308 " g(); \\\n" 5309 " });", 5310 getLLVMStyleWithColumns(11)); 5311 } 5312 5313 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5314 FormatStyle Style = getLLVMStyleWithColumns(40); 5315 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5316 verifyFormat("#ifdef _WIN32\n" 5317 "#define A 0\n" 5318 "#ifdef VAR2\n" 5319 "#define B 1\n" 5320 "#include <someheader.h>\n" 5321 "#define MACRO \\\n" 5322 " some_very_long_func_aaaaaaaaaa();\n" 5323 "#endif\n" 5324 "#else\n" 5325 "#define A 1\n" 5326 "#endif", 5327 Style); 5328 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5329 verifyFormat("#ifdef _WIN32\n" 5330 "# define A 0\n" 5331 "# ifdef VAR2\n" 5332 "# define B 1\n" 5333 "# include <someheader.h>\n" 5334 "# define MACRO \\\n" 5335 " some_very_long_func_aaaaaaaaaa();\n" 5336 "# endif\n" 5337 "#else\n" 5338 "# define A 1\n" 5339 "#endif", 5340 Style); 5341 verifyFormat("#if A\n" 5342 "# define MACRO \\\n" 5343 " void a(int x) { \\\n" 5344 " b(); \\\n" 5345 " c(); \\\n" 5346 " d(); \\\n" 5347 " e(); \\\n" 5348 " f(); \\\n" 5349 " }\n" 5350 "#endif", 5351 Style); 5352 // Comments before include guard. 5353 verifyFormat("// file comment\n" 5354 "// file comment\n" 5355 "#ifndef HEADER_H\n" 5356 "#define HEADER_H\n" 5357 "code();\n" 5358 "#endif", 5359 Style); 5360 // Test with include guards. 5361 verifyFormat("#ifndef HEADER_H\n" 5362 "#define HEADER_H\n" 5363 "code();\n" 5364 "#endif", 5365 Style); 5366 // Include guards must have a #define with the same variable immediately 5367 // after #ifndef. 5368 verifyFormat("#ifndef NOT_GUARD\n" 5369 "# define FOO\n" 5370 "code();\n" 5371 "#endif", 5372 Style); 5373 5374 // Include guards must cover the entire file. 5375 verifyFormat("code();\n" 5376 "code();\n" 5377 "#ifndef NOT_GUARD\n" 5378 "# define NOT_GUARD\n" 5379 "code();\n" 5380 "#endif", 5381 Style); 5382 verifyFormat("#ifndef NOT_GUARD\n" 5383 "# define NOT_GUARD\n" 5384 "code();\n" 5385 "#endif\n" 5386 "code();", 5387 Style); 5388 // Test with trailing blank lines. 5389 verifyFormat("#ifndef HEADER_H\n" 5390 "#define HEADER_H\n" 5391 "code();\n" 5392 "#endif\n", 5393 Style); 5394 // Include guards don't have #else. 5395 verifyFormat("#ifndef NOT_GUARD\n" 5396 "# define NOT_GUARD\n" 5397 "code();\n" 5398 "#else\n" 5399 "#endif", 5400 Style); 5401 verifyFormat("#ifndef NOT_GUARD\n" 5402 "# define NOT_GUARD\n" 5403 "code();\n" 5404 "#elif FOO\n" 5405 "#endif", 5406 Style); 5407 // Non-identifier #define after potential include guard. 5408 verifyFormat("#ifndef FOO\n" 5409 "# define 1\n" 5410 "#endif\n", 5411 Style); 5412 // #if closes past last non-preprocessor line. 5413 verifyFormat("#ifndef FOO\n" 5414 "#define FOO\n" 5415 "#if 1\n" 5416 "int i;\n" 5417 "# define A 0\n" 5418 "#endif\n" 5419 "#endif\n", 5420 Style); 5421 // Don't crash if there is an #elif directive without a condition. 5422 verifyFormat("#if 1\n" 5423 "int x;\n" 5424 "#elif\n" 5425 "int y;\n" 5426 "#else\n" 5427 "int z;\n" 5428 "#endif", 5429 Style); 5430 // FIXME: This doesn't handle the case where there's code between the 5431 // #ifndef and #define but all other conditions hold. This is because when 5432 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5433 // previous code line yet, so we can't detect it. 5434 EXPECT_EQ("#ifndef NOT_GUARD\n" 5435 "code();\n" 5436 "#define NOT_GUARD\n" 5437 "code();\n" 5438 "#endif", 5439 format("#ifndef NOT_GUARD\n" 5440 "code();\n" 5441 "# define NOT_GUARD\n" 5442 "code();\n" 5443 "#endif", 5444 Style)); 5445 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5446 // be outside an include guard. Examples are #pragma once and 5447 // #pragma GCC diagnostic, or anything else that does not change the meaning 5448 // of the file if it's included multiple times. 5449 EXPECT_EQ("#ifdef WIN32\n" 5450 "# pragma once\n" 5451 "#endif\n" 5452 "#ifndef HEADER_H\n" 5453 "# define HEADER_H\n" 5454 "code();\n" 5455 "#endif", 5456 format("#ifdef WIN32\n" 5457 "# pragma once\n" 5458 "#endif\n" 5459 "#ifndef HEADER_H\n" 5460 "#define HEADER_H\n" 5461 "code();\n" 5462 "#endif", 5463 Style)); 5464 // FIXME: This does not detect when there is a single non-preprocessor line 5465 // in front of an include-guard-like structure where other conditions hold 5466 // because ScopedLineState hides the line. 5467 EXPECT_EQ("code();\n" 5468 "#ifndef HEADER_H\n" 5469 "#define HEADER_H\n" 5470 "code();\n" 5471 "#endif", 5472 format("code();\n" 5473 "#ifndef HEADER_H\n" 5474 "# define HEADER_H\n" 5475 "code();\n" 5476 "#endif", 5477 Style)); 5478 // Keep comments aligned with #, otherwise indent comments normally. These 5479 // tests cannot use verifyFormat because messUp manipulates leading 5480 // whitespace. 5481 { 5482 const char *Expected = "" 5483 "void f() {\n" 5484 "#if 1\n" 5485 "// Preprocessor aligned.\n" 5486 "# define A 0\n" 5487 " // Code. Separated by blank line.\n" 5488 "\n" 5489 "# define B 0\n" 5490 " // Code. Not aligned with #\n" 5491 "# define C 0\n" 5492 "#endif"; 5493 const char *ToFormat = "" 5494 "void f() {\n" 5495 "#if 1\n" 5496 "// Preprocessor aligned.\n" 5497 "# define A 0\n" 5498 "// Code. Separated by blank line.\n" 5499 "\n" 5500 "# define B 0\n" 5501 " // Code. Not aligned with #\n" 5502 "# define C 0\n" 5503 "#endif"; 5504 EXPECT_EQ(Expected, format(ToFormat, Style)); 5505 EXPECT_EQ(Expected, format(Expected, Style)); 5506 } 5507 // Keep block quotes aligned. 5508 { 5509 const char *Expected = "" 5510 "void f() {\n" 5511 "#if 1\n" 5512 "/* Preprocessor aligned. */\n" 5513 "# define A 0\n" 5514 " /* Code. Separated by blank line. */\n" 5515 "\n" 5516 "# define B 0\n" 5517 " /* Code. Not aligned with # */\n" 5518 "# define C 0\n" 5519 "#endif"; 5520 const char *ToFormat = "" 5521 "void f() {\n" 5522 "#if 1\n" 5523 "/* Preprocessor aligned. */\n" 5524 "# define A 0\n" 5525 "/* Code. Separated by blank line. */\n" 5526 "\n" 5527 "# define B 0\n" 5528 " /* Code. Not aligned with # */\n" 5529 "# define C 0\n" 5530 "#endif"; 5531 EXPECT_EQ(Expected, format(ToFormat, Style)); 5532 EXPECT_EQ(Expected, format(Expected, Style)); 5533 } 5534 // Keep comments aligned with un-indented directives. 5535 { 5536 const char *Expected = "" 5537 "void f() {\n" 5538 "// Preprocessor aligned.\n" 5539 "#define A 0\n" 5540 " // Code. Separated by blank line.\n" 5541 "\n" 5542 "#define B 0\n" 5543 " // Code. Not aligned with #\n" 5544 "#define C 0\n"; 5545 const char *ToFormat = "" 5546 "void f() {\n" 5547 "// Preprocessor aligned.\n" 5548 "#define A 0\n" 5549 "// Code. Separated by blank line.\n" 5550 "\n" 5551 "#define B 0\n" 5552 " // Code. Not aligned with #\n" 5553 "#define C 0\n"; 5554 EXPECT_EQ(Expected, format(ToFormat, Style)); 5555 EXPECT_EQ(Expected, format(Expected, Style)); 5556 } 5557 // Test AfterHash with tabs. 5558 { 5559 FormatStyle Tabbed = Style; 5560 Tabbed.UseTab = FormatStyle::UT_Always; 5561 Tabbed.IndentWidth = 8; 5562 Tabbed.TabWidth = 8; 5563 verifyFormat("#ifdef _WIN32\n" 5564 "#\tdefine A 0\n" 5565 "#\tifdef VAR2\n" 5566 "#\t\tdefine B 1\n" 5567 "#\t\tinclude <someheader.h>\n" 5568 "#\t\tdefine MACRO \\\n" 5569 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5570 "#\tendif\n" 5571 "#else\n" 5572 "#\tdefine A 1\n" 5573 "#endif", 5574 Tabbed); 5575 } 5576 5577 // Regression test: Multiline-macro inside include guards. 5578 verifyFormat("#ifndef HEADER_H\n" 5579 "#define HEADER_H\n" 5580 "#define A() \\\n" 5581 " int i; \\\n" 5582 " int j;\n" 5583 "#endif // HEADER_H", 5584 getLLVMStyleWithColumns(20)); 5585 5586 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5587 // Basic before hash indent tests 5588 verifyFormat("#ifdef _WIN32\n" 5589 " #define A 0\n" 5590 " #ifdef VAR2\n" 5591 " #define B 1\n" 5592 " #include <someheader.h>\n" 5593 " #define MACRO \\\n" 5594 " some_very_long_func_aaaaaaaaaa();\n" 5595 " #endif\n" 5596 "#else\n" 5597 " #define A 1\n" 5598 "#endif", 5599 Style); 5600 verifyFormat("#if A\n" 5601 " #define MACRO \\\n" 5602 " void a(int x) { \\\n" 5603 " b(); \\\n" 5604 " c(); \\\n" 5605 " d(); \\\n" 5606 " e(); \\\n" 5607 " f(); \\\n" 5608 " }\n" 5609 "#endif", 5610 Style); 5611 // Keep comments aligned with indented directives. These 5612 // tests cannot use verifyFormat because messUp manipulates leading 5613 // whitespace. 5614 { 5615 const char *Expected = "void f() {\n" 5616 "// Aligned to preprocessor.\n" 5617 "#if 1\n" 5618 " // Aligned to code.\n" 5619 " int a;\n" 5620 " #if 1\n" 5621 " // Aligned to preprocessor.\n" 5622 " #define A 0\n" 5623 " // Aligned to code.\n" 5624 " int b;\n" 5625 " #endif\n" 5626 "#endif\n" 5627 "}"; 5628 const char *ToFormat = "void f() {\n" 5629 "// Aligned to preprocessor.\n" 5630 "#if 1\n" 5631 "// Aligned to code.\n" 5632 "int a;\n" 5633 "#if 1\n" 5634 "// Aligned to preprocessor.\n" 5635 "#define A 0\n" 5636 "// Aligned to code.\n" 5637 "int b;\n" 5638 "#endif\n" 5639 "#endif\n" 5640 "}"; 5641 EXPECT_EQ(Expected, format(ToFormat, Style)); 5642 EXPECT_EQ(Expected, format(Expected, Style)); 5643 } 5644 { 5645 const char *Expected = "void f() {\n" 5646 "/* Aligned to preprocessor. */\n" 5647 "#if 1\n" 5648 " /* Aligned to code. */\n" 5649 " int a;\n" 5650 " #if 1\n" 5651 " /* Aligned to preprocessor. */\n" 5652 " #define A 0\n" 5653 " /* Aligned to code. */\n" 5654 " int b;\n" 5655 " #endif\n" 5656 "#endif\n" 5657 "}"; 5658 const char *ToFormat = "void f() {\n" 5659 "/* Aligned to preprocessor. */\n" 5660 "#if 1\n" 5661 "/* Aligned to code. */\n" 5662 "int a;\n" 5663 "#if 1\n" 5664 "/* Aligned to preprocessor. */\n" 5665 "#define A 0\n" 5666 "/* Aligned to code. */\n" 5667 "int b;\n" 5668 "#endif\n" 5669 "#endif\n" 5670 "}"; 5671 EXPECT_EQ(Expected, format(ToFormat, Style)); 5672 EXPECT_EQ(Expected, format(Expected, Style)); 5673 } 5674 5675 // Test single comment before preprocessor 5676 verifyFormat("// Comment\n" 5677 "\n" 5678 "#if 1\n" 5679 "#endif", 5680 Style); 5681 } 5682 5683 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5684 verifyFormat("{\n { a #c; }\n}"); 5685 } 5686 5687 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5688 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5689 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5690 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5691 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5692 } 5693 5694 TEST_F(FormatTest, EscapedNewlines) { 5695 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5696 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5697 format("#define A \\\nint i;\\\n int j;", Narrow)); 5698 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5699 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5700 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5701 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5702 5703 FormatStyle AlignLeft = getLLVMStyle(); 5704 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5705 EXPECT_EQ("#define MACRO(x) \\\n" 5706 "private: \\\n" 5707 " int x(int a);\n", 5708 format("#define MACRO(x) \\\n" 5709 "private: \\\n" 5710 " int x(int a);\n", 5711 AlignLeft)); 5712 5713 // CRLF line endings 5714 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5715 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5716 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5717 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5718 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5719 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5720 EXPECT_EQ("#define MACRO(x) \\\r\n" 5721 "private: \\\r\n" 5722 " int x(int a);\r\n", 5723 format("#define MACRO(x) \\\r\n" 5724 "private: \\\r\n" 5725 " int x(int a);\r\n", 5726 AlignLeft)); 5727 5728 FormatStyle DontAlign = getLLVMStyle(); 5729 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5730 DontAlign.MaxEmptyLinesToKeep = 3; 5731 // FIXME: can't use verifyFormat here because the newline before 5732 // "public:" is not inserted the first time it's reformatted 5733 EXPECT_EQ("#define A \\\n" 5734 " class Foo { \\\n" 5735 " void bar(); \\\n" 5736 "\\\n" 5737 "\\\n" 5738 "\\\n" 5739 " public: \\\n" 5740 " void baz(); \\\n" 5741 " };", 5742 format("#define A \\\n" 5743 " class Foo { \\\n" 5744 " void bar(); \\\n" 5745 "\\\n" 5746 "\\\n" 5747 "\\\n" 5748 " public: \\\n" 5749 " void baz(); \\\n" 5750 " };", 5751 DontAlign)); 5752 } 5753 5754 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5755 verifyFormat("#define A \\\n" 5756 " int v( \\\n" 5757 " a); \\\n" 5758 " int i;", 5759 getLLVMStyleWithColumns(11)); 5760 } 5761 5762 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5763 EXPECT_EQ( 5764 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5765 " \\\n" 5766 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5767 "\n" 5768 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5769 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5770 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5771 "\\\n" 5772 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5773 " \n" 5774 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5775 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5776 } 5777 5778 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5779 EXPECT_EQ("int\n" 5780 "#define A\n" 5781 " a;", 5782 format("int\n#define A\na;")); 5783 verifyFormat("functionCallTo(\n" 5784 " someOtherFunction(\n" 5785 " withSomeParameters, whichInSequence,\n" 5786 " areLongerThanALine(andAnotherCall,\n" 5787 "#define A B\n" 5788 " withMoreParamters,\n" 5789 " whichStronglyInfluenceTheLayout),\n" 5790 " andMoreParameters),\n" 5791 " trailing);", 5792 getLLVMStyleWithColumns(69)); 5793 verifyFormat("Foo::Foo()\n" 5794 "#ifdef BAR\n" 5795 " : baz(0)\n" 5796 "#endif\n" 5797 "{\n" 5798 "}"); 5799 verifyFormat("void f() {\n" 5800 " if (true)\n" 5801 "#ifdef A\n" 5802 " f(42);\n" 5803 " x();\n" 5804 "#else\n" 5805 " g();\n" 5806 " x();\n" 5807 "#endif\n" 5808 "}"); 5809 verifyFormat("void f(param1, param2,\n" 5810 " param3,\n" 5811 "#ifdef A\n" 5812 " param4(param5,\n" 5813 "#ifdef A1\n" 5814 " param6,\n" 5815 "#ifdef A2\n" 5816 " param7),\n" 5817 "#else\n" 5818 " param8),\n" 5819 " param9,\n" 5820 "#endif\n" 5821 " param10,\n" 5822 "#endif\n" 5823 " param11)\n" 5824 "#else\n" 5825 " param12)\n" 5826 "#endif\n" 5827 "{\n" 5828 " x();\n" 5829 "}", 5830 getLLVMStyleWithColumns(28)); 5831 verifyFormat("#if 1\n" 5832 "int i;"); 5833 verifyFormat("#if 1\n" 5834 "#endif\n" 5835 "#if 1\n" 5836 "#else\n" 5837 "#endif\n"); 5838 verifyFormat("DEBUG({\n" 5839 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5840 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5841 "});\n" 5842 "#if a\n" 5843 "#else\n" 5844 "#endif"); 5845 5846 verifyIncompleteFormat("void f(\n" 5847 "#if A\n" 5848 ");\n" 5849 "#else\n" 5850 "#endif"); 5851 } 5852 5853 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5854 verifyFormat("#endif\n" 5855 "#if B"); 5856 } 5857 5858 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5859 FormatStyle SingleLine = getLLVMStyle(); 5860 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5861 verifyFormat("#if 0\n" 5862 "#elif 1\n" 5863 "#endif\n" 5864 "void foo() {\n" 5865 " if (test) foo2();\n" 5866 "}", 5867 SingleLine); 5868 } 5869 5870 TEST_F(FormatTest, LayoutBlockInsideParens) { 5871 verifyFormat("functionCall({ int i; });"); 5872 verifyFormat("functionCall({\n" 5873 " int i;\n" 5874 " int j;\n" 5875 "});"); 5876 verifyFormat("functionCall(\n" 5877 " {\n" 5878 " int i;\n" 5879 " int j;\n" 5880 " },\n" 5881 " aaaa, bbbb, cccc);"); 5882 verifyFormat("functionA(functionB({\n" 5883 " int i;\n" 5884 " int j;\n" 5885 " }),\n" 5886 " aaaa, bbbb, cccc);"); 5887 verifyFormat("functionCall(\n" 5888 " {\n" 5889 " int i;\n" 5890 " int j;\n" 5891 " },\n" 5892 " aaaa, bbbb, // comment\n" 5893 " cccc);"); 5894 verifyFormat("functionA(functionB({\n" 5895 " int i;\n" 5896 " int j;\n" 5897 " }),\n" 5898 " aaaa, bbbb, // comment\n" 5899 " cccc);"); 5900 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5901 verifyFormat("functionCall(aaaa, bbbb, {\n" 5902 " int i;\n" 5903 " int j;\n" 5904 "});"); 5905 verifyFormat( 5906 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5907 " {\n" 5908 " int i; // break\n" 5909 " },\n" 5910 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5911 " ccccccccccccccccc));"); 5912 verifyFormat("DEBUG({\n" 5913 " if (a)\n" 5914 " f();\n" 5915 "});"); 5916 } 5917 5918 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5919 EXPECT_EQ("SOME_MACRO { int i; }\n" 5920 "int i;", 5921 format(" SOME_MACRO {int i;} int i;")); 5922 } 5923 5924 TEST_F(FormatTest, LayoutNestedBlocks) { 5925 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5926 " struct s {\n" 5927 " int i;\n" 5928 " };\n" 5929 " s kBitsToOs[] = {{10}};\n" 5930 " for (int i = 0; i < 10; ++i)\n" 5931 " return;\n" 5932 "}"); 5933 verifyFormat("call(parameter, {\n" 5934 " something();\n" 5935 " // Comment using all columns.\n" 5936 " somethingelse();\n" 5937 "});", 5938 getLLVMStyleWithColumns(40)); 5939 verifyFormat("DEBUG( //\n" 5940 " { f(); }, a);"); 5941 verifyFormat("DEBUG( //\n" 5942 " {\n" 5943 " f(); //\n" 5944 " },\n" 5945 " a);"); 5946 5947 EXPECT_EQ("call(parameter, {\n" 5948 " something();\n" 5949 " // Comment too\n" 5950 " // looooooooooong.\n" 5951 " somethingElse();\n" 5952 "});", 5953 format("call(parameter, {\n" 5954 " something();\n" 5955 " // Comment too looooooooooong.\n" 5956 " somethingElse();\n" 5957 "});", 5958 getLLVMStyleWithColumns(29))); 5959 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5960 EXPECT_EQ("DEBUG({ // comment\n" 5961 " int i;\n" 5962 "});", 5963 format("DEBUG({ // comment\n" 5964 "int i;\n" 5965 "});")); 5966 EXPECT_EQ("DEBUG({\n" 5967 " int i;\n" 5968 "\n" 5969 " // comment\n" 5970 " int j;\n" 5971 "});", 5972 format("DEBUG({\n" 5973 " int i;\n" 5974 "\n" 5975 " // comment\n" 5976 " int j;\n" 5977 "});")); 5978 5979 verifyFormat("DEBUG({\n" 5980 " if (a)\n" 5981 " return;\n" 5982 "});"); 5983 verifyGoogleFormat("DEBUG({\n" 5984 " if (a) return;\n" 5985 "});"); 5986 FormatStyle Style = getGoogleStyle(); 5987 Style.ColumnLimit = 45; 5988 verifyFormat("Debug(\n" 5989 " aaaaa,\n" 5990 " {\n" 5991 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5992 " },\n" 5993 " a);", 5994 Style); 5995 5996 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5997 5998 verifyNoCrash("^{v^{a}}"); 5999 } 6000 6001 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6002 EXPECT_EQ("#define MACRO() \\\n" 6003 " Debug(aaa, /* force line break */ \\\n" 6004 " { \\\n" 6005 " int i; \\\n" 6006 " int j; \\\n" 6007 " })", 6008 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6009 " { int i; int j; })", 6010 getGoogleStyle())); 6011 6012 EXPECT_EQ("#define A \\\n" 6013 " [] { \\\n" 6014 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6015 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6016 " }", 6017 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6018 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6019 getGoogleStyle())); 6020 } 6021 6022 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6023 EXPECT_EQ("{}", format("{}")); 6024 verifyFormat("enum E {};"); 6025 verifyFormat("enum E {}"); 6026 FormatStyle Style = getLLVMStyle(); 6027 Style.SpaceInEmptyBlock = true; 6028 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6029 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6030 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6031 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6032 Style.BraceWrapping.BeforeElse = false; 6033 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6034 verifyFormat("if (a)\n" 6035 "{\n" 6036 "} else if (b)\n" 6037 "{\n" 6038 "} else\n" 6039 "{ }", 6040 Style); 6041 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6042 verifyFormat("if (a) {\n" 6043 "} else if (b) {\n" 6044 "} else {\n" 6045 "}", 6046 Style); 6047 Style.BraceWrapping.BeforeElse = true; 6048 verifyFormat("if (a) { }\n" 6049 "else if (b) { }\n" 6050 "else { }", 6051 Style); 6052 } 6053 6054 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6055 FormatStyle Style = getLLVMStyle(); 6056 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6057 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6058 verifyFormat("FOO_BEGIN\n" 6059 " FOO_ENTRY\n" 6060 "FOO_END", 6061 Style); 6062 verifyFormat("FOO_BEGIN\n" 6063 " NESTED_FOO_BEGIN\n" 6064 " NESTED_FOO_ENTRY\n" 6065 " NESTED_FOO_END\n" 6066 "FOO_END", 6067 Style); 6068 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6069 " int x;\n" 6070 " x = 1;\n" 6071 "FOO_END(Baz)", 6072 Style); 6073 } 6074 6075 //===----------------------------------------------------------------------===// 6076 // Line break tests. 6077 //===----------------------------------------------------------------------===// 6078 6079 TEST_F(FormatTest, PreventConfusingIndents) { 6080 verifyFormat( 6081 "void f() {\n" 6082 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6083 " parameter, parameter, parameter)),\n" 6084 " SecondLongCall(parameter));\n" 6085 "}"); 6086 verifyFormat( 6087 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6088 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6089 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6090 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6091 verifyFormat( 6092 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6093 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6094 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6095 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6096 verifyFormat( 6097 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6098 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6099 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6100 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6101 verifyFormat("int a = bbbb && ccc &&\n" 6102 " fffff(\n" 6103 "#define A Just forcing a new line\n" 6104 " ddd);"); 6105 } 6106 6107 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6108 verifyFormat( 6109 "bool aaaaaaa =\n" 6110 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6111 " bbbbbbbb();"); 6112 verifyFormat( 6113 "bool aaaaaaa =\n" 6114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6115 " bbbbbbbb();"); 6116 6117 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6119 " ccccccccc == ddddddddddd;"); 6120 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6121 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6122 " ccccccccc == ddddddddddd;"); 6123 verifyFormat( 6124 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6125 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6126 " ccccccccc == ddddddddddd;"); 6127 6128 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6129 " aaaaaa) &&\n" 6130 " bbbbbb && cccccc;"); 6131 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6132 " aaaaaa) >>\n" 6133 " bbbbbb;"); 6134 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6135 " SourceMgr.getSpellingColumnNumber(\n" 6136 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6137 " 1);"); 6138 6139 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6140 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6141 " cccccc) {\n}"); 6142 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6143 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6144 " cccccc) {\n}"); 6145 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6146 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6147 " cccccc) {\n}"); 6148 verifyFormat("b = a &&\n" 6149 " // Comment\n" 6150 " b.c && d;"); 6151 6152 // If the LHS of a comparison is not a binary expression itself, the 6153 // additional linebreak confuses many people. 6154 verifyFormat( 6155 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6156 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6157 "}"); 6158 verifyFormat( 6159 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6161 "}"); 6162 verifyFormat( 6163 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6164 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6165 "}"); 6166 verifyFormat( 6167 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6168 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6169 "}"); 6170 // Even explicit parentheses stress the precedence enough to make the 6171 // additional break unnecessary. 6172 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6174 "}"); 6175 // This cases is borderline, but with the indentation it is still readable. 6176 verifyFormat( 6177 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6178 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6179 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6180 "}", 6181 getLLVMStyleWithColumns(75)); 6182 6183 // If the LHS is a binary expression, we should still use the additional break 6184 // as otherwise the formatting hides the operator precedence. 6185 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6186 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6187 " 5) {\n" 6188 "}"); 6189 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6190 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6191 " 5) {\n" 6192 "}"); 6193 6194 FormatStyle OnePerLine = getLLVMStyle(); 6195 OnePerLine.BinPackParameters = false; 6196 verifyFormat( 6197 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6200 OnePerLine); 6201 6202 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6203 " .aaa(aaaaaaaaaaaaa) *\n" 6204 " aaaaaaa +\n" 6205 " aaaaaaa;", 6206 getLLVMStyleWithColumns(40)); 6207 } 6208 6209 TEST_F(FormatTest, ExpressionIndentation) { 6210 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6211 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6212 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6213 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6214 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6215 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6216 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6217 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6218 " ccccccccccccccccccccccccccccccccccccccccc;"); 6219 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6220 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6222 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6223 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6224 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6225 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6226 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6227 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6229 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6230 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6231 verifyFormat("if () {\n" 6232 "} else if (aaaaa && bbbbb > // break\n" 6233 " ccccc) {\n" 6234 "}"); 6235 verifyFormat("if () {\n" 6236 "} else if constexpr (aaaaa && bbbbb > // break\n" 6237 " ccccc) {\n" 6238 "}"); 6239 verifyFormat("if () {\n" 6240 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6241 " ccccc) {\n" 6242 "}"); 6243 verifyFormat("if () {\n" 6244 "} else if (aaaaa &&\n" 6245 " bbbbb > // break\n" 6246 " ccccc &&\n" 6247 " ddddd) {\n" 6248 "}"); 6249 6250 // Presence of a trailing comment used to change indentation of b. 6251 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6252 " b;\n" 6253 "return aaaaaaaaaaaaaaaaaaa +\n" 6254 " b; //", 6255 getLLVMStyleWithColumns(30)); 6256 } 6257 6258 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6259 // Not sure what the best system is here. Like this, the LHS can be found 6260 // immediately above an operator (everything with the same or a higher 6261 // indent). The RHS is aligned right of the operator and so compasses 6262 // everything until something with the same indent as the operator is found. 6263 // FIXME: Is this a good system? 6264 FormatStyle Style = getLLVMStyle(); 6265 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6266 verifyFormat( 6267 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6268 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6269 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6270 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6271 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6272 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6273 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6274 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6275 " > ccccccccccccccccccccccccccccccccccccccccc;", 6276 Style); 6277 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6278 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6279 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6280 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6281 Style); 6282 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6283 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6284 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6285 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6286 Style); 6287 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6288 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6289 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6290 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6291 Style); 6292 verifyFormat("if () {\n" 6293 "} else if (aaaaa\n" 6294 " && bbbbb // break\n" 6295 " > ccccc) {\n" 6296 "}", 6297 Style); 6298 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6299 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6300 Style); 6301 verifyFormat("return (a)\n" 6302 " // comment\n" 6303 " + b;", 6304 Style); 6305 verifyFormat( 6306 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6307 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6308 " + cc;", 6309 Style); 6310 6311 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6312 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6313 Style); 6314 6315 // Forced by comments. 6316 verifyFormat( 6317 "unsigned ContentSize =\n" 6318 " sizeof(int16_t) // DWARF ARange version number\n" 6319 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6320 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6321 " + sizeof(int8_t); // Segment Size (in bytes)"); 6322 6323 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6324 " == boost::fusion::at_c<1>(iiii).second;", 6325 Style); 6326 6327 Style.ColumnLimit = 60; 6328 verifyFormat("zzzzzzzzzz\n" 6329 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6330 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6331 Style); 6332 6333 Style.ColumnLimit = 80; 6334 Style.IndentWidth = 4; 6335 Style.TabWidth = 4; 6336 Style.UseTab = FormatStyle::UT_Always; 6337 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6338 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6339 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6340 "\t&& (someOtherLongishConditionPart1\n" 6341 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6342 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6343 "(someOtherLongishConditionPart1 || " 6344 "someOtherEvenLongerNestedConditionPart2);", 6345 Style)); 6346 } 6347 6348 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6349 FormatStyle Style = getLLVMStyle(); 6350 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6351 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6352 6353 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6354 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6355 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6356 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6357 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6358 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6359 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6360 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6361 " > ccccccccccccccccccccccccccccccccccccccccc;", 6362 Style); 6363 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6364 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6365 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6366 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6367 Style); 6368 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6369 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6370 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6371 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6372 Style); 6373 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6374 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6375 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6376 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6377 Style); 6378 verifyFormat("if () {\n" 6379 "} else if (aaaaa\n" 6380 " && bbbbb // break\n" 6381 " > ccccc) {\n" 6382 "}", 6383 Style); 6384 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6385 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6386 Style); 6387 verifyFormat("return (a)\n" 6388 " // comment\n" 6389 " + b;", 6390 Style); 6391 verifyFormat( 6392 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6393 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6394 " + cc;", 6395 Style); 6396 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6397 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6398 " : 3333333333333333;", 6399 Style); 6400 verifyFormat( 6401 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6402 " : ccccccccccccccc ? dddddddddddddddddd\n" 6403 " : eeeeeeeeeeeeeeeeee)\n" 6404 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6405 " : 3333333333333333;", 6406 Style); 6407 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6408 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6409 Style); 6410 6411 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6412 " == boost::fusion::at_c<1>(iiii).second;", 6413 Style); 6414 6415 Style.ColumnLimit = 60; 6416 verifyFormat("zzzzzzzzzzzzz\n" 6417 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6418 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6419 Style); 6420 6421 // Forced by comments. 6422 Style.ColumnLimit = 80; 6423 verifyFormat( 6424 "unsigned ContentSize\n" 6425 " = sizeof(int16_t) // DWARF ARange version number\n" 6426 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6427 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6428 " + sizeof(int8_t); // Segment Size (in bytes)", 6429 Style); 6430 6431 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6432 verifyFormat( 6433 "unsigned ContentSize =\n" 6434 " sizeof(int16_t) // DWARF ARange version number\n" 6435 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6436 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6437 " + sizeof(int8_t); // Segment Size (in bytes)", 6438 Style); 6439 6440 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6441 verifyFormat( 6442 "unsigned ContentSize =\n" 6443 " sizeof(int16_t) // DWARF ARange version number\n" 6444 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6445 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6446 " + sizeof(int8_t); // Segment Size (in bytes)", 6447 Style); 6448 } 6449 6450 TEST_F(FormatTest, EnforcedOperatorWraps) { 6451 // Here we'd like to wrap after the || operators, but a comment is forcing an 6452 // earlier wrap. 6453 verifyFormat("bool x = aaaaa //\n" 6454 " || bbbbb\n" 6455 " //\n" 6456 " || cccc;"); 6457 } 6458 6459 TEST_F(FormatTest, NoOperandAlignment) { 6460 FormatStyle Style = getLLVMStyle(); 6461 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6462 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6464 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6465 Style); 6466 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6467 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6468 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6469 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6470 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6471 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6472 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6473 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6474 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6475 " > ccccccccccccccccccccccccccccccccccccccccc;", 6476 Style); 6477 6478 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6479 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6480 " + cc;", 6481 Style); 6482 verifyFormat("int a = aa\n" 6483 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6484 " * cccccccccccccccccccccccccccccccccccc;\n", 6485 Style); 6486 6487 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6488 verifyFormat("return (a > b\n" 6489 " // comment1\n" 6490 " // comment2\n" 6491 " || c);", 6492 Style); 6493 } 6494 6495 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6496 FormatStyle Style = getLLVMStyle(); 6497 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6498 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6499 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6500 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6501 Style); 6502 } 6503 6504 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6505 FormatStyle Style = getLLVMStyleWithColumns(40); 6506 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6507 Style.BinPackArguments = false; 6508 verifyFormat("void test() {\n" 6509 " someFunction(\n" 6510 " this + argument + is + quite\n" 6511 " + long + so + it + gets + wrapped\n" 6512 " + but + remains + bin - packed);\n" 6513 "}", 6514 Style); 6515 verifyFormat("void test() {\n" 6516 " someFunction(arg1,\n" 6517 " this + argument + is\n" 6518 " + quite + long + so\n" 6519 " + it + gets + wrapped\n" 6520 " + but + remains + bin\n" 6521 " - packed,\n" 6522 " arg3);\n" 6523 "}", 6524 Style); 6525 verifyFormat("void test() {\n" 6526 " someFunction(\n" 6527 " arg1,\n" 6528 " this + argument + has\n" 6529 " + anotherFunc(nested,\n" 6530 " calls + whose\n" 6531 " + arguments\n" 6532 " + are + also\n" 6533 " + wrapped,\n" 6534 " in + addition)\n" 6535 " + to + being + bin - packed,\n" 6536 " arg3);\n" 6537 "}", 6538 Style); 6539 6540 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6541 verifyFormat("void test() {\n" 6542 " someFunction(\n" 6543 " arg1,\n" 6544 " this + argument + has +\n" 6545 " anotherFunc(nested,\n" 6546 " calls + whose +\n" 6547 " arguments +\n" 6548 " are + also +\n" 6549 " wrapped,\n" 6550 " in + addition) +\n" 6551 " to + being + bin - packed,\n" 6552 " arg3);\n" 6553 "}", 6554 Style); 6555 } 6556 6557 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6558 auto Style = getLLVMStyleWithColumns(45); 6559 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6560 verifyFormat("bool b =\n" 6561 " is_default_constructible_v<hash<T>> and\n" 6562 " is_copy_constructible_v<hash<T>> and\n" 6563 " is_move_constructible_v<hash<T>> and\n" 6564 " is_copy_assignable_v<hash<T>> and\n" 6565 " is_move_assignable_v<hash<T>> and\n" 6566 " is_destructible_v<hash<T>> and\n" 6567 " is_swappable_v<hash<T>> and\n" 6568 " is_callable_v<hash<T>(T)>;", 6569 Style); 6570 6571 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6572 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6573 " and is_copy_constructible_v<hash<T>>\n" 6574 " and is_move_constructible_v<hash<T>>\n" 6575 " and is_copy_assignable_v<hash<T>>\n" 6576 " and is_move_assignable_v<hash<T>>\n" 6577 " and is_destructible_v<hash<T>>\n" 6578 " and is_swappable_v<hash<T>>\n" 6579 " and is_callable_v<hash<T>(T)>;", 6580 Style); 6581 6582 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6583 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6584 " and is_copy_constructible_v<hash<T>>\n" 6585 " and is_move_constructible_v<hash<T>>\n" 6586 " and is_copy_assignable_v<hash<T>>\n" 6587 " and is_move_assignable_v<hash<T>>\n" 6588 " and is_destructible_v<hash<T>>\n" 6589 " and is_swappable_v<hash<T>>\n" 6590 " and is_callable_v<hash<T>(T)>;", 6591 Style); 6592 } 6593 6594 TEST_F(FormatTest, ConstructorInitializers) { 6595 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6596 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6597 getLLVMStyleWithColumns(45)); 6598 verifyFormat("Constructor()\n" 6599 " : Inttializer(FitsOnTheLine) {}", 6600 getLLVMStyleWithColumns(44)); 6601 verifyFormat("Constructor()\n" 6602 " : Inttializer(FitsOnTheLine) {}", 6603 getLLVMStyleWithColumns(43)); 6604 6605 verifyFormat("template <typename T>\n" 6606 "Constructor() : Initializer(FitsOnTheLine) {}", 6607 getLLVMStyleWithColumns(45)); 6608 6609 verifyFormat( 6610 "SomeClass::Constructor()\n" 6611 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6612 6613 verifyFormat( 6614 "SomeClass::Constructor()\n" 6615 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6616 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6617 verifyFormat( 6618 "SomeClass::Constructor()\n" 6619 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6620 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6621 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6622 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6623 " : aaaaaaaaaa(aaaaaa) {}"); 6624 6625 verifyFormat("Constructor()\n" 6626 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6627 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6628 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6629 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6630 6631 verifyFormat("Constructor()\n" 6632 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6633 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6634 6635 verifyFormat("Constructor(int Parameter = 0)\n" 6636 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6637 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6638 verifyFormat("Constructor()\n" 6639 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6640 "}", 6641 getLLVMStyleWithColumns(60)); 6642 verifyFormat("Constructor()\n" 6643 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6644 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6645 6646 // Here a line could be saved by splitting the second initializer onto two 6647 // lines, but that is not desirable. 6648 verifyFormat("Constructor()\n" 6649 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6650 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6651 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6652 6653 FormatStyle OnePerLine = getLLVMStyle(); 6654 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6655 verifyFormat("MyClass::MyClass()\n" 6656 " : a(a),\n" 6657 " b(b),\n" 6658 " c(c) {}", 6659 OnePerLine); 6660 verifyFormat("MyClass::MyClass()\n" 6661 " : a(a), // comment\n" 6662 " b(b),\n" 6663 " c(c) {}", 6664 OnePerLine); 6665 verifyFormat("MyClass::MyClass(int a)\n" 6666 " : b(a), // comment\n" 6667 " c(a + 1) { // lined up\n" 6668 "}", 6669 OnePerLine); 6670 verifyFormat("Constructor()\n" 6671 " : a(b, b, b) {}", 6672 OnePerLine); 6673 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6674 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6675 verifyFormat("SomeClass::Constructor()\n" 6676 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6677 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6678 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6679 OnePerLine); 6680 verifyFormat("SomeClass::Constructor()\n" 6681 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6682 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6683 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6684 OnePerLine); 6685 verifyFormat("MyClass::MyClass(int var)\n" 6686 " : some_var_(var), // 4 space indent\n" 6687 " some_other_var_(var + 1) { // lined up\n" 6688 "}", 6689 OnePerLine); 6690 verifyFormat("Constructor()\n" 6691 " : aaaaa(aaaaaa),\n" 6692 " aaaaa(aaaaaa),\n" 6693 " aaaaa(aaaaaa),\n" 6694 " aaaaa(aaaaaa),\n" 6695 " aaaaa(aaaaaa) {}", 6696 OnePerLine); 6697 verifyFormat("Constructor()\n" 6698 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6699 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6700 OnePerLine); 6701 OnePerLine.BinPackParameters = false; 6702 verifyFormat( 6703 "Constructor()\n" 6704 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6705 " aaaaaaaaaaa().aaa(),\n" 6706 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6707 OnePerLine); 6708 OnePerLine.ColumnLimit = 60; 6709 verifyFormat("Constructor()\n" 6710 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6711 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6712 OnePerLine); 6713 6714 EXPECT_EQ("Constructor()\n" 6715 " : // Comment forcing unwanted break.\n" 6716 " aaaa(aaaa) {}", 6717 format("Constructor() :\n" 6718 " // Comment forcing unwanted break.\n" 6719 " aaaa(aaaa) {}")); 6720 } 6721 6722 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6723 FormatStyle Style = getLLVMStyleWithColumns(60); 6724 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6725 Style.BinPackParameters = false; 6726 6727 for (int i = 0; i < 4; ++i) { 6728 // Test all combinations of parameters that should not have an effect. 6729 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6730 Style.AllowAllArgumentsOnNextLine = i & 2; 6731 6732 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6733 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6734 verifyFormat("Constructor()\n" 6735 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6736 Style); 6737 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6738 6739 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6740 verifyFormat("Constructor()\n" 6741 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6742 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6743 Style); 6744 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6745 6746 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6747 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6748 verifyFormat("Constructor()\n" 6749 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6750 Style); 6751 6752 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6753 verifyFormat("Constructor()\n" 6754 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6755 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6756 Style); 6757 6758 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6759 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6760 verifyFormat("Constructor() :\n" 6761 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6762 Style); 6763 6764 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6765 verifyFormat("Constructor() :\n" 6766 " aaaaaaaaaaaaaaaaaa(a),\n" 6767 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6768 Style); 6769 } 6770 6771 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6772 // AllowAllConstructorInitializersOnNextLine in all 6773 // BreakConstructorInitializers modes 6774 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6775 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6776 verifyFormat("SomeClassWithALongName::Constructor(\n" 6777 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6778 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6779 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6780 Style); 6781 6782 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6783 verifyFormat("SomeClassWithALongName::Constructor(\n" 6784 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6785 " int bbbbbbbbbbbbb,\n" 6786 " int cccccccccccccccc)\n" 6787 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6788 Style); 6789 6790 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6791 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6792 verifyFormat("SomeClassWithALongName::Constructor(\n" 6793 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6794 " int bbbbbbbbbbbbb)\n" 6795 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6796 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6797 Style); 6798 6799 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6800 6801 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6802 verifyFormat("SomeClassWithALongName::Constructor(\n" 6803 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6804 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6805 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6806 Style); 6807 6808 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6809 verifyFormat("SomeClassWithALongName::Constructor(\n" 6810 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6811 " int bbbbbbbbbbbbb,\n" 6812 " int cccccccccccccccc)\n" 6813 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6814 Style); 6815 6816 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6817 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6818 verifyFormat("SomeClassWithALongName::Constructor(\n" 6819 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6820 " int bbbbbbbbbbbbb)\n" 6821 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6822 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6823 Style); 6824 6825 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6826 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6827 verifyFormat("SomeClassWithALongName::Constructor(\n" 6828 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6829 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6830 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6831 Style); 6832 6833 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6834 verifyFormat("SomeClassWithALongName::Constructor(\n" 6835 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6836 " int bbbbbbbbbbbbb,\n" 6837 " int cccccccccccccccc) :\n" 6838 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6839 Style); 6840 6841 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6842 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6843 verifyFormat("SomeClassWithALongName::Constructor(\n" 6844 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6845 " int bbbbbbbbbbbbb) :\n" 6846 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6847 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6848 Style); 6849 } 6850 6851 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6852 FormatStyle Style = getLLVMStyleWithColumns(60); 6853 Style.BinPackArguments = false; 6854 for (int i = 0; i < 4; ++i) { 6855 // Test all combinations of parameters that should not have an effect. 6856 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6857 Style.PackConstructorInitializers = 6858 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6859 6860 Style.AllowAllArgumentsOnNextLine = true; 6861 verifyFormat("void foo() {\n" 6862 " FunctionCallWithReallyLongName(\n" 6863 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6864 "}", 6865 Style); 6866 Style.AllowAllArgumentsOnNextLine = false; 6867 verifyFormat("void foo() {\n" 6868 " FunctionCallWithReallyLongName(\n" 6869 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6870 " bbbbbbbbbbbb);\n" 6871 "}", 6872 Style); 6873 6874 Style.AllowAllArgumentsOnNextLine = true; 6875 verifyFormat("void foo() {\n" 6876 " auto VariableWithReallyLongName = {\n" 6877 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6878 "}", 6879 Style); 6880 Style.AllowAllArgumentsOnNextLine = false; 6881 verifyFormat("void foo() {\n" 6882 " auto VariableWithReallyLongName = {\n" 6883 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6884 " bbbbbbbbbbbb};\n" 6885 "}", 6886 Style); 6887 } 6888 6889 // This parameter should not affect declarations. 6890 Style.BinPackParameters = false; 6891 Style.AllowAllArgumentsOnNextLine = false; 6892 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6893 verifyFormat("void FunctionCallWithReallyLongName(\n" 6894 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6895 Style); 6896 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6897 verifyFormat("void FunctionCallWithReallyLongName(\n" 6898 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6899 " int bbbbbbbbbbbb);", 6900 Style); 6901 } 6902 6903 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6904 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6905 // and BAS_Align. 6906 FormatStyle Style = getLLVMStyleWithColumns(35); 6907 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6908 "void functionDecl(int A, int B, int C);"; 6909 Style.AllowAllArgumentsOnNextLine = false; 6910 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6911 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6912 " paramC);\n" 6913 "void functionDecl(int A, int B,\n" 6914 " int C);"), 6915 format(Input, Style)); 6916 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6917 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6918 " paramC);\n" 6919 "void functionDecl(int A, int B,\n" 6920 " int C);"), 6921 format(Input, Style)); 6922 // However, BAS_AlwaysBreak should take precedence over 6923 // AllowAllArgumentsOnNextLine. 6924 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6925 EXPECT_EQ(StringRef("functionCall(\n" 6926 " paramA, paramB, paramC);\n" 6927 "void functionDecl(\n" 6928 " int A, int B, int C);"), 6929 format(Input, Style)); 6930 6931 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6932 // first argument. 6933 Style.AllowAllArgumentsOnNextLine = true; 6934 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6935 EXPECT_EQ(StringRef("functionCall(\n" 6936 " paramA, paramB, paramC);\n" 6937 "void functionDecl(\n" 6938 " int A, int B, int C);"), 6939 format(Input, Style)); 6940 // It wouldn't fit on one line with aligned parameters so this setting 6941 // doesn't change anything for BAS_Align. 6942 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6943 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6944 " paramC);\n" 6945 "void functionDecl(int A, int B,\n" 6946 " int C);"), 6947 format(Input, Style)); 6948 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6949 EXPECT_EQ(StringRef("functionCall(\n" 6950 " paramA, paramB, paramC);\n" 6951 "void functionDecl(\n" 6952 " int A, int B, int C);"), 6953 format(Input, Style)); 6954 } 6955 6956 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6957 FormatStyle Style = getLLVMStyle(); 6958 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6959 6960 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6961 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6962 getStyleWithColumns(Style, 45)); 6963 verifyFormat("Constructor() :\n" 6964 " Initializer(FitsOnTheLine) {}", 6965 getStyleWithColumns(Style, 44)); 6966 verifyFormat("Constructor() :\n" 6967 " Initializer(FitsOnTheLine) {}", 6968 getStyleWithColumns(Style, 43)); 6969 6970 verifyFormat("template <typename T>\n" 6971 "Constructor() : Initializer(FitsOnTheLine) {}", 6972 getStyleWithColumns(Style, 50)); 6973 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6974 verifyFormat( 6975 "SomeClass::Constructor() :\n" 6976 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6977 Style); 6978 6979 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6980 verifyFormat( 6981 "SomeClass::Constructor() :\n" 6982 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6983 Style); 6984 6985 verifyFormat( 6986 "SomeClass::Constructor() :\n" 6987 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6988 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6989 Style); 6990 verifyFormat( 6991 "SomeClass::Constructor() :\n" 6992 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6993 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6994 Style); 6995 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6996 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6997 " aaaaaaaaaa(aaaaaa) {}", 6998 Style); 6999 7000 verifyFormat("Constructor() :\n" 7001 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7002 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7003 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7004 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7005 Style); 7006 7007 verifyFormat("Constructor() :\n" 7008 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7009 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7010 Style); 7011 7012 verifyFormat("Constructor(int Parameter = 0) :\n" 7013 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7014 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7015 Style); 7016 verifyFormat("Constructor() :\n" 7017 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7018 "}", 7019 getStyleWithColumns(Style, 60)); 7020 verifyFormat("Constructor() :\n" 7021 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7022 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7023 Style); 7024 7025 // Here a line could be saved by splitting the second initializer onto two 7026 // lines, but that is not desirable. 7027 verifyFormat("Constructor() :\n" 7028 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7029 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7030 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7031 Style); 7032 7033 FormatStyle OnePerLine = Style; 7034 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7035 verifyFormat("SomeClass::Constructor() :\n" 7036 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7037 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7038 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7039 OnePerLine); 7040 verifyFormat("SomeClass::Constructor() :\n" 7041 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7042 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7043 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7044 OnePerLine); 7045 verifyFormat("MyClass::MyClass(int var) :\n" 7046 " some_var_(var), // 4 space indent\n" 7047 " some_other_var_(var + 1) { // lined up\n" 7048 "}", 7049 OnePerLine); 7050 verifyFormat("Constructor() :\n" 7051 " aaaaa(aaaaaa),\n" 7052 " aaaaa(aaaaaa),\n" 7053 " aaaaa(aaaaaa),\n" 7054 " aaaaa(aaaaaa),\n" 7055 " aaaaa(aaaaaa) {}", 7056 OnePerLine); 7057 verifyFormat("Constructor() :\n" 7058 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7059 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7060 OnePerLine); 7061 OnePerLine.BinPackParameters = false; 7062 verifyFormat("Constructor() :\n" 7063 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7064 " aaaaaaaaaaa().aaa(),\n" 7065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7066 OnePerLine); 7067 OnePerLine.ColumnLimit = 60; 7068 verifyFormat("Constructor() :\n" 7069 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7070 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7071 OnePerLine); 7072 7073 EXPECT_EQ("Constructor() :\n" 7074 " // Comment forcing unwanted break.\n" 7075 " aaaa(aaaa) {}", 7076 format("Constructor() :\n" 7077 " // Comment forcing unwanted break.\n" 7078 " aaaa(aaaa) {}", 7079 Style)); 7080 7081 Style.ColumnLimit = 0; 7082 verifyFormat("SomeClass::Constructor() :\n" 7083 " a(a) {}", 7084 Style); 7085 verifyFormat("SomeClass::Constructor() noexcept :\n" 7086 " a(a) {}", 7087 Style); 7088 verifyFormat("SomeClass::Constructor() :\n" 7089 " a(a), b(b), c(c) {}", 7090 Style); 7091 verifyFormat("SomeClass::Constructor() :\n" 7092 " a(a) {\n" 7093 " foo();\n" 7094 " bar();\n" 7095 "}", 7096 Style); 7097 7098 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7099 verifyFormat("SomeClass::Constructor() :\n" 7100 " a(a), b(b), c(c) {\n" 7101 "}", 7102 Style); 7103 verifyFormat("SomeClass::Constructor() :\n" 7104 " a(a) {\n" 7105 "}", 7106 Style); 7107 7108 Style.ColumnLimit = 80; 7109 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7110 Style.ConstructorInitializerIndentWidth = 2; 7111 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7112 verifyFormat("SomeClass::Constructor() :\n" 7113 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7114 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7115 Style); 7116 7117 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7118 // well 7119 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7120 verifyFormat( 7121 "class SomeClass\n" 7122 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7123 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7124 Style); 7125 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7126 verifyFormat( 7127 "class SomeClass\n" 7128 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7129 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7130 Style); 7131 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7132 verifyFormat( 7133 "class SomeClass :\n" 7134 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7135 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7136 Style); 7137 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7138 verifyFormat( 7139 "class SomeClass\n" 7140 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7141 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7142 Style); 7143 } 7144 7145 #ifndef EXPENSIVE_CHECKS 7146 // Expensive checks enables libstdc++ checking which includes validating the 7147 // state of ranges used in std::priority_queue - this blows out the 7148 // runtime/scalability of the function and makes this test unacceptably slow. 7149 TEST_F(FormatTest, MemoizationTests) { 7150 // This breaks if the memoization lookup does not take \c Indent and 7151 // \c LastSpace into account. 7152 verifyFormat( 7153 "extern CFRunLoopTimerRef\n" 7154 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7155 " CFTimeInterval interval, CFOptionFlags flags,\n" 7156 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7157 " CFRunLoopTimerContext *context) {}"); 7158 7159 // Deep nesting somewhat works around our memoization. 7160 verifyFormat( 7161 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7162 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7163 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7164 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7165 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7166 getLLVMStyleWithColumns(65)); 7167 verifyFormat( 7168 "aaaaa(\n" 7169 " aaaaa,\n" 7170 " aaaaa(\n" 7171 " aaaaa,\n" 7172 " aaaaa(\n" 7173 " aaaaa,\n" 7174 " aaaaa(\n" 7175 " aaaaa,\n" 7176 " aaaaa(\n" 7177 " aaaaa,\n" 7178 " aaaaa(\n" 7179 " aaaaa,\n" 7180 " aaaaa(\n" 7181 " aaaaa,\n" 7182 " aaaaa(\n" 7183 " aaaaa,\n" 7184 " aaaaa(\n" 7185 " aaaaa,\n" 7186 " aaaaa(\n" 7187 " aaaaa,\n" 7188 " aaaaa(\n" 7189 " aaaaa,\n" 7190 " aaaaa(\n" 7191 " aaaaa,\n" 7192 " aaaaa))))))))))));", 7193 getLLVMStyleWithColumns(65)); 7194 verifyFormat( 7195 "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n" 7196 " a),\n" 7197 " a),\n" 7198 " a),\n" 7199 " a),\n" 7200 " a),\n" 7201 " a),\n" 7202 " a),\n" 7203 " a),\n" 7204 " a),\n" 7205 " a),\n" 7206 " a),\n" 7207 " a),\n" 7208 " a),\n" 7209 " a),\n" 7210 " a),\n" 7211 " a),\n" 7212 " a)", 7213 getLLVMStyleWithColumns(65)); 7214 7215 // This test takes VERY long when memoization is broken. 7216 FormatStyle OnePerLine = getLLVMStyle(); 7217 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7218 OnePerLine.BinPackParameters = false; 7219 std::string input = "Constructor()\n" 7220 " : aaaa(a,\n"; 7221 for (unsigned i = 0, e = 80; i != e; ++i) 7222 input += " a,\n"; 7223 input += " a) {}"; 7224 verifyFormat(input, OnePerLine); 7225 } 7226 #endif 7227 7228 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7229 verifyFormat( 7230 "void f() {\n" 7231 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7232 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7233 " f();\n" 7234 "}"); 7235 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7236 " Intervals[i - 1].getRange().getLast()) {\n}"); 7237 } 7238 7239 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7240 // Principially, we break function declarations in a certain order: 7241 // 1) break amongst arguments. 7242 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7243 " Cccccccccccccc cccccccccccccc);"); 7244 verifyFormat("template <class TemplateIt>\n" 7245 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7246 " TemplateIt *stop) {}"); 7247 7248 // 2) break after return type. 7249 verifyFormat( 7250 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7251 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7252 getGoogleStyle()); 7253 7254 // 3) break after (. 7255 verifyFormat( 7256 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7257 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7258 getGoogleStyle()); 7259 7260 // 4) break before after nested name specifiers. 7261 verifyFormat( 7262 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7263 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7264 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7265 getGoogleStyle()); 7266 7267 // However, there are exceptions, if a sufficient amount of lines can be 7268 // saved. 7269 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7270 // more adjusting. 7271 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7272 " Cccccccccccccc cccccccccc,\n" 7273 " Cccccccccccccc cccccccccc,\n" 7274 " Cccccccccccccc cccccccccc,\n" 7275 " Cccccccccccccc cccccccccc);"); 7276 verifyFormat( 7277 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7278 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7279 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7280 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7281 getGoogleStyle()); 7282 verifyFormat( 7283 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7284 " Cccccccccccccc cccccccccc,\n" 7285 " Cccccccccccccc cccccccccc,\n" 7286 " Cccccccccccccc cccccccccc,\n" 7287 " Cccccccccccccc cccccccccc,\n" 7288 " Cccccccccccccc cccccccccc,\n" 7289 " Cccccccccccccc cccccccccc);"); 7290 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7291 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7292 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7293 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7294 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7295 7296 // Break after multi-line parameters. 7297 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7298 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7299 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7300 " bbbb bbbb);"); 7301 verifyFormat("void SomeLoooooooooooongFunction(\n" 7302 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7303 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7304 " int bbbbbbbbbbbbb);"); 7305 7306 // Treat overloaded operators like other functions. 7307 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7308 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7309 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7310 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7311 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7312 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7313 verifyGoogleFormat( 7314 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7315 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7316 verifyGoogleFormat( 7317 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7318 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7319 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7320 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7321 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7322 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7323 verifyGoogleFormat( 7324 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7325 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7326 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7327 verifyGoogleFormat("template <typename T>\n" 7328 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7329 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7330 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7331 7332 FormatStyle Style = getLLVMStyle(); 7333 Style.PointerAlignment = FormatStyle::PAS_Left; 7334 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7335 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7336 Style); 7337 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7338 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7339 Style); 7340 } 7341 7342 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7343 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7344 // Prefer keeping `::` followed by `operator` together. 7345 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7346 "ccccccccc::operator++() {\n" 7347 " stuff();\n" 7348 "}", 7349 format("const aaaa::bbbbbbb\n" 7350 "&ccccccccc::operator++() { stuff(); }", 7351 getLLVMStyleWithColumns(40))); 7352 } 7353 7354 TEST_F(FormatTest, TrailingReturnType) { 7355 verifyFormat("auto foo() -> int;\n"); 7356 // correct trailing return type spacing 7357 verifyFormat("auto operator->() -> int;\n"); 7358 verifyFormat("auto operator++(int) -> int;\n"); 7359 7360 verifyFormat("struct S {\n" 7361 " auto bar() const -> int;\n" 7362 "};"); 7363 verifyFormat("template <size_t Order, typename T>\n" 7364 "auto load_img(const std::string &filename)\n" 7365 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7366 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7367 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7368 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7369 verifyFormat("template <typename T>\n" 7370 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7371 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7372 7373 // Not trailing return types. 7374 verifyFormat("void f() { auto a = b->c(); }"); 7375 verifyFormat("auto a = p->foo();"); 7376 verifyFormat("int a = p->foo();"); 7377 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7378 } 7379 7380 TEST_F(FormatTest, DeductionGuides) { 7381 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7382 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7383 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7384 verifyFormat( 7385 "template <class... T>\n" 7386 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7387 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7388 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7389 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7390 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7391 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7392 verifyFormat("template <class T> x() -> x<1>;"); 7393 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7394 7395 // Ensure not deduction guides. 7396 verifyFormat("c()->f<int>();"); 7397 verifyFormat("x()->foo<1>;"); 7398 verifyFormat("x = p->foo<3>();"); 7399 verifyFormat("x()->x<1>();"); 7400 verifyFormat("x()->x<1>;"); 7401 } 7402 7403 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7404 // Avoid breaking before trailing 'const' or other trailing annotations, if 7405 // they are not function-like. 7406 FormatStyle Style = getGoogleStyleWithColumns(47); 7407 verifyFormat("void someLongFunction(\n" 7408 " int someLoooooooooooooongParameter) const {\n}", 7409 getLLVMStyleWithColumns(47)); 7410 verifyFormat("LoooooongReturnType\n" 7411 "someLoooooooongFunction() const {}", 7412 getLLVMStyleWithColumns(47)); 7413 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7414 " const {}", 7415 Style); 7416 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7417 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7418 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7419 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7420 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7421 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7422 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7423 " aaaaaaaaaaa aaaaa) const override;"); 7424 verifyGoogleFormat( 7425 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7426 " const override;"); 7427 7428 // Even if the first parameter has to be wrapped. 7429 verifyFormat("void someLongFunction(\n" 7430 " int someLongParameter) const {}", 7431 getLLVMStyleWithColumns(46)); 7432 verifyFormat("void someLongFunction(\n" 7433 " int someLongParameter) const {}", 7434 Style); 7435 verifyFormat("void someLongFunction(\n" 7436 " int someLongParameter) override {}", 7437 Style); 7438 verifyFormat("void someLongFunction(\n" 7439 " int someLongParameter) OVERRIDE {}", 7440 Style); 7441 verifyFormat("void someLongFunction(\n" 7442 " int someLongParameter) final {}", 7443 Style); 7444 verifyFormat("void someLongFunction(\n" 7445 " int someLongParameter) FINAL {}", 7446 Style); 7447 verifyFormat("void someLongFunction(\n" 7448 " int parameter) const override {}", 7449 Style); 7450 7451 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7452 verifyFormat("void someLongFunction(\n" 7453 " int someLongParameter) const\n" 7454 "{\n" 7455 "}", 7456 Style); 7457 7458 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7459 verifyFormat("void someLongFunction(\n" 7460 " int someLongParameter) const\n" 7461 " {\n" 7462 " }", 7463 Style); 7464 7465 // Unless these are unknown annotations. 7466 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7467 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7468 " LONG_AND_UGLY_ANNOTATION;"); 7469 7470 // Breaking before function-like trailing annotations is fine to keep them 7471 // close to their arguments. 7472 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7473 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7474 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7475 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7476 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7477 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7478 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7479 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7480 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7481 7482 verifyFormat( 7483 "void aaaaaaaaaaaaaaaaaa()\n" 7484 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7485 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7486 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7487 " __attribute__((unused));"); 7488 verifyGoogleFormat( 7489 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7490 " GUARDED_BY(aaaaaaaaaaaa);"); 7491 verifyGoogleFormat( 7492 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7493 " GUARDED_BY(aaaaaaaaaaaa);"); 7494 verifyGoogleFormat( 7495 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7496 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7497 verifyGoogleFormat( 7498 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7499 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7500 } 7501 7502 TEST_F(FormatTest, FunctionAnnotations) { 7503 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7504 "int OldFunction(const string ¶meter) {}"); 7505 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7506 "string OldFunction(const string ¶meter) {}"); 7507 verifyFormat("template <typename T>\n" 7508 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7509 "string OldFunction(const string ¶meter) {}"); 7510 7511 // Not function annotations. 7512 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7513 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7514 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7515 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7516 verifyFormat("MACRO(abc).function() // wrap\n" 7517 " << abc;"); 7518 verifyFormat("MACRO(abc)->function() // wrap\n" 7519 " << abc;"); 7520 verifyFormat("MACRO(abc)::function() // wrap\n" 7521 " << abc;"); 7522 } 7523 7524 TEST_F(FormatTest, BreaksDesireably) { 7525 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7526 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7527 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7528 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7529 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7530 "}"); 7531 7532 verifyFormat( 7533 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7534 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7535 7536 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7537 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7538 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7539 7540 verifyFormat( 7541 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7542 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7543 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7544 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7545 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7546 7547 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7548 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7549 7550 verifyFormat( 7551 "void f() {\n" 7552 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7553 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7554 "}"); 7555 verifyFormat( 7556 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7557 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7558 verifyFormat( 7559 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7560 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7561 verifyFormat( 7562 "aaaaaa(aaa,\n" 7563 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7564 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7565 " aaaa);"); 7566 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7567 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7568 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7569 7570 // Indent consistently independent of call expression and unary operator. 7571 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7572 " dddddddddddddddddddddddddddddd));"); 7573 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7574 " dddddddddddddddddddddddddddddd));"); 7575 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7576 " dddddddddddddddddddddddddddddd));"); 7577 7578 // This test case breaks on an incorrect memoization, i.e. an optimization not 7579 // taking into account the StopAt value. 7580 verifyFormat( 7581 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7582 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7583 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7584 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7585 7586 verifyFormat("{\n {\n {\n" 7587 " Annotation.SpaceRequiredBefore =\n" 7588 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7589 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7590 " }\n }\n}"); 7591 7592 // Break on an outer level if there was a break on an inner level. 7593 EXPECT_EQ("f(g(h(a, // comment\n" 7594 " b, c),\n" 7595 " d, e),\n" 7596 " x, y);", 7597 format("f(g(h(a, // comment\n" 7598 " b, c), d, e), x, y);")); 7599 7600 // Prefer breaking similar line breaks. 7601 verifyFormat( 7602 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7603 " NSTrackingMouseEnteredAndExited |\n" 7604 " NSTrackingActiveAlways;"); 7605 } 7606 7607 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7608 FormatStyle NoBinPacking = getGoogleStyle(); 7609 NoBinPacking.BinPackParameters = false; 7610 NoBinPacking.BinPackArguments = true; 7611 verifyFormat("void f() {\n" 7612 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7613 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7614 "}", 7615 NoBinPacking); 7616 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7617 " int aaaaaaaaaaaaaaaaaaaa,\n" 7618 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7619 NoBinPacking); 7620 7621 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7622 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7623 " vector<int> bbbbbbbbbbbbbbb);", 7624 NoBinPacking); 7625 // FIXME: This behavior difference is probably not wanted. However, currently 7626 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7627 // template arguments from BreakBeforeParameter being set because of the 7628 // one-per-line formatting. 7629 verifyFormat( 7630 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7631 " aaaaaaaaaa> aaaaaaaaaa);", 7632 NoBinPacking); 7633 verifyFormat( 7634 "void fffffffffff(\n" 7635 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7636 " aaaaaaaaaa);"); 7637 } 7638 7639 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7640 FormatStyle NoBinPacking = getGoogleStyle(); 7641 NoBinPacking.BinPackParameters = false; 7642 NoBinPacking.BinPackArguments = false; 7643 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7644 " aaaaaaaaaaaaaaaaaaaa,\n" 7645 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7646 NoBinPacking); 7647 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7648 " aaaaaaaaaaaaa,\n" 7649 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7650 NoBinPacking); 7651 verifyFormat( 7652 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7653 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7654 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7655 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7656 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7657 NoBinPacking); 7658 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7659 " .aaaaaaaaaaaaaaaaaa();", 7660 NoBinPacking); 7661 verifyFormat("void f() {\n" 7662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7663 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7664 "}", 7665 NoBinPacking); 7666 7667 verifyFormat( 7668 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7669 " aaaaaaaaaaaa,\n" 7670 " aaaaaaaaaaaa);", 7671 NoBinPacking); 7672 verifyFormat( 7673 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7674 " ddddddddddddddddddddddddddddd),\n" 7675 " test);", 7676 NoBinPacking); 7677 7678 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7679 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7680 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7681 " aaaaaaaaaaaaaaaaaa;", 7682 NoBinPacking); 7683 verifyFormat("a(\"a\"\n" 7684 " \"a\",\n" 7685 " a);"); 7686 7687 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7688 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7689 " aaaaaaaaa,\n" 7690 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7691 NoBinPacking); 7692 verifyFormat( 7693 "void f() {\n" 7694 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7695 " .aaaaaaa();\n" 7696 "}", 7697 NoBinPacking); 7698 verifyFormat( 7699 "template <class SomeType, class SomeOtherType>\n" 7700 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7701 NoBinPacking); 7702 } 7703 7704 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7705 FormatStyle Style = getLLVMStyleWithColumns(15); 7706 Style.ExperimentalAutoDetectBinPacking = true; 7707 EXPECT_EQ("aaa(aaaa,\n" 7708 " aaaa,\n" 7709 " aaaa);\n" 7710 "aaa(aaaa,\n" 7711 " aaaa,\n" 7712 " aaaa);", 7713 format("aaa(aaaa,\n" // one-per-line 7714 " aaaa,\n" 7715 " aaaa );\n" 7716 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7717 Style)); 7718 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7719 " aaaa);\n" 7720 "aaa(aaaa, aaaa,\n" 7721 " aaaa);", 7722 format("aaa(aaaa, aaaa,\n" // bin-packed 7723 " aaaa );\n" 7724 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7725 Style)); 7726 } 7727 7728 TEST_F(FormatTest, FormatsBuilderPattern) { 7729 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7730 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7731 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7732 " .StartsWith(\".init\", ORDER_INIT)\n" 7733 " .StartsWith(\".fini\", ORDER_FINI)\n" 7734 " .StartsWith(\".hash\", ORDER_HASH)\n" 7735 " .Default(ORDER_TEXT);\n"); 7736 7737 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7738 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7739 verifyFormat("aaaaaaa->aaaaaaa\n" 7740 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7741 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7742 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7743 verifyFormat( 7744 "aaaaaaa->aaaaaaa\n" 7745 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7746 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7747 verifyFormat( 7748 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7749 " aaaaaaaaaaaaaa);"); 7750 verifyFormat( 7751 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7752 " aaaaaa->aaaaaaaaaaaa()\n" 7753 " ->aaaaaaaaaaaaaaaa(\n" 7754 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7755 " ->aaaaaaaaaaaaaaaaa();"); 7756 verifyGoogleFormat( 7757 "void f() {\n" 7758 " someo->Add((new util::filetools::Handler(dir))\n" 7759 " ->OnEvent1(NewPermanentCallback(\n" 7760 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7761 " ->OnEvent2(NewPermanentCallback(\n" 7762 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7763 " ->OnEvent3(NewPermanentCallback(\n" 7764 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7765 " ->OnEvent5(NewPermanentCallback(\n" 7766 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7767 " ->OnEvent6(NewPermanentCallback(\n" 7768 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7769 "}"); 7770 7771 verifyFormat( 7772 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7773 verifyFormat("aaaaaaaaaaaaaaa()\n" 7774 " .aaaaaaaaaaaaaaa()\n" 7775 " .aaaaaaaaaaaaaaa()\n" 7776 " .aaaaaaaaaaaaaaa()\n" 7777 " .aaaaaaaaaaaaaaa();"); 7778 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7779 " .aaaaaaaaaaaaaaa()\n" 7780 " .aaaaaaaaaaaaaaa()\n" 7781 " .aaaaaaaaaaaaaaa();"); 7782 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7783 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7784 " .aaaaaaaaaaaaaaa();"); 7785 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7786 " ->aaaaaaaaaaaaaae(0)\n" 7787 " ->aaaaaaaaaaaaaaa();"); 7788 7789 // Don't linewrap after very short segments. 7790 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7791 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7792 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7793 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7794 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7795 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7796 verifyFormat("aaa()\n" 7797 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7798 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7799 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7800 7801 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7802 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7803 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7804 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7805 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7806 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7807 7808 // Prefer not to break after empty parentheses. 7809 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7810 " First->LastNewlineOffset);"); 7811 7812 // Prefer not to create "hanging" indents. 7813 verifyFormat( 7814 "return !soooooooooooooome_map\n" 7815 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7816 " .second;"); 7817 verifyFormat( 7818 "return aaaaaaaaaaaaaaaa\n" 7819 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7820 " .aaaa(aaaaaaaaaaaaaa);"); 7821 // No hanging indent here. 7822 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7823 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7824 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7825 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7826 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7827 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7828 getLLVMStyleWithColumns(60)); 7829 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7830 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7831 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7832 getLLVMStyleWithColumns(59)); 7833 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7834 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7835 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7836 7837 // Dont break if only closing statements before member call 7838 verifyFormat("test() {\n" 7839 " ([]() -> {\n" 7840 " int b = 32;\n" 7841 " return 3;\n" 7842 " }).foo();\n" 7843 "}"); 7844 verifyFormat("test() {\n" 7845 " (\n" 7846 " []() -> {\n" 7847 " int b = 32;\n" 7848 " return 3;\n" 7849 " },\n" 7850 " foo, bar)\n" 7851 " .foo();\n" 7852 "}"); 7853 verifyFormat("test() {\n" 7854 " ([]() -> {\n" 7855 " int b = 32;\n" 7856 " return 3;\n" 7857 " })\n" 7858 " .foo()\n" 7859 " .bar();\n" 7860 "}"); 7861 verifyFormat("test() {\n" 7862 " ([]() -> {\n" 7863 " int b = 32;\n" 7864 " return 3;\n" 7865 " })\n" 7866 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7867 " \"bbbb\");\n" 7868 "}", 7869 getLLVMStyleWithColumns(30)); 7870 } 7871 7872 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7873 verifyFormat( 7874 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7875 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7876 verifyFormat( 7877 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7878 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7879 7880 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7881 " ccccccccccccccccccccccccc) {\n}"); 7882 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7883 " ccccccccccccccccccccccccc) {\n}"); 7884 7885 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7886 " ccccccccccccccccccccccccc) {\n}"); 7887 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7888 " ccccccccccccccccccccccccc) {\n}"); 7889 7890 verifyFormat( 7891 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7892 " ccccccccccccccccccccccccc) {\n}"); 7893 verifyFormat( 7894 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7895 " ccccccccccccccccccccccccc) {\n}"); 7896 7897 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7898 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7899 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7900 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7901 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7902 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7903 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7904 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7905 7906 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7907 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7908 " aaaaaaaaaaaaaaa != aa) {\n}"); 7909 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7910 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7911 " aaaaaaaaaaaaaaa != aa) {\n}"); 7912 } 7913 7914 TEST_F(FormatTest, BreaksAfterAssignments) { 7915 verifyFormat( 7916 "unsigned Cost =\n" 7917 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7918 " SI->getPointerAddressSpaceee());\n"); 7919 verifyFormat( 7920 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7921 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7922 7923 verifyFormat( 7924 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7925 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7926 verifyFormat("unsigned OriginalStartColumn =\n" 7927 " SourceMgr.getSpellingColumnNumber(\n" 7928 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7929 " 1;"); 7930 } 7931 7932 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7933 FormatStyle Style = getLLVMStyle(); 7934 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7935 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7936 Style); 7937 7938 Style.PenaltyBreakAssignment = 20; 7939 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7940 " cccccccccccccccccccccccccc;", 7941 Style); 7942 } 7943 7944 TEST_F(FormatTest, AlignsAfterAssignments) { 7945 verifyFormat( 7946 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7947 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7948 verifyFormat( 7949 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7950 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7951 verifyFormat( 7952 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7953 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7954 verifyFormat( 7955 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7956 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7957 verifyFormat( 7958 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7959 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7960 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7961 } 7962 7963 TEST_F(FormatTest, AlignsAfterReturn) { 7964 verifyFormat( 7965 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7966 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7967 verifyFormat( 7968 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7969 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7970 verifyFormat( 7971 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7972 " aaaaaaaaaaaaaaaaaaaaaa();"); 7973 verifyFormat( 7974 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7975 " aaaaaaaaaaaaaaaaaaaaaa());"); 7976 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7977 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7978 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7979 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7980 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7981 verifyFormat("return\n" 7982 " // true if code is one of a or b.\n" 7983 " code == a || code == b;"); 7984 } 7985 7986 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7987 verifyFormat( 7988 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7989 " aaaaaaaaa aaaaaaa) {}"); 7990 verifyFormat( 7991 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7992 " aaaaaaaaaaa aaaaaaaaa);"); 7993 verifyFormat( 7994 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7995 " aaaaaaaaaaaaaaaaaaaaa));"); 7996 FormatStyle Style = getLLVMStyle(); 7997 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7998 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7999 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8000 Style); 8001 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8002 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8003 Style); 8004 verifyFormat("SomeLongVariableName->someFunction(\n" 8005 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8006 Style); 8007 verifyFormat( 8008 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8009 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8010 Style); 8011 verifyFormat( 8012 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8013 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8014 Style); 8015 verifyFormat( 8016 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8017 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8018 Style); 8019 8020 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8021 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8022 " b));", 8023 Style); 8024 8025 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8026 Style.BinPackArguments = false; 8027 Style.BinPackParameters = false; 8028 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8029 " aaaaaaaaaaa aaaaaaaa,\n" 8030 " aaaaaaaaa aaaaaaa,\n" 8031 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8032 Style); 8033 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8034 " aaaaaaaaaaa aaaaaaaaa,\n" 8035 " aaaaaaaaaaa aaaaaaaaa,\n" 8036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8037 Style); 8038 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8039 " aaaaaaaaaaaaaaa,\n" 8040 " aaaaaaaaaaaaaaaaaaaaa,\n" 8041 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8042 Style); 8043 verifyFormat( 8044 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8045 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8046 Style); 8047 verifyFormat( 8048 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8049 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8050 Style); 8051 verifyFormat( 8052 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8053 " aaaaaaaaaaaaaaaaaaaaa(\n" 8054 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8055 " aaaaaaaaaaaaaaaa);", 8056 Style); 8057 verifyFormat( 8058 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8059 " aaaaaaaaaaaaaaaaaaaaa(\n" 8060 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8061 " aaaaaaaaaaaaaaaa);", 8062 Style); 8063 } 8064 8065 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8066 FormatStyle Style = getLLVMStyleWithColumns(40); 8067 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8068 " bbbbbbbbbbbbbbbbbbbbbb);", 8069 Style); 8070 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8071 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8072 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8073 " bbbbbbbbbbbbbbbbbbbbbb);", 8074 Style); 8075 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8076 Style.AlignOperands = FormatStyle::OAS_Align; 8077 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8078 " bbbbbbbbbbbbbbbbbbbbbb);", 8079 Style); 8080 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8081 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8082 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8083 " bbbbbbbbbbbbbbbbbbbbbb);", 8084 Style); 8085 } 8086 8087 TEST_F(FormatTest, BreaksConditionalExpressions) { 8088 verifyFormat( 8089 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8090 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8091 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8092 verifyFormat( 8093 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8094 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8095 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8096 verifyFormat( 8097 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8098 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8099 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8100 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8101 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8102 verifyFormat( 8103 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8104 " : aaaaaaaaaaaaa);"); 8105 verifyFormat( 8106 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8107 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8108 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8109 " aaaaaaaaaaaaa);"); 8110 verifyFormat( 8111 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8112 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8113 " aaaaaaaaaaaaa);"); 8114 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8115 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8116 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8117 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8119 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8120 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8121 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8122 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8123 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8125 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8126 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8128 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8129 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8130 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8131 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8132 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8133 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8134 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8136 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8137 " : aaaaaaaaaaaaaaaa;"); 8138 verifyFormat( 8139 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8140 " ? aaaaaaaaaaaaaaa\n" 8141 " : aaaaaaaaaaaaaaa;"); 8142 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8143 " aaaaaaaaa\n" 8144 " ? b\n" 8145 " : c);"); 8146 verifyFormat("return aaaa == bbbb\n" 8147 " // comment\n" 8148 " ? aaaa\n" 8149 " : bbbb;"); 8150 verifyFormat("unsigned Indent =\n" 8151 " format(TheLine.First,\n" 8152 " IndentForLevel[TheLine.Level] >= 0\n" 8153 " ? IndentForLevel[TheLine.Level]\n" 8154 " : TheLine * 2,\n" 8155 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8156 getLLVMStyleWithColumns(60)); 8157 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8158 " ? aaaaaaaaaaaaaaa\n" 8159 " : bbbbbbbbbbbbbbb //\n" 8160 " ? ccccccccccccccc\n" 8161 " : ddddddddddddddd;"); 8162 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8163 " ? aaaaaaaaaaaaaaa\n" 8164 " : (bbbbbbbbbbbbbbb //\n" 8165 " ? ccccccccccccccc\n" 8166 " : ddddddddddddddd);"); 8167 verifyFormat( 8168 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8169 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8170 " aaaaaaaaaaaaaaaaaaaaa +\n" 8171 " aaaaaaaaaaaaaaaaaaaaa\n" 8172 " : aaaaaaaaaa;"); 8173 verifyFormat( 8174 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8175 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8176 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8177 8178 FormatStyle NoBinPacking = getLLVMStyle(); 8179 NoBinPacking.BinPackArguments = false; 8180 verifyFormat( 8181 "void f() {\n" 8182 " g(aaa,\n" 8183 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8184 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8185 " ? aaaaaaaaaaaaaaa\n" 8186 " : aaaaaaaaaaaaaaa);\n" 8187 "}", 8188 NoBinPacking); 8189 verifyFormat( 8190 "void f() {\n" 8191 " g(aaa,\n" 8192 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8193 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8194 " ?: aaaaaaaaaaaaaaa);\n" 8195 "}", 8196 NoBinPacking); 8197 8198 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8199 " // comment.\n" 8200 " ccccccccccccccccccccccccccccccccccccccc\n" 8201 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8202 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8203 8204 // Assignments in conditional expressions. Apparently not uncommon :-(. 8205 verifyFormat("return a != b\n" 8206 " // comment\n" 8207 " ? a = b\n" 8208 " : a = b;"); 8209 verifyFormat("return a != b\n" 8210 " // comment\n" 8211 " ? a = a != b\n" 8212 " // comment\n" 8213 " ? a = b\n" 8214 " : a\n" 8215 " : a;\n"); 8216 verifyFormat("return a != b\n" 8217 " // comment\n" 8218 " ? a\n" 8219 " : a = a != b\n" 8220 " // comment\n" 8221 " ? a = b\n" 8222 " : a;"); 8223 8224 // Chained conditionals 8225 FormatStyle Style = getLLVMStyleWithColumns(70); 8226 Style.AlignOperands = FormatStyle::OAS_Align; 8227 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8228 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8229 " : 3333333333333333;", 8230 Style); 8231 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8232 " : bbbbbbbbbb ? 2222222222222222\n" 8233 " : 3333333333333333;", 8234 Style); 8235 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8236 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8237 " : 3333333333333333;", 8238 Style); 8239 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8240 " : bbbbbbbbbbbbbb ? 222222\n" 8241 " : 333333;", 8242 Style); 8243 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8244 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8245 " : cccccccccccccc ? 3333333333333333\n" 8246 " : 4444444444444444;", 8247 Style); 8248 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8249 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8250 " : 3333333333333333;", 8251 Style); 8252 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8253 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8254 " : (aaa ? bbb : ccc);", 8255 Style); 8256 verifyFormat( 8257 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8258 " : cccccccccccccccccc)\n" 8259 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8260 " : 3333333333333333;", 8261 Style); 8262 verifyFormat( 8263 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8264 " : cccccccccccccccccc)\n" 8265 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8266 " : 3333333333333333;", 8267 Style); 8268 verifyFormat( 8269 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8270 " : dddddddddddddddddd)\n" 8271 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8272 " : 3333333333333333;", 8273 Style); 8274 verifyFormat( 8275 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8276 " : dddddddddddddddddd)\n" 8277 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8278 " : 3333333333333333;", 8279 Style); 8280 verifyFormat( 8281 "return aaaaaaaaa ? 1111111111111111\n" 8282 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8283 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8284 " : dddddddddddddddddd)\n", 8285 Style); 8286 verifyFormat( 8287 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8288 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8289 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8290 " : cccccccccccccccccc);", 8291 Style); 8292 verifyFormat( 8293 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8294 " : ccccccccccccccc ? dddddddddddddddddd\n" 8295 " : eeeeeeeeeeeeeeeeee)\n" 8296 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8297 " : 3333333333333333;", 8298 Style); 8299 verifyFormat( 8300 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8301 " : ccccccccccccccc ? dddddddddddddddddd\n" 8302 " : eeeeeeeeeeeeeeeeee)\n" 8303 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8304 " : 3333333333333333;", 8305 Style); 8306 verifyFormat( 8307 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8308 " : cccccccccccc ? dddddddddddddddddd\n" 8309 " : eeeeeeeeeeeeeeeeee)\n" 8310 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8311 " : 3333333333333333;", 8312 Style); 8313 verifyFormat( 8314 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8315 " : cccccccccccccccccc\n" 8316 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8317 " : 3333333333333333;", 8318 Style); 8319 verifyFormat( 8320 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8321 " : cccccccccccccccc ? dddddddddddddddddd\n" 8322 " : eeeeeeeeeeeeeeeeee\n" 8323 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8324 " : 3333333333333333;", 8325 Style); 8326 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8327 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8328 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8329 " : eeeeeeeeeeeeeeeeee)\n" 8330 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8331 " : 3333333333333333;", 8332 Style); 8333 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8334 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8335 " : cccccccccccccccc ? dddddddddddddddddd\n" 8336 " : eeeeeeeeeeeeeeeeee\n" 8337 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8338 " : 3333333333333333;", 8339 Style); 8340 8341 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8342 Style.BreakBeforeTernaryOperators = false; 8343 // FIXME: Aligning the question marks is weird given DontAlign. 8344 // Consider disabling this alignment in this case. Also check whether this 8345 // will render the adjustment from https://reviews.llvm.org/D82199 8346 // unnecessary. 8347 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8348 " bbbb ? cccccccccccccccccc :\n" 8349 " ddddd;\n", 8350 Style); 8351 8352 EXPECT_EQ( 8353 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8354 " /*\n" 8355 " */\n" 8356 " function() {\n" 8357 " try {\n" 8358 " return JJJJJJJJJJJJJJ(\n" 8359 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8360 " }\n" 8361 " } :\n" 8362 " function() {};", 8363 format( 8364 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8365 " /*\n" 8366 " */\n" 8367 " function() {\n" 8368 " try {\n" 8369 " return JJJJJJJJJJJJJJ(\n" 8370 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8371 " }\n" 8372 " } :\n" 8373 " function() {};", 8374 getGoogleStyle(FormatStyle::LK_JavaScript))); 8375 } 8376 8377 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8378 FormatStyle Style = getLLVMStyleWithColumns(70); 8379 Style.BreakBeforeTernaryOperators = false; 8380 verifyFormat( 8381 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8382 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8383 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8384 Style); 8385 verifyFormat( 8386 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8387 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8388 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8389 Style); 8390 verifyFormat( 8391 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8392 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8393 Style); 8394 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8395 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8396 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8397 Style); 8398 verifyFormat( 8399 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8400 " aaaaaaaaaaaaa);", 8401 Style); 8402 verifyFormat( 8403 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8404 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8405 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8406 " aaaaaaaaaaaaa);", 8407 Style); 8408 verifyFormat( 8409 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8410 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8411 " aaaaaaaaaaaaa);", 8412 Style); 8413 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8414 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8415 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8416 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8418 Style); 8419 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8420 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8421 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8422 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8423 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8424 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8425 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8426 Style); 8427 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8428 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8429 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8430 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8431 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8432 Style); 8433 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8434 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8435 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8436 Style); 8437 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8438 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8439 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8440 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8441 Style); 8442 verifyFormat( 8443 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8444 " aaaaaaaaaaaaaaa :\n" 8445 " aaaaaaaaaaaaaaa;", 8446 Style); 8447 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8448 " aaaaaaaaa ?\n" 8449 " b :\n" 8450 " c);", 8451 Style); 8452 verifyFormat("unsigned Indent =\n" 8453 " format(TheLine.First,\n" 8454 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8455 " IndentForLevel[TheLine.Level] :\n" 8456 " TheLine * 2,\n" 8457 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8458 Style); 8459 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8460 " aaaaaaaaaaaaaaa :\n" 8461 " bbbbbbbbbbbbbbb ? //\n" 8462 " ccccccccccccccc :\n" 8463 " ddddddddddddddd;", 8464 Style); 8465 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8466 " aaaaaaaaaaaaaaa :\n" 8467 " (bbbbbbbbbbbbbbb ? //\n" 8468 " ccccccccccccccc :\n" 8469 " ddddddddddddddd);", 8470 Style); 8471 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8472 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8473 " ccccccccccccccccccccccccccc;", 8474 Style); 8475 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8476 " aaaaa :\n" 8477 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8478 Style); 8479 8480 // Chained conditionals 8481 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8482 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8483 " 3333333333333333;", 8484 Style); 8485 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8486 " bbbbbbbbbb ? 2222222222222222 :\n" 8487 " 3333333333333333;", 8488 Style); 8489 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8490 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8491 " 3333333333333333;", 8492 Style); 8493 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8494 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8495 " 333333;", 8496 Style); 8497 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8498 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8499 " cccccccccccccccc ? 3333333333333333 :\n" 8500 " 4444444444444444;", 8501 Style); 8502 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8503 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8504 " 3333333333333333;", 8505 Style); 8506 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8507 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8508 " (aaa ? bbb : ccc);", 8509 Style); 8510 verifyFormat( 8511 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8512 " cccccccccccccccccc) :\n" 8513 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8514 " 3333333333333333;", 8515 Style); 8516 verifyFormat( 8517 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8518 " cccccccccccccccccc) :\n" 8519 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8520 " 3333333333333333;", 8521 Style); 8522 verifyFormat( 8523 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8524 " dddddddddddddddddd) :\n" 8525 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8526 " 3333333333333333;", 8527 Style); 8528 verifyFormat( 8529 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8530 " dddddddddddddddddd) :\n" 8531 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8532 " 3333333333333333;", 8533 Style); 8534 verifyFormat( 8535 "return aaaaaaaaa ? 1111111111111111 :\n" 8536 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8537 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8538 " dddddddddddddddddd)\n", 8539 Style); 8540 verifyFormat( 8541 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8542 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8543 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8544 " cccccccccccccccccc);", 8545 Style); 8546 verifyFormat( 8547 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8548 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8549 " eeeeeeeeeeeeeeeeee) :\n" 8550 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8551 " 3333333333333333;", 8552 Style); 8553 verifyFormat( 8554 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8555 " ccccccccccccc ? dddddddddddddddddd :\n" 8556 " eeeeeeeeeeeeeeeeee) :\n" 8557 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8558 " 3333333333333333;", 8559 Style); 8560 verifyFormat( 8561 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8562 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8563 " eeeeeeeeeeeeeeeeee) :\n" 8564 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8565 " 3333333333333333;", 8566 Style); 8567 verifyFormat( 8568 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8569 " cccccccccccccccccc :\n" 8570 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8571 " 3333333333333333;", 8572 Style); 8573 verifyFormat( 8574 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8575 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8576 " eeeeeeeeeeeeeeeeee :\n" 8577 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8578 " 3333333333333333;", 8579 Style); 8580 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8581 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8582 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8583 " eeeeeeeeeeeeeeeeee) :\n" 8584 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8585 " 3333333333333333;", 8586 Style); 8587 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8588 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8589 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8590 " eeeeeeeeeeeeeeeeee :\n" 8591 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8592 " 3333333333333333;", 8593 Style); 8594 } 8595 8596 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8597 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8598 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8599 verifyFormat("bool a = true, b = false;"); 8600 8601 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8602 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8603 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8604 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8605 verifyFormat( 8606 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8607 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8608 " d = e && f;"); 8609 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8610 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8611 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8612 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8613 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8614 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8615 8616 FormatStyle Style = getGoogleStyle(); 8617 Style.PointerAlignment = FormatStyle::PAS_Left; 8618 Style.DerivePointerAlignment = false; 8619 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8620 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8621 " *b = bbbbbbbbbbbbbbbbbbb;", 8622 Style); 8623 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8624 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8625 Style); 8626 verifyFormat("vector<int*> a, b;", Style); 8627 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8628 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8629 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8630 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8631 Style); 8632 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8633 Style); 8634 verifyFormat( 8635 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8636 Style); 8637 8638 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8639 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8640 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8641 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8642 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8643 Style); 8644 } 8645 8646 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8647 verifyFormat("arr[foo ? bar : baz];"); 8648 verifyFormat("f()[foo ? bar : baz];"); 8649 verifyFormat("(a + b)[foo ? bar : baz];"); 8650 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8651 } 8652 8653 TEST_F(FormatTest, AlignsStringLiterals) { 8654 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8655 " \"short literal\");"); 8656 verifyFormat( 8657 "looooooooooooooooooooooooongFunction(\n" 8658 " \"short literal\"\n" 8659 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8660 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8661 " \" string literals\",\n" 8662 " and, other, parameters);"); 8663 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8664 " \"5678\";", 8665 format("fun + \"1243\" /* comment */\n" 8666 " \"5678\";", 8667 getLLVMStyleWithColumns(28))); 8668 EXPECT_EQ( 8669 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8670 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8671 " \"aaaaaaaaaaaaaaaa\";", 8672 format("aaaaaa =" 8673 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8674 "aaaaaaaaaaaaaaaaaaaaa\" " 8675 "\"aaaaaaaaaaaaaaaa\";")); 8676 verifyFormat("a = a + \"a\"\n" 8677 " \"a\"\n" 8678 " \"a\";"); 8679 verifyFormat("f(\"a\", \"b\"\n" 8680 " \"c\");"); 8681 8682 verifyFormat( 8683 "#define LL_FORMAT \"ll\"\n" 8684 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8685 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8686 8687 verifyFormat("#define A(X) \\\n" 8688 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8689 " \"ccccc\"", 8690 getLLVMStyleWithColumns(23)); 8691 verifyFormat("#define A \"def\"\n" 8692 "f(\"abc\" A \"ghi\"\n" 8693 " \"jkl\");"); 8694 8695 verifyFormat("f(L\"a\"\n" 8696 " L\"b\");"); 8697 verifyFormat("#define A(X) \\\n" 8698 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8699 " L\"ccccc\"", 8700 getLLVMStyleWithColumns(25)); 8701 8702 verifyFormat("f(@\"a\"\n" 8703 " @\"b\");"); 8704 verifyFormat("NSString s = @\"a\"\n" 8705 " @\"b\"\n" 8706 " @\"c\";"); 8707 verifyFormat("NSString s = @\"a\"\n" 8708 " \"b\"\n" 8709 " \"c\";"); 8710 } 8711 8712 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8713 FormatStyle Style = getLLVMStyle(); 8714 // No declarations or definitions should be moved to own line. 8715 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8716 verifyFormat("class A {\n" 8717 " int f() { return 1; }\n" 8718 " int g();\n" 8719 "};\n" 8720 "int f() { return 1; }\n" 8721 "int g();\n", 8722 Style); 8723 8724 // All declarations and definitions should have the return type moved to its 8725 // own line. 8726 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8727 Style.TypenameMacros = {"LIST"}; 8728 verifyFormat("SomeType\n" 8729 "funcdecl(LIST(uint64_t));", 8730 Style); 8731 verifyFormat("class E {\n" 8732 " int\n" 8733 " f() {\n" 8734 " return 1;\n" 8735 " }\n" 8736 " int\n" 8737 " g();\n" 8738 "};\n" 8739 "int\n" 8740 "f() {\n" 8741 " return 1;\n" 8742 "}\n" 8743 "int\n" 8744 "g();\n", 8745 Style); 8746 8747 // Top-level definitions, and no kinds of declarations should have the 8748 // return type moved to its own line. 8749 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8750 verifyFormat("class B {\n" 8751 " int f() { return 1; }\n" 8752 " int g();\n" 8753 "};\n" 8754 "int\n" 8755 "f() {\n" 8756 " return 1;\n" 8757 "}\n" 8758 "int g();\n", 8759 Style); 8760 8761 // Top-level definitions and declarations should have the return type moved 8762 // to its own line. 8763 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8764 verifyFormat("class C {\n" 8765 " int f() { return 1; }\n" 8766 " int g();\n" 8767 "};\n" 8768 "int\n" 8769 "f() {\n" 8770 " return 1;\n" 8771 "}\n" 8772 "int\n" 8773 "g();\n", 8774 Style); 8775 8776 // All definitions should have the return type moved to its own line, but no 8777 // kinds of declarations. 8778 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8779 verifyFormat("class D {\n" 8780 " int\n" 8781 " f() {\n" 8782 " return 1;\n" 8783 " }\n" 8784 " int g();\n" 8785 "};\n" 8786 "int\n" 8787 "f() {\n" 8788 " return 1;\n" 8789 "}\n" 8790 "int g();\n", 8791 Style); 8792 verifyFormat("const char *\n" 8793 "f(void) {\n" // Break here. 8794 " return \"\";\n" 8795 "}\n" 8796 "const char *bar(void);\n", // No break here. 8797 Style); 8798 verifyFormat("template <class T>\n" 8799 "T *\n" 8800 "f(T &c) {\n" // Break here. 8801 " return NULL;\n" 8802 "}\n" 8803 "template <class T> T *f(T &c);\n", // No break here. 8804 Style); 8805 verifyFormat("class C {\n" 8806 " int\n" 8807 " operator+() {\n" 8808 " return 1;\n" 8809 " }\n" 8810 " int\n" 8811 " operator()() {\n" 8812 " return 1;\n" 8813 " }\n" 8814 "};\n", 8815 Style); 8816 verifyFormat("void\n" 8817 "A::operator()() {}\n" 8818 "void\n" 8819 "A::operator>>() {}\n" 8820 "void\n" 8821 "A::operator+() {}\n" 8822 "void\n" 8823 "A::operator*() {}\n" 8824 "void\n" 8825 "A::operator->() {}\n" 8826 "void\n" 8827 "A::operator void *() {}\n" 8828 "void\n" 8829 "A::operator void &() {}\n" 8830 "void\n" 8831 "A::operator void &&() {}\n" 8832 "void\n" 8833 "A::operator char *() {}\n" 8834 "void\n" 8835 "A::operator[]() {}\n" 8836 "void\n" 8837 "A::operator!() {}\n" 8838 "void\n" 8839 "A::operator**() {}\n" 8840 "void\n" 8841 "A::operator<Foo> *() {}\n" 8842 "void\n" 8843 "A::operator<Foo> **() {}\n" 8844 "void\n" 8845 "A::operator<Foo> &() {}\n" 8846 "void\n" 8847 "A::operator void **() {}\n", 8848 Style); 8849 verifyFormat("constexpr auto\n" 8850 "operator()() const -> reference {}\n" 8851 "constexpr auto\n" 8852 "operator>>() const -> reference {}\n" 8853 "constexpr auto\n" 8854 "operator+() const -> reference {}\n" 8855 "constexpr auto\n" 8856 "operator*() const -> reference {}\n" 8857 "constexpr auto\n" 8858 "operator->() const -> reference {}\n" 8859 "constexpr auto\n" 8860 "operator++() const -> reference {}\n" 8861 "constexpr auto\n" 8862 "operator void *() const -> reference {}\n" 8863 "constexpr auto\n" 8864 "operator void **() const -> reference {}\n" 8865 "constexpr auto\n" 8866 "operator void *() const -> reference {}\n" 8867 "constexpr auto\n" 8868 "operator void &() const -> reference {}\n" 8869 "constexpr auto\n" 8870 "operator void &&() const -> reference {}\n" 8871 "constexpr auto\n" 8872 "operator char *() const -> reference {}\n" 8873 "constexpr auto\n" 8874 "operator!() const -> reference {}\n" 8875 "constexpr auto\n" 8876 "operator[]() const -> reference {}\n", 8877 Style); 8878 verifyFormat("void *operator new(std::size_t s);", // No break here. 8879 Style); 8880 verifyFormat("void *\n" 8881 "operator new(std::size_t s) {}", 8882 Style); 8883 verifyFormat("void *\n" 8884 "operator delete[](void *ptr) {}", 8885 Style); 8886 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8887 verifyFormat("const char *\n" 8888 "f(void)\n" // Break here. 8889 "{\n" 8890 " return \"\";\n" 8891 "}\n" 8892 "const char *bar(void);\n", // No break here. 8893 Style); 8894 verifyFormat("template <class T>\n" 8895 "T *\n" // Problem here: no line break 8896 "f(T &c)\n" // Break here. 8897 "{\n" 8898 " return NULL;\n" 8899 "}\n" 8900 "template <class T> T *f(T &c);\n", // No break here. 8901 Style); 8902 verifyFormat("int\n" 8903 "foo(A<bool> a)\n" 8904 "{\n" 8905 " return a;\n" 8906 "}\n", 8907 Style); 8908 verifyFormat("int\n" 8909 "foo(A<8> a)\n" 8910 "{\n" 8911 " return a;\n" 8912 "}\n", 8913 Style); 8914 verifyFormat("int\n" 8915 "foo(A<B<bool>, 8> a)\n" 8916 "{\n" 8917 " return a;\n" 8918 "}\n", 8919 Style); 8920 verifyFormat("int\n" 8921 "foo(A<B<8>, bool> a)\n" 8922 "{\n" 8923 " return a;\n" 8924 "}\n", 8925 Style); 8926 verifyFormat("int\n" 8927 "foo(A<B<bool>, bool> a)\n" 8928 "{\n" 8929 " return a;\n" 8930 "}\n", 8931 Style); 8932 verifyFormat("int\n" 8933 "foo(A<B<8>, 8> a)\n" 8934 "{\n" 8935 " return a;\n" 8936 "}\n", 8937 Style); 8938 8939 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8940 Style.BraceWrapping.AfterFunction = true; 8941 verifyFormat("int f(i);\n" // No break here. 8942 "int\n" // Break here. 8943 "f(i)\n" 8944 "{\n" 8945 " return i + 1;\n" 8946 "}\n" 8947 "int\n" // Break here. 8948 "f(i)\n" 8949 "{\n" 8950 " return i + 1;\n" 8951 "};", 8952 Style); 8953 verifyFormat("int f(a, b, c);\n" // No break here. 8954 "int\n" // Break here. 8955 "f(a, b, c)\n" // Break here. 8956 "short a, b;\n" 8957 "float c;\n" 8958 "{\n" 8959 " return a + b < c;\n" 8960 "}\n" 8961 "int\n" // Break here. 8962 "f(a, b, c)\n" // Break here. 8963 "short a, b;\n" 8964 "float c;\n" 8965 "{\n" 8966 " return a + b < c;\n" 8967 "};", 8968 Style); 8969 verifyFormat("byte *\n" // Break here. 8970 "f(a)\n" // Break here. 8971 "byte a[];\n" 8972 "{\n" 8973 " return a;\n" 8974 "}", 8975 Style); 8976 verifyFormat("bool f(int a, int) override;\n" 8977 "Bar g(int a, Bar) final;\n" 8978 "Bar h(a, Bar) final;", 8979 Style); 8980 verifyFormat("int\n" 8981 "f(a)", 8982 Style); 8983 verifyFormat("bool\n" 8984 "f(size_t = 0, bool b = false)\n" 8985 "{\n" 8986 " return !b;\n" 8987 "}", 8988 Style); 8989 8990 // The return breaking style doesn't affect: 8991 // * function and object definitions with attribute-like macros 8992 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8993 " ABSL_GUARDED_BY(mutex) = {};", 8994 getGoogleStyleWithColumns(40)); 8995 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8996 " ABSL_GUARDED_BY(mutex); // comment", 8997 getGoogleStyleWithColumns(40)); 8998 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8999 " ABSL_GUARDED_BY(mutex1)\n" 9000 " ABSL_GUARDED_BY(mutex2);", 9001 getGoogleStyleWithColumns(40)); 9002 verifyFormat("Tttttt f(int a, int b)\n" 9003 " ABSL_GUARDED_BY(mutex1)\n" 9004 " ABSL_GUARDED_BY(mutex2);", 9005 getGoogleStyleWithColumns(40)); 9006 // * typedefs 9007 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9008 9009 Style = getGNUStyle(); 9010 9011 // Test for comments at the end of function declarations. 9012 verifyFormat("void\n" 9013 "foo (int a, /*abc*/ int b) // def\n" 9014 "{\n" 9015 "}\n", 9016 Style); 9017 9018 verifyFormat("void\n" 9019 "foo (int a, /* abc */ int b) /* def */\n" 9020 "{\n" 9021 "}\n", 9022 Style); 9023 9024 // Definitions that should not break after return type 9025 verifyFormat("void foo (int a, int b); // def\n", Style); 9026 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9027 verifyFormat("void foo (int a, int b);\n", Style); 9028 } 9029 9030 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9031 FormatStyle NoBreak = getLLVMStyle(); 9032 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9033 FormatStyle Break = getLLVMStyle(); 9034 Break.AlwaysBreakBeforeMultilineStrings = true; 9035 verifyFormat("aaaa = \"bbbb\"\n" 9036 " \"cccc\";", 9037 NoBreak); 9038 verifyFormat("aaaa =\n" 9039 " \"bbbb\"\n" 9040 " \"cccc\";", 9041 Break); 9042 verifyFormat("aaaa(\"bbbb\"\n" 9043 " \"cccc\");", 9044 NoBreak); 9045 verifyFormat("aaaa(\n" 9046 " \"bbbb\"\n" 9047 " \"cccc\");", 9048 Break); 9049 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9050 " \"cccc\");", 9051 NoBreak); 9052 verifyFormat("aaaa(qqq,\n" 9053 " \"bbbb\"\n" 9054 " \"cccc\");", 9055 Break); 9056 verifyFormat("aaaa(qqq,\n" 9057 " L\"bbbb\"\n" 9058 " L\"cccc\");", 9059 Break); 9060 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9061 " \"bbbb\"));", 9062 Break); 9063 verifyFormat("string s = someFunction(\n" 9064 " \"abc\"\n" 9065 " \"abc\");", 9066 Break); 9067 9068 // As we break before unary operators, breaking right after them is bad. 9069 verifyFormat("string foo = abc ? \"x\"\n" 9070 " \"blah blah blah blah blah blah\"\n" 9071 " : \"y\";", 9072 Break); 9073 9074 // Don't break if there is no column gain. 9075 verifyFormat("f(\"aaaa\"\n" 9076 " \"bbbb\");", 9077 Break); 9078 9079 // Treat literals with escaped newlines like multi-line string literals. 9080 EXPECT_EQ("x = \"a\\\n" 9081 "b\\\n" 9082 "c\";", 9083 format("x = \"a\\\n" 9084 "b\\\n" 9085 "c\";", 9086 NoBreak)); 9087 EXPECT_EQ("xxxx =\n" 9088 " \"a\\\n" 9089 "b\\\n" 9090 "c\";", 9091 format("xxxx = \"a\\\n" 9092 "b\\\n" 9093 "c\";", 9094 Break)); 9095 9096 EXPECT_EQ("NSString *const kString =\n" 9097 " @\"aaaa\"\n" 9098 " @\"bbbb\";", 9099 format("NSString *const kString = @\"aaaa\"\n" 9100 "@\"bbbb\";", 9101 Break)); 9102 9103 Break.ColumnLimit = 0; 9104 verifyFormat("const char *hello = \"hello llvm\";", Break); 9105 } 9106 9107 TEST_F(FormatTest, AlignsPipes) { 9108 verifyFormat( 9109 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9110 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9111 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9112 verifyFormat( 9113 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9114 " << aaaaaaaaaaaaaaaaaaaa;"); 9115 verifyFormat( 9116 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9117 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9118 verifyFormat( 9119 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9120 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9121 verifyFormat( 9122 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9123 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9124 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9125 verifyFormat( 9126 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9127 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9128 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9129 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9130 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9131 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9132 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9133 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9134 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9135 verifyFormat( 9136 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9137 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9138 verifyFormat( 9139 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9140 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9141 9142 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9143 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9144 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9145 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9146 " aaaaaaaaaaaaaaaaaaaaa)\n" 9147 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9148 verifyFormat("LOG_IF(aaa == //\n" 9149 " bbb)\n" 9150 " << a << b;"); 9151 9152 // But sometimes, breaking before the first "<<" is desirable. 9153 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9154 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9155 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9156 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9157 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9158 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9159 " << BEF << IsTemplate << Description << E->getType();"); 9160 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9161 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9162 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9163 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9164 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9165 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9166 " << aaa;"); 9167 9168 verifyFormat( 9169 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9170 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9171 9172 // Incomplete string literal. 9173 EXPECT_EQ("llvm::errs() << \"\n" 9174 " << a;", 9175 format("llvm::errs() << \"\n<<a;")); 9176 9177 verifyFormat("void f() {\n" 9178 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9179 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9180 "}"); 9181 9182 // Handle 'endl'. 9183 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9184 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9185 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9186 9187 // Handle '\n'. 9188 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9189 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9190 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9191 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9192 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9193 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9194 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9195 } 9196 9197 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9198 verifyFormat("return out << \"somepacket = {\\n\"\n" 9199 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9200 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9201 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9202 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9203 " << \"}\";"); 9204 9205 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9206 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9207 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9208 verifyFormat( 9209 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9210 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9211 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9212 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9213 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9214 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9215 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9216 verifyFormat( 9217 "void f() {\n" 9218 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9219 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9220 "}"); 9221 9222 // Breaking before the first "<<" is generally not desirable. 9223 verifyFormat( 9224 "llvm::errs()\n" 9225 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9226 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9227 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9228 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9229 getLLVMStyleWithColumns(70)); 9230 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9231 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9232 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9233 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9234 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9235 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9236 getLLVMStyleWithColumns(70)); 9237 9238 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9239 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9240 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9241 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9242 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9243 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9244 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9245 " (aaaa + aaaa);", 9246 getLLVMStyleWithColumns(40)); 9247 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9248 " (aaaaaaa + aaaaa));", 9249 getLLVMStyleWithColumns(40)); 9250 verifyFormat( 9251 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9252 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9253 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9254 } 9255 9256 TEST_F(FormatTest, UnderstandsEquals) { 9257 verifyFormat( 9258 "aaaaaaaaaaaaaaaaa =\n" 9259 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9260 verifyFormat( 9261 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9262 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9263 verifyFormat( 9264 "if (a) {\n" 9265 " f();\n" 9266 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9267 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9268 "}"); 9269 9270 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9271 " 100000000 + 10000000) {\n}"); 9272 } 9273 9274 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9275 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9276 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9277 9278 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9279 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9280 9281 verifyFormat( 9282 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9283 " Parameter2);"); 9284 9285 verifyFormat( 9286 "ShortObject->shortFunction(\n" 9287 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9288 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9289 9290 verifyFormat("loooooooooooooongFunction(\n" 9291 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9292 9293 verifyFormat( 9294 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9295 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9296 9297 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9298 " .WillRepeatedly(Return(SomeValue));"); 9299 verifyFormat("void f() {\n" 9300 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9301 " .Times(2)\n" 9302 " .WillRepeatedly(Return(SomeValue));\n" 9303 "}"); 9304 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9305 " ccccccccccccccccccccccc);"); 9306 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9308 " .aaaaa(aaaaa),\n" 9309 " aaaaaaaaaaaaaaaaaaaaa);"); 9310 verifyFormat("void f() {\n" 9311 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9312 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9313 "}"); 9314 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9316 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9317 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9318 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9319 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9320 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9321 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9322 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9323 "}"); 9324 9325 // Here, it is not necessary to wrap at "." or "->". 9326 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9327 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9328 verifyFormat( 9329 "aaaaaaaaaaa->aaaaaaaaa(\n" 9330 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9331 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9332 9333 verifyFormat( 9334 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9335 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9336 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9337 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9338 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9339 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9340 9341 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9342 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9343 " .a();"); 9344 9345 FormatStyle NoBinPacking = getLLVMStyle(); 9346 NoBinPacking.BinPackParameters = false; 9347 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9348 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9349 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9350 " aaaaaaaaaaaaaaaaaaa,\n" 9351 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9352 NoBinPacking); 9353 9354 // If there is a subsequent call, change to hanging indentation. 9355 verifyFormat( 9356 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9357 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9358 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9359 verifyFormat( 9360 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9361 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9362 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9363 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9364 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9365 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9367 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9368 } 9369 9370 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9371 verifyFormat("template <typename T>\n" 9372 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9373 verifyFormat("template <typename T>\n" 9374 "// T should be one of {A, B}.\n" 9375 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9376 verifyFormat( 9377 "template <typename T>\n" 9378 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9379 verifyFormat("template <typename T>\n" 9380 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9381 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9382 verifyFormat( 9383 "template <typename T>\n" 9384 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9385 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9386 verifyFormat( 9387 "template <typename T>\n" 9388 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9389 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9390 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9391 verifyFormat("template <typename T>\n" 9392 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9393 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9394 verifyFormat( 9395 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9396 " typename T4 = char>\n" 9397 "void f();"); 9398 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9399 " template <typename> class cccccccccccccccccccccc,\n" 9400 " typename ddddddddddddd>\n" 9401 "class C {};"); 9402 verifyFormat( 9403 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9404 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9405 9406 verifyFormat("void f() {\n" 9407 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9408 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9409 "}"); 9410 9411 verifyFormat("template <typename T> class C {};"); 9412 verifyFormat("template <typename T> void f();"); 9413 verifyFormat("template <typename T> void f() {}"); 9414 verifyFormat( 9415 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9416 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9418 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9419 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9420 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9421 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9422 getLLVMStyleWithColumns(72)); 9423 EXPECT_EQ("static_cast<A< //\n" 9424 " B> *>(\n" 9425 "\n" 9426 ");", 9427 format("static_cast<A<//\n" 9428 " B>*>(\n" 9429 "\n" 9430 " );")); 9431 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9432 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9433 9434 FormatStyle AlwaysBreak = getLLVMStyle(); 9435 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9436 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9437 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9438 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9439 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9440 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9441 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9442 verifyFormat("template <template <typename> class Fooooooo,\n" 9443 " template <typename> class Baaaaaaar>\n" 9444 "struct C {};", 9445 AlwaysBreak); 9446 verifyFormat("template <typename T> // T can be A, B or C.\n" 9447 "struct C {};", 9448 AlwaysBreak); 9449 verifyFormat("template <enum E> class A {\n" 9450 "public:\n" 9451 " E *f();\n" 9452 "};"); 9453 9454 FormatStyle NeverBreak = getLLVMStyle(); 9455 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9456 verifyFormat("template <typename T> class C {};", NeverBreak); 9457 verifyFormat("template <typename T> void f();", NeverBreak); 9458 verifyFormat("template <typename T> void f() {}", NeverBreak); 9459 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9460 "bbbbbbbbbbbbbbbbbbbb) {}", 9461 NeverBreak); 9462 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9463 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9464 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9465 NeverBreak); 9466 verifyFormat("template <template <typename> class Fooooooo,\n" 9467 " template <typename> class Baaaaaaar>\n" 9468 "struct C {};", 9469 NeverBreak); 9470 verifyFormat("template <typename T> // T can be A, B or C.\n" 9471 "struct C {};", 9472 NeverBreak); 9473 verifyFormat("template <enum E> class A {\n" 9474 "public:\n" 9475 " E *f();\n" 9476 "};", 9477 NeverBreak); 9478 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9479 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9480 "bbbbbbbbbbbbbbbbbbbb) {}", 9481 NeverBreak); 9482 } 9483 9484 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9485 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9486 Style.ColumnLimit = 60; 9487 EXPECT_EQ("// Baseline - no comments.\n" 9488 "template <\n" 9489 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9490 "void f() {}", 9491 format("// Baseline - no comments.\n" 9492 "template <\n" 9493 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9494 "void f() {}", 9495 Style)); 9496 9497 EXPECT_EQ("template <\n" 9498 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9499 "void f() {}", 9500 format("template <\n" 9501 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9502 "void f() {}", 9503 Style)); 9504 9505 EXPECT_EQ( 9506 "template <\n" 9507 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9508 "void f() {}", 9509 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9510 "void f() {}", 9511 Style)); 9512 9513 EXPECT_EQ( 9514 "template <\n" 9515 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9516 " // multiline\n" 9517 "void f() {}", 9518 format("template <\n" 9519 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9520 " // multiline\n" 9521 "void f() {}", 9522 Style)); 9523 9524 EXPECT_EQ( 9525 "template <typename aaaaaaaaaa<\n" 9526 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9527 "void f() {}", 9528 format( 9529 "template <\n" 9530 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9531 "void f() {}", 9532 Style)); 9533 } 9534 9535 TEST_F(FormatTest, WrapsTemplateParameters) { 9536 FormatStyle Style = getLLVMStyle(); 9537 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9538 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9539 verifyFormat( 9540 "template <typename... a> struct q {};\n" 9541 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9542 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9543 " y;", 9544 Style); 9545 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9546 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9547 verifyFormat( 9548 "template <typename... a> struct r {};\n" 9549 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9550 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9551 " y;", 9552 Style); 9553 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9554 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9555 verifyFormat("template <typename... a> struct s {};\n" 9556 "extern s<\n" 9557 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9558 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9559 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9560 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9561 " y;", 9562 Style); 9563 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9564 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9565 verifyFormat("template <typename... a> struct t {};\n" 9566 "extern t<\n" 9567 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9568 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9569 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9570 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9571 " y;", 9572 Style); 9573 } 9574 9575 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9576 verifyFormat( 9577 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9578 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9579 verifyFormat( 9580 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9581 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9582 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9583 9584 // FIXME: Should we have the extra indent after the second break? 9585 verifyFormat( 9586 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9587 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9588 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9589 9590 verifyFormat( 9591 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9592 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9593 9594 // Breaking at nested name specifiers is generally not desirable. 9595 verifyFormat( 9596 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9597 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9598 9599 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9600 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9601 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9602 " aaaaaaaaaaaaaaaaaaaaa);", 9603 getLLVMStyleWithColumns(74)); 9604 9605 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9606 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9607 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9608 } 9609 9610 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9611 verifyFormat("A<int> a;"); 9612 verifyFormat("A<A<A<int>>> a;"); 9613 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9614 verifyFormat("bool x = a < 1 || 2 > a;"); 9615 verifyFormat("bool x = 5 < f<int>();"); 9616 verifyFormat("bool x = f<int>() > 5;"); 9617 verifyFormat("bool x = 5 < a<int>::x;"); 9618 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9619 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9620 9621 verifyGoogleFormat("A<A<int>> a;"); 9622 verifyGoogleFormat("A<A<A<int>>> a;"); 9623 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9624 verifyGoogleFormat("A<A<int> > a;"); 9625 verifyGoogleFormat("A<A<A<int> > > a;"); 9626 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9627 verifyGoogleFormat("A<::A<int>> a;"); 9628 verifyGoogleFormat("A<::A> a;"); 9629 verifyGoogleFormat("A< ::A> a;"); 9630 verifyGoogleFormat("A< ::A<int> > a;"); 9631 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9632 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9633 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9634 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9635 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9636 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9637 9638 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9639 9640 // template closer followed by a token that starts with > or = 9641 verifyFormat("bool b = a<1> > 1;"); 9642 verifyFormat("bool b = a<1> >= 1;"); 9643 verifyFormat("int i = a<1> >> 1;"); 9644 FormatStyle Style = getLLVMStyle(); 9645 Style.SpaceBeforeAssignmentOperators = false; 9646 verifyFormat("bool b= a<1> == 1;", Style); 9647 verifyFormat("a<int> = 1;", Style); 9648 verifyFormat("a<int> >>= 1;", Style); 9649 9650 verifyFormat("test < a | b >> c;"); 9651 verifyFormat("test<test<a | b>> c;"); 9652 verifyFormat("test >> a >> b;"); 9653 verifyFormat("test << a >> b;"); 9654 9655 verifyFormat("f<int>();"); 9656 verifyFormat("template <typename T> void f() {}"); 9657 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9658 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9659 "sizeof(char)>::type>;"); 9660 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9661 verifyFormat("f(a.operator()<A>());"); 9662 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9663 " .template operator()<A>());", 9664 getLLVMStyleWithColumns(35)); 9665 verifyFormat("bool_constant<a && noexcept(f())>"); 9666 verifyFormat("bool_constant<a || noexcept(f())>"); 9667 9668 // Not template parameters. 9669 verifyFormat("return a < b && c > d;"); 9670 verifyFormat("void f() {\n" 9671 " while (a < b && c > d) {\n" 9672 " }\n" 9673 "}"); 9674 verifyFormat("template <typename... Types>\n" 9675 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9676 9677 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9678 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9679 getLLVMStyleWithColumns(60)); 9680 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9681 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9682 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9683 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9684 } 9685 9686 TEST_F(FormatTest, UnderstandsShiftOperators) { 9687 verifyFormat("if (i < x >> 1)"); 9688 verifyFormat("while (i < x >> 1)"); 9689 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9690 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9691 verifyFormat( 9692 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9693 verifyFormat("Foo.call<Bar<Function>>()"); 9694 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9695 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9696 "++i, v = v >> 1)"); 9697 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9698 } 9699 9700 TEST_F(FormatTest, BitshiftOperatorWidth) { 9701 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9702 " bar */", 9703 format("int a=1<<2; /* foo\n" 9704 " bar */")); 9705 9706 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9707 " bar */", 9708 format("int b =256>>1 ; /* foo\n" 9709 " bar */")); 9710 } 9711 9712 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9713 verifyFormat("COMPARE(a, ==, b);"); 9714 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9715 } 9716 9717 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9718 verifyFormat("int A::*x;"); 9719 verifyFormat("int (S::*func)(void *);"); 9720 verifyFormat("void f() { int (S::*func)(void *); }"); 9721 verifyFormat("typedef bool *(Class::*Member)() const;"); 9722 verifyFormat("void f() {\n" 9723 " (a->*f)();\n" 9724 " a->*x;\n" 9725 " (a.*f)();\n" 9726 " ((*a).*f)();\n" 9727 " a.*x;\n" 9728 "}"); 9729 verifyFormat("void f() {\n" 9730 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9731 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9732 "}"); 9733 verifyFormat( 9734 "(aaaaaaaaaa->*bbbbbbb)(\n" 9735 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9736 FormatStyle Style = getLLVMStyle(); 9737 Style.PointerAlignment = FormatStyle::PAS_Left; 9738 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9739 } 9740 9741 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9742 verifyFormat("int a = -2;"); 9743 verifyFormat("f(-1, -2, -3);"); 9744 verifyFormat("a[-1] = 5;"); 9745 verifyFormat("int a = 5 + -2;"); 9746 verifyFormat("if (i == -1) {\n}"); 9747 verifyFormat("if (i != -1) {\n}"); 9748 verifyFormat("if (i > -1) {\n}"); 9749 verifyFormat("if (i < -1) {\n}"); 9750 verifyFormat("++(a->f());"); 9751 verifyFormat("--(a->f());"); 9752 verifyFormat("(a->f())++;"); 9753 verifyFormat("a[42]++;"); 9754 verifyFormat("if (!(a->f())) {\n}"); 9755 verifyFormat("if (!+i) {\n}"); 9756 verifyFormat("~&a;"); 9757 9758 verifyFormat("a-- > b;"); 9759 verifyFormat("b ? -a : c;"); 9760 verifyFormat("n * sizeof char16;"); 9761 verifyFormat("n * alignof char16;", getGoogleStyle()); 9762 verifyFormat("sizeof(char);"); 9763 verifyFormat("alignof(char);", getGoogleStyle()); 9764 9765 verifyFormat("return -1;"); 9766 verifyFormat("throw -1;"); 9767 verifyFormat("switch (a) {\n" 9768 "case -1:\n" 9769 " break;\n" 9770 "}"); 9771 verifyFormat("#define X -1"); 9772 verifyFormat("#define X -kConstant"); 9773 9774 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9775 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9776 9777 verifyFormat("int a = /* confusing comment */ -1;"); 9778 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9779 verifyFormat("int a = i /* confusing comment */++;"); 9780 9781 verifyFormat("co_yield -1;"); 9782 verifyFormat("co_return -1;"); 9783 9784 // Check that * is not treated as a binary operator when we set 9785 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9786 FormatStyle PASLeftStyle = getLLVMStyle(); 9787 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9788 verifyFormat("co_return *a;", PASLeftStyle); 9789 verifyFormat("co_await *a;", PASLeftStyle); 9790 verifyFormat("co_yield *a", PASLeftStyle); 9791 verifyFormat("return *a;", PASLeftStyle); 9792 } 9793 9794 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9795 verifyFormat("if (!aaaaaaaaaa( // break\n" 9796 " aaaaa)) {\n" 9797 "}"); 9798 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9799 " aaaaa));"); 9800 verifyFormat("*aaa = aaaaaaa( // break\n" 9801 " bbbbbb);"); 9802 } 9803 9804 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9805 verifyFormat("bool operator<();"); 9806 verifyFormat("bool operator>();"); 9807 verifyFormat("bool operator=();"); 9808 verifyFormat("bool operator==();"); 9809 verifyFormat("bool operator!=();"); 9810 verifyFormat("int operator+();"); 9811 verifyFormat("int operator++();"); 9812 verifyFormat("int operator++(int) volatile noexcept;"); 9813 verifyFormat("bool operator,();"); 9814 verifyFormat("bool operator();"); 9815 verifyFormat("bool operator()();"); 9816 verifyFormat("bool operator[]();"); 9817 verifyFormat("operator bool();"); 9818 verifyFormat("operator int();"); 9819 verifyFormat("operator void *();"); 9820 verifyFormat("operator SomeType<int>();"); 9821 verifyFormat("operator SomeType<int, int>();"); 9822 verifyFormat("operator SomeType<SomeType<int>>();"); 9823 verifyFormat("operator< <>();"); 9824 verifyFormat("operator<< <>();"); 9825 verifyFormat("< <>"); 9826 9827 verifyFormat("void *operator new(std::size_t size);"); 9828 verifyFormat("void *operator new[](std::size_t size);"); 9829 verifyFormat("void operator delete(void *ptr);"); 9830 verifyFormat("void operator delete[](void *ptr);"); 9831 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9832 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9833 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9834 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9835 9836 verifyFormat( 9837 "ostream &operator<<(ostream &OutputStream,\n" 9838 " SomeReallyLongType WithSomeReallyLongValue);"); 9839 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9840 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9841 " return left.group < right.group;\n" 9842 "}"); 9843 verifyFormat("SomeType &operator=(const SomeType &S);"); 9844 verifyFormat("f.template operator()<int>();"); 9845 9846 verifyGoogleFormat("operator void*();"); 9847 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9848 verifyGoogleFormat("operator ::A();"); 9849 9850 verifyFormat("using A::operator+;"); 9851 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9852 "int i;"); 9853 9854 // Calling an operator as a member function. 9855 verifyFormat("void f() { a.operator*(); }"); 9856 verifyFormat("void f() { a.operator*(b & b); }"); 9857 verifyFormat("void f() { a->operator&(a * b); }"); 9858 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9859 // TODO: Calling an operator as a non-member function is hard to distinguish. 9860 // https://llvm.org/PR50629 9861 // verifyFormat("void f() { operator*(a & a); }"); 9862 // verifyFormat("void f() { operator&(a, b * b); }"); 9863 9864 verifyFormat("::operator delete(foo);"); 9865 verifyFormat("::operator new(n * sizeof(foo));"); 9866 verifyFormat("foo() { ::operator delete(foo); }"); 9867 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9868 } 9869 9870 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9871 verifyFormat("void A::b() && {}"); 9872 verifyFormat("void A::b() &&noexcept {}"); 9873 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9874 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9875 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9876 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9877 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9878 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9879 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9880 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9881 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9882 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9883 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9884 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9885 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9886 verifyFormat("void Fn(T const &) const &;"); 9887 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9888 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9889 verifyFormat("template <typename T>\n" 9890 "void F(T) && = delete;", 9891 getGoogleStyle()); 9892 verifyFormat("template <typename T> void operator=(T) &;"); 9893 verifyFormat("template <typename T> void operator=(T) const &;"); 9894 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9895 verifyFormat("template <typename T> void operator=(T) & = default;"); 9896 verifyFormat("template <typename T> void operator=(T) &&;"); 9897 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9898 verifyFormat("template <typename T> void operator=(T) & {}"); 9899 verifyFormat("template <typename T> void operator=(T) && {}"); 9900 9901 FormatStyle AlignLeft = getLLVMStyle(); 9902 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9903 verifyFormat("void A::b() && {}", AlignLeft); 9904 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9905 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9906 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9907 AlignLeft); 9908 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9909 AlignLeft); 9910 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9911 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9912 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9913 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9914 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9915 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9916 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9917 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9918 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9919 AlignLeft); 9920 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 9921 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 9922 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9923 AlignLeft); 9924 verifyFormat("template <typename T> void operator=(T) & = default;", 9925 AlignLeft); 9926 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9927 verifyFormat("template <typename T> void operator=(T) && = delete;", 9928 AlignLeft); 9929 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9930 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9931 9932 FormatStyle AlignMiddle = getLLVMStyle(); 9933 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9934 verifyFormat("void A::b() && {}", AlignMiddle); 9935 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9936 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9937 AlignMiddle); 9938 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9939 AlignMiddle); 9940 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9941 AlignMiddle); 9942 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9943 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9944 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9945 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9946 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9947 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9948 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9949 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9950 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9951 AlignMiddle); 9952 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 9953 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 9954 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9955 AlignMiddle); 9956 verifyFormat("template <typename T> void operator=(T) & = default;", 9957 AlignMiddle); 9958 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 9959 verifyFormat("template <typename T> void operator=(T) && = delete;", 9960 AlignMiddle); 9961 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 9962 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 9963 9964 FormatStyle Spaces = getLLVMStyle(); 9965 Spaces.SpacesInCStyleCastParentheses = true; 9966 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9967 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9968 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9969 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9970 9971 Spaces.SpacesInCStyleCastParentheses = false; 9972 Spaces.SpacesInParentheses = true; 9973 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9974 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9975 Spaces); 9976 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9977 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9978 9979 FormatStyle BreakTemplate = getLLVMStyle(); 9980 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9981 9982 verifyFormat("struct f {\n" 9983 " template <class T>\n" 9984 " int &foo(const std::string &str) &noexcept {}\n" 9985 "};", 9986 BreakTemplate); 9987 9988 verifyFormat("struct f {\n" 9989 " template <class T>\n" 9990 " int &foo(const std::string &str) &&noexcept {}\n" 9991 "};", 9992 BreakTemplate); 9993 9994 verifyFormat("struct f {\n" 9995 " template <class T>\n" 9996 " int &foo(const std::string &str) const &noexcept {}\n" 9997 "};", 9998 BreakTemplate); 9999 10000 verifyFormat("struct f {\n" 10001 " template <class T>\n" 10002 " int &foo(const std::string &str) const &noexcept {}\n" 10003 "};", 10004 BreakTemplate); 10005 10006 verifyFormat("struct f {\n" 10007 " template <class T>\n" 10008 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10009 "};", 10010 BreakTemplate); 10011 10012 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10013 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10014 FormatStyle::BTDS_Yes; 10015 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10016 10017 verifyFormat("struct f {\n" 10018 " template <class T>\n" 10019 " int& foo(const std::string& str) & noexcept {}\n" 10020 "};", 10021 AlignLeftBreakTemplate); 10022 10023 verifyFormat("struct f {\n" 10024 " template <class T>\n" 10025 " int& foo(const std::string& str) && noexcept {}\n" 10026 "};", 10027 AlignLeftBreakTemplate); 10028 10029 verifyFormat("struct f {\n" 10030 " template <class T>\n" 10031 " int& foo(const std::string& str) const& noexcept {}\n" 10032 "};", 10033 AlignLeftBreakTemplate); 10034 10035 verifyFormat("struct f {\n" 10036 " template <class T>\n" 10037 " int& foo(const std::string& str) const&& noexcept {}\n" 10038 "};", 10039 AlignLeftBreakTemplate); 10040 10041 verifyFormat("struct f {\n" 10042 " template <class T>\n" 10043 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10044 "};", 10045 AlignLeftBreakTemplate); 10046 10047 // The `&` in `Type&` should not be confused with a trailing `&` of 10048 // DEPRECATED(reason) member function. 10049 verifyFormat("struct f {\n" 10050 " template <class T>\n" 10051 " DEPRECATED(reason)\n" 10052 " Type &foo(arguments) {}\n" 10053 "};", 10054 BreakTemplate); 10055 10056 verifyFormat("struct f {\n" 10057 " template <class T>\n" 10058 " DEPRECATED(reason)\n" 10059 " Type& foo(arguments) {}\n" 10060 "};", 10061 AlignLeftBreakTemplate); 10062 10063 verifyFormat("void (*foopt)(int) = &func;"); 10064 10065 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10066 DerivePointerAlignment.DerivePointerAlignment = true; 10067 // There's always a space between the function and its trailing qualifiers. 10068 // This isn't evidence for PAS_Right (or for PAS_Left). 10069 std::string Prefix = "void a() &;\n" 10070 "void b() &;\n"; 10071 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10072 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10073 // Same if the function is an overloaded operator, and with &&. 10074 Prefix = "void operator()() &&;\n" 10075 "void operator()() &&;\n"; 10076 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10077 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10078 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10079 Prefix = "void a() const &;\n" 10080 "void b() const &;\n"; 10081 EXPECT_EQ(Prefix + "int *x;", 10082 format(Prefix + "int* x;", DerivePointerAlignment)); 10083 } 10084 10085 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10086 verifyFormat("void f() {\n" 10087 " A *a = new A;\n" 10088 " A *a = new (placement) A;\n" 10089 " delete a;\n" 10090 " delete (A *)a;\n" 10091 "}"); 10092 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10093 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10094 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10095 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10096 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10097 verifyFormat("delete[] h->p;"); 10098 verifyFormat("delete[] (void *)p;"); 10099 10100 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10101 verifyFormat("void operator new(void *foo) ATTRIB;"); 10102 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10103 verifyFormat("void operator delete(void *ptr) noexcept;"); 10104 10105 EXPECT_EQ("void new(link p);\n" 10106 "void delete(link p);\n", 10107 format("void new (link p);\n" 10108 "void delete (link p);\n")); 10109 } 10110 10111 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10112 verifyFormat("int *f(int *a) {}"); 10113 verifyFormat("int main(int argc, char **argv) {}"); 10114 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10115 verifyIndependentOfContext("f(a, *a);"); 10116 verifyFormat("void g() { f(*a); }"); 10117 verifyIndependentOfContext("int a = b * 10;"); 10118 verifyIndependentOfContext("int a = 10 * b;"); 10119 verifyIndependentOfContext("int a = b * c;"); 10120 verifyIndependentOfContext("int a += b * c;"); 10121 verifyIndependentOfContext("int a -= b * c;"); 10122 verifyIndependentOfContext("int a *= b * c;"); 10123 verifyIndependentOfContext("int a /= b * c;"); 10124 verifyIndependentOfContext("int a = *b;"); 10125 verifyIndependentOfContext("int a = *b * c;"); 10126 verifyIndependentOfContext("int a = b * *c;"); 10127 verifyIndependentOfContext("int a = b * (10);"); 10128 verifyIndependentOfContext("S << b * (10);"); 10129 verifyIndependentOfContext("return 10 * b;"); 10130 verifyIndependentOfContext("return *b * *c;"); 10131 verifyIndependentOfContext("return a & ~b;"); 10132 verifyIndependentOfContext("f(b ? *c : *d);"); 10133 verifyIndependentOfContext("int a = b ? *c : *d;"); 10134 verifyIndependentOfContext("*b = a;"); 10135 verifyIndependentOfContext("a * ~b;"); 10136 verifyIndependentOfContext("a * !b;"); 10137 verifyIndependentOfContext("a * +b;"); 10138 verifyIndependentOfContext("a * -b;"); 10139 verifyIndependentOfContext("a * ++b;"); 10140 verifyIndependentOfContext("a * --b;"); 10141 verifyIndependentOfContext("a[4] * b;"); 10142 verifyIndependentOfContext("a[a * a] = 1;"); 10143 verifyIndependentOfContext("f() * b;"); 10144 verifyIndependentOfContext("a * [self dostuff];"); 10145 verifyIndependentOfContext("int x = a * (a + b);"); 10146 verifyIndependentOfContext("(a *)(a + b);"); 10147 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10148 verifyIndependentOfContext("int *pa = (int *)&a;"); 10149 verifyIndependentOfContext("return sizeof(int **);"); 10150 verifyIndependentOfContext("return sizeof(int ******);"); 10151 verifyIndependentOfContext("return (int **&)a;"); 10152 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10153 verifyFormat("void f(Type (*parameter)[10]) {}"); 10154 verifyFormat("void f(Type (¶meter)[10]) {}"); 10155 verifyGoogleFormat("return sizeof(int**);"); 10156 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10157 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10158 verifyFormat("auto a = [](int **&, int ***) {};"); 10159 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10160 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10161 verifyFormat("[](const decltype(*a) &value) {}"); 10162 verifyFormat("[](const typeof(*a) &value) {}"); 10163 verifyFormat("[](const _Atomic(a *) &value) {}"); 10164 verifyFormat("[](const __underlying_type(a) &value) {}"); 10165 verifyFormat("decltype(a * b) F();"); 10166 verifyFormat("typeof(a * b) F();"); 10167 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10168 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10169 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10170 verifyIndependentOfContext("int i{a * b};"); 10171 verifyIndependentOfContext("aaa && aaa->f();"); 10172 verifyIndependentOfContext("int x = ~*p;"); 10173 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10174 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10175 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10176 verifyFormat("void f() { f(a, c * d); }"); 10177 verifyFormat("void f() { f(new a(), c * d); }"); 10178 verifyFormat("void f(const MyOverride &override);"); 10179 verifyFormat("void f(const MyFinal &final);"); 10180 verifyIndependentOfContext("bool a = f() && override.f();"); 10181 verifyIndependentOfContext("bool a = f() && final.f();"); 10182 10183 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10184 10185 verifyIndependentOfContext("A<int *> a;"); 10186 verifyIndependentOfContext("A<int **> a;"); 10187 verifyIndependentOfContext("A<int *, int *> a;"); 10188 verifyIndependentOfContext("A<int *[]> a;"); 10189 verifyIndependentOfContext( 10190 "const char *const p = reinterpret_cast<const char *const>(q);"); 10191 verifyIndependentOfContext("A<int **, int **> a;"); 10192 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10193 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10194 verifyFormat("for (; a && b;) {\n}"); 10195 verifyFormat("bool foo = true && [] { return false; }();"); 10196 10197 verifyFormat( 10198 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10200 10201 verifyGoogleFormat("int const* a = &b;"); 10202 verifyGoogleFormat("**outparam = 1;"); 10203 verifyGoogleFormat("*outparam = a * b;"); 10204 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10205 verifyGoogleFormat("A<int*> a;"); 10206 verifyGoogleFormat("A<int**> a;"); 10207 verifyGoogleFormat("A<int*, int*> a;"); 10208 verifyGoogleFormat("A<int**, int**> a;"); 10209 verifyGoogleFormat("f(b ? *c : *d);"); 10210 verifyGoogleFormat("int a = b ? *c : *d;"); 10211 verifyGoogleFormat("Type* t = **x;"); 10212 verifyGoogleFormat("Type* t = *++*x;"); 10213 verifyGoogleFormat("*++*x;"); 10214 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10215 verifyGoogleFormat("Type* t = x++ * y;"); 10216 verifyGoogleFormat( 10217 "const char* const p = reinterpret_cast<const char* const>(q);"); 10218 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10219 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10220 verifyGoogleFormat("template <typename T>\n" 10221 "void f(int i = 0, SomeType** temps = NULL);"); 10222 10223 FormatStyle Left = getLLVMStyle(); 10224 Left.PointerAlignment = FormatStyle::PAS_Left; 10225 verifyFormat("x = *a(x) = *a(y);", Left); 10226 verifyFormat("for (;; *a = b) {\n}", Left); 10227 verifyFormat("return *this += 1;", Left); 10228 verifyFormat("throw *x;", Left); 10229 verifyFormat("delete *x;", Left); 10230 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10231 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10232 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10233 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10234 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10235 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10236 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10237 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10238 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10239 10240 verifyIndependentOfContext("a = *(x + y);"); 10241 verifyIndependentOfContext("a = &(x + y);"); 10242 verifyIndependentOfContext("*(x + y).call();"); 10243 verifyIndependentOfContext("&(x + y)->call();"); 10244 verifyFormat("void f() { &(*I).first; }"); 10245 10246 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10247 verifyFormat("f(* /* confusing comment */ foo);"); 10248 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10249 verifyFormat("void foo(int * // this is the first paramters\n" 10250 " ,\n" 10251 " int second);"); 10252 verifyFormat("double term = a * // first\n" 10253 " b;"); 10254 verifyFormat( 10255 "int *MyValues = {\n" 10256 " *A, // Operator detection might be confused by the '{'\n" 10257 " *BB // Operator detection might be confused by previous comment\n" 10258 "};"); 10259 10260 verifyIndependentOfContext("if (int *a = &b)"); 10261 verifyIndependentOfContext("if (int &a = *b)"); 10262 verifyIndependentOfContext("if (a & b[i])"); 10263 verifyIndependentOfContext("if constexpr (a & b[i])"); 10264 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10265 verifyIndependentOfContext("if (a * (b * c))"); 10266 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10267 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10268 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10269 verifyIndependentOfContext("if (*b[i])"); 10270 verifyIndependentOfContext("if (int *a = (&b))"); 10271 verifyIndependentOfContext("while (int *a = &b)"); 10272 verifyIndependentOfContext("while (a * (b * c))"); 10273 verifyIndependentOfContext("size = sizeof *a;"); 10274 verifyIndependentOfContext("if (a && (b = c))"); 10275 verifyFormat("void f() {\n" 10276 " for (const int &v : Values) {\n" 10277 " }\n" 10278 "}"); 10279 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10280 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10281 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10282 10283 verifyFormat("#define A (!a * b)"); 10284 verifyFormat("#define MACRO \\\n" 10285 " int *i = a * b; \\\n" 10286 " void f(a *b);", 10287 getLLVMStyleWithColumns(19)); 10288 10289 verifyIndependentOfContext("A = new SomeType *[Length];"); 10290 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10291 verifyIndependentOfContext("T **t = new T *;"); 10292 verifyIndependentOfContext("T **t = new T *();"); 10293 verifyGoogleFormat("A = new SomeType*[Length]();"); 10294 verifyGoogleFormat("A = new SomeType*[Length];"); 10295 verifyGoogleFormat("T** t = new T*;"); 10296 verifyGoogleFormat("T** t = new T*();"); 10297 10298 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10299 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10300 verifyFormat("template <bool a, bool b> " 10301 "typename t::if<x && y>::type f() {}"); 10302 verifyFormat("template <int *y> f() {}"); 10303 verifyFormat("vector<int *> v;"); 10304 verifyFormat("vector<int *const> v;"); 10305 verifyFormat("vector<int *const **const *> v;"); 10306 verifyFormat("vector<int *volatile> v;"); 10307 verifyFormat("vector<a *_Nonnull> v;"); 10308 verifyFormat("vector<a *_Nullable> v;"); 10309 verifyFormat("vector<a *_Null_unspecified> v;"); 10310 verifyFormat("vector<a *__ptr32> v;"); 10311 verifyFormat("vector<a *__ptr64> v;"); 10312 verifyFormat("vector<a *__capability> v;"); 10313 FormatStyle TypeMacros = getLLVMStyle(); 10314 TypeMacros.TypenameMacros = {"LIST"}; 10315 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10316 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10317 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10318 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10319 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10320 10321 FormatStyle CustomQualifier = getLLVMStyle(); 10322 // Add identifiers that should not be parsed as a qualifier by default. 10323 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10324 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10325 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10326 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10327 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10328 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10329 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10330 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10331 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10332 verifyFormat("vector<a * _NotAQualifier> v;"); 10333 verifyFormat("vector<a * __not_a_qualifier> v;"); 10334 verifyFormat("vector<a * b> v;"); 10335 verifyFormat("foo<b && false>();"); 10336 verifyFormat("foo<b & 1>();"); 10337 verifyFormat("foo<b & (1)>();"); 10338 verifyFormat("foo<b & (~0)>();"); 10339 verifyFormat("foo<b & (true)>();"); 10340 verifyFormat("foo<b & ((1))>();"); 10341 verifyFormat("foo<b & (/*comment*/ 1)>();"); 10342 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10343 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10344 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10345 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10346 verifyFormat( 10347 "template <class T, class = typename std::enable_if<\n" 10348 " std::is_integral<T>::value &&\n" 10349 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10350 "void F();", 10351 getLLVMStyleWithColumns(70)); 10352 verifyFormat("template <class T,\n" 10353 " class = typename std::enable_if<\n" 10354 " std::is_integral<T>::value &&\n" 10355 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10356 " class U>\n" 10357 "void F();", 10358 getLLVMStyleWithColumns(70)); 10359 verifyFormat( 10360 "template <class T,\n" 10361 " class = typename ::std::enable_if<\n" 10362 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10363 "void F();", 10364 getGoogleStyleWithColumns(68)); 10365 10366 verifyIndependentOfContext("MACRO(int *i);"); 10367 verifyIndependentOfContext("MACRO(auto *a);"); 10368 verifyIndependentOfContext("MACRO(const A *a);"); 10369 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10370 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10371 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10372 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10373 verifyIndependentOfContext("MACRO(A *const a);"); 10374 verifyIndependentOfContext("MACRO(A *restrict a);"); 10375 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10376 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10377 verifyIndependentOfContext("MACRO(A *volatile a);"); 10378 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10379 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10380 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10381 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10382 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10383 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10384 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10385 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10386 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10387 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10388 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10389 verifyIndependentOfContext("MACRO(A *__capability);"); 10390 verifyIndependentOfContext("MACRO(A &__capability);"); 10391 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10392 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10393 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10394 // a type declaration: 10395 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10396 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10397 // Also check that TypenameMacros prevents parsing it as multiplication: 10398 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10399 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10400 10401 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10402 verifyFormat("void f() { f(float{1}, a * a); }"); 10403 verifyFormat("void f() { f(float(1), a * a); }"); 10404 10405 verifyFormat("f((void (*)(int))g);"); 10406 verifyFormat("f((void (&)(int))g);"); 10407 verifyFormat("f((void (^)(int))g);"); 10408 10409 // FIXME: Is there a way to make this work? 10410 // verifyIndependentOfContext("MACRO(A *a);"); 10411 verifyFormat("MACRO(A &B);"); 10412 verifyFormat("MACRO(A *B);"); 10413 verifyFormat("void f() { MACRO(A * B); }"); 10414 verifyFormat("void f() { MACRO(A & B); }"); 10415 10416 // This lambda was mis-formatted after D88956 (treating it as a binop): 10417 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10418 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10419 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10420 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10421 10422 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10423 verifyFormat("return options != nullptr && operator==(*options);"); 10424 10425 EXPECT_EQ("#define OP(x) \\\n" 10426 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10427 " return s << a.DebugString(); \\\n" 10428 " }", 10429 format("#define OP(x) \\\n" 10430 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10431 " return s << a.DebugString(); \\\n" 10432 " }", 10433 getLLVMStyleWithColumns(50))); 10434 10435 // FIXME: We cannot handle this case yet; we might be able to figure out that 10436 // foo<x> d > v; doesn't make sense. 10437 verifyFormat("foo<a<b && c> d> v;"); 10438 10439 FormatStyle PointerMiddle = getLLVMStyle(); 10440 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10441 verifyFormat("delete *x;", PointerMiddle); 10442 verifyFormat("int * x;", PointerMiddle); 10443 verifyFormat("int *[] x;", PointerMiddle); 10444 verifyFormat("template <int * y> f() {}", PointerMiddle); 10445 verifyFormat("int * f(int * a) {}", PointerMiddle); 10446 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10447 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10448 verifyFormat("A<int *> a;", PointerMiddle); 10449 verifyFormat("A<int **> a;", PointerMiddle); 10450 verifyFormat("A<int *, int *> a;", PointerMiddle); 10451 verifyFormat("A<int *[]> a;", PointerMiddle); 10452 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10453 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10454 verifyFormat("T ** t = new T *;", PointerMiddle); 10455 10456 // Member function reference qualifiers aren't binary operators. 10457 verifyFormat("string // break\n" 10458 "operator()() & {}"); 10459 verifyFormat("string // break\n" 10460 "operator()() && {}"); 10461 verifyGoogleFormat("template <typename T>\n" 10462 "auto x() & -> int {}"); 10463 10464 // Should be binary operators when used as an argument expression (overloaded 10465 // operator invoked as a member function). 10466 verifyFormat("void f() { a.operator()(a * a); }"); 10467 verifyFormat("void f() { a->operator()(a & a); }"); 10468 verifyFormat("void f() { a.operator()(*a & *a); }"); 10469 verifyFormat("void f() { a->operator()(*a * *a); }"); 10470 10471 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10472 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10473 } 10474 10475 TEST_F(FormatTest, UnderstandsAttributes) { 10476 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10477 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10478 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10479 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10480 FormatStyle AfterType = getLLVMStyle(); 10481 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10482 verifyFormat("__attribute__((nodebug)) void\n" 10483 "foo() {}\n", 10484 AfterType); 10485 verifyFormat("__unused void\n" 10486 "foo() {}", 10487 AfterType); 10488 10489 FormatStyle CustomAttrs = getLLVMStyle(); 10490 CustomAttrs.AttributeMacros.push_back("__unused"); 10491 CustomAttrs.AttributeMacros.push_back("__attr1"); 10492 CustomAttrs.AttributeMacros.push_back("__attr2"); 10493 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10494 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10495 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10496 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10497 // Check that it is parsed as a multiplication without AttributeMacros and 10498 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10499 verifyFormat("vector<SomeType * __attr1> v;"); 10500 verifyFormat("vector<SomeType __attr1 *> v;"); 10501 verifyFormat("vector<SomeType __attr1 *const> v;"); 10502 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10503 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10504 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10505 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10506 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10507 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10508 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10509 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10510 10511 // Check that these are not parsed as function declarations: 10512 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10513 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10514 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10515 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10516 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10517 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10518 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10519 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10520 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10521 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10522 } 10523 10524 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10525 // Check that qualifiers on pointers don't break parsing of casts. 10526 verifyFormat("x = (foo *const)*v;"); 10527 verifyFormat("x = (foo *volatile)*v;"); 10528 verifyFormat("x = (foo *restrict)*v;"); 10529 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10530 verifyFormat("x = (foo *_Nonnull)*v;"); 10531 verifyFormat("x = (foo *_Nullable)*v;"); 10532 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10533 verifyFormat("x = (foo *_Nonnull)*v;"); 10534 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10535 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10536 verifyFormat("x = (foo *__ptr32)*v;"); 10537 verifyFormat("x = (foo *__ptr64)*v;"); 10538 verifyFormat("x = (foo *__capability)*v;"); 10539 10540 // Check that we handle multiple trailing qualifiers and skip them all to 10541 // determine that the expression is a cast to a pointer type. 10542 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10543 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10544 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10545 StringRef AllQualifiers = 10546 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10547 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10548 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10549 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10550 10551 // Also check that address-of is not parsed as a binary bitwise-and: 10552 verifyFormat("x = (foo *const)&v;"); 10553 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10554 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10555 10556 // Check custom qualifiers: 10557 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10558 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10559 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10560 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10561 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10562 CustomQualifier); 10563 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10564 CustomQualifier); 10565 10566 // Check that unknown identifiers result in binary operator parsing: 10567 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10568 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10569 } 10570 10571 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10572 verifyFormat("SomeType s [[unused]] (InitValue);"); 10573 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10574 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10575 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10576 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10577 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10578 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10579 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10580 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10581 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10582 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10583 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10584 10585 // Make sure we do not mistake attributes for array subscripts. 10586 verifyFormat("int a() {}\n" 10587 "[[unused]] int b() {}\n"); 10588 verifyFormat("NSArray *arr;\n" 10589 "arr[[Foo() bar]];"); 10590 10591 // On the other hand, we still need to correctly find array subscripts. 10592 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10593 10594 // Make sure that we do not mistake Objective-C method inside array literals 10595 // as attributes, even if those method names are also keywords. 10596 verifyFormat("@[ [foo bar] ];"); 10597 verifyFormat("@[ [NSArray class] ];"); 10598 verifyFormat("@[ [foo enum] ];"); 10599 10600 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10601 10602 // Make sure we do not parse attributes as lambda introducers. 10603 FormatStyle MultiLineFunctions = getLLVMStyle(); 10604 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10605 verifyFormat("[[unused]] int b() {\n" 10606 " return 42;\n" 10607 "}\n", 10608 MultiLineFunctions); 10609 } 10610 10611 TEST_F(FormatTest, AttributeClass) { 10612 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10613 verifyFormat("class S {\n" 10614 " S(S&&) = default;\n" 10615 "};", 10616 Style); 10617 verifyFormat("class [[nodiscard]] S {\n" 10618 " S(S&&) = default;\n" 10619 "};", 10620 Style); 10621 verifyFormat("class __attribute((maybeunused)) S {\n" 10622 " S(S&&) = default;\n" 10623 "};", 10624 Style); 10625 verifyFormat("struct S {\n" 10626 " S(S&&) = default;\n" 10627 "};", 10628 Style); 10629 verifyFormat("struct [[nodiscard]] S {\n" 10630 " S(S&&) = default;\n" 10631 "};", 10632 Style); 10633 } 10634 10635 TEST_F(FormatTest, AttributesAfterMacro) { 10636 FormatStyle Style = getLLVMStyle(); 10637 verifyFormat("MACRO;\n" 10638 "__attribute__((maybe_unused)) int foo() {\n" 10639 " //...\n" 10640 "}"); 10641 10642 verifyFormat("MACRO;\n" 10643 "[[nodiscard]] int foo() {\n" 10644 " //...\n" 10645 "}"); 10646 10647 EXPECT_EQ("MACRO\n\n" 10648 "__attribute__((maybe_unused)) int foo() {\n" 10649 " //...\n" 10650 "}", 10651 format("MACRO\n\n" 10652 "__attribute__((maybe_unused)) int foo() {\n" 10653 " //...\n" 10654 "}")); 10655 10656 EXPECT_EQ("MACRO\n\n" 10657 "[[nodiscard]] int foo() {\n" 10658 " //...\n" 10659 "}", 10660 format("MACRO\n\n" 10661 "[[nodiscard]] int foo() {\n" 10662 " //...\n" 10663 "}")); 10664 } 10665 10666 TEST_F(FormatTest, AttributePenaltyBreaking) { 10667 FormatStyle Style = getLLVMStyle(); 10668 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10669 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10670 Style); 10671 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10672 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10673 Style); 10674 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10675 "shared_ptr<ALongTypeName> &C d) {\n}", 10676 Style); 10677 } 10678 10679 TEST_F(FormatTest, UnderstandsEllipsis) { 10680 FormatStyle Style = getLLVMStyle(); 10681 verifyFormat("int printf(const char *fmt, ...);"); 10682 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10683 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10684 10685 verifyFormat("template <int *...PP> a;", Style); 10686 10687 Style.PointerAlignment = FormatStyle::PAS_Left; 10688 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10689 10690 verifyFormat("template <int*... PP> a;", Style); 10691 10692 Style.PointerAlignment = FormatStyle::PAS_Middle; 10693 verifyFormat("template <int *... PP> a;", Style); 10694 } 10695 10696 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10697 EXPECT_EQ("int *a;\n" 10698 "int *a;\n" 10699 "int *a;", 10700 format("int *a;\n" 10701 "int* a;\n" 10702 "int *a;", 10703 getGoogleStyle())); 10704 EXPECT_EQ("int* a;\n" 10705 "int* a;\n" 10706 "int* a;", 10707 format("int* a;\n" 10708 "int* a;\n" 10709 "int *a;", 10710 getGoogleStyle())); 10711 EXPECT_EQ("int *a;\n" 10712 "int *a;\n" 10713 "int *a;", 10714 format("int *a;\n" 10715 "int * a;\n" 10716 "int * a;", 10717 getGoogleStyle())); 10718 EXPECT_EQ("auto x = [] {\n" 10719 " int *a;\n" 10720 " int *a;\n" 10721 " int *a;\n" 10722 "};", 10723 format("auto x=[]{int *a;\n" 10724 "int * a;\n" 10725 "int * a;};", 10726 getGoogleStyle())); 10727 } 10728 10729 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10730 verifyFormat("int f(int &&a) {}"); 10731 verifyFormat("int f(int a, char &&b) {}"); 10732 verifyFormat("void f() { int &&a = b; }"); 10733 verifyGoogleFormat("int f(int a, char&& b) {}"); 10734 verifyGoogleFormat("void f() { int&& a = b; }"); 10735 10736 verifyIndependentOfContext("A<int &&> a;"); 10737 verifyIndependentOfContext("A<int &&, int &&> a;"); 10738 verifyGoogleFormat("A<int&&> a;"); 10739 verifyGoogleFormat("A<int&&, int&&> a;"); 10740 10741 // Not rvalue references: 10742 verifyFormat("template <bool B, bool C> class A {\n" 10743 " static_assert(B && C, \"Something is wrong\");\n" 10744 "};"); 10745 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10746 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10747 verifyFormat("#define A(a, b) (a && b)"); 10748 } 10749 10750 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10751 verifyFormat("void f() {\n" 10752 " x[aaaaaaaaa -\n" 10753 " b] = 23;\n" 10754 "}", 10755 getLLVMStyleWithColumns(15)); 10756 } 10757 10758 TEST_F(FormatTest, FormatsCasts) { 10759 verifyFormat("Type *A = static_cast<Type *>(P);"); 10760 verifyFormat("static_cast<Type *>(P);"); 10761 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10762 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10763 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10764 // Check that static_cast<...>(...) does not require the next token to be on 10765 // the same line. 10766 verifyFormat("some_loooong_output << something_something__ << " 10767 "static_cast<const void *>(R)\n" 10768 " << something;"); 10769 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10770 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10771 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10772 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10773 verifyFormat("Type *A = (Type *)P;"); 10774 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10775 verifyFormat("int a = (int)(2.0f);"); 10776 verifyFormat("int a = (int)2.0f;"); 10777 verifyFormat("x[(int32)y];"); 10778 verifyFormat("x = (int32)y;"); 10779 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10780 verifyFormat("int a = (int)*b;"); 10781 verifyFormat("int a = (int)2.0f;"); 10782 verifyFormat("int a = (int)~0;"); 10783 verifyFormat("int a = (int)++a;"); 10784 verifyFormat("int a = (int)sizeof(int);"); 10785 verifyFormat("int a = (int)+2;"); 10786 verifyFormat("my_int a = (my_int)2.0f;"); 10787 verifyFormat("my_int a = (my_int)sizeof(int);"); 10788 verifyFormat("return (my_int)aaa;"); 10789 verifyFormat("#define x ((int)-1)"); 10790 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10791 verifyFormat("#define p(q) ((int *)&q)"); 10792 verifyFormat("fn(a)(b) + 1;"); 10793 10794 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10795 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10796 verifyFormat("my_int a = (my_int)~0;"); 10797 verifyFormat("my_int a = (my_int)++a;"); 10798 verifyFormat("my_int a = (my_int)-2;"); 10799 verifyFormat("my_int a = (my_int)1;"); 10800 verifyFormat("my_int a = (my_int *)1;"); 10801 verifyFormat("my_int a = (const my_int)-1;"); 10802 verifyFormat("my_int a = (const my_int *)-1;"); 10803 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10804 verifyFormat("my_int a = (ns::my_int)-2;"); 10805 verifyFormat("case (my_int)ONE:"); 10806 verifyFormat("auto x = (X)this;"); 10807 // Casts in Obj-C style calls used to not be recognized as such. 10808 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10809 10810 // FIXME: single value wrapped with paren will be treated as cast. 10811 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10812 10813 verifyFormat("{ (void)F; }"); 10814 10815 // Don't break after a cast's 10816 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10817 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10818 " bbbbbbbbbbbbbbbbbbbbbb);"); 10819 10820 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10821 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10822 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10823 verifyFormat("bool *y = (bool *)(void *)(x);"); 10824 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10825 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10826 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10827 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10828 10829 // These are not casts. 10830 verifyFormat("void f(int *) {}"); 10831 verifyFormat("f(foo)->b;"); 10832 verifyFormat("f(foo).b;"); 10833 verifyFormat("f(foo)(b);"); 10834 verifyFormat("f(foo)[b];"); 10835 verifyFormat("[](foo) { return 4; }(bar);"); 10836 verifyFormat("(*funptr)(foo)[4];"); 10837 verifyFormat("funptrs[4](foo)[4];"); 10838 verifyFormat("void f(int *);"); 10839 verifyFormat("void f(int *) = 0;"); 10840 verifyFormat("void f(SmallVector<int>) {}"); 10841 verifyFormat("void f(SmallVector<int>);"); 10842 verifyFormat("void f(SmallVector<int>) = 0;"); 10843 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10844 verifyFormat("int a = sizeof(int) * b;"); 10845 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10846 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10847 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10848 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10849 10850 // These are not casts, but at some point were confused with casts. 10851 verifyFormat("virtual void foo(int *) override;"); 10852 verifyFormat("virtual void foo(char &) const;"); 10853 verifyFormat("virtual void foo(int *a, char *) const;"); 10854 verifyFormat("int a = sizeof(int *) + b;"); 10855 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10856 verifyFormat("bool b = f(g<int>) && c;"); 10857 verifyFormat("typedef void (*f)(int i) func;"); 10858 verifyFormat("void operator++(int) noexcept;"); 10859 verifyFormat("void operator++(int &) noexcept;"); 10860 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10861 "&) noexcept;"); 10862 verifyFormat( 10863 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10864 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10865 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10866 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10867 verifyFormat("void operator delete(foo &) noexcept;"); 10868 verifyFormat("void operator delete(foo) noexcept;"); 10869 verifyFormat("void operator delete(int) noexcept;"); 10870 verifyFormat("void operator delete(int &) noexcept;"); 10871 verifyFormat("void operator delete(int &) volatile noexcept;"); 10872 verifyFormat("void operator delete(int &) const"); 10873 verifyFormat("void operator delete(int &) = default"); 10874 verifyFormat("void operator delete(int &) = delete"); 10875 verifyFormat("void operator delete(int &) [[noreturn]]"); 10876 verifyFormat("void operator delete(int &) throw();"); 10877 verifyFormat("void operator delete(int &) throw(int);"); 10878 verifyFormat("auto operator delete(int &) -> int;"); 10879 verifyFormat("auto operator delete(int &) override"); 10880 verifyFormat("auto operator delete(int &) final"); 10881 10882 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10883 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10884 // FIXME: The indentation here is not ideal. 10885 verifyFormat( 10886 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10887 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10888 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10889 } 10890 10891 TEST_F(FormatTest, FormatsFunctionTypes) { 10892 verifyFormat("A<bool()> a;"); 10893 verifyFormat("A<SomeType()> a;"); 10894 verifyFormat("A<void (*)(int, std::string)> a;"); 10895 verifyFormat("A<void *(int)>;"); 10896 verifyFormat("void *(*a)(int *, SomeType *);"); 10897 verifyFormat("int (*func)(void *);"); 10898 verifyFormat("void f() { int (*func)(void *); }"); 10899 verifyFormat("template <class CallbackClass>\n" 10900 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10901 10902 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10903 verifyGoogleFormat("void* (*a)(int);"); 10904 verifyGoogleFormat( 10905 "template <class CallbackClass>\n" 10906 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10907 10908 // Other constructs can look somewhat like function types: 10909 verifyFormat("A<sizeof(*x)> a;"); 10910 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10911 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10912 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10913 verifyFormat("int x = f(&h)();"); 10914 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10915 verifyFormat("std::function<\n" 10916 " LooooooooooongTemplatedType<\n" 10917 " SomeType>*(\n" 10918 " LooooooooooooooooongType type)>\n" 10919 " function;", 10920 getGoogleStyleWithColumns(40)); 10921 } 10922 10923 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10924 verifyFormat("A (*foo_)[6];"); 10925 verifyFormat("vector<int> (*foo_)[6];"); 10926 } 10927 10928 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10929 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10930 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10931 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10932 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10933 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10934 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10935 10936 // Different ways of ()-initializiation. 10937 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10938 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10939 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10940 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10941 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10942 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10943 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10944 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10945 10946 // Lambdas should not confuse the variable declaration heuristic. 10947 verifyFormat("LooooooooooooooooongType\n" 10948 " variable(nullptr, [](A *a) {});", 10949 getLLVMStyleWithColumns(40)); 10950 } 10951 10952 TEST_F(FormatTest, BreaksLongDeclarations) { 10953 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10954 " AnotherNameForTheLongType;"); 10955 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10956 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10957 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10958 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10959 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10960 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10961 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10962 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10963 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10964 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10965 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10966 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10967 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10968 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10969 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10970 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10971 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10972 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10973 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10974 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10975 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10976 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10977 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10978 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10979 FormatStyle Indented = getLLVMStyle(); 10980 Indented.IndentWrappedFunctionNames = true; 10981 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10982 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10983 Indented); 10984 verifyFormat( 10985 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10986 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10987 Indented); 10988 verifyFormat( 10989 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10990 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10991 Indented); 10992 verifyFormat( 10993 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10994 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10995 Indented); 10996 10997 // FIXME: Without the comment, this breaks after "(". 10998 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10999 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 11000 getGoogleStyle()); 11001 11002 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 11003 " int LoooooooooooooooooooongParam2) {}"); 11004 verifyFormat( 11005 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 11006 " SourceLocation L, IdentifierIn *II,\n" 11007 " Type *T) {}"); 11008 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 11009 "ReallyReaaallyLongFunctionName(\n" 11010 " const std::string &SomeParameter,\n" 11011 " const SomeType<string, SomeOtherTemplateParameter>\n" 11012 " &ReallyReallyLongParameterName,\n" 11013 " const SomeType<string, SomeOtherTemplateParameter>\n" 11014 " &AnotherLongParameterName) {}"); 11015 verifyFormat("template <typename A>\n" 11016 "SomeLoooooooooooooooooooooongType<\n" 11017 " typename some_namespace::SomeOtherType<A>::Type>\n" 11018 "Function() {}"); 11019 11020 verifyGoogleFormat( 11021 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11022 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11023 verifyGoogleFormat( 11024 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11025 " SourceLocation L) {}"); 11026 verifyGoogleFormat( 11027 "some_namespace::LongReturnType\n" 11028 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11029 " int first_long_parameter, int second_parameter) {}"); 11030 11031 verifyGoogleFormat("template <typename T>\n" 11032 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11033 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11034 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11035 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11036 11037 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11038 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11039 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11040 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11041 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11042 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11043 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11044 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11045 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11046 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11047 11048 verifyFormat("template <typename T> // Templates on own line.\n" 11049 "static int // Some comment.\n" 11050 "MyFunction(int a);", 11051 getLLVMStyle()); 11052 } 11053 11054 TEST_F(FormatTest, FormatsAccessModifiers) { 11055 FormatStyle Style = getLLVMStyle(); 11056 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11057 FormatStyle::ELBAMS_LogicalBlock); 11058 verifyFormat("struct foo {\n" 11059 "private:\n" 11060 " void f() {}\n" 11061 "\n" 11062 "private:\n" 11063 " int i;\n" 11064 "\n" 11065 "protected:\n" 11066 " int j;\n" 11067 "};\n", 11068 Style); 11069 verifyFormat("struct foo {\n" 11070 "private:\n" 11071 " void f() {}\n" 11072 "\n" 11073 "private:\n" 11074 " int i;\n" 11075 "\n" 11076 "protected:\n" 11077 " int j;\n" 11078 "};\n", 11079 "struct foo {\n" 11080 "private:\n" 11081 " void f() {}\n" 11082 "private:\n" 11083 " int i;\n" 11084 "protected:\n" 11085 " int j;\n" 11086 "};\n", 11087 Style); 11088 verifyFormat("struct foo { /* comment */\n" 11089 "private:\n" 11090 " int i;\n" 11091 " // comment\n" 11092 "private:\n" 11093 " int j;\n" 11094 "};\n", 11095 Style); 11096 verifyFormat("struct foo {\n" 11097 "#ifdef FOO\n" 11098 "#endif\n" 11099 "private:\n" 11100 " int i;\n" 11101 "#ifdef FOO\n" 11102 "private:\n" 11103 "#endif\n" 11104 " int j;\n" 11105 "};\n", 11106 Style); 11107 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11108 verifyFormat("struct foo {\n" 11109 "private:\n" 11110 " void f() {}\n" 11111 "private:\n" 11112 " int i;\n" 11113 "protected:\n" 11114 " int j;\n" 11115 "};\n", 11116 Style); 11117 verifyFormat("struct foo {\n" 11118 "private:\n" 11119 " void f() {}\n" 11120 "private:\n" 11121 " int i;\n" 11122 "protected:\n" 11123 " int j;\n" 11124 "};\n", 11125 "struct foo {\n" 11126 "\n" 11127 "private:\n" 11128 " void f() {}\n" 11129 "\n" 11130 "private:\n" 11131 " int i;\n" 11132 "\n" 11133 "protected:\n" 11134 " int j;\n" 11135 "};\n", 11136 Style); 11137 verifyFormat("struct foo { /* comment */\n" 11138 "private:\n" 11139 " int i;\n" 11140 " // comment\n" 11141 "private:\n" 11142 " int j;\n" 11143 "};\n", 11144 "struct foo { /* comment */\n" 11145 "\n" 11146 "private:\n" 11147 " int i;\n" 11148 " // comment\n" 11149 "\n" 11150 "private:\n" 11151 " int j;\n" 11152 "};\n", 11153 Style); 11154 verifyFormat("struct foo {\n" 11155 "#ifdef FOO\n" 11156 "#endif\n" 11157 "private:\n" 11158 " int i;\n" 11159 "#ifdef FOO\n" 11160 "private:\n" 11161 "#endif\n" 11162 " int j;\n" 11163 "};\n", 11164 "struct foo {\n" 11165 "#ifdef FOO\n" 11166 "#endif\n" 11167 "\n" 11168 "private:\n" 11169 " int i;\n" 11170 "#ifdef FOO\n" 11171 "\n" 11172 "private:\n" 11173 "#endif\n" 11174 " int j;\n" 11175 "};\n", 11176 Style); 11177 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11178 verifyFormat("struct foo {\n" 11179 "private:\n" 11180 " void f() {}\n" 11181 "\n" 11182 "private:\n" 11183 " int i;\n" 11184 "\n" 11185 "protected:\n" 11186 " int j;\n" 11187 "};\n", 11188 Style); 11189 verifyFormat("struct foo {\n" 11190 "private:\n" 11191 " void f() {}\n" 11192 "\n" 11193 "private:\n" 11194 " int i;\n" 11195 "\n" 11196 "protected:\n" 11197 " int j;\n" 11198 "};\n", 11199 "struct foo {\n" 11200 "private:\n" 11201 " void f() {}\n" 11202 "private:\n" 11203 " int i;\n" 11204 "protected:\n" 11205 " int j;\n" 11206 "};\n", 11207 Style); 11208 verifyFormat("struct foo { /* comment */\n" 11209 "private:\n" 11210 " int i;\n" 11211 " // comment\n" 11212 "\n" 11213 "private:\n" 11214 " int j;\n" 11215 "};\n", 11216 "struct foo { /* comment */\n" 11217 "private:\n" 11218 " int i;\n" 11219 " // comment\n" 11220 "\n" 11221 "private:\n" 11222 " int j;\n" 11223 "};\n", 11224 Style); 11225 verifyFormat("struct foo {\n" 11226 "#ifdef FOO\n" 11227 "#endif\n" 11228 "\n" 11229 "private:\n" 11230 " int i;\n" 11231 "#ifdef FOO\n" 11232 "\n" 11233 "private:\n" 11234 "#endif\n" 11235 " int j;\n" 11236 "};\n", 11237 "struct foo {\n" 11238 "#ifdef FOO\n" 11239 "#endif\n" 11240 "private:\n" 11241 " int i;\n" 11242 "#ifdef FOO\n" 11243 "private:\n" 11244 "#endif\n" 11245 " int j;\n" 11246 "};\n", 11247 Style); 11248 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11249 EXPECT_EQ("struct foo {\n" 11250 "\n" 11251 "private:\n" 11252 " void f() {}\n" 11253 "\n" 11254 "private:\n" 11255 " int i;\n" 11256 "\n" 11257 "protected:\n" 11258 " int j;\n" 11259 "};\n", 11260 format("struct foo {\n" 11261 "\n" 11262 "private:\n" 11263 " void f() {}\n" 11264 "\n" 11265 "private:\n" 11266 " int i;\n" 11267 "\n" 11268 "protected:\n" 11269 " int j;\n" 11270 "};\n", 11271 Style)); 11272 verifyFormat("struct foo {\n" 11273 "private:\n" 11274 " void f() {}\n" 11275 "private:\n" 11276 " int i;\n" 11277 "protected:\n" 11278 " int j;\n" 11279 "};\n", 11280 Style); 11281 EXPECT_EQ("struct foo { /* comment */\n" 11282 "\n" 11283 "private:\n" 11284 " int i;\n" 11285 " // comment\n" 11286 "\n" 11287 "private:\n" 11288 " int j;\n" 11289 "};\n", 11290 format("struct foo { /* comment */\n" 11291 "\n" 11292 "private:\n" 11293 " int i;\n" 11294 " // comment\n" 11295 "\n" 11296 "private:\n" 11297 " int j;\n" 11298 "};\n", 11299 Style)); 11300 verifyFormat("struct foo { /* comment */\n" 11301 "private:\n" 11302 " int i;\n" 11303 " // comment\n" 11304 "private:\n" 11305 " int j;\n" 11306 "};\n", 11307 Style); 11308 EXPECT_EQ("struct foo {\n" 11309 "#ifdef FOO\n" 11310 "#endif\n" 11311 "\n" 11312 "private:\n" 11313 " int i;\n" 11314 "#ifdef FOO\n" 11315 "\n" 11316 "private:\n" 11317 "#endif\n" 11318 " int j;\n" 11319 "};\n", 11320 format("struct foo {\n" 11321 "#ifdef FOO\n" 11322 "#endif\n" 11323 "\n" 11324 "private:\n" 11325 " int i;\n" 11326 "#ifdef FOO\n" 11327 "\n" 11328 "private:\n" 11329 "#endif\n" 11330 " int j;\n" 11331 "};\n", 11332 Style)); 11333 verifyFormat("struct foo {\n" 11334 "#ifdef FOO\n" 11335 "#endif\n" 11336 "private:\n" 11337 " int i;\n" 11338 "#ifdef FOO\n" 11339 "private:\n" 11340 "#endif\n" 11341 " int j;\n" 11342 "};\n", 11343 Style); 11344 11345 FormatStyle NoEmptyLines = getLLVMStyle(); 11346 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11347 verifyFormat("struct foo {\n" 11348 "private:\n" 11349 " void f() {}\n" 11350 "\n" 11351 "private:\n" 11352 " int i;\n" 11353 "\n" 11354 "public:\n" 11355 "protected:\n" 11356 " int j;\n" 11357 "};\n", 11358 NoEmptyLines); 11359 11360 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11361 verifyFormat("struct foo {\n" 11362 "private:\n" 11363 " void f() {}\n" 11364 "private:\n" 11365 " int i;\n" 11366 "public:\n" 11367 "protected:\n" 11368 " int j;\n" 11369 "};\n", 11370 NoEmptyLines); 11371 11372 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11373 verifyFormat("struct foo {\n" 11374 "private:\n" 11375 " void f() {}\n" 11376 "\n" 11377 "private:\n" 11378 " int i;\n" 11379 "\n" 11380 "public:\n" 11381 "\n" 11382 "protected:\n" 11383 " int j;\n" 11384 "};\n", 11385 NoEmptyLines); 11386 } 11387 11388 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11389 11390 FormatStyle Style = getLLVMStyle(); 11391 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11392 verifyFormat("struct foo {\n" 11393 "private:\n" 11394 " void f() {}\n" 11395 "\n" 11396 "private:\n" 11397 " int i;\n" 11398 "\n" 11399 "protected:\n" 11400 " int j;\n" 11401 "};\n", 11402 Style); 11403 11404 // Check if lines are removed. 11405 verifyFormat("struct foo {\n" 11406 "private:\n" 11407 " void f() {}\n" 11408 "\n" 11409 "private:\n" 11410 " int i;\n" 11411 "\n" 11412 "protected:\n" 11413 " int j;\n" 11414 "};\n", 11415 "struct foo {\n" 11416 "private:\n" 11417 "\n" 11418 " void f() {}\n" 11419 "\n" 11420 "private:\n" 11421 "\n" 11422 " int i;\n" 11423 "\n" 11424 "protected:\n" 11425 "\n" 11426 " int j;\n" 11427 "};\n", 11428 Style); 11429 11430 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11431 verifyFormat("struct foo {\n" 11432 "private:\n" 11433 "\n" 11434 " void f() {}\n" 11435 "\n" 11436 "private:\n" 11437 "\n" 11438 " int i;\n" 11439 "\n" 11440 "protected:\n" 11441 "\n" 11442 " int j;\n" 11443 "};\n", 11444 Style); 11445 11446 // Check if lines are added. 11447 verifyFormat("struct foo {\n" 11448 "private:\n" 11449 "\n" 11450 " void f() {}\n" 11451 "\n" 11452 "private:\n" 11453 "\n" 11454 " int i;\n" 11455 "\n" 11456 "protected:\n" 11457 "\n" 11458 " int j;\n" 11459 "};\n", 11460 "struct foo {\n" 11461 "private:\n" 11462 " void f() {}\n" 11463 "\n" 11464 "private:\n" 11465 " int i;\n" 11466 "\n" 11467 "protected:\n" 11468 " int j;\n" 11469 "};\n", 11470 Style); 11471 11472 // Leave tests rely on the code layout, test::messUp can not be used. 11473 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11474 Style.MaxEmptyLinesToKeep = 0u; 11475 verifyFormat("struct foo {\n" 11476 "private:\n" 11477 " void f() {}\n" 11478 "\n" 11479 "private:\n" 11480 " int i;\n" 11481 "\n" 11482 "protected:\n" 11483 " int j;\n" 11484 "};\n", 11485 Style); 11486 11487 // Check if MaxEmptyLinesToKeep is respected. 11488 EXPECT_EQ("struct foo {\n" 11489 "private:\n" 11490 " void f() {}\n" 11491 "\n" 11492 "private:\n" 11493 " int i;\n" 11494 "\n" 11495 "protected:\n" 11496 " int j;\n" 11497 "};\n", 11498 format("struct foo {\n" 11499 "private:\n" 11500 "\n\n\n" 11501 " void f() {}\n" 11502 "\n" 11503 "private:\n" 11504 "\n\n\n" 11505 " int i;\n" 11506 "\n" 11507 "protected:\n" 11508 "\n\n\n" 11509 " int j;\n" 11510 "};\n", 11511 Style)); 11512 11513 Style.MaxEmptyLinesToKeep = 1u; 11514 EXPECT_EQ("struct foo {\n" 11515 "private:\n" 11516 "\n" 11517 " void f() {}\n" 11518 "\n" 11519 "private:\n" 11520 "\n" 11521 " int i;\n" 11522 "\n" 11523 "protected:\n" 11524 "\n" 11525 " int j;\n" 11526 "};\n", 11527 format("struct foo {\n" 11528 "private:\n" 11529 "\n" 11530 " void f() {}\n" 11531 "\n" 11532 "private:\n" 11533 "\n" 11534 " int i;\n" 11535 "\n" 11536 "protected:\n" 11537 "\n" 11538 " int j;\n" 11539 "};\n", 11540 Style)); 11541 // Check if no lines are kept. 11542 EXPECT_EQ("struct foo {\n" 11543 "private:\n" 11544 " void f() {}\n" 11545 "\n" 11546 "private:\n" 11547 " int i;\n" 11548 "\n" 11549 "protected:\n" 11550 " int j;\n" 11551 "};\n", 11552 format("struct foo {\n" 11553 "private:\n" 11554 " void f() {}\n" 11555 "\n" 11556 "private:\n" 11557 " int i;\n" 11558 "\n" 11559 "protected:\n" 11560 " int j;\n" 11561 "};\n", 11562 Style)); 11563 // Check if MaxEmptyLinesToKeep is respected. 11564 EXPECT_EQ("struct foo {\n" 11565 "private:\n" 11566 "\n" 11567 " void f() {}\n" 11568 "\n" 11569 "private:\n" 11570 "\n" 11571 " int i;\n" 11572 "\n" 11573 "protected:\n" 11574 "\n" 11575 " int j;\n" 11576 "};\n", 11577 format("struct foo {\n" 11578 "private:\n" 11579 "\n\n\n" 11580 " void f() {}\n" 11581 "\n" 11582 "private:\n" 11583 "\n\n\n" 11584 " int i;\n" 11585 "\n" 11586 "protected:\n" 11587 "\n\n\n" 11588 " int j;\n" 11589 "};\n", 11590 Style)); 11591 11592 Style.MaxEmptyLinesToKeep = 10u; 11593 EXPECT_EQ("struct foo {\n" 11594 "private:\n" 11595 "\n\n\n" 11596 " void f() {}\n" 11597 "\n" 11598 "private:\n" 11599 "\n\n\n" 11600 " int i;\n" 11601 "\n" 11602 "protected:\n" 11603 "\n\n\n" 11604 " int j;\n" 11605 "};\n", 11606 format("struct foo {\n" 11607 "private:\n" 11608 "\n\n\n" 11609 " void f() {}\n" 11610 "\n" 11611 "private:\n" 11612 "\n\n\n" 11613 " int i;\n" 11614 "\n" 11615 "protected:\n" 11616 "\n\n\n" 11617 " int j;\n" 11618 "};\n", 11619 Style)); 11620 11621 // Test with comments. 11622 Style = getLLVMStyle(); 11623 verifyFormat("struct foo {\n" 11624 "private:\n" 11625 " // comment\n" 11626 " void f() {}\n" 11627 "\n" 11628 "private: /* comment */\n" 11629 " int i;\n" 11630 "};\n", 11631 Style); 11632 verifyFormat("struct foo {\n" 11633 "private:\n" 11634 " // comment\n" 11635 " void f() {}\n" 11636 "\n" 11637 "private: /* comment */\n" 11638 " int i;\n" 11639 "};\n", 11640 "struct foo {\n" 11641 "private:\n" 11642 "\n" 11643 " // comment\n" 11644 " void f() {}\n" 11645 "\n" 11646 "private: /* comment */\n" 11647 "\n" 11648 " int i;\n" 11649 "};\n", 11650 Style); 11651 11652 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11653 verifyFormat("struct foo {\n" 11654 "private:\n" 11655 "\n" 11656 " // comment\n" 11657 " void f() {}\n" 11658 "\n" 11659 "private: /* comment */\n" 11660 "\n" 11661 " int i;\n" 11662 "};\n", 11663 "struct foo {\n" 11664 "private:\n" 11665 " // comment\n" 11666 " void f() {}\n" 11667 "\n" 11668 "private: /* comment */\n" 11669 " int i;\n" 11670 "};\n", 11671 Style); 11672 verifyFormat("struct foo {\n" 11673 "private:\n" 11674 "\n" 11675 " // comment\n" 11676 " void f() {}\n" 11677 "\n" 11678 "private: /* comment */\n" 11679 "\n" 11680 " int i;\n" 11681 "};\n", 11682 Style); 11683 11684 // Test with preprocessor defines. 11685 Style = getLLVMStyle(); 11686 verifyFormat("struct foo {\n" 11687 "private:\n" 11688 "#ifdef FOO\n" 11689 "#endif\n" 11690 " void f() {}\n" 11691 "};\n", 11692 Style); 11693 verifyFormat("struct foo {\n" 11694 "private:\n" 11695 "#ifdef FOO\n" 11696 "#endif\n" 11697 " void f() {}\n" 11698 "};\n", 11699 "struct foo {\n" 11700 "private:\n" 11701 "\n" 11702 "#ifdef FOO\n" 11703 "#endif\n" 11704 " void f() {}\n" 11705 "};\n", 11706 Style); 11707 11708 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11709 verifyFormat("struct foo {\n" 11710 "private:\n" 11711 "\n" 11712 "#ifdef FOO\n" 11713 "#endif\n" 11714 " void f() {}\n" 11715 "};\n", 11716 "struct foo {\n" 11717 "private:\n" 11718 "#ifdef FOO\n" 11719 "#endif\n" 11720 " void f() {}\n" 11721 "};\n", 11722 Style); 11723 verifyFormat("struct foo {\n" 11724 "private:\n" 11725 "\n" 11726 "#ifdef FOO\n" 11727 "#endif\n" 11728 " void f() {}\n" 11729 "};\n", 11730 Style); 11731 } 11732 11733 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11734 // Combined tests of EmptyLineAfterAccessModifier and 11735 // EmptyLineBeforeAccessModifier. 11736 FormatStyle Style = getLLVMStyle(); 11737 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11738 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11739 verifyFormat("struct foo {\n" 11740 "private:\n" 11741 "\n" 11742 "protected:\n" 11743 "};\n", 11744 Style); 11745 11746 Style.MaxEmptyLinesToKeep = 10u; 11747 // Both remove all new lines. 11748 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11749 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11750 verifyFormat("struct foo {\n" 11751 "private:\n" 11752 "protected:\n" 11753 "};\n", 11754 "struct foo {\n" 11755 "private:\n" 11756 "\n\n\n" 11757 "protected:\n" 11758 "};\n", 11759 Style); 11760 11761 // Leave tests rely on the code layout, test::messUp can not be used. 11762 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11763 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11764 Style.MaxEmptyLinesToKeep = 10u; 11765 EXPECT_EQ("struct foo {\n" 11766 "private:\n" 11767 "\n\n\n" 11768 "protected:\n" 11769 "};\n", 11770 format("struct foo {\n" 11771 "private:\n" 11772 "\n\n\n" 11773 "protected:\n" 11774 "};\n", 11775 Style)); 11776 Style.MaxEmptyLinesToKeep = 3u; 11777 EXPECT_EQ("struct foo {\n" 11778 "private:\n" 11779 "\n\n\n" 11780 "protected:\n" 11781 "};\n", 11782 format("struct foo {\n" 11783 "private:\n" 11784 "\n\n\n" 11785 "protected:\n" 11786 "};\n", 11787 Style)); 11788 Style.MaxEmptyLinesToKeep = 1u; 11789 EXPECT_EQ("struct foo {\n" 11790 "private:\n" 11791 "\n\n\n" 11792 "protected:\n" 11793 "};\n", 11794 format("struct foo {\n" 11795 "private:\n" 11796 "\n\n\n" 11797 "protected:\n" 11798 "};\n", 11799 Style)); // Based on new lines in original document and not 11800 // on the setting. 11801 11802 Style.MaxEmptyLinesToKeep = 10u; 11803 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11804 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11805 // Newlines are kept if they are greater than zero, 11806 // test::messUp removes all new lines which changes the logic 11807 EXPECT_EQ("struct foo {\n" 11808 "private:\n" 11809 "\n\n\n" 11810 "protected:\n" 11811 "};\n", 11812 format("struct foo {\n" 11813 "private:\n" 11814 "\n\n\n" 11815 "protected:\n" 11816 "};\n", 11817 Style)); 11818 11819 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11820 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11821 // test::messUp removes all new lines which changes the logic 11822 EXPECT_EQ("struct foo {\n" 11823 "private:\n" 11824 "\n\n\n" 11825 "protected:\n" 11826 "};\n", 11827 format("struct foo {\n" 11828 "private:\n" 11829 "\n\n\n" 11830 "protected:\n" 11831 "};\n", 11832 Style)); 11833 11834 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11835 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11836 EXPECT_EQ("struct foo {\n" 11837 "private:\n" 11838 "\n\n\n" 11839 "protected:\n" 11840 "};\n", 11841 format("struct foo {\n" 11842 "private:\n" 11843 "\n\n\n" 11844 "protected:\n" 11845 "};\n", 11846 Style)); // test::messUp removes all new lines which changes 11847 // the logic. 11848 11849 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11850 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11851 verifyFormat("struct foo {\n" 11852 "private:\n" 11853 "protected:\n" 11854 "};\n", 11855 "struct foo {\n" 11856 "private:\n" 11857 "\n\n\n" 11858 "protected:\n" 11859 "};\n", 11860 Style); 11861 11862 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11863 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11864 EXPECT_EQ("struct foo {\n" 11865 "private:\n" 11866 "\n\n\n" 11867 "protected:\n" 11868 "};\n", 11869 format("struct foo {\n" 11870 "private:\n" 11871 "\n\n\n" 11872 "protected:\n" 11873 "};\n", 11874 Style)); // test::messUp removes all new lines which changes 11875 // the logic. 11876 11877 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11878 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11879 verifyFormat("struct foo {\n" 11880 "private:\n" 11881 "protected:\n" 11882 "};\n", 11883 "struct foo {\n" 11884 "private:\n" 11885 "\n\n\n" 11886 "protected:\n" 11887 "};\n", 11888 Style); 11889 11890 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11891 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11892 verifyFormat("struct foo {\n" 11893 "private:\n" 11894 "protected:\n" 11895 "};\n", 11896 "struct foo {\n" 11897 "private:\n" 11898 "\n\n\n" 11899 "protected:\n" 11900 "};\n", 11901 Style); 11902 11903 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11904 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11905 verifyFormat("struct foo {\n" 11906 "private:\n" 11907 "protected:\n" 11908 "};\n", 11909 "struct foo {\n" 11910 "private:\n" 11911 "\n\n\n" 11912 "protected:\n" 11913 "};\n", 11914 Style); 11915 11916 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11917 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11918 verifyFormat("struct foo {\n" 11919 "private:\n" 11920 "protected:\n" 11921 "};\n", 11922 "struct foo {\n" 11923 "private:\n" 11924 "\n\n\n" 11925 "protected:\n" 11926 "};\n", 11927 Style); 11928 } 11929 11930 TEST_F(FormatTest, FormatsArrays) { 11931 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11932 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11933 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11934 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11935 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11936 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11937 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11938 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11939 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11940 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11941 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11942 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11943 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11944 verifyFormat( 11945 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11946 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11947 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11948 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11949 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11950 11951 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11952 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11953 verifyFormat( 11954 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11955 " .aaaaaaa[0]\n" 11956 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11957 verifyFormat("a[::b::c];"); 11958 11959 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11960 11961 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11962 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11963 } 11964 11965 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11966 verifyFormat("(a)->b();"); 11967 verifyFormat("--a;"); 11968 } 11969 11970 TEST_F(FormatTest, HandlesIncludeDirectives) { 11971 verifyFormat("#include <string>\n" 11972 "#include <a/b/c.h>\n" 11973 "#include \"a/b/string\"\n" 11974 "#include \"string.h\"\n" 11975 "#include \"string.h\"\n" 11976 "#include <a-a>\n" 11977 "#include < path with space >\n" 11978 "#include_next <test.h>" 11979 "#include \"abc.h\" // this is included for ABC\n" 11980 "#include \"some long include\" // with a comment\n" 11981 "#include \"some very long include path\"\n" 11982 "#include <some/very/long/include/path>\n", 11983 getLLVMStyleWithColumns(35)); 11984 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11985 EXPECT_EQ("#include <a>", format("#include<a>")); 11986 11987 verifyFormat("#import <string>"); 11988 verifyFormat("#import <a/b/c.h>"); 11989 verifyFormat("#import \"a/b/string\""); 11990 verifyFormat("#import \"string.h\""); 11991 verifyFormat("#import \"string.h\""); 11992 verifyFormat("#if __has_include(<strstream>)\n" 11993 "#include <strstream>\n" 11994 "#endif"); 11995 11996 verifyFormat("#define MY_IMPORT <a/b>"); 11997 11998 verifyFormat("#if __has_include(<a/b>)"); 11999 verifyFormat("#if __has_include_next(<a/b>)"); 12000 verifyFormat("#define F __has_include(<a/b>)"); 12001 verifyFormat("#define F __has_include_next(<a/b>)"); 12002 12003 // Protocol buffer definition or missing "#". 12004 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 12005 getLLVMStyleWithColumns(30)); 12006 12007 FormatStyle Style = getLLVMStyle(); 12008 Style.AlwaysBreakBeforeMultilineStrings = true; 12009 Style.ColumnLimit = 0; 12010 verifyFormat("#import \"abc.h\"", Style); 12011 12012 // But 'import' might also be a regular C++ namespace. 12013 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12014 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12015 } 12016 12017 //===----------------------------------------------------------------------===// 12018 // Error recovery tests. 12019 //===----------------------------------------------------------------------===// 12020 12021 TEST_F(FormatTest, IncompleteParameterLists) { 12022 FormatStyle NoBinPacking = getLLVMStyle(); 12023 NoBinPacking.BinPackParameters = false; 12024 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12025 " double *min_x,\n" 12026 " double *max_x,\n" 12027 " double *min_y,\n" 12028 " double *max_y,\n" 12029 " double *min_z,\n" 12030 " double *max_z, ) {}", 12031 NoBinPacking); 12032 } 12033 12034 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12035 verifyFormat("void f() { return; }\n42"); 12036 verifyFormat("void f() {\n" 12037 " if (0)\n" 12038 " return;\n" 12039 "}\n" 12040 "42"); 12041 verifyFormat("void f() { return }\n42"); 12042 verifyFormat("void f() {\n" 12043 " if (0)\n" 12044 " return\n" 12045 "}\n" 12046 "42"); 12047 } 12048 12049 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12050 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12051 EXPECT_EQ("void f() {\n" 12052 " if (a)\n" 12053 " return\n" 12054 "}", 12055 format("void f ( ) { if ( a ) return }")); 12056 EXPECT_EQ("namespace N {\n" 12057 "void f()\n" 12058 "}", 12059 format("namespace N { void f() }")); 12060 EXPECT_EQ("namespace N {\n" 12061 "void f() {}\n" 12062 "void g()\n" 12063 "} // namespace N", 12064 format("namespace N { void f( ) { } void g( ) }")); 12065 } 12066 12067 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12068 verifyFormat("int aaaaaaaa =\n" 12069 " // Overlylongcomment\n" 12070 " b;", 12071 getLLVMStyleWithColumns(20)); 12072 verifyFormat("function(\n" 12073 " ShortArgument,\n" 12074 " LoooooooooooongArgument);\n", 12075 getLLVMStyleWithColumns(20)); 12076 } 12077 12078 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12079 verifyFormat("public:"); 12080 verifyFormat("class A {\n" 12081 "public\n" 12082 " void f() {}\n" 12083 "};"); 12084 verifyFormat("public\n" 12085 "int qwerty;"); 12086 verifyFormat("public\n" 12087 "B {}"); 12088 verifyFormat("public\n" 12089 "{}"); 12090 verifyFormat("public\n" 12091 "B { int x; }"); 12092 } 12093 12094 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12095 verifyFormat("{"); 12096 verifyFormat("#})"); 12097 verifyNoCrash("(/**/[:!] ?[)."); 12098 } 12099 12100 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12101 // Found by oss-fuzz: 12102 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12103 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12104 Style.ColumnLimit = 60; 12105 verifyNoCrash( 12106 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12107 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12108 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12109 Style); 12110 } 12111 12112 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12113 verifyFormat("do {\n}"); 12114 verifyFormat("do {\n}\n" 12115 "f();"); 12116 verifyFormat("do {\n}\n" 12117 "wheeee(fun);"); 12118 verifyFormat("do {\n" 12119 " f();\n" 12120 "}"); 12121 } 12122 12123 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12124 verifyFormat("if {\n foo;\n foo();\n}"); 12125 verifyFormat("switch {\n foo;\n foo();\n}"); 12126 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12127 verifyIncompleteFormat("ERROR: for target;"); 12128 verifyFormat("while {\n foo;\n foo();\n}"); 12129 verifyFormat("do {\n foo;\n foo();\n} while;"); 12130 } 12131 12132 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12133 verifyIncompleteFormat("namespace {\n" 12134 "class Foo { Foo (\n" 12135 "};\n" 12136 "} // namespace"); 12137 } 12138 12139 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12140 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12141 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12142 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12143 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12144 12145 EXPECT_EQ("{\n" 12146 " {\n" 12147 " breakme(\n" 12148 " qwe);\n" 12149 " }\n", 12150 format("{\n" 12151 " {\n" 12152 " breakme(qwe);\n" 12153 "}\n", 12154 getLLVMStyleWithColumns(10))); 12155 } 12156 12157 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12158 verifyFormat("int x = {\n" 12159 " avariable,\n" 12160 " b(alongervariable)};", 12161 getLLVMStyleWithColumns(25)); 12162 } 12163 12164 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12165 verifyFormat("return (a)(b){1, 2, 3};"); 12166 } 12167 12168 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12169 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12170 verifyFormat("vector<int> x{\n" 12171 " 1,\n" 12172 " 2,\n" 12173 " 3,\n" 12174 " 4,\n" 12175 "};"); 12176 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12177 verifyFormat("f({1, 2});"); 12178 verifyFormat("auto v = Foo{-1};"); 12179 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12180 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12181 verifyFormat("new vector<int>{1, 2, 3};"); 12182 verifyFormat("new int[3]{1, 2, 3};"); 12183 verifyFormat("new int{1};"); 12184 verifyFormat("return {arg1, arg2};"); 12185 verifyFormat("return {arg1, SomeType{parameter}};"); 12186 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12187 verifyFormat("new T{arg1, arg2};"); 12188 verifyFormat("f(MyMap[{composite, key}]);"); 12189 verifyFormat("class Class {\n" 12190 " T member = {arg1, arg2};\n" 12191 "};"); 12192 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12193 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12194 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12195 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12196 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12197 12198 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12199 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12200 verifyFormat("auto i = decltype(x){};"); 12201 verifyFormat("auto i = typeof(x){};"); 12202 verifyFormat("auto i = _Atomic(x){};"); 12203 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12204 verifyFormat("Node n{1, Node{1000}, //\n" 12205 " 2};"); 12206 verifyFormat("Aaaa aaaaaaa{\n" 12207 " {\n" 12208 " aaaa,\n" 12209 " },\n" 12210 "};"); 12211 verifyFormat("class C : public D {\n" 12212 " SomeClass SC{2};\n" 12213 "};"); 12214 verifyFormat("class C : public A {\n" 12215 " class D : public B {\n" 12216 " void f() { int i{2}; }\n" 12217 " };\n" 12218 "};"); 12219 verifyFormat("#define A {a, a},"); 12220 // Don't confuse braced list initializers with compound statements. 12221 verifyFormat( 12222 "class A {\n" 12223 " A() : a{} {}\n" 12224 " A(int b) : b(b) {}\n" 12225 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12226 " int a, b;\n" 12227 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12228 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12229 "{}\n" 12230 "};"); 12231 12232 // Avoid breaking between equal sign and opening brace 12233 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12234 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12235 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12236 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12237 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12238 " {\"ccccccccccccccccccccc\", 2}};", 12239 AvoidBreakingFirstArgument); 12240 12241 // Binpacking only if there is no trailing comma 12242 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12243 " cccccccccc, dddddddddd};", 12244 getLLVMStyleWithColumns(50)); 12245 verifyFormat("const Aaaaaa aaaaa = {\n" 12246 " aaaaaaaaaaa,\n" 12247 " bbbbbbbbbbb,\n" 12248 " ccccccccccc,\n" 12249 " ddddddddddd,\n" 12250 "};", 12251 getLLVMStyleWithColumns(50)); 12252 12253 // Cases where distinguising braced lists and blocks is hard. 12254 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12255 verifyFormat("void f() {\n" 12256 " return; // comment\n" 12257 "}\n" 12258 "SomeType t;"); 12259 verifyFormat("void f() {\n" 12260 " if (a) {\n" 12261 " f();\n" 12262 " }\n" 12263 "}\n" 12264 "SomeType t;"); 12265 12266 // In combination with BinPackArguments = false. 12267 FormatStyle NoBinPacking = getLLVMStyle(); 12268 NoBinPacking.BinPackArguments = false; 12269 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12270 " bbbbb,\n" 12271 " ccccc,\n" 12272 " ddddd,\n" 12273 " eeeee,\n" 12274 " ffffff,\n" 12275 " ggggg,\n" 12276 " hhhhhh,\n" 12277 " iiiiii,\n" 12278 " jjjjjj,\n" 12279 " kkkkkk};", 12280 NoBinPacking); 12281 verifyFormat("const Aaaaaa aaaaa = {\n" 12282 " aaaaa,\n" 12283 " bbbbb,\n" 12284 " ccccc,\n" 12285 " ddddd,\n" 12286 " eeeee,\n" 12287 " ffffff,\n" 12288 " ggggg,\n" 12289 " hhhhhh,\n" 12290 " iiiiii,\n" 12291 " jjjjjj,\n" 12292 " kkkkkk,\n" 12293 "};", 12294 NoBinPacking); 12295 verifyFormat( 12296 "const Aaaaaa aaaaa = {\n" 12297 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12298 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12299 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12300 "};", 12301 NoBinPacking); 12302 12303 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12304 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12305 " CDDDP83848_BMCR_REGISTER,\n" 12306 " CDDDP83848_BMSR_REGISTER,\n" 12307 " CDDDP83848_RBR_REGISTER};", 12308 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12309 " CDDDP83848_BMSR_REGISTER,\n" 12310 " CDDDP83848_RBR_REGISTER};", 12311 NoBinPacking)); 12312 12313 // FIXME: The alignment of these trailing comments might be bad. Then again, 12314 // this might be utterly useless in real code. 12315 verifyFormat("Constructor::Constructor()\n" 12316 " : some_value{ //\n" 12317 " aaaaaaa, //\n" 12318 " bbbbbbb} {}"); 12319 12320 // In braced lists, the first comment is always assumed to belong to the 12321 // first element. Thus, it can be moved to the next or previous line as 12322 // appropriate. 12323 EXPECT_EQ("function({// First element:\n" 12324 " 1,\n" 12325 " // Second element:\n" 12326 " 2});", 12327 format("function({\n" 12328 " // First element:\n" 12329 " 1,\n" 12330 " // Second element:\n" 12331 " 2});")); 12332 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12333 " // First element:\n" 12334 " 1,\n" 12335 " // Second element:\n" 12336 " 2};", 12337 format("std::vector<int> MyNumbers{// First element:\n" 12338 " 1,\n" 12339 " // Second element:\n" 12340 " 2};", 12341 getLLVMStyleWithColumns(30))); 12342 // A trailing comma should still lead to an enforced line break and no 12343 // binpacking. 12344 EXPECT_EQ("vector<int> SomeVector = {\n" 12345 " // aaa\n" 12346 " 1,\n" 12347 " 2,\n" 12348 "};", 12349 format("vector<int> SomeVector = { // aaa\n" 12350 " 1, 2, };")); 12351 12352 // C++11 brace initializer list l-braces should not be treated any differently 12353 // when breaking before lambda bodies is enabled 12354 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12355 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12356 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12357 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12358 verifyFormat( 12359 "std::runtime_error{\n" 12360 " \"Long string which will force a break onto the next line...\"};", 12361 BreakBeforeLambdaBody); 12362 12363 FormatStyle ExtraSpaces = getLLVMStyle(); 12364 ExtraSpaces.Cpp11BracedListStyle = false; 12365 ExtraSpaces.ColumnLimit = 75; 12366 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12367 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12368 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12369 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12370 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12371 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12372 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12373 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12374 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12375 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12376 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12377 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12378 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12379 verifyFormat("class Class {\n" 12380 " T member = { arg1, arg2 };\n" 12381 "};", 12382 ExtraSpaces); 12383 verifyFormat( 12384 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12385 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12386 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12387 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12388 ExtraSpaces); 12389 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12390 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12391 ExtraSpaces); 12392 verifyFormat( 12393 "someFunction(OtherParam,\n" 12394 " BracedList{ // comment 1 (Forcing interesting break)\n" 12395 " param1, param2,\n" 12396 " // comment 2\n" 12397 " param3, param4 });", 12398 ExtraSpaces); 12399 verifyFormat( 12400 "std::this_thread::sleep_for(\n" 12401 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12402 ExtraSpaces); 12403 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12404 " aaaaaaa,\n" 12405 " aaaaaaaaaa,\n" 12406 " aaaaa,\n" 12407 " aaaaaaaaaaaaaaa,\n" 12408 " aaa,\n" 12409 " aaaaaaaaaa,\n" 12410 " a,\n" 12411 " aaaaaaaaaaaaaaaaaaaaa,\n" 12412 " aaaaaaaaaaaa,\n" 12413 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12414 " aaaaaaa,\n" 12415 " a};"); 12416 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12417 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12418 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12419 12420 // Avoid breaking between initializer/equal sign and opening brace 12421 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12422 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12423 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12424 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12425 " { \"ccccccccccccccccccccc\", 2 }\n" 12426 "};", 12427 ExtraSpaces); 12428 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12429 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12430 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12431 " { \"ccccccccccccccccccccc\", 2 }\n" 12432 "};", 12433 ExtraSpaces); 12434 12435 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12436 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12437 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12438 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12439 12440 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12441 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12442 SpaceBetweenBraces.SpacesInParentheses = true; 12443 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12444 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12445 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12446 verifyFormat("vector< int > x{ // comment 1\n" 12447 " 1, 2, 3, 4 };", 12448 SpaceBetweenBraces); 12449 SpaceBetweenBraces.ColumnLimit = 20; 12450 EXPECT_EQ("vector< int > x{\n" 12451 " 1, 2, 3, 4 };", 12452 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12453 SpaceBetweenBraces.ColumnLimit = 24; 12454 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12455 " 3, 4 };", 12456 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12457 EXPECT_EQ("vector< int > x{\n" 12458 " 1,\n" 12459 " 2,\n" 12460 " 3,\n" 12461 " 4,\n" 12462 "};", 12463 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12464 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12465 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12466 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12467 } 12468 12469 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12470 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12471 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12472 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12473 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12474 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12475 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12476 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12477 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12478 " 1, 22, 333, 4444, 55555, //\n" 12479 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12480 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12481 verifyFormat( 12482 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12483 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12484 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12485 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12486 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12487 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12488 " 7777777};"); 12489 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12490 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12491 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12492 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12493 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12494 " // Separating comment.\n" 12495 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12496 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12497 " // Leading comment\n" 12498 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12499 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12500 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12501 " 1, 1, 1, 1};", 12502 getLLVMStyleWithColumns(39)); 12503 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12504 " 1, 1, 1, 1};", 12505 getLLVMStyleWithColumns(38)); 12506 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12507 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12508 getLLVMStyleWithColumns(43)); 12509 verifyFormat( 12510 "static unsigned SomeValues[10][3] = {\n" 12511 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12512 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12513 verifyFormat("static auto fields = new vector<string>{\n" 12514 " \"aaaaaaaaaaaaa\",\n" 12515 " \"aaaaaaaaaaaaa\",\n" 12516 " \"aaaaaaaaaaaa\",\n" 12517 " \"aaaaaaaaaaaaaa\",\n" 12518 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12519 " \"aaaaaaaaaaaa\",\n" 12520 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12521 "};"); 12522 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12523 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12524 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12525 " 3, cccccccccccccccccccccc};", 12526 getLLVMStyleWithColumns(60)); 12527 12528 // Trailing commas. 12529 verifyFormat("vector<int> x = {\n" 12530 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12531 "};", 12532 getLLVMStyleWithColumns(39)); 12533 verifyFormat("vector<int> x = {\n" 12534 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12535 "};", 12536 getLLVMStyleWithColumns(39)); 12537 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12538 " 1, 1, 1, 1,\n" 12539 " /**/ /**/};", 12540 getLLVMStyleWithColumns(39)); 12541 12542 // Trailing comment in the first line. 12543 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12544 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12545 " 111111111, 222222222, 3333333333, 444444444, //\n" 12546 " 11111111, 22222222, 333333333, 44444444};"); 12547 // Trailing comment in the last line. 12548 verifyFormat("int aaaaa[] = {\n" 12549 " 1, 2, 3, // comment\n" 12550 " 4, 5, 6 // comment\n" 12551 "};"); 12552 12553 // With nested lists, we should either format one item per line or all nested 12554 // lists one on line. 12555 // FIXME: For some nested lists, we can do better. 12556 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12557 " {aaaaaaaaaaaaaaaaaaa},\n" 12558 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12559 " {aaaaaaaaaaaaaaaaa}};", 12560 getLLVMStyleWithColumns(60)); 12561 verifyFormat( 12562 "SomeStruct my_struct_array = {\n" 12563 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12564 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12565 " {aaa, aaa},\n" 12566 " {aaa, aaa},\n" 12567 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12568 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12569 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12570 12571 // No column layout should be used here. 12572 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12573 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12574 12575 verifyNoCrash("a<,"); 12576 12577 // No braced initializer here. 12578 verifyFormat("void f() {\n" 12579 " struct Dummy {};\n" 12580 " f(v);\n" 12581 "}"); 12582 12583 // Long lists should be formatted in columns even if they are nested. 12584 verifyFormat( 12585 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12586 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12587 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12588 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12589 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12590 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12591 12592 // Allow "single-column" layout even if that violates the column limit. There 12593 // isn't going to be a better way. 12594 verifyFormat("std::vector<int> a = {\n" 12595 " aaaaaaaa,\n" 12596 " aaaaaaaa,\n" 12597 " aaaaaaaa,\n" 12598 " aaaaaaaa,\n" 12599 " aaaaaaaaaa,\n" 12600 " aaaaaaaa,\n" 12601 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12602 getLLVMStyleWithColumns(30)); 12603 verifyFormat("vector<int> aaaa = {\n" 12604 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12605 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12606 " aaaaaa.aaaaaaa,\n" 12607 " aaaaaa.aaaaaaa,\n" 12608 " aaaaaa.aaaaaaa,\n" 12609 " aaaaaa.aaaaaaa,\n" 12610 "};"); 12611 12612 // Don't create hanging lists. 12613 verifyFormat("someFunction(Param, {List1, List2,\n" 12614 " List3});", 12615 getLLVMStyleWithColumns(35)); 12616 verifyFormat("someFunction(Param, Param,\n" 12617 " {List1, List2,\n" 12618 " List3});", 12619 getLLVMStyleWithColumns(35)); 12620 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12621 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12622 } 12623 12624 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12625 FormatStyle DoNotMerge = getLLVMStyle(); 12626 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12627 12628 verifyFormat("void f() { return 42; }"); 12629 verifyFormat("void f() {\n" 12630 " return 42;\n" 12631 "}", 12632 DoNotMerge); 12633 verifyFormat("void f() {\n" 12634 " // Comment\n" 12635 "}"); 12636 verifyFormat("{\n" 12637 "#error {\n" 12638 " int a;\n" 12639 "}"); 12640 verifyFormat("{\n" 12641 " int a;\n" 12642 "#error {\n" 12643 "}"); 12644 verifyFormat("void f() {} // comment"); 12645 verifyFormat("void f() { int a; } // comment"); 12646 verifyFormat("void f() {\n" 12647 "} // comment", 12648 DoNotMerge); 12649 verifyFormat("void f() {\n" 12650 " int a;\n" 12651 "} // comment", 12652 DoNotMerge); 12653 verifyFormat("void f() {\n" 12654 "} // comment", 12655 getLLVMStyleWithColumns(15)); 12656 12657 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12658 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12659 12660 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12661 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12662 verifyFormat("class C {\n" 12663 " C()\n" 12664 " : iiiiiiii(nullptr),\n" 12665 " kkkkkkk(nullptr),\n" 12666 " mmmmmmm(nullptr),\n" 12667 " nnnnnnn(nullptr) {}\n" 12668 "};", 12669 getGoogleStyle()); 12670 12671 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12672 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12673 EXPECT_EQ("class C {\n" 12674 " A() : b(0) {}\n" 12675 "};", 12676 format("class C{A():b(0){}};", NoColumnLimit)); 12677 EXPECT_EQ("A()\n" 12678 " : b(0) {\n" 12679 "}", 12680 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12681 12682 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12683 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12684 FormatStyle::SFS_None; 12685 EXPECT_EQ("A()\n" 12686 " : b(0) {\n" 12687 "}", 12688 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12689 EXPECT_EQ("A()\n" 12690 " : b(0) {\n" 12691 "}", 12692 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12693 12694 verifyFormat("#define A \\\n" 12695 " void f() { \\\n" 12696 " int i; \\\n" 12697 " }", 12698 getLLVMStyleWithColumns(20)); 12699 verifyFormat("#define A \\\n" 12700 " void f() { int i; }", 12701 getLLVMStyleWithColumns(21)); 12702 verifyFormat("#define A \\\n" 12703 " void f() { \\\n" 12704 " int i; \\\n" 12705 " } \\\n" 12706 " int j;", 12707 getLLVMStyleWithColumns(22)); 12708 verifyFormat("#define A \\\n" 12709 " void f() { int i; } \\\n" 12710 " int j;", 12711 getLLVMStyleWithColumns(23)); 12712 } 12713 12714 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12715 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12716 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12717 verifyFormat("class C {\n" 12718 " int f() {}\n" 12719 "};", 12720 MergeEmptyOnly); 12721 verifyFormat("class C {\n" 12722 " int f() {\n" 12723 " return 42;\n" 12724 " }\n" 12725 "};", 12726 MergeEmptyOnly); 12727 verifyFormat("int f() {}", MergeEmptyOnly); 12728 verifyFormat("int f() {\n" 12729 " return 42;\n" 12730 "}", 12731 MergeEmptyOnly); 12732 12733 // Also verify behavior when BraceWrapping.AfterFunction = true 12734 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12735 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12736 verifyFormat("int f() {}", MergeEmptyOnly); 12737 verifyFormat("class C {\n" 12738 " int f() {}\n" 12739 "};", 12740 MergeEmptyOnly); 12741 } 12742 12743 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12744 FormatStyle MergeInlineOnly = getLLVMStyle(); 12745 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12746 verifyFormat("class C {\n" 12747 " int f() { return 42; }\n" 12748 "};", 12749 MergeInlineOnly); 12750 verifyFormat("int f() {\n" 12751 " return 42;\n" 12752 "}", 12753 MergeInlineOnly); 12754 12755 // SFS_Inline implies SFS_Empty 12756 verifyFormat("class C {\n" 12757 " int f() {}\n" 12758 "};", 12759 MergeInlineOnly); 12760 verifyFormat("int f() {}", MergeInlineOnly); 12761 // https://llvm.org/PR54147 12762 verifyFormat("auto lambda = []() {\n" 12763 " // comment\n" 12764 " f();\n" 12765 " g();\n" 12766 "};", 12767 MergeInlineOnly); 12768 12769 // Also verify behavior when BraceWrapping.AfterFunction = true 12770 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12771 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12772 verifyFormat("class C {\n" 12773 " int f() { return 42; }\n" 12774 "};", 12775 MergeInlineOnly); 12776 verifyFormat("int f()\n" 12777 "{\n" 12778 " return 42;\n" 12779 "}", 12780 MergeInlineOnly); 12781 12782 // SFS_Inline implies SFS_Empty 12783 verifyFormat("int f() {}", MergeInlineOnly); 12784 verifyFormat("class C {\n" 12785 " int f() {}\n" 12786 "};", 12787 MergeInlineOnly); 12788 12789 MergeInlineOnly.BraceWrapping.AfterClass = true; 12790 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12791 verifyFormat("class C\n" 12792 "{\n" 12793 " int f() { return 42; }\n" 12794 "};", 12795 MergeInlineOnly); 12796 verifyFormat("struct C\n" 12797 "{\n" 12798 " int f() { return 42; }\n" 12799 "};", 12800 MergeInlineOnly); 12801 verifyFormat("int f()\n" 12802 "{\n" 12803 " return 42;\n" 12804 "}", 12805 MergeInlineOnly); 12806 verifyFormat("int f() {}", MergeInlineOnly); 12807 verifyFormat("class C\n" 12808 "{\n" 12809 " int f() { return 42; }\n" 12810 "};", 12811 MergeInlineOnly); 12812 verifyFormat("struct C\n" 12813 "{\n" 12814 " int f() { return 42; }\n" 12815 "};", 12816 MergeInlineOnly); 12817 verifyFormat("struct C\n" 12818 "// comment\n" 12819 "/* comment */\n" 12820 "// comment\n" 12821 "{\n" 12822 " int f() { return 42; }\n" 12823 "};", 12824 MergeInlineOnly); 12825 verifyFormat("/* comment */ struct C\n" 12826 "{\n" 12827 " int f() { return 42; }\n" 12828 "};", 12829 MergeInlineOnly); 12830 } 12831 12832 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12833 FormatStyle MergeInlineOnly = getLLVMStyle(); 12834 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12835 FormatStyle::SFS_InlineOnly; 12836 verifyFormat("class C {\n" 12837 " int f() { return 42; }\n" 12838 "};", 12839 MergeInlineOnly); 12840 verifyFormat("int f() {\n" 12841 " return 42;\n" 12842 "}", 12843 MergeInlineOnly); 12844 12845 // SFS_InlineOnly does not imply SFS_Empty 12846 verifyFormat("class C {\n" 12847 " int f() {}\n" 12848 "};", 12849 MergeInlineOnly); 12850 verifyFormat("int f() {\n" 12851 "}", 12852 MergeInlineOnly); 12853 12854 // Also verify behavior when BraceWrapping.AfterFunction = true 12855 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12856 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12857 verifyFormat("class C {\n" 12858 " int f() { return 42; }\n" 12859 "};", 12860 MergeInlineOnly); 12861 verifyFormat("int f()\n" 12862 "{\n" 12863 " return 42;\n" 12864 "}", 12865 MergeInlineOnly); 12866 12867 // SFS_InlineOnly does not imply SFS_Empty 12868 verifyFormat("int f()\n" 12869 "{\n" 12870 "}", 12871 MergeInlineOnly); 12872 verifyFormat("class C {\n" 12873 " int f() {}\n" 12874 "};", 12875 MergeInlineOnly); 12876 } 12877 12878 TEST_F(FormatTest, SplitEmptyFunction) { 12879 FormatStyle Style = getLLVMStyleWithColumns(40); 12880 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12881 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12882 Style.BraceWrapping.AfterFunction = true; 12883 Style.BraceWrapping.SplitEmptyFunction = false; 12884 12885 verifyFormat("int f()\n" 12886 "{}", 12887 Style); 12888 verifyFormat("int f()\n" 12889 "{\n" 12890 " return 42;\n" 12891 "}", 12892 Style); 12893 verifyFormat("int f()\n" 12894 "{\n" 12895 " // some comment\n" 12896 "}", 12897 Style); 12898 12899 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12900 verifyFormat("int f() {}", Style); 12901 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12902 "{}", 12903 Style); 12904 verifyFormat("int f()\n" 12905 "{\n" 12906 " return 0;\n" 12907 "}", 12908 Style); 12909 12910 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12911 verifyFormat("class Foo {\n" 12912 " int f() {}\n" 12913 "};\n", 12914 Style); 12915 verifyFormat("class Foo {\n" 12916 " int f() { return 0; }\n" 12917 "};\n", 12918 Style); 12919 verifyFormat("class Foo {\n" 12920 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12921 " {}\n" 12922 "};\n", 12923 Style); 12924 verifyFormat("class Foo {\n" 12925 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12926 " {\n" 12927 " return 0;\n" 12928 " }\n" 12929 "};\n", 12930 Style); 12931 12932 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12933 verifyFormat("int f() {}", Style); 12934 verifyFormat("int f() { return 0; }", Style); 12935 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12936 "{}", 12937 Style); 12938 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12939 "{\n" 12940 " return 0;\n" 12941 "}", 12942 Style); 12943 } 12944 12945 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12946 FormatStyle Style = getLLVMStyleWithColumns(40); 12947 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12948 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12949 Style.BraceWrapping.AfterFunction = true; 12950 Style.BraceWrapping.SplitEmptyFunction = true; 12951 Style.BraceWrapping.SplitEmptyRecord = false; 12952 12953 verifyFormat("class C {};", Style); 12954 verifyFormat("struct C {};", Style); 12955 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12956 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12957 "{\n" 12958 "}", 12959 Style); 12960 verifyFormat("class C {\n" 12961 " C()\n" 12962 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12963 " bbbbbbbbbbbbbbbbbbb()\n" 12964 " {\n" 12965 " }\n" 12966 " void\n" 12967 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12968 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12969 " {\n" 12970 " }\n" 12971 "};", 12972 Style); 12973 } 12974 12975 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12976 FormatStyle Style = getLLVMStyle(); 12977 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12978 verifyFormat("#ifdef A\n" 12979 "int f() {}\n" 12980 "#else\n" 12981 "int g() {}\n" 12982 "#endif", 12983 Style); 12984 } 12985 12986 TEST_F(FormatTest, SplitEmptyClass) { 12987 FormatStyle Style = getLLVMStyle(); 12988 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12989 Style.BraceWrapping.AfterClass = true; 12990 Style.BraceWrapping.SplitEmptyRecord = false; 12991 12992 verifyFormat("class Foo\n" 12993 "{};", 12994 Style); 12995 verifyFormat("/* something */ class Foo\n" 12996 "{};", 12997 Style); 12998 verifyFormat("template <typename X> class Foo\n" 12999 "{};", 13000 Style); 13001 verifyFormat("class Foo\n" 13002 "{\n" 13003 " Foo();\n" 13004 "};", 13005 Style); 13006 verifyFormat("typedef class Foo\n" 13007 "{\n" 13008 "} Foo_t;", 13009 Style); 13010 13011 Style.BraceWrapping.SplitEmptyRecord = true; 13012 Style.BraceWrapping.AfterStruct = true; 13013 verifyFormat("class rep\n" 13014 "{\n" 13015 "};", 13016 Style); 13017 verifyFormat("struct rep\n" 13018 "{\n" 13019 "};", 13020 Style); 13021 verifyFormat("template <typename T> class rep\n" 13022 "{\n" 13023 "};", 13024 Style); 13025 verifyFormat("template <typename T> struct rep\n" 13026 "{\n" 13027 "};", 13028 Style); 13029 verifyFormat("class rep\n" 13030 "{\n" 13031 " int x;\n" 13032 "};", 13033 Style); 13034 verifyFormat("struct rep\n" 13035 "{\n" 13036 " int x;\n" 13037 "};", 13038 Style); 13039 verifyFormat("template <typename T> class rep\n" 13040 "{\n" 13041 " int x;\n" 13042 "};", 13043 Style); 13044 verifyFormat("template <typename T> struct rep\n" 13045 "{\n" 13046 " int x;\n" 13047 "};", 13048 Style); 13049 verifyFormat("template <typename T> class rep // Foo\n" 13050 "{\n" 13051 " int x;\n" 13052 "};", 13053 Style); 13054 verifyFormat("template <typename T> struct rep // Bar\n" 13055 "{\n" 13056 " int x;\n" 13057 "};", 13058 Style); 13059 13060 verifyFormat("template <typename T> class rep<T>\n" 13061 "{\n" 13062 " int x;\n" 13063 "};", 13064 Style); 13065 13066 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13067 "{\n" 13068 " int x;\n" 13069 "};", 13070 Style); 13071 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13072 "{\n" 13073 "};", 13074 Style); 13075 13076 verifyFormat("#include \"stdint.h\"\n" 13077 "namespace rep {}", 13078 Style); 13079 verifyFormat("#include <stdint.h>\n" 13080 "namespace rep {}", 13081 Style); 13082 verifyFormat("#include <stdint.h>\n" 13083 "namespace rep {}", 13084 "#include <stdint.h>\n" 13085 "namespace rep {\n" 13086 "\n" 13087 "\n" 13088 "}", 13089 Style); 13090 } 13091 13092 TEST_F(FormatTest, SplitEmptyStruct) { 13093 FormatStyle Style = getLLVMStyle(); 13094 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13095 Style.BraceWrapping.AfterStruct = true; 13096 Style.BraceWrapping.SplitEmptyRecord = false; 13097 13098 verifyFormat("struct Foo\n" 13099 "{};", 13100 Style); 13101 verifyFormat("/* something */ struct Foo\n" 13102 "{};", 13103 Style); 13104 verifyFormat("template <typename X> struct Foo\n" 13105 "{};", 13106 Style); 13107 verifyFormat("struct Foo\n" 13108 "{\n" 13109 " Foo();\n" 13110 "};", 13111 Style); 13112 verifyFormat("typedef struct Foo\n" 13113 "{\n" 13114 "} Foo_t;", 13115 Style); 13116 // typedef struct Bar {} Bar_t; 13117 } 13118 13119 TEST_F(FormatTest, SplitEmptyUnion) { 13120 FormatStyle Style = getLLVMStyle(); 13121 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13122 Style.BraceWrapping.AfterUnion = true; 13123 Style.BraceWrapping.SplitEmptyRecord = false; 13124 13125 verifyFormat("union Foo\n" 13126 "{};", 13127 Style); 13128 verifyFormat("/* something */ union Foo\n" 13129 "{};", 13130 Style); 13131 verifyFormat("union Foo\n" 13132 "{\n" 13133 " A,\n" 13134 "};", 13135 Style); 13136 verifyFormat("typedef union Foo\n" 13137 "{\n" 13138 "} Foo_t;", 13139 Style); 13140 } 13141 13142 TEST_F(FormatTest, SplitEmptyNamespace) { 13143 FormatStyle Style = getLLVMStyle(); 13144 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13145 Style.BraceWrapping.AfterNamespace = true; 13146 Style.BraceWrapping.SplitEmptyNamespace = false; 13147 13148 verifyFormat("namespace Foo\n" 13149 "{};", 13150 Style); 13151 verifyFormat("/* something */ namespace Foo\n" 13152 "{};", 13153 Style); 13154 verifyFormat("inline namespace Foo\n" 13155 "{};", 13156 Style); 13157 verifyFormat("/* something */ inline namespace Foo\n" 13158 "{};", 13159 Style); 13160 verifyFormat("export namespace Foo\n" 13161 "{};", 13162 Style); 13163 verifyFormat("namespace Foo\n" 13164 "{\n" 13165 "void Bar();\n" 13166 "};", 13167 Style); 13168 } 13169 13170 TEST_F(FormatTest, NeverMergeShortRecords) { 13171 FormatStyle Style = getLLVMStyle(); 13172 13173 verifyFormat("class Foo {\n" 13174 " Foo();\n" 13175 "};", 13176 Style); 13177 verifyFormat("typedef class Foo {\n" 13178 " Foo();\n" 13179 "} Foo_t;", 13180 Style); 13181 verifyFormat("struct Foo {\n" 13182 " Foo();\n" 13183 "};", 13184 Style); 13185 verifyFormat("typedef struct Foo {\n" 13186 " Foo();\n" 13187 "} Foo_t;", 13188 Style); 13189 verifyFormat("union Foo {\n" 13190 " A,\n" 13191 "};", 13192 Style); 13193 verifyFormat("typedef union Foo {\n" 13194 " A,\n" 13195 "} Foo_t;", 13196 Style); 13197 verifyFormat("namespace Foo {\n" 13198 "void Bar();\n" 13199 "};", 13200 Style); 13201 13202 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13203 Style.BraceWrapping.AfterClass = true; 13204 Style.BraceWrapping.AfterStruct = true; 13205 Style.BraceWrapping.AfterUnion = true; 13206 Style.BraceWrapping.AfterNamespace = true; 13207 verifyFormat("class Foo\n" 13208 "{\n" 13209 " Foo();\n" 13210 "};", 13211 Style); 13212 verifyFormat("typedef class Foo\n" 13213 "{\n" 13214 " Foo();\n" 13215 "} Foo_t;", 13216 Style); 13217 verifyFormat("struct Foo\n" 13218 "{\n" 13219 " Foo();\n" 13220 "};", 13221 Style); 13222 verifyFormat("typedef struct Foo\n" 13223 "{\n" 13224 " Foo();\n" 13225 "} Foo_t;", 13226 Style); 13227 verifyFormat("union Foo\n" 13228 "{\n" 13229 " A,\n" 13230 "};", 13231 Style); 13232 verifyFormat("typedef union Foo\n" 13233 "{\n" 13234 " A,\n" 13235 "} Foo_t;", 13236 Style); 13237 verifyFormat("namespace Foo\n" 13238 "{\n" 13239 "void Bar();\n" 13240 "};", 13241 Style); 13242 } 13243 13244 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13245 // Elaborate type variable declarations. 13246 verifyFormat("struct foo a = {bar};\nint n;"); 13247 verifyFormat("class foo a = {bar};\nint n;"); 13248 verifyFormat("union foo a = {bar};\nint n;"); 13249 13250 // Elaborate types inside function definitions. 13251 verifyFormat("struct foo f() {}\nint n;"); 13252 verifyFormat("class foo f() {}\nint n;"); 13253 verifyFormat("union foo f() {}\nint n;"); 13254 13255 // Templates. 13256 verifyFormat("template <class X> void f() {}\nint n;"); 13257 verifyFormat("template <struct X> void f() {}\nint n;"); 13258 verifyFormat("template <union X> void f() {}\nint n;"); 13259 13260 // Actual definitions... 13261 verifyFormat("struct {\n} n;"); 13262 verifyFormat( 13263 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13264 verifyFormat("union Z {\n int n;\n} x;"); 13265 verifyFormat("class MACRO Z {\n} n;"); 13266 verifyFormat("class MACRO(X) Z {\n} n;"); 13267 verifyFormat("class __attribute__(X) Z {\n} n;"); 13268 verifyFormat("class __declspec(X) Z {\n} n;"); 13269 verifyFormat("class A##B##C {\n} n;"); 13270 verifyFormat("class alignas(16) Z {\n} n;"); 13271 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13272 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13273 13274 // Redefinition from nested context: 13275 verifyFormat("class A::B::C {\n} n;"); 13276 13277 // Template definitions. 13278 verifyFormat( 13279 "template <typename F>\n" 13280 "Matcher(const Matcher<F> &Other,\n" 13281 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13282 " !is_same<F, T>::value>::type * = 0)\n" 13283 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13284 13285 // FIXME: This is still incorrectly handled at the formatter side. 13286 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13287 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13288 13289 // FIXME: 13290 // This now gets parsed incorrectly as class definition. 13291 // verifyFormat("class A<int> f() {\n}\nint n;"); 13292 13293 // Elaborate types where incorrectly parsing the structural element would 13294 // break the indent. 13295 verifyFormat("if (true)\n" 13296 " class X x;\n" 13297 "else\n" 13298 " f();\n"); 13299 13300 // This is simply incomplete. Formatting is not important, but must not crash. 13301 verifyFormat("class A:"); 13302 } 13303 13304 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13305 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13306 format("#error Leave all white!!!!! space* alone!\n")); 13307 EXPECT_EQ( 13308 "#warning Leave all white!!!!! space* alone!\n", 13309 format("#warning Leave all white!!!!! space* alone!\n")); 13310 EXPECT_EQ("#error 1", format(" # error 1")); 13311 EXPECT_EQ("#warning 1", format(" # warning 1")); 13312 } 13313 13314 TEST_F(FormatTest, FormatHashIfExpressions) { 13315 verifyFormat("#if AAAA && BBBB"); 13316 verifyFormat("#if (AAAA && BBBB)"); 13317 verifyFormat("#elif (AAAA && BBBB)"); 13318 // FIXME: Come up with a better indentation for #elif. 13319 verifyFormat( 13320 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13321 " defined(BBBBBBBB)\n" 13322 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13323 " defined(BBBBBBBB)\n" 13324 "#endif", 13325 getLLVMStyleWithColumns(65)); 13326 } 13327 13328 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13329 FormatStyle AllowsMergedIf = getGoogleStyle(); 13330 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13331 FormatStyle::SIS_WithoutElse; 13332 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13333 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13334 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13335 EXPECT_EQ("if (true) return 42;", 13336 format("if (true)\nreturn 42;", AllowsMergedIf)); 13337 FormatStyle ShortMergedIf = AllowsMergedIf; 13338 ShortMergedIf.ColumnLimit = 25; 13339 verifyFormat("#define A \\\n" 13340 " if (true) return 42;", 13341 ShortMergedIf); 13342 verifyFormat("#define A \\\n" 13343 " f(); \\\n" 13344 " if (true)\n" 13345 "#define B", 13346 ShortMergedIf); 13347 verifyFormat("#define A \\\n" 13348 " f(); \\\n" 13349 " if (true)\n" 13350 "g();", 13351 ShortMergedIf); 13352 verifyFormat("{\n" 13353 "#ifdef A\n" 13354 " // Comment\n" 13355 " if (true) continue;\n" 13356 "#endif\n" 13357 " // Comment\n" 13358 " if (true) continue;\n" 13359 "}", 13360 ShortMergedIf); 13361 ShortMergedIf.ColumnLimit = 33; 13362 verifyFormat("#define A \\\n" 13363 " if constexpr (true) return 42;", 13364 ShortMergedIf); 13365 verifyFormat("#define A \\\n" 13366 " if CONSTEXPR (true) return 42;", 13367 ShortMergedIf); 13368 ShortMergedIf.ColumnLimit = 29; 13369 verifyFormat("#define A \\\n" 13370 " if (aaaaaaaaaa) return 1; \\\n" 13371 " return 2;", 13372 ShortMergedIf); 13373 ShortMergedIf.ColumnLimit = 28; 13374 verifyFormat("#define A \\\n" 13375 " if (aaaaaaaaaa) \\\n" 13376 " return 1; \\\n" 13377 " return 2;", 13378 ShortMergedIf); 13379 verifyFormat("#define A \\\n" 13380 " if constexpr (aaaaaaa) \\\n" 13381 " return 1; \\\n" 13382 " return 2;", 13383 ShortMergedIf); 13384 verifyFormat("#define A \\\n" 13385 " if CONSTEXPR (aaaaaaa) \\\n" 13386 " return 1; \\\n" 13387 " return 2;", 13388 ShortMergedIf); 13389 } 13390 13391 TEST_F(FormatTest, FormatStarDependingOnContext) { 13392 verifyFormat("void f(int *a);"); 13393 verifyFormat("void f() { f(fint * b); }"); 13394 verifyFormat("class A {\n void f(int *a);\n};"); 13395 verifyFormat("class A {\n int *a;\n};"); 13396 verifyFormat("namespace a {\n" 13397 "namespace b {\n" 13398 "class A {\n" 13399 " void f() {}\n" 13400 " int *a;\n" 13401 "};\n" 13402 "} // namespace b\n" 13403 "} // namespace a"); 13404 } 13405 13406 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13407 verifyFormat("while"); 13408 verifyFormat("operator"); 13409 } 13410 13411 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13412 // This code would be painfully slow to format if we didn't skip it. 13413 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 13414 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13415 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13416 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13417 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13418 "A(1, 1)\n" 13419 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13420 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13421 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13422 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13423 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13424 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13425 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13426 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13427 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13428 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13429 // Deeply nested part is untouched, rest is formatted. 13430 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13431 format(std::string("int i;\n") + Code + "int j;\n", 13432 getLLVMStyle(), SC_ExpectIncomplete)); 13433 } 13434 13435 //===----------------------------------------------------------------------===// 13436 // Objective-C tests. 13437 //===----------------------------------------------------------------------===// 13438 13439 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13440 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13441 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13442 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13443 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13444 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13445 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13446 format("-(NSInteger)Method3:(id)anObject;")); 13447 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13448 format("-(NSInteger)Method4:(id)anObject;")); 13449 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13450 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13451 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13452 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13453 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13454 "forAllCells:(BOOL)flag;", 13455 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13456 "forAllCells:(BOOL)flag;")); 13457 13458 // Very long objectiveC method declaration. 13459 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13460 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13461 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13462 " inRange:(NSRange)range\n" 13463 " outRange:(NSRange)out_range\n" 13464 " outRange1:(NSRange)out_range1\n" 13465 " outRange2:(NSRange)out_range2\n" 13466 " outRange3:(NSRange)out_range3\n" 13467 " outRange4:(NSRange)out_range4\n" 13468 " outRange5:(NSRange)out_range5\n" 13469 " outRange6:(NSRange)out_range6\n" 13470 " outRange7:(NSRange)out_range7\n" 13471 " outRange8:(NSRange)out_range8\n" 13472 " outRange9:(NSRange)out_range9;"); 13473 13474 // When the function name has to be wrapped. 13475 FormatStyle Style = getLLVMStyle(); 13476 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13477 // and always indents instead. 13478 Style.IndentWrappedFunctionNames = false; 13479 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13480 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13481 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13482 "}", 13483 Style); 13484 Style.IndentWrappedFunctionNames = true; 13485 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13486 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13487 " anotherName:(NSString)dddddddddddddd {\n" 13488 "}", 13489 Style); 13490 13491 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13492 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13493 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13494 // protocol lists (but not for template classes): 13495 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13496 13497 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13498 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13499 13500 // If there's no return type (very rare in practice!), LLVM and Google style 13501 // agree. 13502 verifyFormat("- foo;"); 13503 verifyFormat("- foo:(int)f;"); 13504 verifyGoogleFormat("- foo:(int)foo;"); 13505 } 13506 13507 TEST_F(FormatTest, BreaksStringLiterals) { 13508 EXPECT_EQ("\"some text \"\n" 13509 "\"other\";", 13510 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13511 EXPECT_EQ("\"some text \"\n" 13512 "\"other\";", 13513 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13514 EXPECT_EQ( 13515 "#define A \\\n" 13516 " \"some \" \\\n" 13517 " \"text \" \\\n" 13518 " \"other\";", 13519 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13520 EXPECT_EQ( 13521 "#define A \\\n" 13522 " \"so \" \\\n" 13523 " \"text \" \\\n" 13524 " \"other\";", 13525 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13526 13527 EXPECT_EQ("\"some text\"", 13528 format("\"some text\"", getLLVMStyleWithColumns(1))); 13529 EXPECT_EQ("\"some text\"", 13530 format("\"some text\"", getLLVMStyleWithColumns(11))); 13531 EXPECT_EQ("\"some \"\n" 13532 "\"text\"", 13533 format("\"some text\"", getLLVMStyleWithColumns(10))); 13534 EXPECT_EQ("\"some \"\n" 13535 "\"text\"", 13536 format("\"some text\"", getLLVMStyleWithColumns(7))); 13537 EXPECT_EQ("\"some\"\n" 13538 "\" tex\"\n" 13539 "\"t\"", 13540 format("\"some text\"", getLLVMStyleWithColumns(6))); 13541 EXPECT_EQ("\"some\"\n" 13542 "\" tex\"\n" 13543 "\" and\"", 13544 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13545 EXPECT_EQ("\"some\"\n" 13546 "\"/tex\"\n" 13547 "\"/and\"", 13548 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13549 13550 EXPECT_EQ("variable =\n" 13551 " \"long string \"\n" 13552 " \"literal\";", 13553 format("variable = \"long string literal\";", 13554 getLLVMStyleWithColumns(20))); 13555 13556 EXPECT_EQ("variable = f(\n" 13557 " \"long string \"\n" 13558 " \"literal\",\n" 13559 " short,\n" 13560 " loooooooooooooooooooong);", 13561 format("variable = f(\"long string literal\", short, " 13562 "loooooooooooooooooooong);", 13563 getLLVMStyleWithColumns(20))); 13564 13565 EXPECT_EQ( 13566 "f(g(\"long string \"\n" 13567 " \"literal\"),\n" 13568 " b);", 13569 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13570 EXPECT_EQ("f(g(\"long string \"\n" 13571 " \"literal\",\n" 13572 " a),\n" 13573 " b);", 13574 format("f(g(\"long string literal\", a), b);", 13575 getLLVMStyleWithColumns(20))); 13576 EXPECT_EQ( 13577 "f(\"one two\".split(\n" 13578 " variable));", 13579 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13580 EXPECT_EQ("f(\"one two three four five six \"\n" 13581 " \"seven\".split(\n" 13582 " really_looooong_variable));", 13583 format("f(\"one two three four five six seven\"." 13584 "split(really_looooong_variable));", 13585 getLLVMStyleWithColumns(33))); 13586 13587 EXPECT_EQ("f(\"some \"\n" 13588 " \"text\",\n" 13589 " other);", 13590 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13591 13592 // Only break as a last resort. 13593 verifyFormat( 13594 "aaaaaaaaaaaaaaaaaaaa(\n" 13595 " aaaaaaaaaaaaaaaaaaaa,\n" 13596 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13597 13598 EXPECT_EQ("\"splitmea\"\n" 13599 "\"trandomp\"\n" 13600 "\"oint\"", 13601 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13602 13603 EXPECT_EQ("\"split/\"\n" 13604 "\"pathat/\"\n" 13605 "\"slashes\"", 13606 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13607 13608 EXPECT_EQ("\"split/\"\n" 13609 "\"pathat/\"\n" 13610 "\"slashes\"", 13611 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13612 EXPECT_EQ("\"split at \"\n" 13613 "\"spaces/at/\"\n" 13614 "\"slashes.at.any$\"\n" 13615 "\"non-alphanumeric%\"\n" 13616 "\"1111111111characte\"\n" 13617 "\"rs\"", 13618 format("\"split at " 13619 "spaces/at/" 13620 "slashes.at." 13621 "any$non-" 13622 "alphanumeric%" 13623 "1111111111characte" 13624 "rs\"", 13625 getLLVMStyleWithColumns(20))); 13626 13627 // Verify that splitting the strings understands 13628 // Style::AlwaysBreakBeforeMultilineStrings. 13629 EXPECT_EQ("aaaaaaaaaaaa(\n" 13630 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13631 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13632 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13633 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13634 "aaaaaaaaaaaaaaaaaaaaaa\");", 13635 getGoogleStyle())); 13636 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13637 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13638 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13639 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13640 "aaaaaaaaaaaaaaaaaaaaaa\";", 13641 getGoogleStyle())); 13642 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13643 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13644 format("llvm::outs() << " 13645 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13646 "aaaaaaaaaaaaaaaaaaa\";")); 13647 EXPECT_EQ("ffff(\n" 13648 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13649 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13650 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13651 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13652 getGoogleStyle())); 13653 13654 FormatStyle Style = getLLVMStyleWithColumns(12); 13655 Style.BreakStringLiterals = false; 13656 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13657 13658 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13659 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13660 EXPECT_EQ("#define A \\\n" 13661 " \"some \" \\\n" 13662 " \"text \" \\\n" 13663 " \"other\";", 13664 format("#define A \"some text other\";", AlignLeft)); 13665 } 13666 13667 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13668 EXPECT_EQ("C a = \"some more \"\n" 13669 " \"text\";", 13670 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13671 } 13672 13673 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13674 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13675 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13676 EXPECT_EQ("int i = a(b());", 13677 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13678 } 13679 13680 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13681 EXPECT_EQ( 13682 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13683 "(\n" 13684 " \"x\t\");", 13685 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13686 "aaaaaaa(" 13687 "\"x\t\");")); 13688 } 13689 13690 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13691 EXPECT_EQ( 13692 "u8\"utf8 string \"\n" 13693 "u8\"literal\";", 13694 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13695 EXPECT_EQ( 13696 "u\"utf16 string \"\n" 13697 "u\"literal\";", 13698 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13699 EXPECT_EQ( 13700 "U\"utf32 string \"\n" 13701 "U\"literal\";", 13702 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13703 EXPECT_EQ("L\"wide string \"\n" 13704 "L\"literal\";", 13705 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13706 EXPECT_EQ("@\"NSString \"\n" 13707 "@\"literal\";", 13708 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13709 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13710 13711 // This input makes clang-format try to split the incomplete unicode escape 13712 // sequence, which used to lead to a crasher. 13713 verifyNoCrash( 13714 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13715 getLLVMStyleWithColumns(60)); 13716 } 13717 13718 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13719 FormatStyle Style = getGoogleStyleWithColumns(15); 13720 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13721 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13722 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13723 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13724 EXPECT_EQ("u8R\"x(raw literal)x\";", 13725 format("u8R\"x(raw literal)x\";", Style)); 13726 } 13727 13728 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13729 FormatStyle Style = getLLVMStyleWithColumns(20); 13730 EXPECT_EQ( 13731 "_T(\"aaaaaaaaaaaaaa\")\n" 13732 "_T(\"aaaaaaaaaaaaaa\")\n" 13733 "_T(\"aaaaaaaaaaaa\")", 13734 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13735 EXPECT_EQ("f(x,\n" 13736 " _T(\"aaaaaaaaaaaa\")\n" 13737 " _T(\"aaa\"),\n" 13738 " z);", 13739 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13740 13741 // FIXME: Handle embedded spaces in one iteration. 13742 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13743 // "_T(\"aaaaaaaaaaaaa\")\n" 13744 // "_T(\"aaaaaaaaaaaaa\")\n" 13745 // "_T(\"a\")", 13746 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13747 // getLLVMStyleWithColumns(20))); 13748 EXPECT_EQ( 13749 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13750 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13751 EXPECT_EQ("f(\n" 13752 "#if !TEST\n" 13753 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13754 "#endif\n" 13755 ");", 13756 format("f(\n" 13757 "#if !TEST\n" 13758 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13759 "#endif\n" 13760 ");")); 13761 EXPECT_EQ("f(\n" 13762 "\n" 13763 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13764 format("f(\n" 13765 "\n" 13766 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13767 // Regression test for accessing tokens past the end of a vector in the 13768 // TokenLexer. 13769 verifyNoCrash(R"(_T( 13770 " 13771 ) 13772 )"); 13773 } 13774 13775 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13776 // In a function call with two operands, the second can be broken with no line 13777 // break before it. 13778 EXPECT_EQ( 13779 "func(a, \"long long \"\n" 13780 " \"long long\");", 13781 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13782 // In a function call with three operands, the second must be broken with a 13783 // line break before it. 13784 EXPECT_EQ("func(a,\n" 13785 " \"long long long \"\n" 13786 " \"long\",\n" 13787 " c);", 13788 format("func(a, \"long long long long\", c);", 13789 getLLVMStyleWithColumns(24))); 13790 // In a function call with three operands, the third must be broken with a 13791 // line break before it. 13792 EXPECT_EQ("func(a, b,\n" 13793 " \"long long long \"\n" 13794 " \"long\");", 13795 format("func(a, b, \"long long long long\");", 13796 getLLVMStyleWithColumns(24))); 13797 // In a function call with three operands, both the second and the third must 13798 // be broken with a line break before them. 13799 EXPECT_EQ("func(a,\n" 13800 " \"long long long \"\n" 13801 " \"long\",\n" 13802 " \"long long long \"\n" 13803 " \"long\");", 13804 format("func(a, \"long long long long\", \"long long long long\");", 13805 getLLVMStyleWithColumns(24))); 13806 // In a chain of << with two operands, the second can be broken with no line 13807 // break before it. 13808 EXPECT_EQ("a << \"line line \"\n" 13809 " \"line\";", 13810 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13811 // In a chain of << with three operands, the second can be broken with no line 13812 // break before it. 13813 EXPECT_EQ( 13814 "abcde << \"line \"\n" 13815 " \"line line\"\n" 13816 " << c;", 13817 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13818 // In a chain of << with three operands, the third must be broken with a line 13819 // break before it. 13820 EXPECT_EQ( 13821 "a << b\n" 13822 " << \"line line \"\n" 13823 " \"line\";", 13824 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13825 // In a chain of << with three operands, the second can be broken with no line 13826 // break before it and the third must be broken with a line break before it. 13827 EXPECT_EQ("abcd << \"line line \"\n" 13828 " \"line\"\n" 13829 " << \"line line \"\n" 13830 " \"line\";", 13831 format("abcd << \"line line line\" << \"line line line\";", 13832 getLLVMStyleWithColumns(20))); 13833 // In a chain of binary operators with two operands, the second can be broken 13834 // with no line break before it. 13835 EXPECT_EQ( 13836 "abcd + \"line line \"\n" 13837 " \"line line\";", 13838 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13839 // In a chain of binary operators with three operands, the second must be 13840 // broken with a line break before it. 13841 EXPECT_EQ("abcd +\n" 13842 " \"line line \"\n" 13843 " \"line line\" +\n" 13844 " e;", 13845 format("abcd + \"line line line line\" + e;", 13846 getLLVMStyleWithColumns(20))); 13847 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13848 // the first must be broken with a line break before it. 13849 FormatStyle Style = getLLVMStyleWithColumns(25); 13850 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13851 EXPECT_EQ("someFunction(\n" 13852 " \"long long long \"\n" 13853 " \"long\",\n" 13854 " a);", 13855 format("someFunction(\"long long long long\", a);", Style)); 13856 } 13857 13858 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13859 EXPECT_EQ( 13860 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13861 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13862 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13863 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13864 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13865 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13866 } 13867 13868 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13869 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13870 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13871 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13872 "multiline raw string literal xxxxxxxxxxxxxx\n" 13873 ")x\",\n" 13874 " a),\n" 13875 " b);", 13876 format("fffffffffff(g(R\"x(\n" 13877 "multiline raw string literal xxxxxxxxxxxxxx\n" 13878 ")x\", a), b);", 13879 getGoogleStyleWithColumns(20))); 13880 EXPECT_EQ("fffffffffff(\n" 13881 " g(R\"x(qqq\n" 13882 "multiline raw string literal xxxxxxxxxxxxxx\n" 13883 ")x\",\n" 13884 " a),\n" 13885 " b);", 13886 format("fffffffffff(g(R\"x(qqq\n" 13887 "multiline raw string literal xxxxxxxxxxxxxx\n" 13888 ")x\", a), b);", 13889 getGoogleStyleWithColumns(20))); 13890 13891 EXPECT_EQ("fffffffffff(R\"x(\n" 13892 "multiline raw string literal xxxxxxxxxxxxxx\n" 13893 ")x\");", 13894 format("fffffffffff(R\"x(\n" 13895 "multiline raw string literal xxxxxxxxxxxxxx\n" 13896 ")x\");", 13897 getGoogleStyleWithColumns(20))); 13898 EXPECT_EQ("fffffffffff(R\"x(\n" 13899 "multiline raw string literal xxxxxxxxxxxxxx\n" 13900 ")x\" + bbbbbb);", 13901 format("fffffffffff(R\"x(\n" 13902 "multiline raw string literal xxxxxxxxxxxxxx\n" 13903 ")x\" + bbbbbb);", 13904 getGoogleStyleWithColumns(20))); 13905 EXPECT_EQ("fffffffffff(\n" 13906 " R\"x(\n" 13907 "multiline raw string literal xxxxxxxxxxxxxx\n" 13908 ")x\" +\n" 13909 " bbbbbb);", 13910 format("fffffffffff(\n" 13911 " R\"x(\n" 13912 "multiline raw string literal xxxxxxxxxxxxxx\n" 13913 ")x\" + bbbbbb);", 13914 getGoogleStyleWithColumns(20))); 13915 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13916 format("fffffffffff(\n" 13917 " R\"(single line raw string)\" + bbbbbb);")); 13918 } 13919 13920 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13921 verifyFormat("string a = \"unterminated;"); 13922 EXPECT_EQ("function(\"unterminated,\n" 13923 " OtherParameter);", 13924 format("function( \"unterminated,\n" 13925 " OtherParameter);")); 13926 } 13927 13928 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13929 FormatStyle Style = getLLVMStyle(); 13930 Style.Standard = FormatStyle::LS_Cpp03; 13931 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13932 format("#define x(_a) printf(\"foo\"_a);", Style)); 13933 } 13934 13935 TEST_F(FormatTest, CppLexVersion) { 13936 FormatStyle Style = getLLVMStyle(); 13937 // Formatting of x * y differs if x is a type. 13938 verifyFormat("void foo() { MACRO(a * b); }", Style); 13939 verifyFormat("void foo() { MACRO(int *b); }", Style); 13940 13941 // LLVM style uses latest lexer. 13942 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13943 Style.Standard = FormatStyle::LS_Cpp17; 13944 // But in c++17, char8_t isn't a keyword. 13945 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13946 } 13947 13948 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13949 13950 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13951 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13952 " \"ddeeefff\");", 13953 format("someFunction(\"aaabbbcccdddeeefff\");", 13954 getLLVMStyleWithColumns(25))); 13955 EXPECT_EQ("someFunction1234567890(\n" 13956 " \"aaabbbcccdddeeefff\");", 13957 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13958 getLLVMStyleWithColumns(26))); 13959 EXPECT_EQ("someFunction1234567890(\n" 13960 " \"aaabbbcccdddeeeff\"\n" 13961 " \"f\");", 13962 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13963 getLLVMStyleWithColumns(25))); 13964 EXPECT_EQ("someFunction1234567890(\n" 13965 " \"aaabbbcccdddeeeff\"\n" 13966 " \"f\");", 13967 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13968 getLLVMStyleWithColumns(24))); 13969 EXPECT_EQ("someFunction(\n" 13970 " \"aaabbbcc ddde \"\n" 13971 " \"efff\");", 13972 format("someFunction(\"aaabbbcc ddde efff\");", 13973 getLLVMStyleWithColumns(25))); 13974 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13975 " \"ddeeefff\");", 13976 format("someFunction(\"aaabbbccc ddeeefff\");", 13977 getLLVMStyleWithColumns(25))); 13978 EXPECT_EQ("someFunction1234567890(\n" 13979 " \"aaabb \"\n" 13980 " \"cccdddeeefff\");", 13981 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13982 getLLVMStyleWithColumns(25))); 13983 EXPECT_EQ("#define A \\\n" 13984 " string s = \\\n" 13985 " \"123456789\" \\\n" 13986 " \"0\"; \\\n" 13987 " int i;", 13988 format("#define A string s = \"1234567890\"; int i;", 13989 getLLVMStyleWithColumns(20))); 13990 EXPECT_EQ("someFunction(\n" 13991 " \"aaabbbcc \"\n" 13992 " \"dddeeefff\");", 13993 format("someFunction(\"aaabbbcc dddeeefff\");", 13994 getLLVMStyleWithColumns(25))); 13995 } 13996 13997 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13998 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13999 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 14000 EXPECT_EQ("\"test\"\n" 14001 "\"\\n\"", 14002 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 14003 EXPECT_EQ("\"tes\\\\\"\n" 14004 "\"n\"", 14005 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 14006 EXPECT_EQ("\"\\\\\\\\\"\n" 14007 "\"\\n\"", 14008 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 14009 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 14010 EXPECT_EQ("\"\\uff01\"\n" 14011 "\"test\"", 14012 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14013 EXPECT_EQ("\"\\Uff01ff02\"", 14014 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14015 EXPECT_EQ("\"\\x000000000001\"\n" 14016 "\"next\"", 14017 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14018 EXPECT_EQ("\"\\x000000000001next\"", 14019 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14020 EXPECT_EQ("\"\\x000000000001\"", 14021 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14022 EXPECT_EQ("\"test\"\n" 14023 "\"\\000000\"\n" 14024 "\"000001\"", 14025 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14026 EXPECT_EQ("\"test\\000\"\n" 14027 "\"00000000\"\n" 14028 "\"1\"", 14029 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14030 } 14031 14032 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14033 verifyFormat("void f() {\n" 14034 " return g() {}\n" 14035 " void h() {}"); 14036 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14037 "g();\n" 14038 "}"); 14039 } 14040 14041 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14042 verifyFormat( 14043 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14044 } 14045 14046 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14047 verifyFormat("class X {\n" 14048 " void f() {\n" 14049 " }\n" 14050 "};", 14051 getLLVMStyleWithColumns(12)); 14052 } 14053 14054 TEST_F(FormatTest, ConfigurableIndentWidth) { 14055 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14056 EightIndent.IndentWidth = 8; 14057 EightIndent.ContinuationIndentWidth = 8; 14058 verifyFormat("void f() {\n" 14059 " someFunction();\n" 14060 " if (true) {\n" 14061 " f();\n" 14062 " }\n" 14063 "}", 14064 EightIndent); 14065 verifyFormat("class X {\n" 14066 " void f() {\n" 14067 " }\n" 14068 "};", 14069 EightIndent); 14070 verifyFormat("int x[] = {\n" 14071 " call(),\n" 14072 " call()};", 14073 EightIndent); 14074 } 14075 14076 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14077 verifyFormat("double\n" 14078 "f();", 14079 getLLVMStyleWithColumns(8)); 14080 } 14081 14082 TEST_F(FormatTest, ConfigurableUseOfTab) { 14083 FormatStyle Tab = getLLVMStyleWithColumns(42); 14084 Tab.IndentWidth = 8; 14085 Tab.UseTab = FormatStyle::UT_Always; 14086 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14087 14088 EXPECT_EQ("if (aaaaaaaa && // q\n" 14089 " bb)\t\t// w\n" 14090 "\t;", 14091 format("if (aaaaaaaa &&// q\n" 14092 "bb)// w\n" 14093 ";", 14094 Tab)); 14095 EXPECT_EQ("if (aaa && bbb) // w\n" 14096 "\t;", 14097 format("if(aaa&&bbb)// w\n" 14098 ";", 14099 Tab)); 14100 14101 verifyFormat("class X {\n" 14102 "\tvoid f() {\n" 14103 "\t\tsomeFunction(parameter1,\n" 14104 "\t\t\t parameter2);\n" 14105 "\t}\n" 14106 "};", 14107 Tab); 14108 verifyFormat("#define A \\\n" 14109 "\tvoid f() { \\\n" 14110 "\t\tsomeFunction( \\\n" 14111 "\t\t parameter1, \\\n" 14112 "\t\t parameter2); \\\n" 14113 "\t}", 14114 Tab); 14115 verifyFormat("int a;\t // x\n" 14116 "int bbbbbbbb; // x\n", 14117 Tab); 14118 14119 Tab.TabWidth = 4; 14120 Tab.IndentWidth = 8; 14121 verifyFormat("class TabWidth4Indent8 {\n" 14122 "\t\tvoid f() {\n" 14123 "\t\t\t\tsomeFunction(parameter1,\n" 14124 "\t\t\t\t\t\t\t parameter2);\n" 14125 "\t\t}\n" 14126 "};", 14127 Tab); 14128 14129 Tab.TabWidth = 4; 14130 Tab.IndentWidth = 4; 14131 verifyFormat("class TabWidth4Indent4 {\n" 14132 "\tvoid f() {\n" 14133 "\t\tsomeFunction(parameter1,\n" 14134 "\t\t\t\t\t parameter2);\n" 14135 "\t}\n" 14136 "};", 14137 Tab); 14138 14139 Tab.TabWidth = 8; 14140 Tab.IndentWidth = 4; 14141 verifyFormat("class TabWidth8Indent4 {\n" 14142 " void f() {\n" 14143 "\tsomeFunction(parameter1,\n" 14144 "\t\t parameter2);\n" 14145 " }\n" 14146 "};", 14147 Tab); 14148 14149 Tab.TabWidth = 8; 14150 Tab.IndentWidth = 8; 14151 EXPECT_EQ("/*\n" 14152 "\t a\t\tcomment\n" 14153 "\t in multiple lines\n" 14154 " */", 14155 format(" /*\t \t \n" 14156 " \t \t a\t\tcomment\t \t\n" 14157 " \t \t in multiple lines\t\n" 14158 " \t */", 14159 Tab)); 14160 14161 Tab.UseTab = FormatStyle::UT_ForIndentation; 14162 verifyFormat("{\n" 14163 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14164 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14165 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14166 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14167 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14168 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14169 "};", 14170 Tab); 14171 verifyFormat("enum AA {\n" 14172 "\ta1, // Force multiple lines\n" 14173 "\ta2,\n" 14174 "\ta3\n" 14175 "};", 14176 Tab); 14177 EXPECT_EQ("if (aaaaaaaa && // q\n" 14178 " bb) // w\n" 14179 "\t;", 14180 format("if (aaaaaaaa &&// q\n" 14181 "bb)// w\n" 14182 ";", 14183 Tab)); 14184 verifyFormat("class X {\n" 14185 "\tvoid f() {\n" 14186 "\t\tsomeFunction(parameter1,\n" 14187 "\t\t parameter2);\n" 14188 "\t}\n" 14189 "};", 14190 Tab); 14191 verifyFormat("{\n" 14192 "\tQ(\n" 14193 "\t {\n" 14194 "\t\t int a;\n" 14195 "\t\t someFunction(aaaaaaaa,\n" 14196 "\t\t bbbbbbb);\n" 14197 "\t },\n" 14198 "\t p);\n" 14199 "}", 14200 Tab); 14201 EXPECT_EQ("{\n" 14202 "\t/* aaaa\n" 14203 "\t bbbb */\n" 14204 "}", 14205 format("{\n" 14206 "/* aaaa\n" 14207 " bbbb */\n" 14208 "}", 14209 Tab)); 14210 EXPECT_EQ("{\n" 14211 "\t/*\n" 14212 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14213 "\t bbbbbbbbbbbbb\n" 14214 "\t*/\n" 14215 "}", 14216 format("{\n" 14217 "/*\n" 14218 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14219 "*/\n" 14220 "}", 14221 Tab)); 14222 EXPECT_EQ("{\n" 14223 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14224 "\t// bbbbbbbbbbbbb\n" 14225 "}", 14226 format("{\n" 14227 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14228 "}", 14229 Tab)); 14230 EXPECT_EQ("{\n" 14231 "\t/*\n" 14232 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14233 "\t bbbbbbbbbbbbb\n" 14234 "\t*/\n" 14235 "}", 14236 format("{\n" 14237 "\t/*\n" 14238 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14239 "\t*/\n" 14240 "}", 14241 Tab)); 14242 EXPECT_EQ("{\n" 14243 "\t/*\n" 14244 "\n" 14245 "\t*/\n" 14246 "}", 14247 format("{\n" 14248 "\t/*\n" 14249 "\n" 14250 "\t*/\n" 14251 "}", 14252 Tab)); 14253 EXPECT_EQ("{\n" 14254 "\t/*\n" 14255 " asdf\n" 14256 "\t*/\n" 14257 "}", 14258 format("{\n" 14259 "\t/*\n" 14260 " asdf\n" 14261 "\t*/\n" 14262 "}", 14263 Tab)); 14264 14265 verifyFormat("void f() {\n" 14266 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14267 "\t : bbbbbbbbbbbbbbbbbb\n" 14268 "}", 14269 Tab); 14270 FormatStyle TabNoBreak = Tab; 14271 TabNoBreak.BreakBeforeTernaryOperators = false; 14272 verifyFormat("void f() {\n" 14273 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14274 "\t bbbbbbbbbbbbbbbbbb\n" 14275 "}", 14276 TabNoBreak); 14277 verifyFormat("void f() {\n" 14278 "\treturn true ?\n" 14279 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14280 "\t bbbbbbbbbbbbbbbbbbbb\n" 14281 "}", 14282 TabNoBreak); 14283 14284 Tab.UseTab = FormatStyle::UT_Never; 14285 EXPECT_EQ("/*\n" 14286 " a\t\tcomment\n" 14287 " in multiple lines\n" 14288 " */", 14289 format(" /*\t \t \n" 14290 " \t \t a\t\tcomment\t \t\n" 14291 " \t \t in multiple lines\t\n" 14292 " \t */", 14293 Tab)); 14294 EXPECT_EQ("/* some\n" 14295 " comment */", 14296 format(" \t \t /* some\n" 14297 " \t \t comment */", 14298 Tab)); 14299 EXPECT_EQ("int a; /* some\n" 14300 " comment */", 14301 format(" \t \t int a; /* some\n" 14302 " \t \t comment */", 14303 Tab)); 14304 14305 EXPECT_EQ("int a; /* some\n" 14306 "comment */", 14307 format(" \t \t int\ta; /* some\n" 14308 " \t \t comment */", 14309 Tab)); 14310 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14311 " comment */", 14312 format(" \t \t f(\"\t\t\"); /* some\n" 14313 " \t \t comment */", 14314 Tab)); 14315 EXPECT_EQ("{\n" 14316 " /*\n" 14317 " * Comment\n" 14318 " */\n" 14319 " int i;\n" 14320 "}", 14321 format("{\n" 14322 "\t/*\n" 14323 "\t * Comment\n" 14324 "\t */\n" 14325 "\t int i;\n" 14326 "}", 14327 Tab)); 14328 14329 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14330 Tab.TabWidth = 8; 14331 Tab.IndentWidth = 8; 14332 EXPECT_EQ("if (aaaaaaaa && // q\n" 14333 " bb) // w\n" 14334 "\t;", 14335 format("if (aaaaaaaa &&// q\n" 14336 "bb)// w\n" 14337 ";", 14338 Tab)); 14339 EXPECT_EQ("if (aaa && bbb) // w\n" 14340 "\t;", 14341 format("if(aaa&&bbb)// w\n" 14342 ";", 14343 Tab)); 14344 verifyFormat("class X {\n" 14345 "\tvoid f() {\n" 14346 "\t\tsomeFunction(parameter1,\n" 14347 "\t\t\t parameter2);\n" 14348 "\t}\n" 14349 "};", 14350 Tab); 14351 verifyFormat("#define A \\\n" 14352 "\tvoid f() { \\\n" 14353 "\t\tsomeFunction( \\\n" 14354 "\t\t parameter1, \\\n" 14355 "\t\t parameter2); \\\n" 14356 "\t}", 14357 Tab); 14358 Tab.TabWidth = 4; 14359 Tab.IndentWidth = 8; 14360 verifyFormat("class TabWidth4Indent8 {\n" 14361 "\t\tvoid f() {\n" 14362 "\t\t\t\tsomeFunction(parameter1,\n" 14363 "\t\t\t\t\t\t\t parameter2);\n" 14364 "\t\t}\n" 14365 "};", 14366 Tab); 14367 Tab.TabWidth = 4; 14368 Tab.IndentWidth = 4; 14369 verifyFormat("class TabWidth4Indent4 {\n" 14370 "\tvoid f() {\n" 14371 "\t\tsomeFunction(parameter1,\n" 14372 "\t\t\t\t\t parameter2);\n" 14373 "\t}\n" 14374 "};", 14375 Tab); 14376 Tab.TabWidth = 8; 14377 Tab.IndentWidth = 4; 14378 verifyFormat("class TabWidth8Indent4 {\n" 14379 " void f() {\n" 14380 "\tsomeFunction(parameter1,\n" 14381 "\t\t parameter2);\n" 14382 " }\n" 14383 "};", 14384 Tab); 14385 Tab.TabWidth = 8; 14386 Tab.IndentWidth = 8; 14387 EXPECT_EQ("/*\n" 14388 "\t a\t\tcomment\n" 14389 "\t in multiple lines\n" 14390 " */", 14391 format(" /*\t \t \n" 14392 " \t \t a\t\tcomment\t \t\n" 14393 " \t \t in multiple lines\t\n" 14394 " \t */", 14395 Tab)); 14396 verifyFormat("{\n" 14397 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14398 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14399 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14400 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14401 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14402 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14403 "};", 14404 Tab); 14405 verifyFormat("enum AA {\n" 14406 "\ta1, // Force multiple lines\n" 14407 "\ta2,\n" 14408 "\ta3\n" 14409 "};", 14410 Tab); 14411 EXPECT_EQ("if (aaaaaaaa && // q\n" 14412 " bb) // w\n" 14413 "\t;", 14414 format("if (aaaaaaaa &&// q\n" 14415 "bb)// w\n" 14416 ";", 14417 Tab)); 14418 verifyFormat("class X {\n" 14419 "\tvoid f() {\n" 14420 "\t\tsomeFunction(parameter1,\n" 14421 "\t\t\t parameter2);\n" 14422 "\t}\n" 14423 "};", 14424 Tab); 14425 verifyFormat("{\n" 14426 "\tQ(\n" 14427 "\t {\n" 14428 "\t\t int a;\n" 14429 "\t\t someFunction(aaaaaaaa,\n" 14430 "\t\t\t\t bbbbbbb);\n" 14431 "\t },\n" 14432 "\t p);\n" 14433 "}", 14434 Tab); 14435 EXPECT_EQ("{\n" 14436 "\t/* aaaa\n" 14437 "\t bbbb */\n" 14438 "}", 14439 format("{\n" 14440 "/* aaaa\n" 14441 " bbbb */\n" 14442 "}", 14443 Tab)); 14444 EXPECT_EQ("{\n" 14445 "\t/*\n" 14446 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14447 "\t bbbbbbbbbbbbb\n" 14448 "\t*/\n" 14449 "}", 14450 format("{\n" 14451 "/*\n" 14452 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14453 "*/\n" 14454 "}", 14455 Tab)); 14456 EXPECT_EQ("{\n" 14457 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14458 "\t// bbbbbbbbbbbbb\n" 14459 "}", 14460 format("{\n" 14461 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14462 "}", 14463 Tab)); 14464 EXPECT_EQ("{\n" 14465 "\t/*\n" 14466 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14467 "\t bbbbbbbbbbbbb\n" 14468 "\t*/\n" 14469 "}", 14470 format("{\n" 14471 "\t/*\n" 14472 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14473 "\t*/\n" 14474 "}", 14475 Tab)); 14476 EXPECT_EQ("{\n" 14477 "\t/*\n" 14478 "\n" 14479 "\t*/\n" 14480 "}", 14481 format("{\n" 14482 "\t/*\n" 14483 "\n" 14484 "\t*/\n" 14485 "}", 14486 Tab)); 14487 EXPECT_EQ("{\n" 14488 "\t/*\n" 14489 " asdf\n" 14490 "\t*/\n" 14491 "}", 14492 format("{\n" 14493 "\t/*\n" 14494 " asdf\n" 14495 "\t*/\n" 14496 "}", 14497 Tab)); 14498 EXPECT_EQ("/* some\n" 14499 " comment */", 14500 format(" \t \t /* some\n" 14501 " \t \t comment */", 14502 Tab)); 14503 EXPECT_EQ("int a; /* some\n" 14504 " comment */", 14505 format(" \t \t int a; /* some\n" 14506 " \t \t comment */", 14507 Tab)); 14508 EXPECT_EQ("int a; /* some\n" 14509 "comment */", 14510 format(" \t \t int\ta; /* some\n" 14511 " \t \t comment */", 14512 Tab)); 14513 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14514 " comment */", 14515 format(" \t \t f(\"\t\t\"); /* some\n" 14516 " \t \t comment */", 14517 Tab)); 14518 EXPECT_EQ("{\n" 14519 "\t/*\n" 14520 "\t * Comment\n" 14521 "\t */\n" 14522 "\tint i;\n" 14523 "}", 14524 format("{\n" 14525 "\t/*\n" 14526 "\t * Comment\n" 14527 "\t */\n" 14528 "\t int i;\n" 14529 "}", 14530 Tab)); 14531 Tab.TabWidth = 2; 14532 Tab.IndentWidth = 2; 14533 EXPECT_EQ("{\n" 14534 "\t/* aaaa\n" 14535 "\t\t bbbb */\n" 14536 "}", 14537 format("{\n" 14538 "/* aaaa\n" 14539 "\t bbbb */\n" 14540 "}", 14541 Tab)); 14542 EXPECT_EQ("{\n" 14543 "\t/*\n" 14544 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14545 "\t\tbbbbbbbbbbbbb\n" 14546 "\t*/\n" 14547 "}", 14548 format("{\n" 14549 "/*\n" 14550 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14551 "*/\n" 14552 "}", 14553 Tab)); 14554 Tab.AlignConsecutiveAssignments.Enabled = true; 14555 Tab.AlignConsecutiveDeclarations.Enabled = true; 14556 Tab.TabWidth = 4; 14557 Tab.IndentWidth = 4; 14558 verifyFormat("class Assign {\n" 14559 "\tvoid f() {\n" 14560 "\t\tint x = 123;\n" 14561 "\t\tint random = 4;\n" 14562 "\t\tstd::string alphabet =\n" 14563 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14564 "\t}\n" 14565 "};", 14566 Tab); 14567 14568 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14569 Tab.TabWidth = 8; 14570 Tab.IndentWidth = 8; 14571 EXPECT_EQ("if (aaaaaaaa && // q\n" 14572 " bb) // w\n" 14573 "\t;", 14574 format("if (aaaaaaaa &&// q\n" 14575 "bb)// w\n" 14576 ";", 14577 Tab)); 14578 EXPECT_EQ("if (aaa && bbb) // w\n" 14579 "\t;", 14580 format("if(aaa&&bbb)// w\n" 14581 ";", 14582 Tab)); 14583 verifyFormat("class X {\n" 14584 "\tvoid f() {\n" 14585 "\t\tsomeFunction(parameter1,\n" 14586 "\t\t parameter2);\n" 14587 "\t}\n" 14588 "};", 14589 Tab); 14590 verifyFormat("#define A \\\n" 14591 "\tvoid f() { \\\n" 14592 "\t\tsomeFunction( \\\n" 14593 "\t\t parameter1, \\\n" 14594 "\t\t parameter2); \\\n" 14595 "\t}", 14596 Tab); 14597 Tab.TabWidth = 4; 14598 Tab.IndentWidth = 8; 14599 verifyFormat("class TabWidth4Indent8 {\n" 14600 "\t\tvoid f() {\n" 14601 "\t\t\t\tsomeFunction(parameter1,\n" 14602 "\t\t\t\t parameter2);\n" 14603 "\t\t}\n" 14604 "};", 14605 Tab); 14606 Tab.TabWidth = 4; 14607 Tab.IndentWidth = 4; 14608 verifyFormat("class TabWidth4Indent4 {\n" 14609 "\tvoid f() {\n" 14610 "\t\tsomeFunction(parameter1,\n" 14611 "\t\t parameter2);\n" 14612 "\t}\n" 14613 "};", 14614 Tab); 14615 Tab.TabWidth = 8; 14616 Tab.IndentWidth = 4; 14617 verifyFormat("class TabWidth8Indent4 {\n" 14618 " void f() {\n" 14619 "\tsomeFunction(parameter1,\n" 14620 "\t parameter2);\n" 14621 " }\n" 14622 "};", 14623 Tab); 14624 Tab.TabWidth = 8; 14625 Tab.IndentWidth = 8; 14626 EXPECT_EQ("/*\n" 14627 " a\t\tcomment\n" 14628 " in multiple lines\n" 14629 " */", 14630 format(" /*\t \t \n" 14631 " \t \t a\t\tcomment\t \t\n" 14632 " \t \t in multiple lines\t\n" 14633 " \t */", 14634 Tab)); 14635 verifyFormat("{\n" 14636 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14637 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14638 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14639 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14640 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14641 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14642 "};", 14643 Tab); 14644 verifyFormat("enum AA {\n" 14645 "\ta1, // Force multiple lines\n" 14646 "\ta2,\n" 14647 "\ta3\n" 14648 "};", 14649 Tab); 14650 EXPECT_EQ("if (aaaaaaaa && // q\n" 14651 " bb) // w\n" 14652 "\t;", 14653 format("if (aaaaaaaa &&// q\n" 14654 "bb)// w\n" 14655 ";", 14656 Tab)); 14657 verifyFormat("class X {\n" 14658 "\tvoid f() {\n" 14659 "\t\tsomeFunction(parameter1,\n" 14660 "\t\t parameter2);\n" 14661 "\t}\n" 14662 "};", 14663 Tab); 14664 verifyFormat("{\n" 14665 "\tQ(\n" 14666 "\t {\n" 14667 "\t\t int a;\n" 14668 "\t\t someFunction(aaaaaaaa,\n" 14669 "\t\t bbbbbbb);\n" 14670 "\t },\n" 14671 "\t p);\n" 14672 "}", 14673 Tab); 14674 EXPECT_EQ("{\n" 14675 "\t/* aaaa\n" 14676 "\t bbbb */\n" 14677 "}", 14678 format("{\n" 14679 "/* aaaa\n" 14680 " bbbb */\n" 14681 "}", 14682 Tab)); 14683 EXPECT_EQ("{\n" 14684 "\t/*\n" 14685 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14686 "\t bbbbbbbbbbbbb\n" 14687 "\t*/\n" 14688 "}", 14689 format("{\n" 14690 "/*\n" 14691 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14692 "*/\n" 14693 "}", 14694 Tab)); 14695 EXPECT_EQ("{\n" 14696 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14697 "\t// bbbbbbbbbbbbb\n" 14698 "}", 14699 format("{\n" 14700 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14701 "}", 14702 Tab)); 14703 EXPECT_EQ("{\n" 14704 "\t/*\n" 14705 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14706 "\t bbbbbbbbbbbbb\n" 14707 "\t*/\n" 14708 "}", 14709 format("{\n" 14710 "\t/*\n" 14711 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14712 "\t*/\n" 14713 "}", 14714 Tab)); 14715 EXPECT_EQ("{\n" 14716 "\t/*\n" 14717 "\n" 14718 "\t*/\n" 14719 "}", 14720 format("{\n" 14721 "\t/*\n" 14722 "\n" 14723 "\t*/\n" 14724 "}", 14725 Tab)); 14726 EXPECT_EQ("{\n" 14727 "\t/*\n" 14728 " asdf\n" 14729 "\t*/\n" 14730 "}", 14731 format("{\n" 14732 "\t/*\n" 14733 " asdf\n" 14734 "\t*/\n" 14735 "}", 14736 Tab)); 14737 EXPECT_EQ("/* some\n" 14738 " comment */", 14739 format(" \t \t /* some\n" 14740 " \t \t comment */", 14741 Tab)); 14742 EXPECT_EQ("int a; /* some\n" 14743 " comment */", 14744 format(" \t \t int a; /* some\n" 14745 " \t \t comment */", 14746 Tab)); 14747 EXPECT_EQ("int a; /* some\n" 14748 "comment */", 14749 format(" \t \t int\ta; /* some\n" 14750 " \t \t comment */", 14751 Tab)); 14752 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14753 " comment */", 14754 format(" \t \t f(\"\t\t\"); /* some\n" 14755 " \t \t comment */", 14756 Tab)); 14757 EXPECT_EQ("{\n" 14758 "\t/*\n" 14759 "\t * Comment\n" 14760 "\t */\n" 14761 "\tint i;\n" 14762 "}", 14763 format("{\n" 14764 "\t/*\n" 14765 "\t * Comment\n" 14766 "\t */\n" 14767 "\t int i;\n" 14768 "}", 14769 Tab)); 14770 Tab.TabWidth = 2; 14771 Tab.IndentWidth = 2; 14772 EXPECT_EQ("{\n" 14773 "\t/* aaaa\n" 14774 "\t bbbb */\n" 14775 "}", 14776 format("{\n" 14777 "/* aaaa\n" 14778 " bbbb */\n" 14779 "}", 14780 Tab)); 14781 EXPECT_EQ("{\n" 14782 "\t/*\n" 14783 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14784 "\t bbbbbbbbbbbbb\n" 14785 "\t*/\n" 14786 "}", 14787 format("{\n" 14788 "/*\n" 14789 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14790 "*/\n" 14791 "}", 14792 Tab)); 14793 Tab.AlignConsecutiveAssignments.Enabled = true; 14794 Tab.AlignConsecutiveDeclarations.Enabled = true; 14795 Tab.TabWidth = 4; 14796 Tab.IndentWidth = 4; 14797 verifyFormat("class Assign {\n" 14798 "\tvoid f() {\n" 14799 "\t\tint x = 123;\n" 14800 "\t\tint random = 4;\n" 14801 "\t\tstd::string alphabet =\n" 14802 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14803 "\t}\n" 14804 "};", 14805 Tab); 14806 Tab.AlignOperands = FormatStyle::OAS_Align; 14807 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14808 " cccccccccccccccccccc;", 14809 Tab); 14810 // no alignment 14811 verifyFormat("int aaaaaaaaaa =\n" 14812 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14813 Tab); 14814 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14815 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14816 " : 333333333333333;", 14817 Tab); 14818 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14819 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14820 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14821 " + cccccccccccccccccccc;", 14822 Tab); 14823 } 14824 14825 TEST_F(FormatTest, ZeroTabWidth) { 14826 FormatStyle Tab = getLLVMStyleWithColumns(42); 14827 Tab.IndentWidth = 8; 14828 Tab.UseTab = FormatStyle::UT_Never; 14829 Tab.TabWidth = 0; 14830 EXPECT_EQ("void a(){\n" 14831 " // line starts with '\t'\n" 14832 "};", 14833 format("void a(){\n" 14834 "\t// line starts with '\t'\n" 14835 "};", 14836 Tab)); 14837 14838 EXPECT_EQ("void a(){\n" 14839 " // line starts with '\t'\n" 14840 "};", 14841 format("void a(){\n" 14842 "\t\t// line starts with '\t'\n" 14843 "};", 14844 Tab)); 14845 14846 Tab.UseTab = FormatStyle::UT_ForIndentation; 14847 EXPECT_EQ("void a(){\n" 14848 " // line starts with '\t'\n" 14849 "};", 14850 format("void a(){\n" 14851 "\t// line starts with '\t'\n" 14852 "};", 14853 Tab)); 14854 14855 EXPECT_EQ("void a(){\n" 14856 " // line starts with '\t'\n" 14857 "};", 14858 format("void a(){\n" 14859 "\t\t// line starts with '\t'\n" 14860 "};", 14861 Tab)); 14862 14863 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14864 EXPECT_EQ("void a(){\n" 14865 " // line starts with '\t'\n" 14866 "};", 14867 format("void a(){\n" 14868 "\t// line starts with '\t'\n" 14869 "};", 14870 Tab)); 14871 14872 EXPECT_EQ("void a(){\n" 14873 " // line starts with '\t'\n" 14874 "};", 14875 format("void a(){\n" 14876 "\t\t// line starts with '\t'\n" 14877 "};", 14878 Tab)); 14879 14880 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14881 EXPECT_EQ("void a(){\n" 14882 " // line starts with '\t'\n" 14883 "};", 14884 format("void a(){\n" 14885 "\t// line starts with '\t'\n" 14886 "};", 14887 Tab)); 14888 14889 EXPECT_EQ("void a(){\n" 14890 " // line starts with '\t'\n" 14891 "};", 14892 format("void a(){\n" 14893 "\t\t// line starts with '\t'\n" 14894 "};", 14895 Tab)); 14896 14897 Tab.UseTab = FormatStyle::UT_Always; 14898 EXPECT_EQ("void a(){\n" 14899 "// line starts with '\t'\n" 14900 "};", 14901 format("void a(){\n" 14902 "\t// line starts with '\t'\n" 14903 "};", 14904 Tab)); 14905 14906 EXPECT_EQ("void a(){\n" 14907 "// line starts with '\t'\n" 14908 "};", 14909 format("void a(){\n" 14910 "\t\t// line starts with '\t'\n" 14911 "};", 14912 Tab)); 14913 } 14914 14915 TEST_F(FormatTest, CalculatesOriginalColumn) { 14916 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14917 "q\"; /* some\n" 14918 " comment */", 14919 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14920 "q\"; /* some\n" 14921 " comment */", 14922 getLLVMStyle())); 14923 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14924 "/* some\n" 14925 " comment */", 14926 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14927 " /* some\n" 14928 " comment */", 14929 getLLVMStyle())); 14930 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14931 "qqq\n" 14932 "/* some\n" 14933 " comment */", 14934 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14935 "qqq\n" 14936 " /* some\n" 14937 " comment */", 14938 getLLVMStyle())); 14939 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14940 "wwww; /* some\n" 14941 " comment */", 14942 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14943 "wwww; /* some\n" 14944 " comment */", 14945 getLLVMStyle())); 14946 } 14947 14948 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14949 FormatStyle NoSpace = getLLVMStyle(); 14950 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14951 14952 verifyFormat("while(true)\n" 14953 " continue;", 14954 NoSpace); 14955 verifyFormat("for(;;)\n" 14956 " continue;", 14957 NoSpace); 14958 verifyFormat("if(true)\n" 14959 " f();\n" 14960 "else if(true)\n" 14961 " f();", 14962 NoSpace); 14963 verifyFormat("do {\n" 14964 " do_something();\n" 14965 "} while(something());", 14966 NoSpace); 14967 verifyFormat("switch(x) {\n" 14968 "default:\n" 14969 " break;\n" 14970 "}", 14971 NoSpace); 14972 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14973 verifyFormat("size_t x = sizeof(x);", NoSpace); 14974 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14975 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14976 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14977 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14978 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14979 verifyFormat("alignas(128) char a[128];", NoSpace); 14980 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14981 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14982 verifyFormat("int f() throw(Deprecated);", NoSpace); 14983 verifyFormat("typedef void (*cb)(int);", NoSpace); 14984 verifyFormat("T A::operator()();", NoSpace); 14985 verifyFormat("X A::operator++(T);", NoSpace); 14986 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14987 14988 FormatStyle Space = getLLVMStyle(); 14989 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14990 14991 verifyFormat("int f ();", Space); 14992 verifyFormat("void f (int a, T b) {\n" 14993 " while (true)\n" 14994 " continue;\n" 14995 "}", 14996 Space); 14997 verifyFormat("if (true)\n" 14998 " f ();\n" 14999 "else if (true)\n" 15000 " f ();", 15001 Space); 15002 verifyFormat("do {\n" 15003 " do_something ();\n" 15004 "} while (something ());", 15005 Space); 15006 verifyFormat("switch (x) {\n" 15007 "default:\n" 15008 " break;\n" 15009 "}", 15010 Space); 15011 verifyFormat("A::A () : a (1) {}", Space); 15012 verifyFormat("void f () __attribute__ ((asdf));", Space); 15013 verifyFormat("*(&a + 1);\n" 15014 "&((&a)[1]);\n" 15015 "a[(b + c) * d];\n" 15016 "(((a + 1) * 2) + 3) * 4;", 15017 Space); 15018 verifyFormat("#define A(x) x", Space); 15019 verifyFormat("#define A (x) x", Space); 15020 verifyFormat("#if defined(x)\n" 15021 "#endif", 15022 Space); 15023 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15024 verifyFormat("size_t x = sizeof (x);", Space); 15025 verifyFormat("auto f (int x) -> decltype (x);", Space); 15026 verifyFormat("auto f (int x) -> typeof (x);", Space); 15027 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15028 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15029 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15030 verifyFormat("alignas (128) char a[128];", Space); 15031 verifyFormat("size_t x = alignof (MyType);", Space); 15032 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15033 verifyFormat("int f () throw (Deprecated);", Space); 15034 verifyFormat("typedef void (*cb) (int);", Space); 15035 // FIXME these tests regressed behaviour. 15036 // verifyFormat("T A::operator() ();", Space); 15037 // verifyFormat("X A::operator++ (T);", Space); 15038 verifyFormat("auto lambda = [] () { return 0; };", Space); 15039 verifyFormat("int x = int (y);", Space); 15040 15041 FormatStyle SomeSpace = getLLVMStyle(); 15042 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15043 15044 verifyFormat("[]() -> float {}", SomeSpace); 15045 verifyFormat("[] (auto foo) {}", SomeSpace); 15046 verifyFormat("[foo]() -> int {}", SomeSpace); 15047 verifyFormat("int f();", SomeSpace); 15048 verifyFormat("void f (int a, T b) {\n" 15049 " while (true)\n" 15050 " continue;\n" 15051 "}", 15052 SomeSpace); 15053 verifyFormat("if (true)\n" 15054 " f();\n" 15055 "else if (true)\n" 15056 " f();", 15057 SomeSpace); 15058 verifyFormat("do {\n" 15059 " do_something();\n" 15060 "} while (something());", 15061 SomeSpace); 15062 verifyFormat("switch (x) {\n" 15063 "default:\n" 15064 " break;\n" 15065 "}", 15066 SomeSpace); 15067 verifyFormat("A::A() : a (1) {}", SomeSpace); 15068 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15069 verifyFormat("*(&a + 1);\n" 15070 "&((&a)[1]);\n" 15071 "a[(b + c) * d];\n" 15072 "(((a + 1) * 2) + 3) * 4;", 15073 SomeSpace); 15074 verifyFormat("#define A(x) x", SomeSpace); 15075 verifyFormat("#define A (x) x", SomeSpace); 15076 verifyFormat("#if defined(x)\n" 15077 "#endif", 15078 SomeSpace); 15079 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15080 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15081 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15082 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15083 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15084 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15085 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15086 verifyFormat("alignas (128) char a[128];", SomeSpace); 15087 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15088 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15089 SomeSpace); 15090 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15091 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15092 verifyFormat("T A::operator()();", SomeSpace); 15093 // FIXME these tests regressed behaviour. 15094 // verifyFormat("X A::operator++ (T);", SomeSpace); 15095 verifyFormat("int x = int (y);", SomeSpace); 15096 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15097 15098 FormatStyle SpaceControlStatements = getLLVMStyle(); 15099 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15100 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15101 15102 verifyFormat("while (true)\n" 15103 " continue;", 15104 SpaceControlStatements); 15105 verifyFormat("if (true)\n" 15106 " f();\n" 15107 "else if (true)\n" 15108 " f();", 15109 SpaceControlStatements); 15110 verifyFormat("for (;;) {\n" 15111 " do_something();\n" 15112 "}", 15113 SpaceControlStatements); 15114 verifyFormat("do {\n" 15115 " do_something();\n" 15116 "} while (something());", 15117 SpaceControlStatements); 15118 verifyFormat("switch (x) {\n" 15119 "default:\n" 15120 " break;\n" 15121 "}", 15122 SpaceControlStatements); 15123 15124 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15125 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15126 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15127 15128 verifyFormat("int f ();", SpaceFuncDecl); 15129 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15130 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15131 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15132 verifyFormat("#define A(x) x", SpaceFuncDecl); 15133 verifyFormat("#define A (x) x", SpaceFuncDecl); 15134 verifyFormat("#if defined(x)\n" 15135 "#endif", 15136 SpaceFuncDecl); 15137 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15138 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15139 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15140 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15141 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15142 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15143 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15144 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15145 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15146 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15147 SpaceFuncDecl); 15148 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15149 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15150 // FIXME these tests regressed behaviour. 15151 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15152 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15153 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15154 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15155 verifyFormat("int x = int(y);", SpaceFuncDecl); 15156 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15157 SpaceFuncDecl); 15158 15159 FormatStyle SpaceFuncDef = getLLVMStyle(); 15160 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15161 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15162 15163 verifyFormat("int f();", SpaceFuncDef); 15164 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15165 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15166 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15167 verifyFormat("#define A(x) x", SpaceFuncDef); 15168 verifyFormat("#define A (x) x", SpaceFuncDef); 15169 verifyFormat("#if defined(x)\n" 15170 "#endif", 15171 SpaceFuncDef); 15172 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15173 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15174 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15175 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15176 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15177 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15178 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15179 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15180 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15181 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15182 SpaceFuncDef); 15183 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15184 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15185 verifyFormat("T A::operator()();", SpaceFuncDef); 15186 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15187 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15188 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15189 verifyFormat("int x = int(y);", SpaceFuncDef); 15190 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15191 SpaceFuncDef); 15192 15193 FormatStyle SpaceIfMacros = getLLVMStyle(); 15194 SpaceIfMacros.IfMacros.clear(); 15195 SpaceIfMacros.IfMacros.push_back("MYIF"); 15196 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15197 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15198 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15199 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15200 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15201 15202 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15203 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15204 FormatStyle::SBS_Never); 15205 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15206 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15207 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15208 verifyFormat("for (;;) {\n" 15209 "}", 15210 SpaceForeachMacros); 15211 verifyFormat("foreach (Item *item, itemlist) {\n" 15212 "}", 15213 SpaceForeachMacros); 15214 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15215 "}", 15216 SpaceForeachMacros); 15217 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15218 "}", 15219 SpaceForeachMacros); 15220 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15221 15222 FormatStyle SomeSpace2 = getLLVMStyle(); 15223 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15224 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15225 verifyFormat("[]() -> float {}", SomeSpace2); 15226 verifyFormat("[] (auto foo) {}", SomeSpace2); 15227 verifyFormat("[foo]() -> int {}", SomeSpace2); 15228 verifyFormat("int f();", SomeSpace2); 15229 verifyFormat("void f (int a, T b) {\n" 15230 " while (true)\n" 15231 " continue;\n" 15232 "}", 15233 SomeSpace2); 15234 verifyFormat("if (true)\n" 15235 " f();\n" 15236 "else if (true)\n" 15237 " f();", 15238 SomeSpace2); 15239 verifyFormat("do {\n" 15240 " do_something();\n" 15241 "} while (something());", 15242 SomeSpace2); 15243 verifyFormat("switch (x) {\n" 15244 "default:\n" 15245 " break;\n" 15246 "}", 15247 SomeSpace2); 15248 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15249 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15250 verifyFormat("*(&a + 1);\n" 15251 "&((&a)[1]);\n" 15252 "a[(b + c) * d];\n" 15253 "(((a + 1) * 2) + 3) * 4;", 15254 SomeSpace2); 15255 verifyFormat("#define A(x) x", SomeSpace2); 15256 verifyFormat("#define A (x) x", SomeSpace2); 15257 verifyFormat("#if defined(x)\n" 15258 "#endif", 15259 SomeSpace2); 15260 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15261 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15262 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15263 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15264 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15265 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15266 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15267 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15268 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15269 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15270 SomeSpace2); 15271 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15272 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15273 verifyFormat("T A::operator()();", SomeSpace2); 15274 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15275 verifyFormat("int x = int (y);", SomeSpace2); 15276 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15277 15278 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15279 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15280 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15281 .AfterOverloadedOperator = true; 15282 15283 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15284 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15285 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15286 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15287 15288 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15289 .AfterOverloadedOperator = false; 15290 15291 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15292 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15293 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15294 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15295 15296 auto SpaceAfterRequires = getLLVMStyle(); 15297 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15298 EXPECT_FALSE( 15299 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15300 EXPECT_FALSE( 15301 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15302 verifyFormat("void f(auto x)\n" 15303 " requires requires(int i) { x + i; }\n" 15304 "{}", 15305 SpaceAfterRequires); 15306 verifyFormat("void f(auto x)\n" 15307 " requires(requires(int i) { x + i; })\n" 15308 "{}", 15309 SpaceAfterRequires); 15310 verifyFormat("if (requires(int i) { x + i; })\n" 15311 " return;", 15312 SpaceAfterRequires); 15313 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15314 verifyFormat("template <typename T>\n" 15315 " requires(Foo<T>)\n" 15316 "class Bar;", 15317 SpaceAfterRequires); 15318 15319 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15320 verifyFormat("void f(auto x)\n" 15321 " requires requires(int i) { x + i; }\n" 15322 "{}", 15323 SpaceAfterRequires); 15324 verifyFormat("void f(auto x)\n" 15325 " requires (requires(int i) { x + i; })\n" 15326 "{}", 15327 SpaceAfterRequires); 15328 verifyFormat("if (requires(int i) { x + i; })\n" 15329 " return;", 15330 SpaceAfterRequires); 15331 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15332 verifyFormat("template <typename T>\n" 15333 " requires (Foo<T>)\n" 15334 "class Bar;", 15335 SpaceAfterRequires); 15336 15337 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15338 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15339 verifyFormat("void f(auto x)\n" 15340 " requires requires (int i) { x + i; }\n" 15341 "{}", 15342 SpaceAfterRequires); 15343 verifyFormat("void f(auto x)\n" 15344 " requires(requires (int i) { x + i; })\n" 15345 "{}", 15346 SpaceAfterRequires); 15347 verifyFormat("if (requires (int i) { x + i; })\n" 15348 " return;", 15349 SpaceAfterRequires); 15350 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15351 verifyFormat("template <typename T>\n" 15352 " requires(Foo<T>)\n" 15353 "class Bar;", 15354 SpaceAfterRequires); 15355 15356 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15357 verifyFormat("void f(auto x)\n" 15358 " requires requires (int i) { x + i; }\n" 15359 "{}", 15360 SpaceAfterRequires); 15361 verifyFormat("void f(auto x)\n" 15362 " requires (requires (int i) { x + i; })\n" 15363 "{}", 15364 SpaceAfterRequires); 15365 verifyFormat("if (requires (int i) { x + i; })\n" 15366 " return;", 15367 SpaceAfterRequires); 15368 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15369 verifyFormat("template <typename T>\n" 15370 " requires (Foo<T>)\n" 15371 "class Bar;", 15372 SpaceAfterRequires); 15373 } 15374 15375 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15376 FormatStyle Spaces = getLLVMStyle(); 15377 Spaces.SpaceAfterLogicalNot = true; 15378 15379 verifyFormat("bool x = ! y", Spaces); 15380 verifyFormat("if (! isFailure())", Spaces); 15381 verifyFormat("if (! (a && b))", Spaces); 15382 verifyFormat("\"Error!\"", Spaces); 15383 verifyFormat("! ! x", Spaces); 15384 } 15385 15386 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15387 FormatStyle Spaces = getLLVMStyle(); 15388 15389 Spaces.SpacesInParentheses = true; 15390 verifyFormat("do_something( ::globalVar );", Spaces); 15391 verifyFormat("call( x, y, z );", Spaces); 15392 verifyFormat("call();", Spaces); 15393 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15394 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15395 Spaces); 15396 verifyFormat("while ( (bool)1 )\n" 15397 " continue;", 15398 Spaces); 15399 verifyFormat("for ( ;; )\n" 15400 " continue;", 15401 Spaces); 15402 verifyFormat("if ( true )\n" 15403 " f();\n" 15404 "else if ( true )\n" 15405 " f();", 15406 Spaces); 15407 verifyFormat("do {\n" 15408 " do_something( (int)i );\n" 15409 "} while ( something() );", 15410 Spaces); 15411 verifyFormat("switch ( x ) {\n" 15412 "default:\n" 15413 " break;\n" 15414 "}", 15415 Spaces); 15416 15417 Spaces.SpacesInParentheses = false; 15418 Spaces.SpacesInCStyleCastParentheses = true; 15419 verifyFormat("Type *A = ( Type * )P;", Spaces); 15420 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15421 verifyFormat("x = ( int32 )y;", Spaces); 15422 verifyFormat("int a = ( int )(2.0f);", Spaces); 15423 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15424 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15425 verifyFormat("#define x (( int )-1)", Spaces); 15426 15427 // Run the first set of tests again with: 15428 Spaces.SpacesInParentheses = false; 15429 Spaces.SpaceInEmptyParentheses = true; 15430 Spaces.SpacesInCStyleCastParentheses = true; 15431 verifyFormat("call(x, y, z);", Spaces); 15432 verifyFormat("call( );", Spaces); 15433 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15434 verifyFormat("while (( bool )1)\n" 15435 " continue;", 15436 Spaces); 15437 verifyFormat("for (;;)\n" 15438 " continue;", 15439 Spaces); 15440 verifyFormat("if (true)\n" 15441 " f( );\n" 15442 "else if (true)\n" 15443 " f( );", 15444 Spaces); 15445 verifyFormat("do {\n" 15446 " do_something(( int )i);\n" 15447 "} while (something( ));", 15448 Spaces); 15449 verifyFormat("switch (x) {\n" 15450 "default:\n" 15451 " break;\n" 15452 "}", 15453 Spaces); 15454 15455 // Run the first set of tests again with: 15456 Spaces.SpaceAfterCStyleCast = true; 15457 verifyFormat("call(x, y, z);", Spaces); 15458 verifyFormat("call( );", Spaces); 15459 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15460 verifyFormat("while (( bool ) 1)\n" 15461 " continue;", 15462 Spaces); 15463 verifyFormat("for (;;)\n" 15464 " continue;", 15465 Spaces); 15466 verifyFormat("if (true)\n" 15467 " f( );\n" 15468 "else if (true)\n" 15469 " f( );", 15470 Spaces); 15471 verifyFormat("do {\n" 15472 " do_something(( int ) i);\n" 15473 "} while (something( ));", 15474 Spaces); 15475 verifyFormat("switch (x) {\n" 15476 "default:\n" 15477 " break;\n" 15478 "}", 15479 Spaces); 15480 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15481 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15482 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15483 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15484 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15485 15486 // Run subset of tests again with: 15487 Spaces.SpacesInCStyleCastParentheses = false; 15488 Spaces.SpaceAfterCStyleCast = true; 15489 verifyFormat("while ((bool) 1)\n" 15490 " continue;", 15491 Spaces); 15492 verifyFormat("do {\n" 15493 " do_something((int) i);\n" 15494 "} while (something( ));", 15495 Spaces); 15496 15497 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15498 verifyFormat("size_t idx = (size_t) a;", Spaces); 15499 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15500 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15501 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15502 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15503 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15504 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15505 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15506 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15507 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15508 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15509 Spaces.ColumnLimit = 80; 15510 Spaces.IndentWidth = 4; 15511 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15512 verifyFormat("void foo( ) {\n" 15513 " size_t foo = (*(function))(\n" 15514 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15515 "BarrrrrrrrrrrrLong,\n" 15516 " FoooooooooLooooong);\n" 15517 "}", 15518 Spaces); 15519 Spaces.SpaceAfterCStyleCast = false; 15520 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15521 verifyFormat("size_t idx = (size_t)a;", Spaces); 15522 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15523 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15524 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15525 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15526 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15527 15528 verifyFormat("void foo( ) {\n" 15529 " size_t foo = (*(function))(\n" 15530 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15531 "BarrrrrrrrrrrrLong,\n" 15532 " FoooooooooLooooong);\n" 15533 "}", 15534 Spaces); 15535 } 15536 15537 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15538 verifyFormat("int a[5];"); 15539 verifyFormat("a[3] += 42;"); 15540 15541 FormatStyle Spaces = getLLVMStyle(); 15542 Spaces.SpacesInSquareBrackets = true; 15543 // Not lambdas. 15544 verifyFormat("int a[ 5 ];", Spaces); 15545 verifyFormat("a[ 3 ] += 42;", Spaces); 15546 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15547 verifyFormat("double &operator[](int i) { return 0; }\n" 15548 "int i;", 15549 Spaces); 15550 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15551 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15552 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15553 // Lambdas. 15554 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15555 verifyFormat("return [ i, args... ] {};", Spaces); 15556 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15557 verifyFormat("int foo = [ = ]() {};", Spaces); 15558 verifyFormat("int foo = [ & ]() {};", Spaces); 15559 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15560 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15561 } 15562 15563 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15564 FormatStyle NoSpaceStyle = getLLVMStyle(); 15565 verifyFormat("int a[5];", NoSpaceStyle); 15566 verifyFormat("a[3] += 42;", NoSpaceStyle); 15567 15568 verifyFormat("int a[1];", NoSpaceStyle); 15569 verifyFormat("int 1 [a];", NoSpaceStyle); 15570 verifyFormat("int a[1][2];", NoSpaceStyle); 15571 verifyFormat("a[7] = 5;", NoSpaceStyle); 15572 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15573 verifyFormat("f([] {})", NoSpaceStyle); 15574 15575 FormatStyle Space = getLLVMStyle(); 15576 Space.SpaceBeforeSquareBrackets = true; 15577 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15578 verifyFormat("return [i, args...] {};", Space); 15579 15580 verifyFormat("int a [5];", Space); 15581 verifyFormat("a [3] += 42;", Space); 15582 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15583 verifyFormat("double &operator[](int i) { return 0; }\n" 15584 "int i;", 15585 Space); 15586 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15587 verifyFormat("int i = a [a][a]->f();", Space); 15588 verifyFormat("int i = (*b) [a]->f();", Space); 15589 15590 verifyFormat("int a [1];", Space); 15591 verifyFormat("int 1 [a];", Space); 15592 verifyFormat("int a [1][2];", Space); 15593 verifyFormat("a [7] = 5;", Space); 15594 verifyFormat("int a = (f()) [23];", Space); 15595 verifyFormat("f([] {})", Space); 15596 } 15597 15598 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15599 verifyFormat("int a = 5;"); 15600 verifyFormat("a += 42;"); 15601 verifyFormat("a or_eq 8;"); 15602 15603 FormatStyle Spaces = getLLVMStyle(); 15604 Spaces.SpaceBeforeAssignmentOperators = false; 15605 verifyFormat("int a= 5;", Spaces); 15606 verifyFormat("a+= 42;", Spaces); 15607 verifyFormat("a or_eq 8;", Spaces); 15608 } 15609 15610 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15611 verifyFormat("class Foo : public Bar {};"); 15612 verifyFormat("Foo::Foo() : foo(1) {}"); 15613 verifyFormat("for (auto a : b) {\n}"); 15614 verifyFormat("int x = a ? b : c;"); 15615 verifyFormat("{\n" 15616 "label0:\n" 15617 " int x = 0;\n" 15618 "}"); 15619 verifyFormat("switch (x) {\n" 15620 "case 1:\n" 15621 "default:\n" 15622 "}"); 15623 verifyFormat("switch (allBraces) {\n" 15624 "case 1: {\n" 15625 " break;\n" 15626 "}\n" 15627 "case 2: {\n" 15628 " [[fallthrough]];\n" 15629 "}\n" 15630 "default: {\n" 15631 " break;\n" 15632 "}\n" 15633 "}"); 15634 15635 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15636 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15637 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15638 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15639 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15640 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15641 verifyFormat("{\n" 15642 "label1:\n" 15643 " int x = 0;\n" 15644 "}", 15645 CtorInitializerStyle); 15646 verifyFormat("switch (x) {\n" 15647 "case 1:\n" 15648 "default:\n" 15649 "}", 15650 CtorInitializerStyle); 15651 verifyFormat("switch (allBraces) {\n" 15652 "case 1: {\n" 15653 " break;\n" 15654 "}\n" 15655 "case 2: {\n" 15656 " [[fallthrough]];\n" 15657 "}\n" 15658 "default: {\n" 15659 " break;\n" 15660 "}\n" 15661 "}", 15662 CtorInitializerStyle); 15663 CtorInitializerStyle.BreakConstructorInitializers = 15664 FormatStyle::BCIS_AfterColon; 15665 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15666 " aaaaaaaaaaaaaaaa(1),\n" 15667 " bbbbbbbbbbbbbbbb(2) {}", 15668 CtorInitializerStyle); 15669 CtorInitializerStyle.BreakConstructorInitializers = 15670 FormatStyle::BCIS_BeforeComma; 15671 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15672 " : aaaaaaaaaaaaaaaa(1)\n" 15673 " , bbbbbbbbbbbbbbbb(2) {}", 15674 CtorInitializerStyle); 15675 CtorInitializerStyle.BreakConstructorInitializers = 15676 FormatStyle::BCIS_BeforeColon; 15677 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15678 " : aaaaaaaaaaaaaaaa(1),\n" 15679 " bbbbbbbbbbbbbbbb(2) {}", 15680 CtorInitializerStyle); 15681 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15682 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15683 ": aaaaaaaaaaaaaaaa(1),\n" 15684 " bbbbbbbbbbbbbbbb(2) {}", 15685 CtorInitializerStyle); 15686 15687 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15688 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15689 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15690 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15691 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15692 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15693 verifyFormat("{\n" 15694 "label2:\n" 15695 " int x = 0;\n" 15696 "}", 15697 InheritanceStyle); 15698 verifyFormat("switch (x) {\n" 15699 "case 1:\n" 15700 "default:\n" 15701 "}", 15702 InheritanceStyle); 15703 verifyFormat("switch (allBraces) {\n" 15704 "case 1: {\n" 15705 " break;\n" 15706 "}\n" 15707 "case 2: {\n" 15708 " [[fallthrough]];\n" 15709 "}\n" 15710 "default: {\n" 15711 " break;\n" 15712 "}\n" 15713 "}", 15714 InheritanceStyle); 15715 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15716 verifyFormat("class Foooooooooooooooooooooo\n" 15717 " : public aaaaaaaaaaaaaaaaaa,\n" 15718 " public bbbbbbbbbbbbbbbbbb {\n" 15719 "}", 15720 InheritanceStyle); 15721 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15722 verifyFormat("class Foooooooooooooooooooooo:\n" 15723 " public aaaaaaaaaaaaaaaaaa,\n" 15724 " public bbbbbbbbbbbbbbbbbb {\n" 15725 "}", 15726 InheritanceStyle); 15727 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15728 verifyFormat("class Foooooooooooooooooooooo\n" 15729 " : public aaaaaaaaaaaaaaaaaa\n" 15730 " , public bbbbbbbbbbbbbbbbbb {\n" 15731 "}", 15732 InheritanceStyle); 15733 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15734 verifyFormat("class Foooooooooooooooooooooo\n" 15735 " : public aaaaaaaaaaaaaaaaaa,\n" 15736 " public bbbbbbbbbbbbbbbbbb {\n" 15737 "}", 15738 InheritanceStyle); 15739 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15740 verifyFormat("class Foooooooooooooooooooooo\n" 15741 ": public aaaaaaaaaaaaaaaaaa,\n" 15742 " public bbbbbbbbbbbbbbbbbb {}", 15743 InheritanceStyle); 15744 15745 FormatStyle ForLoopStyle = getLLVMStyle(); 15746 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15747 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15748 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15749 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15750 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15751 verifyFormat("{\n" 15752 "label2:\n" 15753 " int x = 0;\n" 15754 "}", 15755 ForLoopStyle); 15756 verifyFormat("switch (x) {\n" 15757 "case 1:\n" 15758 "default:\n" 15759 "}", 15760 ForLoopStyle); 15761 verifyFormat("switch (allBraces) {\n" 15762 "case 1: {\n" 15763 " break;\n" 15764 "}\n" 15765 "case 2: {\n" 15766 " [[fallthrough]];\n" 15767 "}\n" 15768 "default: {\n" 15769 " break;\n" 15770 "}\n" 15771 "}", 15772 ForLoopStyle); 15773 15774 FormatStyle CaseStyle = getLLVMStyle(); 15775 CaseStyle.SpaceBeforeCaseColon = true; 15776 verifyFormat("class Foo : public Bar {};", CaseStyle); 15777 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15778 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15779 verifyFormat("int x = a ? b : c;", CaseStyle); 15780 verifyFormat("switch (x) {\n" 15781 "case 1 :\n" 15782 "default :\n" 15783 "}", 15784 CaseStyle); 15785 verifyFormat("switch (allBraces) {\n" 15786 "case 1 : {\n" 15787 " break;\n" 15788 "}\n" 15789 "case 2 : {\n" 15790 " [[fallthrough]];\n" 15791 "}\n" 15792 "default : {\n" 15793 " break;\n" 15794 "}\n" 15795 "}", 15796 CaseStyle); 15797 15798 FormatStyle NoSpaceStyle = getLLVMStyle(); 15799 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15800 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15801 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15802 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15803 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15804 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15805 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15806 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15807 verifyFormat("{\n" 15808 "label3:\n" 15809 " int x = 0;\n" 15810 "}", 15811 NoSpaceStyle); 15812 verifyFormat("switch (x) {\n" 15813 "case 1:\n" 15814 "default:\n" 15815 "}", 15816 NoSpaceStyle); 15817 verifyFormat("switch (allBraces) {\n" 15818 "case 1: {\n" 15819 " break;\n" 15820 "}\n" 15821 "case 2: {\n" 15822 " [[fallthrough]];\n" 15823 "}\n" 15824 "default: {\n" 15825 " break;\n" 15826 "}\n" 15827 "}", 15828 NoSpaceStyle); 15829 15830 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15831 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15832 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15833 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15834 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15835 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15836 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15837 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15838 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15839 verifyFormat("{\n" 15840 "label3:\n" 15841 " int x = 0;\n" 15842 "}", 15843 InvertedSpaceStyle); 15844 verifyFormat("switch (x) {\n" 15845 "case 1 :\n" 15846 "case 2 : {\n" 15847 " break;\n" 15848 "}\n" 15849 "default :\n" 15850 " break;\n" 15851 "}", 15852 InvertedSpaceStyle); 15853 verifyFormat("switch (allBraces) {\n" 15854 "case 1 : {\n" 15855 " break;\n" 15856 "}\n" 15857 "case 2 : {\n" 15858 " [[fallthrough]];\n" 15859 "}\n" 15860 "default : {\n" 15861 " break;\n" 15862 "}\n" 15863 "}", 15864 InvertedSpaceStyle); 15865 } 15866 15867 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15868 FormatStyle Style = getLLVMStyle(); 15869 15870 Style.PointerAlignment = FormatStyle::PAS_Left; 15871 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15872 verifyFormat("void* const* x = NULL;", Style); 15873 15874 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15875 do { \ 15876 Style.PointerAlignment = FormatStyle::Pointers; \ 15877 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15878 verifyFormat(Code, Style); \ 15879 } while (false) 15880 15881 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15882 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15883 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15884 15885 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15886 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15887 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15888 15889 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15890 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15891 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15892 15893 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15894 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15895 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15896 15897 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15898 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15899 SAPQ_Default); 15900 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15901 SAPQ_Default); 15902 15903 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15904 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15905 SAPQ_Before); 15906 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15907 SAPQ_Before); 15908 15909 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15910 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15911 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15912 SAPQ_After); 15913 15914 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15915 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15916 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15917 15918 #undef verifyQualifierSpaces 15919 15920 FormatStyle Spaces = getLLVMStyle(); 15921 Spaces.AttributeMacros.push_back("qualified"); 15922 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15923 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15924 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15925 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15926 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15927 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15928 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15929 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15930 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15931 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15932 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15933 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15934 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15935 15936 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15937 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15938 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15939 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15940 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15941 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15942 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15943 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15944 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15945 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15946 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15947 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15948 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15949 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15950 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15951 15952 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15953 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15954 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15955 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15956 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15957 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15958 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15959 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15960 } 15961 15962 TEST_F(FormatTest, AlignConsecutiveMacros) { 15963 FormatStyle Style = getLLVMStyle(); 15964 Style.AlignConsecutiveAssignments.Enabled = true; 15965 Style.AlignConsecutiveDeclarations.Enabled = true; 15966 15967 verifyFormat("#define a 3\n" 15968 "#define bbbb 4\n" 15969 "#define ccc (5)", 15970 Style); 15971 15972 verifyFormat("#define f(x) (x * x)\n" 15973 "#define fff(x, y, z) (x * y + z)\n" 15974 "#define ffff(x, y) (x - y)", 15975 Style); 15976 15977 verifyFormat("#define foo(x, y) (x + y)\n" 15978 "#define bar (5, 6)(2 + 2)", 15979 Style); 15980 15981 verifyFormat("#define a 3\n" 15982 "#define bbbb 4\n" 15983 "#define ccc (5)\n" 15984 "#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 Style.AlignConsecutiveMacros.Enabled = true; 15990 verifyFormat("#define a 3\n" 15991 "#define bbbb 4\n" 15992 "#define ccc (5)", 15993 Style); 15994 15995 verifyFormat("#define f(x) (x * x)\n" 15996 "#define fff(x, y, z) (x * y + z)\n" 15997 "#define ffff(x, y) (x - y)", 15998 Style); 15999 16000 verifyFormat("#define foo(x, y) (x + y)\n" 16001 "#define bar (5, 6)(2 + 2)", 16002 Style); 16003 16004 verifyFormat("#define a 3\n" 16005 "#define bbbb 4\n" 16006 "#define ccc (5)\n" 16007 "#define f(x) (x * x)\n" 16008 "#define fff(x, y, z) (x * y + z)\n" 16009 "#define ffff(x, y) (x - y)", 16010 Style); 16011 16012 verifyFormat("#define a 5\n" 16013 "#define foo(x, y) (x + y)\n" 16014 "#define CCC (6)\n" 16015 "auto lambda = []() {\n" 16016 " auto ii = 0;\n" 16017 " float j = 0;\n" 16018 " return 0;\n" 16019 "};\n" 16020 "int i = 0;\n" 16021 "float i2 = 0;\n" 16022 "auto v = type{\n" 16023 " i = 1, //\n" 16024 " (i = 2), //\n" 16025 " i = 3 //\n" 16026 "};", 16027 Style); 16028 16029 Style.AlignConsecutiveMacros.Enabled = false; 16030 Style.ColumnLimit = 20; 16031 16032 verifyFormat("#define a \\\n" 16033 " \"aabbbbbbbbbbbb\"\n" 16034 "#define D \\\n" 16035 " \"aabbbbbbbbbbbb\" \\\n" 16036 " \"ccddeeeeeeeee\"\n" 16037 "#define B \\\n" 16038 " \"QQQQQQQQQQQQQ\" \\\n" 16039 " \"FFFFFFFFFFFFF\" \\\n" 16040 " \"LLLLLLLL\"\n", 16041 Style); 16042 16043 Style.AlignConsecutiveMacros.Enabled = true; 16044 verifyFormat("#define a \\\n" 16045 " \"aabbbbbbbbbbbb\"\n" 16046 "#define D \\\n" 16047 " \"aabbbbbbbbbbbb\" \\\n" 16048 " \"ccddeeeeeeeee\"\n" 16049 "#define B \\\n" 16050 " \"QQQQQQQQQQQQQ\" \\\n" 16051 " \"FFFFFFFFFFFFF\" \\\n" 16052 " \"LLLLLLLL\"\n", 16053 Style); 16054 16055 // Test across comments 16056 Style.MaxEmptyLinesToKeep = 10; 16057 Style.ReflowComments = false; 16058 Style.AlignConsecutiveMacros.AcrossComments = true; 16059 EXPECT_EQ("#define a 3\n" 16060 "// line comment\n" 16061 "#define bbbb 4\n" 16062 "#define ccc (5)", 16063 format("#define a 3\n" 16064 "// line comment\n" 16065 "#define bbbb 4\n" 16066 "#define ccc (5)", 16067 Style)); 16068 16069 EXPECT_EQ("#define a 3\n" 16070 "/* block comment */\n" 16071 "#define bbbb 4\n" 16072 "#define ccc (5)", 16073 format("#define a 3\n" 16074 "/* block comment */\n" 16075 "#define bbbb 4\n" 16076 "#define ccc (5)", 16077 Style)); 16078 16079 EXPECT_EQ("#define a 3\n" 16080 "/* multi-line *\n" 16081 " * block comment */\n" 16082 "#define bbbb 4\n" 16083 "#define ccc (5)", 16084 format("#define a 3\n" 16085 "/* multi-line *\n" 16086 " * block comment */\n" 16087 "#define bbbb 4\n" 16088 "#define ccc (5)", 16089 Style)); 16090 16091 EXPECT_EQ("#define a 3\n" 16092 "// multi-line line comment\n" 16093 "//\n" 16094 "#define bbbb 4\n" 16095 "#define ccc (5)", 16096 format("#define a 3\n" 16097 "// multi-line line comment\n" 16098 "//\n" 16099 "#define bbbb 4\n" 16100 "#define ccc (5)", 16101 Style)); 16102 16103 EXPECT_EQ("#define a 3\n" 16104 "// empty lines still break.\n" 16105 "\n" 16106 "#define bbbb 4\n" 16107 "#define ccc (5)", 16108 format("#define a 3\n" 16109 "// empty lines still break.\n" 16110 "\n" 16111 "#define bbbb 4\n" 16112 "#define ccc (5)", 16113 Style)); 16114 16115 // Test across empty lines 16116 Style.AlignConsecutiveMacros.AcrossComments = false; 16117 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16118 EXPECT_EQ("#define a 3\n" 16119 "\n" 16120 "#define bbbb 4\n" 16121 "#define ccc (5)", 16122 format("#define a 3\n" 16123 "\n" 16124 "#define bbbb 4\n" 16125 "#define ccc (5)", 16126 Style)); 16127 16128 EXPECT_EQ("#define a 3\n" 16129 "\n" 16130 "\n" 16131 "\n" 16132 "#define bbbb 4\n" 16133 "#define ccc (5)", 16134 format("#define a 3\n" 16135 "\n" 16136 "\n" 16137 "\n" 16138 "#define bbbb 4\n" 16139 "#define ccc (5)", 16140 Style)); 16141 16142 EXPECT_EQ("#define a 3\n" 16143 "// comments should break alignment\n" 16144 "//\n" 16145 "#define bbbb 4\n" 16146 "#define ccc (5)", 16147 format("#define a 3\n" 16148 "// comments should break alignment\n" 16149 "//\n" 16150 "#define bbbb 4\n" 16151 "#define ccc (5)", 16152 Style)); 16153 16154 // Test across empty lines and comments 16155 Style.AlignConsecutiveMacros.AcrossComments = true; 16156 verifyFormat("#define a 3\n" 16157 "\n" 16158 "// line comment\n" 16159 "#define bbbb 4\n" 16160 "#define ccc (5)", 16161 Style); 16162 16163 EXPECT_EQ("#define a 3\n" 16164 "\n" 16165 "\n" 16166 "/* multi-line *\n" 16167 " * block comment */\n" 16168 "\n" 16169 "\n" 16170 "#define bbbb 4\n" 16171 "#define ccc (5)", 16172 format("#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 Style)); 16182 16183 EXPECT_EQ("#define a 3\n" 16184 "\n" 16185 "\n" 16186 "/* multi-line *\n" 16187 " * block comment */\n" 16188 "\n" 16189 "\n" 16190 "#define bbbb 4\n" 16191 "#define ccc (5)", 16192 format("#define a 3\n" 16193 "\n" 16194 "\n" 16195 "/* multi-line *\n" 16196 " * block comment */\n" 16197 "\n" 16198 "\n" 16199 "#define bbbb 4\n" 16200 "#define ccc (5)", 16201 Style)); 16202 } 16203 16204 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16205 FormatStyle Alignment = getLLVMStyle(); 16206 Alignment.AlignConsecutiveMacros.Enabled = true; 16207 Alignment.AlignConsecutiveAssignments.Enabled = true; 16208 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16209 16210 Alignment.MaxEmptyLinesToKeep = 10; 16211 /* Test alignment across empty lines */ 16212 EXPECT_EQ("int a = 5;\n" 16213 "\n" 16214 "int oneTwoThree = 123;", 16215 format("int a = 5;\n" 16216 "\n" 16217 "int oneTwoThree= 123;", 16218 Alignment)); 16219 EXPECT_EQ("int a = 5;\n" 16220 "int one = 1;\n" 16221 "\n" 16222 "int oneTwoThree = 123;", 16223 format("int a = 5;\n" 16224 "int one = 1;\n" 16225 "\n" 16226 "int oneTwoThree = 123;", 16227 Alignment)); 16228 EXPECT_EQ("int a = 5;\n" 16229 "int one = 1;\n" 16230 "\n" 16231 "int oneTwoThree = 123;\n" 16232 "int oneTwo = 12;", 16233 format("int a = 5;\n" 16234 "int one = 1;\n" 16235 "\n" 16236 "int oneTwoThree = 123;\n" 16237 "int oneTwo = 12;", 16238 Alignment)); 16239 16240 /* Test across comments */ 16241 EXPECT_EQ("int a = 5;\n" 16242 "/* block comment */\n" 16243 "int oneTwoThree = 123;", 16244 format("int a = 5;\n" 16245 "/* block comment */\n" 16246 "int oneTwoThree=123;", 16247 Alignment)); 16248 16249 EXPECT_EQ("int a = 5;\n" 16250 "// line comment\n" 16251 "int oneTwoThree = 123;", 16252 format("int a = 5;\n" 16253 "// line comment\n" 16254 "int oneTwoThree=123;", 16255 Alignment)); 16256 16257 /* Test across comments and newlines */ 16258 EXPECT_EQ("int a = 5;\n" 16259 "\n" 16260 "/* block comment */\n" 16261 "int oneTwoThree = 123;", 16262 format("int a = 5;\n" 16263 "\n" 16264 "/* block comment */\n" 16265 "int oneTwoThree=123;", 16266 Alignment)); 16267 16268 EXPECT_EQ("int a = 5;\n" 16269 "\n" 16270 "// line comment\n" 16271 "int oneTwoThree = 123;", 16272 format("int a = 5;\n" 16273 "\n" 16274 "// line comment\n" 16275 "int oneTwoThree=123;", 16276 Alignment)); 16277 } 16278 16279 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16280 FormatStyle Alignment = getLLVMStyle(); 16281 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16282 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16283 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16284 16285 Alignment.MaxEmptyLinesToKeep = 10; 16286 /* Test alignment across empty lines */ 16287 EXPECT_EQ("int a = 5;\n" 16288 "\n" 16289 "float const oneTwoThree = 123;", 16290 format("int a = 5;\n" 16291 "\n" 16292 "float const oneTwoThree = 123;", 16293 Alignment)); 16294 EXPECT_EQ("int a = 5;\n" 16295 "float const one = 1;\n" 16296 "\n" 16297 "int oneTwoThree = 123;", 16298 format("int a = 5;\n" 16299 "float const one = 1;\n" 16300 "\n" 16301 "int oneTwoThree = 123;", 16302 Alignment)); 16303 16304 /* Test across comments */ 16305 EXPECT_EQ("float const a = 5;\n" 16306 "/* block comment */\n" 16307 "int oneTwoThree = 123;", 16308 format("float const a = 5;\n" 16309 "/* block comment */\n" 16310 "int oneTwoThree=123;", 16311 Alignment)); 16312 16313 EXPECT_EQ("float const a = 5;\n" 16314 "// line comment\n" 16315 "int oneTwoThree = 123;", 16316 format("float const a = 5;\n" 16317 "// line comment\n" 16318 "int oneTwoThree=123;", 16319 Alignment)); 16320 16321 /* Test across comments and newlines */ 16322 EXPECT_EQ("float const a = 5;\n" 16323 "\n" 16324 "/* block comment */\n" 16325 "int oneTwoThree = 123;", 16326 format("float const a = 5;\n" 16327 "\n" 16328 "/* block comment */\n" 16329 "int oneTwoThree=123;", 16330 Alignment)); 16331 16332 EXPECT_EQ("float const a = 5;\n" 16333 "\n" 16334 "// line comment\n" 16335 "int oneTwoThree = 123;", 16336 format("float const a = 5;\n" 16337 "\n" 16338 "// line comment\n" 16339 "int oneTwoThree=123;", 16340 Alignment)); 16341 } 16342 16343 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16344 FormatStyle Alignment = getLLVMStyle(); 16345 Alignment.AlignConsecutiveBitFields.Enabled = true; 16346 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16347 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16348 16349 Alignment.MaxEmptyLinesToKeep = 10; 16350 /* Test alignment across empty lines */ 16351 EXPECT_EQ("int a : 5;\n" 16352 "\n" 16353 "int longbitfield : 6;", 16354 format("int a : 5;\n" 16355 "\n" 16356 "int longbitfield : 6;", 16357 Alignment)); 16358 EXPECT_EQ("int a : 5;\n" 16359 "int one : 1;\n" 16360 "\n" 16361 "int longbitfield : 6;", 16362 format("int a : 5;\n" 16363 "int one : 1;\n" 16364 "\n" 16365 "int longbitfield : 6;", 16366 Alignment)); 16367 16368 /* Test across comments */ 16369 EXPECT_EQ("int a : 5;\n" 16370 "/* block comment */\n" 16371 "int longbitfield : 6;", 16372 format("int a : 5;\n" 16373 "/* block comment */\n" 16374 "int longbitfield : 6;", 16375 Alignment)); 16376 EXPECT_EQ("int a : 5;\n" 16377 "int one : 1;\n" 16378 "// line comment\n" 16379 "int longbitfield : 6;", 16380 format("int a : 5;\n" 16381 "int one : 1;\n" 16382 "// line comment\n" 16383 "int longbitfield : 6;", 16384 Alignment)); 16385 16386 /* Test across comments and newlines */ 16387 EXPECT_EQ("int a : 5;\n" 16388 "/* block comment */\n" 16389 "\n" 16390 "int longbitfield : 6;", 16391 format("int a : 5;\n" 16392 "/* block comment */\n" 16393 "\n" 16394 "int longbitfield : 6;", 16395 Alignment)); 16396 EXPECT_EQ("int a : 5;\n" 16397 "int one : 1;\n" 16398 "\n" 16399 "// line comment\n" 16400 "\n" 16401 "int longbitfield : 6;", 16402 format("int a : 5;\n" 16403 "int one : 1;\n" 16404 "\n" 16405 "// line comment \n" 16406 "\n" 16407 "int longbitfield : 6;", 16408 Alignment)); 16409 } 16410 16411 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16412 FormatStyle Alignment = getLLVMStyle(); 16413 Alignment.AlignConsecutiveMacros.Enabled = true; 16414 Alignment.AlignConsecutiveAssignments.Enabled = true; 16415 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16416 16417 Alignment.MaxEmptyLinesToKeep = 10; 16418 /* Test alignment across empty lines */ 16419 EXPECT_EQ("int a = 5;\n" 16420 "\n" 16421 "int oneTwoThree = 123;", 16422 format("int a = 5;\n" 16423 "\n" 16424 "int oneTwoThree= 123;", 16425 Alignment)); 16426 EXPECT_EQ("int a = 5;\n" 16427 "int one = 1;\n" 16428 "\n" 16429 "int oneTwoThree = 123;", 16430 format("int a = 5;\n" 16431 "int one = 1;\n" 16432 "\n" 16433 "int oneTwoThree = 123;", 16434 Alignment)); 16435 16436 /* Test across comments */ 16437 EXPECT_EQ("int a = 5;\n" 16438 "/* block comment */\n" 16439 "int oneTwoThree = 123;", 16440 format("int a = 5;\n" 16441 "/* block comment */\n" 16442 "int oneTwoThree=123;", 16443 Alignment)); 16444 16445 EXPECT_EQ("int a = 5;\n" 16446 "// line comment\n" 16447 "int oneTwoThree = 123;", 16448 format("int a = 5;\n" 16449 "// line comment\n" 16450 "int oneTwoThree=123;", 16451 Alignment)); 16452 16453 EXPECT_EQ("int a = 5;\n" 16454 "/*\n" 16455 " * multi-line block comment\n" 16456 " */\n" 16457 "int oneTwoThree = 123;", 16458 format("int a = 5;\n" 16459 "/*\n" 16460 " * multi-line block comment\n" 16461 " */\n" 16462 "int oneTwoThree=123;", 16463 Alignment)); 16464 16465 EXPECT_EQ("int a = 5;\n" 16466 "//\n" 16467 "// multi-line line comment\n" 16468 "//\n" 16469 "int oneTwoThree = 123;", 16470 format("int a = 5;\n" 16471 "//\n" 16472 "// multi-line line comment\n" 16473 "//\n" 16474 "int oneTwoThree=123;", 16475 Alignment)); 16476 16477 /* Test across comments and newlines */ 16478 EXPECT_EQ("int a = 5;\n" 16479 "\n" 16480 "/* block comment */\n" 16481 "int oneTwoThree = 123;", 16482 format("int a = 5;\n" 16483 "\n" 16484 "/* block comment */\n" 16485 "int oneTwoThree=123;", 16486 Alignment)); 16487 16488 EXPECT_EQ("int a = 5;\n" 16489 "\n" 16490 "// line comment\n" 16491 "int oneTwoThree = 123;", 16492 format("int a = 5;\n" 16493 "\n" 16494 "// line comment\n" 16495 "int oneTwoThree=123;", 16496 Alignment)); 16497 } 16498 16499 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16500 FormatStyle Alignment = getLLVMStyle(); 16501 Alignment.AlignConsecutiveMacros.Enabled = true; 16502 Alignment.AlignConsecutiveAssignments.Enabled = true; 16503 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16504 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16505 verifyFormat("int a = 5;\n" 16506 "int oneTwoThree = 123;", 16507 Alignment); 16508 verifyFormat("int a = method();\n" 16509 "int oneTwoThree = 133;", 16510 Alignment); 16511 verifyFormat("a &= 5;\n" 16512 "bcd *= 5;\n" 16513 "ghtyf += 5;\n" 16514 "dvfvdb -= 5;\n" 16515 "a /= 5;\n" 16516 "vdsvsv %= 5;\n" 16517 "sfdbddfbdfbb ^= 5;\n" 16518 "dvsdsv |= 5;\n" 16519 "int dsvvdvsdvvv = 123;", 16520 Alignment); 16521 verifyFormat("int i = 1, j = 10;\n" 16522 "something = 2000;", 16523 Alignment); 16524 verifyFormat("something = 2000;\n" 16525 "int i = 1, j = 10;\n", 16526 Alignment); 16527 verifyFormat("something = 2000;\n" 16528 "another = 911;\n" 16529 "int i = 1, j = 10;\n" 16530 "oneMore = 1;\n" 16531 "i = 2;", 16532 Alignment); 16533 verifyFormat("int a = 5;\n" 16534 "int one = 1;\n" 16535 "method();\n" 16536 "int oneTwoThree = 123;\n" 16537 "int oneTwo = 12;", 16538 Alignment); 16539 verifyFormat("int oneTwoThree = 123;\n" 16540 "int oneTwo = 12;\n" 16541 "method();\n", 16542 Alignment); 16543 verifyFormat("int oneTwoThree = 123; // comment\n" 16544 "int oneTwo = 12; // comment", 16545 Alignment); 16546 16547 // Bug 25167 16548 /* Uncomment when fixed 16549 verifyFormat("#if A\n" 16550 "#else\n" 16551 "int aaaaaaaa = 12;\n" 16552 "#endif\n" 16553 "#if B\n" 16554 "#else\n" 16555 "int a = 12;\n" 16556 "#endif\n", 16557 Alignment); 16558 verifyFormat("enum foo {\n" 16559 "#if A\n" 16560 "#else\n" 16561 " aaaaaaaa = 12;\n" 16562 "#endif\n" 16563 "#if B\n" 16564 "#else\n" 16565 " a = 12;\n" 16566 "#endif\n" 16567 "};\n", 16568 Alignment); 16569 */ 16570 16571 Alignment.MaxEmptyLinesToKeep = 10; 16572 /* Test alignment across empty lines */ 16573 EXPECT_EQ("int a = 5;\n" 16574 "\n" 16575 "int oneTwoThree = 123;", 16576 format("int a = 5;\n" 16577 "\n" 16578 "int oneTwoThree= 123;", 16579 Alignment)); 16580 EXPECT_EQ("int a = 5;\n" 16581 "int one = 1;\n" 16582 "\n" 16583 "int oneTwoThree = 123;", 16584 format("int a = 5;\n" 16585 "int one = 1;\n" 16586 "\n" 16587 "int oneTwoThree = 123;", 16588 Alignment)); 16589 EXPECT_EQ("int a = 5;\n" 16590 "int one = 1;\n" 16591 "\n" 16592 "int oneTwoThree = 123;\n" 16593 "int oneTwo = 12;", 16594 format("int a = 5;\n" 16595 "int one = 1;\n" 16596 "\n" 16597 "int oneTwoThree = 123;\n" 16598 "int oneTwo = 12;", 16599 Alignment)); 16600 16601 /* Test across comments */ 16602 EXPECT_EQ("int a = 5;\n" 16603 "/* block comment */\n" 16604 "int oneTwoThree = 123;", 16605 format("int a = 5;\n" 16606 "/* block comment */\n" 16607 "int oneTwoThree=123;", 16608 Alignment)); 16609 16610 EXPECT_EQ("int a = 5;\n" 16611 "// line comment\n" 16612 "int oneTwoThree = 123;", 16613 format("int a = 5;\n" 16614 "// line comment\n" 16615 "int oneTwoThree=123;", 16616 Alignment)); 16617 16618 /* Test across comments and newlines */ 16619 EXPECT_EQ("int a = 5;\n" 16620 "\n" 16621 "/* block comment */\n" 16622 "int oneTwoThree = 123;", 16623 format("int a = 5;\n" 16624 "\n" 16625 "/* block comment */\n" 16626 "int oneTwoThree=123;", 16627 Alignment)); 16628 16629 EXPECT_EQ("int a = 5;\n" 16630 "\n" 16631 "// line comment\n" 16632 "int oneTwoThree = 123;", 16633 format("int a = 5;\n" 16634 "\n" 16635 "// line comment\n" 16636 "int oneTwoThree=123;", 16637 Alignment)); 16638 16639 EXPECT_EQ("int a = 5;\n" 16640 "//\n" 16641 "// multi-line line comment\n" 16642 "//\n" 16643 "int oneTwoThree = 123;", 16644 format("int a = 5;\n" 16645 "//\n" 16646 "// multi-line line comment\n" 16647 "//\n" 16648 "int oneTwoThree=123;", 16649 Alignment)); 16650 16651 EXPECT_EQ("int a = 5;\n" 16652 "/*\n" 16653 " * multi-line block comment\n" 16654 " */\n" 16655 "int oneTwoThree = 123;", 16656 format("int a = 5;\n" 16657 "/*\n" 16658 " * multi-line block comment\n" 16659 " */\n" 16660 "int oneTwoThree=123;", 16661 Alignment)); 16662 16663 EXPECT_EQ("int a = 5;\n" 16664 "\n" 16665 "/* block comment */\n" 16666 "\n" 16667 "\n" 16668 "\n" 16669 "int oneTwoThree = 123;", 16670 format("int a = 5;\n" 16671 "\n" 16672 "/* block comment */\n" 16673 "\n" 16674 "\n" 16675 "\n" 16676 "int oneTwoThree=123;", 16677 Alignment)); 16678 16679 EXPECT_EQ("int a = 5;\n" 16680 "\n" 16681 "// line comment\n" 16682 "\n" 16683 "\n" 16684 "\n" 16685 "int oneTwoThree = 123;", 16686 format("int a = 5;\n" 16687 "\n" 16688 "// line comment\n" 16689 "\n" 16690 "\n" 16691 "\n" 16692 "int oneTwoThree=123;", 16693 Alignment)); 16694 16695 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16696 verifyFormat("#define A \\\n" 16697 " int aaaa = 12; \\\n" 16698 " int b = 23; \\\n" 16699 " int ccc = 234; \\\n" 16700 " int dddddddddd = 2345;", 16701 Alignment); 16702 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16703 verifyFormat("#define A \\\n" 16704 " int aaaa = 12; \\\n" 16705 " int b = 23; \\\n" 16706 " int ccc = 234; \\\n" 16707 " int dddddddddd = 2345;", 16708 Alignment); 16709 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16710 verifyFormat("#define A " 16711 " \\\n" 16712 " int aaaa = 12; " 16713 " \\\n" 16714 " int b = 23; " 16715 " \\\n" 16716 " int ccc = 234; " 16717 " \\\n" 16718 " int dddddddddd = 2345;", 16719 Alignment); 16720 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16721 "k = 4, int l = 5,\n" 16722 " int m = 6) {\n" 16723 " int j = 10;\n" 16724 " otherThing = 1;\n" 16725 "}", 16726 Alignment); 16727 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16728 " int i = 1;\n" 16729 " int j = 2;\n" 16730 " int big = 10000;\n" 16731 "}", 16732 Alignment); 16733 verifyFormat("class C {\n" 16734 "public:\n" 16735 " int i = 1;\n" 16736 " virtual void f() = 0;\n" 16737 "};", 16738 Alignment); 16739 verifyFormat("int i = 1;\n" 16740 "if (SomeType t = getSomething()) {\n" 16741 "}\n" 16742 "int j = 2;\n" 16743 "int big = 10000;", 16744 Alignment); 16745 verifyFormat("int j = 7;\n" 16746 "for (int k = 0; k < N; ++k) {\n" 16747 "}\n" 16748 "int j = 2;\n" 16749 "int big = 10000;\n" 16750 "}", 16751 Alignment); 16752 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16753 verifyFormat("int i = 1;\n" 16754 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16755 " = someLooooooooooooooooongFunction();\n" 16756 "int j = 2;", 16757 Alignment); 16758 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16759 verifyFormat("int i = 1;\n" 16760 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16761 " someLooooooooooooooooongFunction();\n" 16762 "int j = 2;", 16763 Alignment); 16764 16765 verifyFormat("auto lambda = []() {\n" 16766 " auto i = 0;\n" 16767 " return 0;\n" 16768 "};\n" 16769 "int i = 0;\n" 16770 "auto v = type{\n" 16771 " i = 1, //\n" 16772 " (i = 2), //\n" 16773 " i = 3 //\n" 16774 "};", 16775 Alignment); 16776 16777 verifyFormat( 16778 "int i = 1;\n" 16779 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16780 " loooooooooooooooooooooongParameterB);\n" 16781 "int j = 2;", 16782 Alignment); 16783 16784 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16785 " typename B = very_long_type_name_1,\n" 16786 " typename T_2 = very_long_type_name_2>\n" 16787 "auto foo() {}\n", 16788 Alignment); 16789 verifyFormat("int a, b = 1;\n" 16790 "int c = 2;\n" 16791 "int dd = 3;\n", 16792 Alignment); 16793 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16794 "float b[1][] = {{3.f}};\n", 16795 Alignment); 16796 verifyFormat("for (int i = 0; i < 1; i++)\n" 16797 " int x = 1;\n", 16798 Alignment); 16799 verifyFormat("for (i = 0; i < 1; i++)\n" 16800 " x = 1;\n" 16801 "y = 1;\n", 16802 Alignment); 16803 16804 Alignment.ReflowComments = true; 16805 Alignment.ColumnLimit = 50; 16806 EXPECT_EQ("int x = 0;\n" 16807 "int yy = 1; /// specificlennospace\n" 16808 "int zzz = 2;\n", 16809 format("int x = 0;\n" 16810 "int yy = 1; ///specificlennospace\n" 16811 "int zzz = 2;\n", 16812 Alignment)); 16813 } 16814 16815 TEST_F(FormatTest, AlignCompoundAssignments) { 16816 FormatStyle Alignment = getLLVMStyle(); 16817 Alignment.AlignConsecutiveAssignments.Enabled = true; 16818 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 16819 Alignment.AlignConsecutiveAssignments.PadOperators = false; 16820 verifyFormat("sfdbddfbdfbb = 5;\n" 16821 "dvsdsv = 5;\n" 16822 "int dsvvdvsdvvv = 123;", 16823 Alignment); 16824 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16825 "dvsdsv |= 5;\n" 16826 "int dsvvdvsdvvv = 123;", 16827 Alignment); 16828 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16829 "dvsdsv <<= 5;\n" 16830 "int dsvvdvsdvvv = 123;", 16831 Alignment); 16832 // Test that `<=` is not treated as a compound assignment. 16833 verifyFormat("aa &= 5;\n" 16834 "b <= 10;\n" 16835 "c = 15;", 16836 Alignment); 16837 Alignment.AlignConsecutiveAssignments.PadOperators = true; 16838 verifyFormat("sfdbddfbdfbb = 5;\n" 16839 "dvsdsv = 5;\n" 16840 "int dsvvdvsdvvv = 123;", 16841 Alignment); 16842 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16843 "dvsdsv |= 5;\n" 16844 "int dsvvdvsdvvv = 123;", 16845 Alignment); 16846 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16847 "dvsdsv <<= 5;\n" 16848 "int dsvvdvsdvvv = 123;", 16849 Alignment); 16850 EXPECT_EQ("a += 5;\n" 16851 "one = 1;\n" 16852 "\n" 16853 "oneTwoThree = 123;\n", 16854 format("a += 5;\n" 16855 "one = 1;\n" 16856 "\n" 16857 "oneTwoThree = 123;\n", 16858 Alignment)); 16859 EXPECT_EQ("a += 5;\n" 16860 "one = 1;\n" 16861 "//\n" 16862 "oneTwoThree = 123;\n", 16863 format("a += 5;\n" 16864 "one = 1;\n" 16865 "//\n" 16866 "oneTwoThree = 123;\n", 16867 Alignment)); 16868 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16869 EXPECT_EQ("a += 5;\n" 16870 "one = 1;\n" 16871 "\n" 16872 "oneTwoThree = 123;\n", 16873 format("a += 5;\n" 16874 "one = 1;\n" 16875 "\n" 16876 "oneTwoThree = 123;\n", 16877 Alignment)); 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 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 16888 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16889 EXPECT_EQ("a += 5;\n" 16890 "one = 1;\n" 16891 "\n" 16892 "oneTwoThree = 123;\n", 16893 format("a += 5;\n" 16894 "one = 1;\n" 16895 "\n" 16896 "oneTwoThree = 123;\n", 16897 Alignment)); 16898 EXPECT_EQ("a += 5;\n" 16899 "one = 1;\n" 16900 "//\n" 16901 "oneTwoThree = 123;\n", 16902 format("a += 5;\n" 16903 "one = 1;\n" 16904 "//\n" 16905 "oneTwoThree = 123;\n", 16906 Alignment)); 16907 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16908 EXPECT_EQ("a += 5;\n" 16909 "one >>= 1;\n" 16910 "\n" 16911 "oneTwoThree = 123;\n", 16912 format("a += 5;\n" 16913 "one >>= 1;\n" 16914 "\n" 16915 "oneTwoThree = 123;\n", 16916 Alignment)); 16917 EXPECT_EQ("a += 5;\n" 16918 "one = 1;\n" 16919 "//\n" 16920 "oneTwoThree <<= 123;\n", 16921 format("a += 5;\n" 16922 "one = 1;\n" 16923 "//\n" 16924 "oneTwoThree <<= 123;\n", 16925 Alignment)); 16926 } 16927 16928 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16929 FormatStyle Alignment = getLLVMStyle(); 16930 Alignment.AlignConsecutiveMacros.Enabled = true; 16931 verifyFormat("int a = 5;\n" 16932 "int oneTwoThree = 123;", 16933 Alignment); 16934 verifyFormat("int a = 5;\n" 16935 "int oneTwoThree = 123;", 16936 Alignment); 16937 16938 Alignment.AlignConsecutiveAssignments.Enabled = true; 16939 verifyFormat("int a = 5;\n" 16940 "int oneTwoThree = 123;", 16941 Alignment); 16942 verifyFormat("int a = method();\n" 16943 "int oneTwoThree = 133;", 16944 Alignment); 16945 verifyFormat("aa <= 5;\n" 16946 "a &= 5;\n" 16947 "bcd *= 5;\n" 16948 "ghtyf += 5;\n" 16949 "dvfvdb -= 5;\n" 16950 "a /= 5;\n" 16951 "vdsvsv %= 5;\n" 16952 "sfdbddfbdfbb ^= 5;\n" 16953 "dvsdsv |= 5;\n" 16954 "int dsvvdvsdvvv = 123;", 16955 Alignment); 16956 verifyFormat("int i = 1, j = 10;\n" 16957 "something = 2000;", 16958 Alignment); 16959 verifyFormat("something = 2000;\n" 16960 "int i = 1, j = 10;\n", 16961 Alignment); 16962 verifyFormat("something = 2000;\n" 16963 "another = 911;\n" 16964 "int i = 1, j = 10;\n" 16965 "oneMore = 1;\n" 16966 "i = 2;", 16967 Alignment); 16968 verifyFormat("int a = 5;\n" 16969 "int one = 1;\n" 16970 "method();\n" 16971 "int oneTwoThree = 123;\n" 16972 "int oneTwo = 12;", 16973 Alignment); 16974 verifyFormat("int oneTwoThree = 123;\n" 16975 "int oneTwo = 12;\n" 16976 "method();\n", 16977 Alignment); 16978 verifyFormat("int oneTwoThree = 123; // comment\n" 16979 "int oneTwo = 12; // comment", 16980 Alignment); 16981 verifyFormat("int f() = default;\n" 16982 "int &operator() = default;\n" 16983 "int &operator=() {", 16984 Alignment); 16985 verifyFormat("int f() = delete;\n" 16986 "int &operator() = delete;\n" 16987 "int &operator=() {", 16988 Alignment); 16989 verifyFormat("int f() = default; // comment\n" 16990 "int &operator() = default; // comment\n" 16991 "int &operator=() {", 16992 Alignment); 16993 verifyFormat("int f() = default;\n" 16994 "int &operator() = default;\n" 16995 "int &operator==() {", 16996 Alignment); 16997 verifyFormat("int f() = default;\n" 16998 "int &operator() = default;\n" 16999 "int &operator<=() {", 17000 Alignment); 17001 verifyFormat("int f() = default;\n" 17002 "int &operator() = default;\n" 17003 "int &operator!=() {", 17004 Alignment); 17005 verifyFormat("int f() = default;\n" 17006 "int &operator() = default;\n" 17007 "int &operator=();", 17008 Alignment); 17009 verifyFormat("int f() = delete;\n" 17010 "int &operator() = delete;\n" 17011 "int &operator=();", 17012 Alignment); 17013 verifyFormat("/* long long padding */ int f() = default;\n" 17014 "int &operator() = default;\n" 17015 "int &operator/**/ =();", 17016 Alignment); 17017 // https://llvm.org/PR33697 17018 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17019 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17020 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17021 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17022 " void f() = delete;\n" 17023 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17024 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17025 "};\n", 17026 AlignmentWithPenalty); 17027 17028 // Bug 25167 17029 /* Uncomment when fixed 17030 verifyFormat("#if A\n" 17031 "#else\n" 17032 "int aaaaaaaa = 12;\n" 17033 "#endif\n" 17034 "#if B\n" 17035 "#else\n" 17036 "int a = 12;\n" 17037 "#endif\n", 17038 Alignment); 17039 verifyFormat("enum foo {\n" 17040 "#if A\n" 17041 "#else\n" 17042 " aaaaaaaa = 12;\n" 17043 "#endif\n" 17044 "#if B\n" 17045 "#else\n" 17046 " a = 12;\n" 17047 "#endif\n" 17048 "};\n", 17049 Alignment); 17050 */ 17051 17052 EXPECT_EQ("int a = 5;\n" 17053 "\n" 17054 "int oneTwoThree = 123;", 17055 format("int a = 5;\n" 17056 "\n" 17057 "int oneTwoThree= 123;", 17058 Alignment)); 17059 EXPECT_EQ("int a = 5;\n" 17060 "int one = 1;\n" 17061 "\n" 17062 "int oneTwoThree = 123;", 17063 format("int a = 5;\n" 17064 "int one = 1;\n" 17065 "\n" 17066 "int oneTwoThree = 123;", 17067 Alignment)); 17068 EXPECT_EQ("int a = 5;\n" 17069 "int one = 1;\n" 17070 "\n" 17071 "int oneTwoThree = 123;\n" 17072 "int oneTwo = 12;", 17073 format("int a = 5;\n" 17074 "int one = 1;\n" 17075 "\n" 17076 "int oneTwoThree = 123;\n" 17077 "int oneTwo = 12;", 17078 Alignment)); 17079 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17080 verifyFormat("#define A \\\n" 17081 " int aaaa = 12; \\\n" 17082 " int b = 23; \\\n" 17083 " int ccc = 234; \\\n" 17084 " int dddddddddd = 2345;", 17085 Alignment); 17086 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17087 verifyFormat("#define A \\\n" 17088 " int aaaa = 12; \\\n" 17089 " int b = 23; \\\n" 17090 " int ccc = 234; \\\n" 17091 " int dddddddddd = 2345;", 17092 Alignment); 17093 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17094 verifyFormat("#define A " 17095 " \\\n" 17096 " int aaaa = 12; " 17097 " \\\n" 17098 " int b = 23; " 17099 " \\\n" 17100 " int ccc = 234; " 17101 " \\\n" 17102 " int dddddddddd = 2345;", 17103 Alignment); 17104 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17105 "k = 4, int l = 5,\n" 17106 " int m = 6) {\n" 17107 " int j = 10;\n" 17108 " otherThing = 1;\n" 17109 "}", 17110 Alignment); 17111 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17112 " int i = 1;\n" 17113 " int j = 2;\n" 17114 " int big = 10000;\n" 17115 "}", 17116 Alignment); 17117 verifyFormat("class C {\n" 17118 "public:\n" 17119 " int i = 1;\n" 17120 " virtual void f() = 0;\n" 17121 "};", 17122 Alignment); 17123 verifyFormat("int i = 1;\n" 17124 "if (SomeType t = getSomething()) {\n" 17125 "}\n" 17126 "int j = 2;\n" 17127 "int big = 10000;", 17128 Alignment); 17129 verifyFormat("int j = 7;\n" 17130 "for (int k = 0; k < N; ++k) {\n" 17131 "}\n" 17132 "int j = 2;\n" 17133 "int big = 10000;\n" 17134 "}", 17135 Alignment); 17136 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17137 verifyFormat("int i = 1;\n" 17138 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17139 " = someLooooooooooooooooongFunction();\n" 17140 "int j = 2;", 17141 Alignment); 17142 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17143 verifyFormat("int i = 1;\n" 17144 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17145 " someLooooooooooooooooongFunction();\n" 17146 "int j = 2;", 17147 Alignment); 17148 17149 verifyFormat("auto lambda = []() {\n" 17150 " auto i = 0;\n" 17151 " return 0;\n" 17152 "};\n" 17153 "int i = 0;\n" 17154 "auto v = type{\n" 17155 " i = 1, //\n" 17156 " (i = 2), //\n" 17157 " i = 3 //\n" 17158 "};", 17159 Alignment); 17160 17161 verifyFormat( 17162 "int i = 1;\n" 17163 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17164 " loooooooooooooooooooooongParameterB);\n" 17165 "int j = 2;", 17166 Alignment); 17167 17168 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17169 " typename B = very_long_type_name_1,\n" 17170 " typename T_2 = very_long_type_name_2>\n" 17171 "auto foo() {}\n", 17172 Alignment); 17173 verifyFormat("int a, b = 1;\n" 17174 "int c = 2;\n" 17175 "int dd = 3;\n", 17176 Alignment); 17177 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17178 "float b[1][] = {{3.f}};\n", 17179 Alignment); 17180 verifyFormat("for (int i = 0; i < 1; i++)\n" 17181 " int x = 1;\n", 17182 Alignment); 17183 verifyFormat("for (i = 0; i < 1; i++)\n" 17184 " x = 1;\n" 17185 "y = 1;\n", 17186 Alignment); 17187 17188 EXPECT_EQ(Alignment.ReflowComments, true); 17189 Alignment.ColumnLimit = 50; 17190 EXPECT_EQ("int x = 0;\n" 17191 "int yy = 1; /// specificlennospace\n" 17192 "int zzz = 2;\n", 17193 format("int x = 0;\n" 17194 "int yy = 1; ///specificlennospace\n" 17195 "int zzz = 2;\n", 17196 Alignment)); 17197 17198 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17199 "auto b = [] {\n" 17200 " f();\n" 17201 " return;\n" 17202 "};", 17203 Alignment); 17204 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17205 "auto b = g([] {\n" 17206 " f();\n" 17207 " return;\n" 17208 "});", 17209 Alignment); 17210 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17211 "auto b = g(param, [] {\n" 17212 " f();\n" 17213 " return;\n" 17214 "});", 17215 Alignment); 17216 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17217 "auto b = [] {\n" 17218 " if (condition) {\n" 17219 " return;\n" 17220 " }\n" 17221 "};", 17222 Alignment); 17223 17224 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17225 " ccc ? aaaaa : bbbbb,\n" 17226 " dddddddddddddddddddddddddd);", 17227 Alignment); 17228 // FIXME: https://llvm.org/PR53497 17229 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17230 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17231 // " ccc ? aaaaa : bbbbb,\n" 17232 // " dddddddddddddddddddddddddd);", 17233 // Alignment); 17234 } 17235 17236 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17237 FormatStyle Alignment = getLLVMStyle(); 17238 Alignment.AlignConsecutiveBitFields.Enabled = true; 17239 verifyFormat("int const a : 5;\n" 17240 "int oneTwoThree : 23;", 17241 Alignment); 17242 17243 // Initializers are allowed starting with c++2a 17244 verifyFormat("int const a : 5 = 1;\n" 17245 "int oneTwoThree : 23 = 0;", 17246 Alignment); 17247 17248 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17249 verifyFormat("int const a : 5;\n" 17250 "int oneTwoThree : 23;", 17251 Alignment); 17252 17253 verifyFormat("int const a : 5; // comment\n" 17254 "int oneTwoThree : 23; // comment", 17255 Alignment); 17256 17257 verifyFormat("int const a : 5 = 1;\n" 17258 "int oneTwoThree : 23 = 0;", 17259 Alignment); 17260 17261 Alignment.AlignConsecutiveAssignments.Enabled = true; 17262 verifyFormat("int const a : 5 = 1;\n" 17263 "int oneTwoThree : 23 = 0;", 17264 Alignment); 17265 verifyFormat("int const a : 5 = {1};\n" 17266 "int oneTwoThree : 23 = 0;", 17267 Alignment); 17268 17269 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17270 verifyFormat("int const a :5;\n" 17271 "int oneTwoThree:23;", 17272 Alignment); 17273 17274 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17275 verifyFormat("int const a :5;\n" 17276 "int oneTwoThree :23;", 17277 Alignment); 17278 17279 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17280 verifyFormat("int const a : 5;\n" 17281 "int oneTwoThree: 23;", 17282 Alignment); 17283 17284 // Known limitations: ':' is only recognized as a bitfield colon when 17285 // followed by a number. 17286 /* 17287 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17288 "int a : 5;", 17289 Alignment); 17290 */ 17291 } 17292 17293 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17294 FormatStyle Alignment = getLLVMStyle(); 17295 Alignment.AlignConsecutiveMacros.Enabled = true; 17296 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17297 verifyFormat("float const a = 5;\n" 17298 "int oneTwoThree = 123;", 17299 Alignment); 17300 verifyFormat("int a = 5;\n" 17301 "float const oneTwoThree = 123;", 17302 Alignment); 17303 17304 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17305 verifyFormat("float const a = 5;\n" 17306 "int oneTwoThree = 123;", 17307 Alignment); 17308 verifyFormat("int a = method();\n" 17309 "float const oneTwoThree = 133;", 17310 Alignment); 17311 verifyFormat("int i = 1, j = 10;\n" 17312 "something = 2000;", 17313 Alignment); 17314 verifyFormat("something = 2000;\n" 17315 "int i = 1, j = 10;\n", 17316 Alignment); 17317 verifyFormat("float something = 2000;\n" 17318 "double another = 911;\n" 17319 "int i = 1, j = 10;\n" 17320 "const int *oneMore = 1;\n" 17321 "unsigned i = 2;", 17322 Alignment); 17323 verifyFormat("float a = 5;\n" 17324 "int one = 1;\n" 17325 "method();\n" 17326 "const double oneTwoThree = 123;\n" 17327 "const unsigned int oneTwo = 12;", 17328 Alignment); 17329 verifyFormat("int oneTwoThree{0}; // comment\n" 17330 "unsigned oneTwo; // comment", 17331 Alignment); 17332 verifyFormat("unsigned int *a;\n" 17333 "int *b;\n" 17334 "unsigned int Const *c;\n" 17335 "unsigned int const *d;\n" 17336 "unsigned int Const &e;\n" 17337 "unsigned int const &f;", 17338 Alignment); 17339 verifyFormat("Const unsigned int *c;\n" 17340 "const unsigned int *d;\n" 17341 "Const unsigned int &e;\n" 17342 "const unsigned int &f;\n" 17343 "const unsigned g;\n" 17344 "Const unsigned h;", 17345 Alignment); 17346 EXPECT_EQ("float const a = 5;\n" 17347 "\n" 17348 "int oneTwoThree = 123;", 17349 format("float const a = 5;\n" 17350 "\n" 17351 "int oneTwoThree= 123;", 17352 Alignment)); 17353 EXPECT_EQ("float a = 5;\n" 17354 "int one = 1;\n" 17355 "\n" 17356 "unsigned oneTwoThree = 123;", 17357 format("float a = 5;\n" 17358 "int one = 1;\n" 17359 "\n" 17360 "unsigned oneTwoThree = 123;", 17361 Alignment)); 17362 EXPECT_EQ("float a = 5;\n" 17363 "int one = 1;\n" 17364 "\n" 17365 "unsigned oneTwoThree = 123;\n" 17366 "int oneTwo = 12;", 17367 format("float a = 5;\n" 17368 "int one = 1;\n" 17369 "\n" 17370 "unsigned oneTwoThree = 123;\n" 17371 "int oneTwo = 12;", 17372 Alignment)); 17373 // Function prototype alignment 17374 verifyFormat("int a();\n" 17375 "double b();", 17376 Alignment); 17377 verifyFormat("int a(int x);\n" 17378 "double b();", 17379 Alignment); 17380 unsigned OldColumnLimit = Alignment.ColumnLimit; 17381 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17382 // otherwise the function parameters will be re-flowed onto a single line. 17383 Alignment.ColumnLimit = 0; 17384 EXPECT_EQ("int a(int x,\n" 17385 " float y);\n" 17386 "double b(int x,\n" 17387 " double y);", 17388 format("int a(int x,\n" 17389 " float y);\n" 17390 "double b(int x,\n" 17391 " double y);", 17392 Alignment)); 17393 // This ensures that function parameters of function declarations are 17394 // correctly indented when their owning functions are indented. 17395 // The failure case here is for 'double y' to not be indented enough. 17396 EXPECT_EQ("double a(int x);\n" 17397 "int b(int y,\n" 17398 " double z);", 17399 format("double a(int x);\n" 17400 "int b(int y,\n" 17401 " double z);", 17402 Alignment)); 17403 // Set ColumnLimit low so that we induce wrapping immediately after 17404 // the function name and opening paren. 17405 Alignment.ColumnLimit = 13; 17406 verifyFormat("int function(\n" 17407 " int x,\n" 17408 " bool y);", 17409 Alignment); 17410 Alignment.ColumnLimit = OldColumnLimit; 17411 // Ensure function pointers don't screw up recursive alignment 17412 verifyFormat("int a(int x, void (*fp)(int y));\n" 17413 "double b();", 17414 Alignment); 17415 Alignment.AlignConsecutiveAssignments.Enabled = true; 17416 // Ensure recursive alignment is broken by function braces, so that the 17417 // "a = 1" does not align with subsequent assignments inside the function 17418 // body. 17419 verifyFormat("int func(int a = 1) {\n" 17420 " int b = 2;\n" 17421 " int cc = 3;\n" 17422 "}", 17423 Alignment); 17424 verifyFormat("float something = 2000;\n" 17425 "double another = 911;\n" 17426 "int i = 1, j = 10;\n" 17427 "const int *oneMore = 1;\n" 17428 "unsigned i = 2;", 17429 Alignment); 17430 verifyFormat("int oneTwoThree = {0}; // comment\n" 17431 "unsigned oneTwo = 0; // comment", 17432 Alignment); 17433 // Make sure that scope is correctly tracked, in the absence of braces 17434 verifyFormat("for (int i = 0; i < n; i++)\n" 17435 " j = i;\n" 17436 "double x = 1;\n", 17437 Alignment); 17438 verifyFormat("if (int i = 0)\n" 17439 " j = i;\n" 17440 "double x = 1;\n", 17441 Alignment); 17442 // Ensure operator[] and operator() are comprehended 17443 verifyFormat("struct test {\n" 17444 " long long int foo();\n" 17445 " int operator[](int a);\n" 17446 " double bar();\n" 17447 "};\n", 17448 Alignment); 17449 verifyFormat("struct test {\n" 17450 " long long int foo();\n" 17451 " int operator()(int a);\n" 17452 " double bar();\n" 17453 "};\n", 17454 Alignment); 17455 // http://llvm.org/PR52914 17456 verifyFormat("char *a[] = {\"a\", // comment\n" 17457 " \"bb\"};\n" 17458 "int bbbbbbb = 0;", 17459 Alignment); 17460 17461 // PAS_Right 17462 EXPECT_EQ("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 format("void SomeFunction(int parameter= 0) {\n" 17474 " int const i= 1;\n" 17475 " int *j=2;\n" 17476 " int big = 10000;\n" 17477 "\n" 17478 "unsigned oneTwoThree =123;\n" 17479 "int oneTwo = 12;\n" 17480 " method();\n" 17481 "float k= 2;\n" 17482 "int ll=10000;\n" 17483 "}", 17484 Alignment)); 17485 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17486 " int const i = 1;\n" 17487 " int **j = 2, ***k;\n" 17488 " int &k = i;\n" 17489 " int &&l = i + j;\n" 17490 " int big = 10000;\n" 17491 "\n" 17492 " unsigned oneTwoThree = 123;\n" 17493 " int oneTwo = 12;\n" 17494 " method();\n" 17495 " float k = 2;\n" 17496 " int ll = 10000;\n" 17497 "}", 17498 format("void SomeFunction(int parameter= 0) {\n" 17499 " int const i= 1;\n" 17500 " int **j=2,***k;\n" 17501 "int &k=i;\n" 17502 "int &&l=i+j;\n" 17503 " int big = 10000;\n" 17504 "\n" 17505 "unsigned oneTwoThree =123;\n" 17506 "int oneTwo = 12;\n" 17507 " method();\n" 17508 "float k= 2;\n" 17509 "int ll=10000;\n" 17510 "}", 17511 Alignment)); 17512 // variables are aligned at their name, pointers are at the right most 17513 // position 17514 verifyFormat("int *a;\n" 17515 "int **b;\n" 17516 "int ***c;\n" 17517 "int foobar;\n", 17518 Alignment); 17519 17520 // PAS_Left 17521 FormatStyle AlignmentLeft = Alignment; 17522 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17523 EXPECT_EQ("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 format("void SomeFunction(int parameter= 0) {\n" 17535 " int const i= 1;\n" 17536 " int *j=2;\n" 17537 " int big = 10000;\n" 17538 "\n" 17539 "unsigned oneTwoThree =123;\n" 17540 "int oneTwo = 12;\n" 17541 " method();\n" 17542 "float k= 2;\n" 17543 "int ll=10000;\n" 17544 "}", 17545 AlignmentLeft)); 17546 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17547 " int const i = 1;\n" 17548 " int** j = 2;\n" 17549 " int& k = i;\n" 17550 " int&& l = i + j;\n" 17551 " int big = 10000;\n" 17552 "\n" 17553 " unsigned oneTwoThree = 123;\n" 17554 " int oneTwo = 12;\n" 17555 " method();\n" 17556 " float k = 2;\n" 17557 " int ll = 10000;\n" 17558 "}", 17559 format("void SomeFunction(int parameter= 0) {\n" 17560 " int const i= 1;\n" 17561 " int **j=2;\n" 17562 "int &k=i;\n" 17563 "int &&l=i+j;\n" 17564 " int big = 10000;\n" 17565 "\n" 17566 "unsigned oneTwoThree =123;\n" 17567 "int oneTwo = 12;\n" 17568 " method();\n" 17569 "float k= 2;\n" 17570 "int ll=10000;\n" 17571 "}", 17572 AlignmentLeft)); 17573 // variables are aligned at their name, pointers are at the left most position 17574 verifyFormat("int* a;\n" 17575 "int** b;\n" 17576 "int*** c;\n" 17577 "int foobar;\n", 17578 AlignmentLeft); 17579 17580 // PAS_Middle 17581 FormatStyle AlignmentMiddle = Alignment; 17582 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17583 EXPECT_EQ("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 format("void SomeFunction(int parameter= 0) {\n" 17595 " int const i= 1;\n" 17596 " int *j=2;\n" 17597 " int big = 10000;\n" 17598 "\n" 17599 "unsigned oneTwoThree =123;\n" 17600 "int oneTwo = 12;\n" 17601 " method();\n" 17602 "float k= 2;\n" 17603 "int ll=10000;\n" 17604 "}", 17605 AlignmentMiddle)); 17606 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17607 " int const i = 1;\n" 17608 " int ** j = 2, ***k;\n" 17609 " int & k = i;\n" 17610 " int && l = i + j;\n" 17611 " int big = 10000;\n" 17612 "\n" 17613 " unsigned oneTwoThree = 123;\n" 17614 " int oneTwo = 12;\n" 17615 " method();\n" 17616 " float k = 2;\n" 17617 " int ll = 10000;\n" 17618 "}", 17619 format("void SomeFunction(int parameter= 0) {\n" 17620 " int const i= 1;\n" 17621 " int **j=2,***k;\n" 17622 "int &k=i;\n" 17623 "int &&l=i+j;\n" 17624 " int big = 10000;\n" 17625 "\n" 17626 "unsigned oneTwoThree =123;\n" 17627 "int oneTwo = 12;\n" 17628 " method();\n" 17629 "float k= 2;\n" 17630 "int ll=10000;\n" 17631 "}", 17632 AlignmentMiddle)); 17633 // variables are aligned at their name, pointers are in the middle 17634 verifyFormat("int * a;\n" 17635 "int * b;\n" 17636 "int *** c;\n" 17637 "int foobar;\n", 17638 AlignmentMiddle); 17639 17640 Alignment.AlignConsecutiveAssignments.Enabled = false; 17641 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17642 verifyFormat("#define A \\\n" 17643 " int aaaa = 12; \\\n" 17644 " float b = 23; \\\n" 17645 " const int ccc = 234; \\\n" 17646 " unsigned dddddddddd = 2345;", 17647 Alignment); 17648 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17649 verifyFormat("#define A \\\n" 17650 " int aaaa = 12; \\\n" 17651 " float b = 23; \\\n" 17652 " const int ccc = 234; \\\n" 17653 " unsigned dddddddddd = 2345;", 17654 Alignment); 17655 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17656 Alignment.ColumnLimit = 30; 17657 verifyFormat("#define A \\\n" 17658 " int aaaa = 12; \\\n" 17659 " float b = 23; \\\n" 17660 " const int ccc = 234; \\\n" 17661 " int dddddddddd = 2345;", 17662 Alignment); 17663 Alignment.ColumnLimit = 80; 17664 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17665 "k = 4, int l = 5,\n" 17666 " int m = 6) {\n" 17667 " const int j = 10;\n" 17668 " otherThing = 1;\n" 17669 "}", 17670 Alignment); 17671 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17672 " int const i = 1;\n" 17673 " int *j = 2;\n" 17674 " int big = 10000;\n" 17675 "}", 17676 Alignment); 17677 verifyFormat("class C {\n" 17678 "public:\n" 17679 " int i = 1;\n" 17680 " virtual void f() = 0;\n" 17681 "};", 17682 Alignment); 17683 verifyFormat("float i = 1;\n" 17684 "if (SomeType t = getSomething()) {\n" 17685 "}\n" 17686 "const unsigned j = 2;\n" 17687 "int big = 10000;", 17688 Alignment); 17689 verifyFormat("float j = 7;\n" 17690 "for (int k = 0; k < N; ++k) {\n" 17691 "}\n" 17692 "unsigned j = 2;\n" 17693 "int big = 10000;\n" 17694 "}", 17695 Alignment); 17696 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17697 verifyFormat("float i = 1;\n" 17698 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17699 " = someLooooooooooooooooongFunction();\n" 17700 "int j = 2;", 17701 Alignment); 17702 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17703 verifyFormat("int i = 1;\n" 17704 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17705 " someLooooooooooooooooongFunction();\n" 17706 "int j = 2;", 17707 Alignment); 17708 17709 Alignment.AlignConsecutiveAssignments.Enabled = true; 17710 verifyFormat("auto lambda = []() {\n" 17711 " auto ii = 0;\n" 17712 " float j = 0;\n" 17713 " return 0;\n" 17714 "};\n" 17715 "int i = 0;\n" 17716 "float i2 = 0;\n" 17717 "auto v = type{\n" 17718 " i = 1, //\n" 17719 " (i = 2), //\n" 17720 " i = 3 //\n" 17721 "};", 17722 Alignment); 17723 Alignment.AlignConsecutiveAssignments.Enabled = false; 17724 17725 verifyFormat( 17726 "int i = 1;\n" 17727 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17728 " loooooooooooooooooooooongParameterB);\n" 17729 "int j = 2;", 17730 Alignment); 17731 17732 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17733 // We expect declarations and assignments to align, as long as it doesn't 17734 // exceed the column limit, starting a new alignment sequence whenever it 17735 // happens. 17736 Alignment.AlignConsecutiveAssignments.Enabled = true; 17737 Alignment.ColumnLimit = 30; 17738 verifyFormat("float ii = 1;\n" 17739 "unsigned j = 2;\n" 17740 "int someVerylongVariable = 1;\n" 17741 "AnotherLongType ll = 123456;\n" 17742 "VeryVeryLongType k = 2;\n" 17743 "int myvar = 1;", 17744 Alignment); 17745 Alignment.ColumnLimit = 80; 17746 Alignment.AlignConsecutiveAssignments.Enabled = false; 17747 17748 verifyFormat( 17749 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17750 " typename LongType, typename B>\n" 17751 "auto foo() {}\n", 17752 Alignment); 17753 verifyFormat("float a, b = 1;\n" 17754 "int c = 2;\n" 17755 "int dd = 3;\n", 17756 Alignment); 17757 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17758 "float b[1][] = {{3.f}};\n", 17759 Alignment); 17760 Alignment.AlignConsecutiveAssignments.Enabled = true; 17761 verifyFormat("float a, b = 1;\n" 17762 "int c = 2;\n" 17763 "int dd = 3;\n", 17764 Alignment); 17765 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17766 "float b[1][] = {{3.f}};\n", 17767 Alignment); 17768 Alignment.AlignConsecutiveAssignments.Enabled = false; 17769 17770 Alignment.ColumnLimit = 30; 17771 Alignment.BinPackParameters = false; 17772 verifyFormat("void foo(float a,\n" 17773 " float b,\n" 17774 " int c,\n" 17775 " uint32_t *d) {\n" 17776 " int *e = 0;\n" 17777 " float f = 0;\n" 17778 " double g = 0;\n" 17779 "}\n" 17780 "void bar(ino_t a,\n" 17781 " int b,\n" 17782 " uint32_t *c,\n" 17783 " bool d) {}\n", 17784 Alignment); 17785 Alignment.BinPackParameters = true; 17786 Alignment.ColumnLimit = 80; 17787 17788 // Bug 33507 17789 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17790 verifyFormat( 17791 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17792 " static const Version verVs2017;\n" 17793 " return true;\n" 17794 "});\n", 17795 Alignment); 17796 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17797 17798 // See llvm.org/PR35641 17799 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17800 verifyFormat("int func() { //\n" 17801 " int b;\n" 17802 " unsigned c;\n" 17803 "}", 17804 Alignment); 17805 17806 // See PR37175 17807 FormatStyle Style = getMozillaStyle(); 17808 Style.AlignConsecutiveDeclarations.Enabled = true; 17809 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17810 "foo(int a);", 17811 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17812 17813 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17814 verifyFormat("unsigned int* a;\n" 17815 "int* b;\n" 17816 "unsigned int Const* c;\n" 17817 "unsigned int const* d;\n" 17818 "unsigned int Const& e;\n" 17819 "unsigned int const& f;", 17820 Alignment); 17821 verifyFormat("Const unsigned int* c;\n" 17822 "const unsigned int* d;\n" 17823 "Const unsigned int& e;\n" 17824 "const unsigned int& f;\n" 17825 "const unsigned g;\n" 17826 "Const unsigned h;", 17827 Alignment); 17828 17829 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17830 verifyFormat("unsigned int * a;\n" 17831 "int * b;\n" 17832 "unsigned int Const * c;\n" 17833 "unsigned int const * d;\n" 17834 "unsigned int Const & e;\n" 17835 "unsigned int const & f;", 17836 Alignment); 17837 verifyFormat("Const unsigned int * c;\n" 17838 "const unsigned int * d;\n" 17839 "Const unsigned int & e;\n" 17840 "const unsigned int & f;\n" 17841 "const unsigned g;\n" 17842 "Const unsigned h;", 17843 Alignment); 17844 17845 // See PR46529 17846 FormatStyle BracedAlign = getLLVMStyle(); 17847 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 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 BracedAlign.Cpp11BracedListStyle = false; 17859 verifyFormat("const auto result{ []() {\n" 17860 " const auto something = 1;\n" 17861 " return 2;\n" 17862 "} };", 17863 BracedAlign); 17864 verifyFormat("int foo{ []() {\n" 17865 " int bar{ 0 };\n" 17866 " return 0;\n" 17867 "}() };", 17868 BracedAlign); 17869 } 17870 17871 TEST_F(FormatTest, AlignWithLineBreaks) { 17872 auto Style = getLLVMStyleWithColumns(120); 17873 17874 EXPECT_EQ(Style.AlignConsecutiveAssignments, 17875 FormatStyle::AlignConsecutiveStyle( 17876 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 17877 /*AcrossComments=*/false, /*AlignCompound=*/false, 17878 /*PadOperators=*/true})); 17879 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 17880 FormatStyle::AlignConsecutiveStyle({})); 17881 verifyFormat("void foo() {\n" 17882 " int myVar = 5;\n" 17883 " double x = 3.14;\n" 17884 " auto str = \"Hello \"\n" 17885 " \"World\";\n" 17886 " auto s = \"Hello \"\n" 17887 " \"Again\";\n" 17888 "}", 17889 Style); 17890 17891 // clang-format off 17892 verifyFormat("void foo() {\n" 17893 " const int capacityBefore = Entries.capacity();\n" 17894 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17895 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17896 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17897 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17898 "}", 17899 Style); 17900 // clang-format on 17901 17902 Style.AlignConsecutiveAssignments.Enabled = true; 17903 verifyFormat("void foo() {\n" 17904 " int myVar = 5;\n" 17905 " double x = 3.14;\n" 17906 " auto str = \"Hello \"\n" 17907 " \"World\";\n" 17908 " auto s = \"Hello \"\n" 17909 " \"Again\";\n" 17910 "}", 17911 Style); 17912 17913 // clang-format off 17914 verifyFormat("void foo() {\n" 17915 " const int capacityBefore = Entries.capacity();\n" 17916 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17917 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17918 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17919 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17920 "}", 17921 Style); 17922 // clang-format on 17923 17924 Style.AlignConsecutiveAssignments.Enabled = false; 17925 Style.AlignConsecutiveDeclarations.Enabled = true; 17926 verifyFormat("void foo() {\n" 17927 " int myVar = 5;\n" 17928 " double x = 3.14;\n" 17929 " auto str = \"Hello \"\n" 17930 " \"World\";\n" 17931 " auto s = \"Hello \"\n" 17932 " \"Again\";\n" 17933 "}", 17934 Style); 17935 17936 // clang-format off 17937 verifyFormat("void foo() {\n" 17938 " const int capacityBefore = Entries.capacity();\n" 17939 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17940 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17941 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17942 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17943 "}", 17944 Style); 17945 // clang-format on 17946 17947 Style.AlignConsecutiveAssignments.Enabled = true; 17948 Style.AlignConsecutiveDeclarations.Enabled = true; 17949 17950 verifyFormat("void foo() {\n" 17951 " int myVar = 5;\n" 17952 " double x = 3.14;\n" 17953 " auto str = \"Hello \"\n" 17954 " \"World\";\n" 17955 " auto s = \"Hello \"\n" 17956 " \"Again\";\n" 17957 "}", 17958 Style); 17959 17960 // clang-format off 17961 verifyFormat("void foo() {\n" 17962 " const int capacityBefore = Entries.capacity();\n" 17963 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17964 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17965 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17966 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17967 "}", 17968 Style); 17969 // clang-format on 17970 17971 Style = getLLVMStyleWithColumns(120); 17972 Style.AlignConsecutiveAssignments.Enabled = true; 17973 Style.ContinuationIndentWidth = 4; 17974 Style.IndentWidth = 4; 17975 17976 // clang-format off 17977 verifyFormat("void SomeFunc() {\n" 17978 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17979 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17980 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17981 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17982 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17983 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17984 "}", 17985 Style); 17986 // clang-format on 17987 17988 Style.BinPackArguments = false; 17989 17990 // clang-format off 17991 verifyFormat("void SomeFunc() {\n" 17992 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17993 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17994 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17995 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17996 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17997 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17998 "}", 17999 Style); 18000 // clang-format on 18001 } 18002 18003 TEST_F(FormatTest, AlignWithInitializerPeriods) { 18004 auto Style = getLLVMStyleWithColumns(60); 18005 18006 verifyFormat("void foo1(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 = true; 18016 Style.AlignConsecutiveDeclarations.Enabled = false; 18017 verifyFormat("void foo2(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 = false; 18027 Style.AlignConsecutiveDeclarations.Enabled = true; 18028 verifyFormat("void foo3(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 Style.AlignConsecutiveAssignments.Enabled = true; 18038 Style.AlignConsecutiveDeclarations.Enabled = true; 18039 verifyFormat("void foo4(void) {\n" 18040 " BYTE p[1] = 1;\n" 18041 " A B = {.one_foooooooooooooooo = 2,\n" 18042 " .two_fooooooooooooo = 3,\n" 18043 " .three_fooooooooooooo = 4};\n" 18044 " BYTE payload = 2;\n" 18045 "}", 18046 Style); 18047 } 18048 18049 TEST_F(FormatTest, LinuxBraceBreaking) { 18050 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18051 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18052 verifyFormat("namespace a\n" 18053 "{\n" 18054 "class A\n" 18055 "{\n" 18056 " void f()\n" 18057 " {\n" 18058 " if (true) {\n" 18059 " a();\n" 18060 " b();\n" 18061 " } else {\n" 18062 " a();\n" 18063 " }\n" 18064 " }\n" 18065 " void g() { return; }\n" 18066 "};\n" 18067 "struct B {\n" 18068 " int x;\n" 18069 "};\n" 18070 "} // namespace a\n", 18071 LinuxBraceStyle); 18072 verifyFormat("enum X {\n" 18073 " Y = 0,\n" 18074 "}\n", 18075 LinuxBraceStyle); 18076 verifyFormat("struct S {\n" 18077 " int Type;\n" 18078 " union {\n" 18079 " int x;\n" 18080 " double y;\n" 18081 " } Value;\n" 18082 " class C\n" 18083 " {\n" 18084 " MyFavoriteType Value;\n" 18085 " } Class;\n" 18086 "}\n", 18087 LinuxBraceStyle); 18088 } 18089 18090 TEST_F(FormatTest, MozillaBraceBreaking) { 18091 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18092 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18093 MozillaBraceStyle.FixNamespaceComments = false; 18094 verifyFormat("namespace a {\n" 18095 "class A\n" 18096 "{\n" 18097 " void f()\n" 18098 " {\n" 18099 " if (true) {\n" 18100 " a();\n" 18101 " b();\n" 18102 " }\n" 18103 " }\n" 18104 " void g() { return; }\n" 18105 "};\n" 18106 "enum E\n" 18107 "{\n" 18108 " A,\n" 18109 " // foo\n" 18110 " B,\n" 18111 " C\n" 18112 "};\n" 18113 "struct B\n" 18114 "{\n" 18115 " int x;\n" 18116 "};\n" 18117 "}\n", 18118 MozillaBraceStyle); 18119 verifyFormat("struct S\n" 18120 "{\n" 18121 " int Type;\n" 18122 " union\n" 18123 " {\n" 18124 " int x;\n" 18125 " double y;\n" 18126 " } Value;\n" 18127 " class C\n" 18128 " {\n" 18129 " MyFavoriteType Value;\n" 18130 " } Class;\n" 18131 "}\n", 18132 MozillaBraceStyle); 18133 } 18134 18135 TEST_F(FormatTest, StroustrupBraceBreaking) { 18136 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18137 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18138 verifyFormat("namespace a {\n" 18139 "class A {\n" 18140 " void f()\n" 18141 " {\n" 18142 " if (true) {\n" 18143 " a();\n" 18144 " b();\n" 18145 " }\n" 18146 " }\n" 18147 " void g() { return; }\n" 18148 "};\n" 18149 "struct B {\n" 18150 " int x;\n" 18151 "};\n" 18152 "} // namespace a\n", 18153 StroustrupBraceStyle); 18154 18155 verifyFormat("void foo()\n" 18156 "{\n" 18157 " if (a) {\n" 18158 " a();\n" 18159 " }\n" 18160 " else {\n" 18161 " b();\n" 18162 " }\n" 18163 "}\n", 18164 StroustrupBraceStyle); 18165 18166 verifyFormat("#ifdef _DEBUG\n" 18167 "int foo(int i = 0)\n" 18168 "#else\n" 18169 "int foo(int i = 5)\n" 18170 "#endif\n" 18171 "{\n" 18172 " return i;\n" 18173 "}", 18174 StroustrupBraceStyle); 18175 18176 verifyFormat("void foo() {}\n" 18177 "void bar()\n" 18178 "#ifdef _DEBUG\n" 18179 "{\n" 18180 " foo();\n" 18181 "}\n" 18182 "#else\n" 18183 "{\n" 18184 "}\n" 18185 "#endif", 18186 StroustrupBraceStyle); 18187 18188 verifyFormat("void foobar() { int i = 5; }\n" 18189 "#ifdef _DEBUG\n" 18190 "void bar() {}\n" 18191 "#else\n" 18192 "void bar() { foobar(); }\n" 18193 "#endif", 18194 StroustrupBraceStyle); 18195 } 18196 18197 TEST_F(FormatTest, AllmanBraceBreaking) { 18198 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18199 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18200 18201 EXPECT_EQ("namespace a\n" 18202 "{\n" 18203 "void f();\n" 18204 "void g();\n" 18205 "} // namespace a\n", 18206 format("namespace a\n" 18207 "{\n" 18208 "void f();\n" 18209 "void g();\n" 18210 "}\n", 18211 AllmanBraceStyle)); 18212 18213 verifyFormat("namespace a\n" 18214 "{\n" 18215 "class A\n" 18216 "{\n" 18217 " void f()\n" 18218 " {\n" 18219 " if (true)\n" 18220 " {\n" 18221 " a();\n" 18222 " b();\n" 18223 " }\n" 18224 " }\n" 18225 " void g() { return; }\n" 18226 "};\n" 18227 "struct B\n" 18228 "{\n" 18229 " int x;\n" 18230 "};\n" 18231 "union C\n" 18232 "{\n" 18233 "};\n" 18234 "} // namespace a", 18235 AllmanBraceStyle); 18236 18237 verifyFormat("void f()\n" 18238 "{\n" 18239 " if (true)\n" 18240 " {\n" 18241 " a();\n" 18242 " }\n" 18243 " else if (false)\n" 18244 " {\n" 18245 " b();\n" 18246 " }\n" 18247 " else\n" 18248 " {\n" 18249 " c();\n" 18250 " }\n" 18251 "}\n", 18252 AllmanBraceStyle); 18253 18254 verifyFormat("void f()\n" 18255 "{\n" 18256 " for (int i = 0; i < 10; ++i)\n" 18257 " {\n" 18258 " a();\n" 18259 " }\n" 18260 " while (false)\n" 18261 " {\n" 18262 " b();\n" 18263 " }\n" 18264 " do\n" 18265 " {\n" 18266 " c();\n" 18267 " } while (false)\n" 18268 "}\n", 18269 AllmanBraceStyle); 18270 18271 verifyFormat("void f(int a)\n" 18272 "{\n" 18273 " switch (a)\n" 18274 " {\n" 18275 " case 0:\n" 18276 " break;\n" 18277 " case 1:\n" 18278 " {\n" 18279 " break;\n" 18280 " }\n" 18281 " case 2:\n" 18282 " {\n" 18283 " }\n" 18284 " break;\n" 18285 " default:\n" 18286 " break;\n" 18287 " }\n" 18288 "}\n", 18289 AllmanBraceStyle); 18290 18291 verifyFormat("enum X\n" 18292 "{\n" 18293 " Y = 0,\n" 18294 "}\n", 18295 AllmanBraceStyle); 18296 verifyFormat("enum X\n" 18297 "{\n" 18298 " Y = 0\n" 18299 "}\n", 18300 AllmanBraceStyle); 18301 18302 verifyFormat("@interface BSApplicationController ()\n" 18303 "{\n" 18304 "@private\n" 18305 " id _extraIvar;\n" 18306 "}\n" 18307 "@end\n", 18308 AllmanBraceStyle); 18309 18310 verifyFormat("#ifdef _DEBUG\n" 18311 "int foo(int i = 0)\n" 18312 "#else\n" 18313 "int foo(int i = 5)\n" 18314 "#endif\n" 18315 "{\n" 18316 " return i;\n" 18317 "}", 18318 AllmanBraceStyle); 18319 18320 verifyFormat("void foo() {}\n" 18321 "void bar()\n" 18322 "#ifdef _DEBUG\n" 18323 "{\n" 18324 " foo();\n" 18325 "}\n" 18326 "#else\n" 18327 "{\n" 18328 "}\n" 18329 "#endif", 18330 AllmanBraceStyle); 18331 18332 verifyFormat("void foobar() { int i = 5; }\n" 18333 "#ifdef _DEBUG\n" 18334 "void bar() {}\n" 18335 "#else\n" 18336 "void bar() { foobar(); }\n" 18337 "#endif", 18338 AllmanBraceStyle); 18339 18340 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18341 FormatStyle::SLS_All); 18342 18343 verifyFormat("[](int i) { return i + 2; };\n" 18344 "[](int i, int j)\n" 18345 "{\n" 18346 " auto x = i + j;\n" 18347 " auto y = i * j;\n" 18348 " return x ^ y;\n" 18349 "};\n" 18350 "void foo()\n" 18351 "{\n" 18352 " auto shortLambda = [](int i) { return i + 2; };\n" 18353 " auto longLambda = [](int i, int j)\n" 18354 " {\n" 18355 " auto x = i + j;\n" 18356 " auto y = i * j;\n" 18357 " return x ^ y;\n" 18358 " };\n" 18359 "}", 18360 AllmanBraceStyle); 18361 18362 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18363 18364 verifyFormat("[](int i)\n" 18365 "{\n" 18366 " return i + 2;\n" 18367 "};\n" 18368 "[](int i, int j)\n" 18369 "{\n" 18370 " auto x = i + j;\n" 18371 " auto y = i * j;\n" 18372 " return x ^ y;\n" 18373 "};\n" 18374 "void foo()\n" 18375 "{\n" 18376 " auto shortLambda = [](int i)\n" 18377 " {\n" 18378 " return i + 2;\n" 18379 " };\n" 18380 " auto longLambda = [](int i, int j)\n" 18381 " {\n" 18382 " auto x = i + j;\n" 18383 " auto y = i * j;\n" 18384 " return x ^ y;\n" 18385 " };\n" 18386 "}", 18387 AllmanBraceStyle); 18388 18389 // Reset 18390 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18391 18392 // This shouldn't affect ObjC blocks.. 18393 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18394 " // ...\n" 18395 " int i;\n" 18396 "}];", 18397 AllmanBraceStyle); 18398 verifyFormat("void (^block)(void) = ^{\n" 18399 " // ...\n" 18400 " int i;\n" 18401 "};", 18402 AllmanBraceStyle); 18403 // .. or dict literals. 18404 verifyFormat("void f()\n" 18405 "{\n" 18406 " // ...\n" 18407 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18408 "}", 18409 AllmanBraceStyle); 18410 verifyFormat("void f()\n" 18411 "{\n" 18412 " // ...\n" 18413 " [object someMethod:@{a : @\"b\"}];\n" 18414 "}", 18415 AllmanBraceStyle); 18416 verifyFormat("int f()\n" 18417 "{ // comment\n" 18418 " return 42;\n" 18419 "}", 18420 AllmanBraceStyle); 18421 18422 AllmanBraceStyle.ColumnLimit = 19; 18423 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18424 AllmanBraceStyle.ColumnLimit = 18; 18425 verifyFormat("void f()\n" 18426 "{\n" 18427 " int i;\n" 18428 "}", 18429 AllmanBraceStyle); 18430 AllmanBraceStyle.ColumnLimit = 80; 18431 18432 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18433 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18434 FormatStyle::SIS_WithoutElse; 18435 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18436 verifyFormat("void f(bool b)\n" 18437 "{\n" 18438 " if (b)\n" 18439 " {\n" 18440 " return;\n" 18441 " }\n" 18442 "}\n", 18443 BreakBeforeBraceShortIfs); 18444 verifyFormat("void f(bool b)\n" 18445 "{\n" 18446 " if constexpr (b)\n" 18447 " {\n" 18448 " return;\n" 18449 " }\n" 18450 "}\n", 18451 BreakBeforeBraceShortIfs); 18452 verifyFormat("void f(bool b)\n" 18453 "{\n" 18454 " if CONSTEXPR (b)\n" 18455 " {\n" 18456 " return;\n" 18457 " }\n" 18458 "}\n", 18459 BreakBeforeBraceShortIfs); 18460 verifyFormat("void f(bool b)\n" 18461 "{\n" 18462 " if (b) return;\n" 18463 "}\n", 18464 BreakBeforeBraceShortIfs); 18465 verifyFormat("void f(bool b)\n" 18466 "{\n" 18467 " if constexpr (b) return;\n" 18468 "}\n", 18469 BreakBeforeBraceShortIfs); 18470 verifyFormat("void f(bool b)\n" 18471 "{\n" 18472 " if CONSTEXPR (b) return;\n" 18473 "}\n", 18474 BreakBeforeBraceShortIfs); 18475 verifyFormat("void f(bool b)\n" 18476 "{\n" 18477 " while (b)\n" 18478 " {\n" 18479 " return;\n" 18480 " }\n" 18481 "}\n", 18482 BreakBeforeBraceShortIfs); 18483 } 18484 18485 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18486 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18487 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18488 18489 // Make a few changes to the style for testing purposes 18490 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18491 FormatStyle::SFS_Empty; 18492 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18493 18494 // FIXME: this test case can't decide whether there should be a blank line 18495 // after the ~D() line or not. It adds one if one doesn't exist in the test 18496 // and it removes the line if one exists. 18497 /* 18498 verifyFormat("class A;\n" 18499 "namespace B\n" 18500 " {\n" 18501 "class C;\n" 18502 "// Comment\n" 18503 "class D\n" 18504 " {\n" 18505 "public:\n" 18506 " D();\n" 18507 " ~D() {}\n" 18508 "private:\n" 18509 " enum E\n" 18510 " {\n" 18511 " F\n" 18512 " }\n" 18513 " };\n" 18514 " } // namespace B\n", 18515 WhitesmithsBraceStyle); 18516 */ 18517 18518 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18519 verifyFormat("namespace a\n" 18520 " {\n" 18521 "class A\n" 18522 " {\n" 18523 " void f()\n" 18524 " {\n" 18525 " if (true)\n" 18526 " {\n" 18527 " a();\n" 18528 " b();\n" 18529 " }\n" 18530 " }\n" 18531 " void g()\n" 18532 " {\n" 18533 " return;\n" 18534 " }\n" 18535 " };\n" 18536 "struct B\n" 18537 " {\n" 18538 " int x;\n" 18539 " };\n" 18540 " } // namespace a", 18541 WhitesmithsBraceStyle); 18542 18543 verifyFormat("namespace a\n" 18544 " {\n" 18545 "namespace b\n" 18546 " {\n" 18547 "class A\n" 18548 " {\n" 18549 " void f()\n" 18550 " {\n" 18551 " if (true)\n" 18552 " {\n" 18553 " a();\n" 18554 " b();\n" 18555 " }\n" 18556 " }\n" 18557 " void g()\n" 18558 " {\n" 18559 " return;\n" 18560 " }\n" 18561 " };\n" 18562 "struct B\n" 18563 " {\n" 18564 " int x;\n" 18565 " };\n" 18566 " } // namespace b\n" 18567 " } // namespace a", 18568 WhitesmithsBraceStyle); 18569 18570 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18571 verifyFormat("namespace a\n" 18572 " {\n" 18573 "namespace b\n" 18574 " {\n" 18575 " class A\n" 18576 " {\n" 18577 " void f()\n" 18578 " {\n" 18579 " if (true)\n" 18580 " {\n" 18581 " a();\n" 18582 " b();\n" 18583 " }\n" 18584 " }\n" 18585 " void g()\n" 18586 " {\n" 18587 " return;\n" 18588 " }\n" 18589 " };\n" 18590 " struct B\n" 18591 " {\n" 18592 " int x;\n" 18593 " };\n" 18594 " } // namespace b\n" 18595 " } // namespace a", 18596 WhitesmithsBraceStyle); 18597 18598 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18599 verifyFormat("namespace a\n" 18600 " {\n" 18601 " namespace b\n" 18602 " {\n" 18603 " class A\n" 18604 " {\n" 18605 " void f()\n" 18606 " {\n" 18607 " if (true)\n" 18608 " {\n" 18609 " a();\n" 18610 " b();\n" 18611 " }\n" 18612 " }\n" 18613 " void g()\n" 18614 " {\n" 18615 " return;\n" 18616 " }\n" 18617 " };\n" 18618 " struct B\n" 18619 " {\n" 18620 " int x;\n" 18621 " };\n" 18622 " } // namespace b\n" 18623 " } // namespace a", 18624 WhitesmithsBraceStyle); 18625 18626 verifyFormat("void f()\n" 18627 " {\n" 18628 " if (true)\n" 18629 " {\n" 18630 " a();\n" 18631 " }\n" 18632 " else if (false)\n" 18633 " {\n" 18634 " b();\n" 18635 " }\n" 18636 " else\n" 18637 " {\n" 18638 " c();\n" 18639 " }\n" 18640 " }\n", 18641 WhitesmithsBraceStyle); 18642 18643 verifyFormat("void f()\n" 18644 " {\n" 18645 " for (int i = 0; i < 10; ++i)\n" 18646 " {\n" 18647 " a();\n" 18648 " }\n" 18649 " while (false)\n" 18650 " {\n" 18651 " b();\n" 18652 " }\n" 18653 " do\n" 18654 " {\n" 18655 " c();\n" 18656 " } while (false)\n" 18657 " }\n", 18658 WhitesmithsBraceStyle); 18659 18660 WhitesmithsBraceStyle.IndentCaseLabels = true; 18661 verifyFormat("void switchTest1(int a)\n" 18662 " {\n" 18663 " switch (a)\n" 18664 " {\n" 18665 " case 2:\n" 18666 " {\n" 18667 " }\n" 18668 " break;\n" 18669 " }\n" 18670 " }\n", 18671 WhitesmithsBraceStyle); 18672 18673 verifyFormat("void switchTest2(int a)\n" 18674 " {\n" 18675 " switch (a)\n" 18676 " {\n" 18677 " case 0:\n" 18678 " break;\n" 18679 " case 1:\n" 18680 " {\n" 18681 " break;\n" 18682 " }\n" 18683 " case 2:\n" 18684 " {\n" 18685 " }\n" 18686 " break;\n" 18687 " default:\n" 18688 " break;\n" 18689 " }\n" 18690 " }\n", 18691 WhitesmithsBraceStyle); 18692 18693 verifyFormat("void switchTest3(int a)\n" 18694 " {\n" 18695 " switch (a)\n" 18696 " {\n" 18697 " case 0:\n" 18698 " {\n" 18699 " foo(x);\n" 18700 " }\n" 18701 " break;\n" 18702 " default:\n" 18703 " {\n" 18704 " foo(1);\n" 18705 " }\n" 18706 " break;\n" 18707 " }\n" 18708 " }\n", 18709 WhitesmithsBraceStyle); 18710 18711 WhitesmithsBraceStyle.IndentCaseLabels = false; 18712 18713 verifyFormat("void switchTest4(int a)\n" 18714 " {\n" 18715 " switch (a)\n" 18716 " {\n" 18717 " case 2:\n" 18718 " {\n" 18719 " }\n" 18720 " break;\n" 18721 " }\n" 18722 " }\n", 18723 WhitesmithsBraceStyle); 18724 18725 verifyFormat("void switchTest5(int a)\n" 18726 " {\n" 18727 " switch (a)\n" 18728 " {\n" 18729 " case 0:\n" 18730 " break;\n" 18731 " case 1:\n" 18732 " {\n" 18733 " foo();\n" 18734 " break;\n" 18735 " }\n" 18736 " case 2:\n" 18737 " {\n" 18738 " }\n" 18739 " break;\n" 18740 " default:\n" 18741 " break;\n" 18742 " }\n" 18743 " }\n", 18744 WhitesmithsBraceStyle); 18745 18746 verifyFormat("void switchTest6(int a)\n" 18747 " {\n" 18748 " switch (a)\n" 18749 " {\n" 18750 " case 0:\n" 18751 " {\n" 18752 " foo(x);\n" 18753 " }\n" 18754 " break;\n" 18755 " default:\n" 18756 " {\n" 18757 " foo(1);\n" 18758 " }\n" 18759 " break;\n" 18760 " }\n" 18761 " }\n", 18762 WhitesmithsBraceStyle); 18763 18764 verifyFormat("enum X\n" 18765 " {\n" 18766 " Y = 0, // testing\n" 18767 " }\n", 18768 WhitesmithsBraceStyle); 18769 18770 verifyFormat("enum X\n" 18771 " {\n" 18772 " Y = 0\n" 18773 " }\n", 18774 WhitesmithsBraceStyle); 18775 verifyFormat("enum X\n" 18776 " {\n" 18777 " Y = 0,\n" 18778 " Z = 1\n" 18779 " };\n", 18780 WhitesmithsBraceStyle); 18781 18782 verifyFormat("@interface BSApplicationController ()\n" 18783 " {\n" 18784 "@private\n" 18785 " id _extraIvar;\n" 18786 " }\n" 18787 "@end\n", 18788 WhitesmithsBraceStyle); 18789 18790 verifyFormat("#ifdef _DEBUG\n" 18791 "int foo(int i = 0)\n" 18792 "#else\n" 18793 "int foo(int i = 5)\n" 18794 "#endif\n" 18795 " {\n" 18796 " return i;\n" 18797 " }", 18798 WhitesmithsBraceStyle); 18799 18800 verifyFormat("void foo() {}\n" 18801 "void bar()\n" 18802 "#ifdef _DEBUG\n" 18803 " {\n" 18804 " foo();\n" 18805 " }\n" 18806 "#else\n" 18807 " {\n" 18808 " }\n" 18809 "#endif", 18810 WhitesmithsBraceStyle); 18811 18812 verifyFormat("void foobar()\n" 18813 " {\n" 18814 " int i = 5;\n" 18815 " }\n" 18816 "#ifdef _DEBUG\n" 18817 "void bar()\n" 18818 " {\n" 18819 " }\n" 18820 "#else\n" 18821 "void bar()\n" 18822 " {\n" 18823 " foobar();\n" 18824 " }\n" 18825 "#endif", 18826 WhitesmithsBraceStyle); 18827 18828 // This shouldn't affect ObjC blocks.. 18829 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18830 " // ...\n" 18831 " int i;\n" 18832 "}];", 18833 WhitesmithsBraceStyle); 18834 verifyFormat("void (^block)(void) = ^{\n" 18835 " // ...\n" 18836 " int i;\n" 18837 "};", 18838 WhitesmithsBraceStyle); 18839 // .. or dict literals. 18840 verifyFormat("void f()\n" 18841 " {\n" 18842 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18843 " }", 18844 WhitesmithsBraceStyle); 18845 18846 verifyFormat("int f()\n" 18847 " { // comment\n" 18848 " return 42;\n" 18849 " }", 18850 WhitesmithsBraceStyle); 18851 18852 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18853 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18854 FormatStyle::SIS_OnlyFirstIf; 18855 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18856 verifyFormat("void f(bool b)\n" 18857 " {\n" 18858 " if (b)\n" 18859 " {\n" 18860 " return;\n" 18861 " }\n" 18862 " }\n", 18863 BreakBeforeBraceShortIfs); 18864 verifyFormat("void f(bool b)\n" 18865 " {\n" 18866 " if (b) return;\n" 18867 " }\n", 18868 BreakBeforeBraceShortIfs); 18869 verifyFormat("void f(bool b)\n" 18870 " {\n" 18871 " while (b)\n" 18872 " {\n" 18873 " return;\n" 18874 " }\n" 18875 " }\n", 18876 BreakBeforeBraceShortIfs); 18877 } 18878 18879 TEST_F(FormatTest, GNUBraceBreaking) { 18880 FormatStyle GNUBraceStyle = getLLVMStyle(); 18881 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18882 verifyFormat("namespace a\n" 18883 "{\n" 18884 "class A\n" 18885 "{\n" 18886 " void f()\n" 18887 " {\n" 18888 " int a;\n" 18889 " {\n" 18890 " int b;\n" 18891 " }\n" 18892 " if (true)\n" 18893 " {\n" 18894 " a();\n" 18895 " b();\n" 18896 " }\n" 18897 " }\n" 18898 " void g() { return; }\n" 18899 "}\n" 18900 "} // namespace a", 18901 GNUBraceStyle); 18902 18903 verifyFormat("void f()\n" 18904 "{\n" 18905 " if (true)\n" 18906 " {\n" 18907 " a();\n" 18908 " }\n" 18909 " else if (false)\n" 18910 " {\n" 18911 " b();\n" 18912 " }\n" 18913 " else\n" 18914 " {\n" 18915 " c();\n" 18916 " }\n" 18917 "}\n", 18918 GNUBraceStyle); 18919 18920 verifyFormat("void f()\n" 18921 "{\n" 18922 " for (int i = 0; i < 10; ++i)\n" 18923 " {\n" 18924 " a();\n" 18925 " }\n" 18926 " while (false)\n" 18927 " {\n" 18928 " b();\n" 18929 " }\n" 18930 " do\n" 18931 " {\n" 18932 " c();\n" 18933 " }\n" 18934 " while (false);\n" 18935 "}\n", 18936 GNUBraceStyle); 18937 18938 verifyFormat("void f(int a)\n" 18939 "{\n" 18940 " switch (a)\n" 18941 " {\n" 18942 " case 0:\n" 18943 " break;\n" 18944 " case 1:\n" 18945 " {\n" 18946 " break;\n" 18947 " }\n" 18948 " case 2:\n" 18949 " {\n" 18950 " }\n" 18951 " break;\n" 18952 " default:\n" 18953 " break;\n" 18954 " }\n" 18955 "}\n", 18956 GNUBraceStyle); 18957 18958 verifyFormat("enum X\n" 18959 "{\n" 18960 " Y = 0,\n" 18961 "}\n", 18962 GNUBraceStyle); 18963 18964 verifyFormat("@interface BSApplicationController ()\n" 18965 "{\n" 18966 "@private\n" 18967 " id _extraIvar;\n" 18968 "}\n" 18969 "@end\n", 18970 GNUBraceStyle); 18971 18972 verifyFormat("#ifdef _DEBUG\n" 18973 "int foo(int i = 0)\n" 18974 "#else\n" 18975 "int foo(int i = 5)\n" 18976 "#endif\n" 18977 "{\n" 18978 " return i;\n" 18979 "}", 18980 GNUBraceStyle); 18981 18982 verifyFormat("void foo() {}\n" 18983 "void bar()\n" 18984 "#ifdef _DEBUG\n" 18985 "{\n" 18986 " foo();\n" 18987 "}\n" 18988 "#else\n" 18989 "{\n" 18990 "}\n" 18991 "#endif", 18992 GNUBraceStyle); 18993 18994 verifyFormat("void foobar() { int i = 5; }\n" 18995 "#ifdef _DEBUG\n" 18996 "void bar() {}\n" 18997 "#else\n" 18998 "void bar() { foobar(); }\n" 18999 "#endif", 19000 GNUBraceStyle); 19001 } 19002 19003 TEST_F(FormatTest, WebKitBraceBreaking) { 19004 FormatStyle WebKitBraceStyle = getLLVMStyle(); 19005 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 19006 WebKitBraceStyle.FixNamespaceComments = false; 19007 verifyFormat("namespace a {\n" 19008 "class A {\n" 19009 " void f()\n" 19010 " {\n" 19011 " if (true) {\n" 19012 " a();\n" 19013 " b();\n" 19014 " }\n" 19015 " }\n" 19016 " void g() { return; }\n" 19017 "};\n" 19018 "enum E {\n" 19019 " A,\n" 19020 " // foo\n" 19021 " B,\n" 19022 " C\n" 19023 "};\n" 19024 "struct B {\n" 19025 " int x;\n" 19026 "};\n" 19027 "}\n", 19028 WebKitBraceStyle); 19029 verifyFormat("struct S {\n" 19030 " int Type;\n" 19031 " union {\n" 19032 " int x;\n" 19033 " double y;\n" 19034 " } Value;\n" 19035 " class C {\n" 19036 " MyFavoriteType Value;\n" 19037 " } Class;\n" 19038 "};\n", 19039 WebKitBraceStyle); 19040 } 19041 19042 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19043 verifyFormat("void f() {\n" 19044 " try {\n" 19045 " } catch (const Exception &e) {\n" 19046 " }\n" 19047 "}\n", 19048 getLLVMStyle()); 19049 } 19050 19051 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19052 auto Style = getLLVMStyle(); 19053 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19054 Style.AlignConsecutiveAssignments.Enabled = true; 19055 Style.AlignConsecutiveDeclarations.Enabled = true; 19056 verifyFormat("struct test demo[] = {\n" 19057 " {56, 23, \"hello\"},\n" 19058 " {-1, 93463, \"world\"},\n" 19059 " { 7, 5, \"!!\"}\n" 19060 "};\n", 19061 Style); 19062 19063 verifyFormat("struct test demo[] = {\n" 19064 " {56, 23, \"hello\"}, // first line\n" 19065 " {-1, 93463, \"world\"}, // second line\n" 19066 " { 7, 5, \"!!\"} // third line\n" 19067 "};\n", 19068 Style); 19069 19070 verifyFormat("struct test demo[4] = {\n" 19071 " { 56, 23, 21, \"oh\"}, // first line\n" 19072 " { -1, 93463, 22, \"my\"}, // second line\n" 19073 " { 7, 5, 1, \"goodness\"} // third line\n" 19074 " {234, 5, 1, \"gracious\"} // fourth line\n" 19075 "};\n", 19076 Style); 19077 19078 verifyFormat("struct test demo[3] = {\n" 19079 " {56, 23, \"hello\"},\n" 19080 " {-1, 93463, \"world\"},\n" 19081 " { 7, 5, \"!!\"}\n" 19082 "};\n", 19083 Style); 19084 19085 verifyFormat("struct test demo[3] = {\n" 19086 " {int{56}, 23, \"hello\"},\n" 19087 " {int{-1}, 93463, \"world\"},\n" 19088 " { int{7}, 5, \"!!\"}\n" 19089 "};\n", 19090 Style); 19091 19092 verifyFormat("struct test demo[] = {\n" 19093 " {56, 23, \"hello\"},\n" 19094 " {-1, 93463, \"world\"},\n" 19095 " { 7, 5, \"!!\"},\n" 19096 "};\n", 19097 Style); 19098 19099 verifyFormat("test demo[] = {\n" 19100 " {56, 23, \"hello\"},\n" 19101 " {-1, 93463, \"world\"},\n" 19102 " { 7, 5, \"!!\"},\n" 19103 "};\n", 19104 Style); 19105 19106 verifyFormat("demo = std::array<struct test, 3>{\n" 19107 " test{56, 23, \"hello\"},\n" 19108 " test{-1, 93463, \"world\"},\n" 19109 " test{ 7, 5, \"!!\"},\n" 19110 "};\n", 19111 Style); 19112 19113 verifyFormat("test demo[] = {\n" 19114 " {56, 23, \"hello\"},\n" 19115 "#if X\n" 19116 " {-1, 93463, \"world\"},\n" 19117 "#endif\n" 19118 " { 7, 5, \"!!\"}\n" 19119 "};\n", 19120 Style); 19121 19122 verifyFormat( 19123 "test demo[] = {\n" 19124 " { 7, 23,\n" 19125 " \"hello world i am a very long line that really, in any\"\n" 19126 " \"just world, ought to be split over multiple lines\"},\n" 19127 " {-1, 93463, \"world\"},\n" 19128 " {56, 5, \"!!\"}\n" 19129 "};\n", 19130 Style); 19131 19132 verifyFormat("return GradForUnaryCwise(g, {\n" 19133 " {{\"sign\"}, \"Sign\", " 19134 " {\"x\", \"dy\"}},\n" 19135 " { {\"dx\"}, \"Mul\", {\"dy\"" 19136 ", \"sign\"}},\n" 19137 "});\n", 19138 Style); 19139 19140 Style.ColumnLimit = 0; 19141 EXPECT_EQ( 19142 "test demo[] = {\n" 19143 " {56, 23, \"hello world i am a very long line that really, " 19144 "in any just world, ought to be split over multiple lines\"},\n" 19145 " {-1, 93463, " 19146 " \"world\"},\n" 19147 " { 7, 5, " 19148 " \"!!\"},\n" 19149 "};", 19150 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19151 "that really, in any just world, ought to be split over multiple " 19152 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19153 Style)); 19154 19155 Style.ColumnLimit = 80; 19156 verifyFormat("test demo[] = {\n" 19157 " {56, 23, /* a comment */ \"hello\"},\n" 19158 " {-1, 93463, \"world\"},\n" 19159 " { 7, 5, \"!!\"}\n" 19160 "};\n", 19161 Style); 19162 19163 verifyFormat("test demo[] = {\n" 19164 " {56, 23, \"hello\"},\n" 19165 " {-1, 93463, \"world\" /* comment here */},\n" 19166 " { 7, 5, \"!!\"}\n" 19167 "};\n", 19168 Style); 19169 19170 verifyFormat("test demo[] = {\n" 19171 " {56, /* a comment */ 23, \"hello\"},\n" 19172 " {-1, 93463, \"world\"},\n" 19173 " { 7, 5, \"!!\"}\n" 19174 "};\n", 19175 Style); 19176 19177 Style.ColumnLimit = 20; 19178 EXPECT_EQ( 19179 "demo = std::array<\n" 19180 " struct test, 3>{\n" 19181 " test{\n" 19182 " 56, 23,\n" 19183 " \"hello \"\n" 19184 " \"world i \"\n" 19185 " \"am a very \"\n" 19186 " \"long line \"\n" 19187 " \"that \"\n" 19188 " \"really, \"\n" 19189 " \"in any \"\n" 19190 " \"just \"\n" 19191 " \"world, \"\n" 19192 " \"ought to \"\n" 19193 " \"be split \"\n" 19194 " \"over \"\n" 19195 " \"multiple \"\n" 19196 " \"lines\"},\n" 19197 " test{-1, 93463,\n" 19198 " \"world\"},\n" 19199 " test{ 7, 5,\n" 19200 " \"!!\" },\n" 19201 "};", 19202 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19203 "i am a very long line that really, in any just world, ought " 19204 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19205 "test{7, 5, \"!!\"},};", 19206 Style)); 19207 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19208 Style = getLLVMStyleWithColumns(50); 19209 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19210 verifyFormat("static A x = {\n" 19211 " {{init1, init2, init3, init4},\n" 19212 " {init1, init2, init3, init4}}\n" 19213 "};", 19214 Style); 19215 // TODO: Fix the indentations below when this option is fully functional. 19216 verifyFormat("int a[][] = {\n" 19217 " {\n" 19218 " {0, 2}, //\n" 19219 " {1, 2} //\n" 19220 " }\n" 19221 "};", 19222 Style); 19223 Style.ColumnLimit = 100; 19224 EXPECT_EQ( 19225 "test demo[] = {\n" 19226 " {56, 23,\n" 19227 " \"hello world i am a very long line that really, in any just world" 19228 ", ought to be split over \"\n" 19229 " \"multiple lines\" },\n" 19230 " {-1, 93463, \"world\"},\n" 19231 " { 7, 5, \"!!\"},\n" 19232 "};", 19233 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19234 "that really, in any just world, ought to be split over multiple " 19235 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19236 Style)); 19237 19238 Style = getLLVMStyleWithColumns(50); 19239 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19240 verifyFormat("struct test demo[] = {\n" 19241 " {56, 23, \"hello\"},\n" 19242 " {-1, 93463, \"world\"},\n" 19243 " { 7, 5, \"!!\"}\n" 19244 "};\n" 19245 "static A x = {\n" 19246 " {{init1, init2, init3, init4},\n" 19247 " {init1, init2, init3, init4}}\n" 19248 "};", 19249 Style); 19250 Style.ColumnLimit = 100; 19251 Style.AlignConsecutiveAssignments.AcrossComments = true; 19252 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19253 verifyFormat("struct test demo[] = {\n" 19254 " {56, 23, \"hello\"},\n" 19255 " {-1, 93463, \"world\"},\n" 19256 " { 7, 5, \"!!\"}\n" 19257 "};\n" 19258 "struct test demo[4] = {\n" 19259 " { 56, 23, 21, \"oh\"}, // first line\n" 19260 " { -1, 93463, 22, \"my\"}, // second line\n" 19261 " { 7, 5, 1, \"goodness\"} // third line\n" 19262 " {234, 5, 1, \"gracious\"} // fourth line\n" 19263 "};\n", 19264 Style); 19265 EXPECT_EQ( 19266 "test demo[] = {\n" 19267 " {56,\n" 19268 " \"hello world i am a very long line that really, in any just world" 19269 ", ought to be split over \"\n" 19270 " \"multiple lines\", 23},\n" 19271 " {-1, \"world\", 93463},\n" 19272 " { 7, \"!!\", 5},\n" 19273 "};", 19274 format("test demo[] = {{56, \"hello world i am a very long line " 19275 "that really, in any just world, ought to be split over multiple " 19276 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19277 Style)); 19278 } 19279 19280 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19281 auto Style = getLLVMStyle(); 19282 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19283 /* FIXME: This case gets misformatted. 19284 verifyFormat("auto foo = Items{\n" 19285 " Section{0, bar(), },\n" 19286 " Section{1, boo() }\n" 19287 "};\n", 19288 Style); 19289 */ 19290 verifyFormat("auto foo = Items{\n" 19291 " Section{\n" 19292 " 0, bar(),\n" 19293 " }\n" 19294 "};\n", 19295 Style); 19296 verifyFormat("struct test demo[] = {\n" 19297 " {56, 23, \"hello\"},\n" 19298 " {-1, 93463, \"world\"},\n" 19299 " {7, 5, \"!!\" }\n" 19300 "};\n", 19301 Style); 19302 verifyFormat("struct test demo[] = {\n" 19303 " {56, 23, \"hello\"}, // first line\n" 19304 " {-1, 93463, \"world\"}, // second line\n" 19305 " {7, 5, \"!!\" } // third line\n" 19306 "};\n", 19307 Style); 19308 verifyFormat("struct test demo[4] = {\n" 19309 " {56, 23, 21, \"oh\" }, // first line\n" 19310 " {-1, 93463, 22, \"my\" }, // second line\n" 19311 " {7, 5, 1, \"goodness\"} // third line\n" 19312 " {234, 5, 1, \"gracious\"} // fourth line\n" 19313 "};\n", 19314 Style); 19315 verifyFormat("struct test demo[3] = {\n" 19316 " {56, 23, \"hello\"},\n" 19317 " {-1, 93463, \"world\"},\n" 19318 " {7, 5, \"!!\" }\n" 19319 "};\n", 19320 Style); 19321 19322 verifyFormat("struct test demo[3] = {\n" 19323 " {int{56}, 23, \"hello\"},\n" 19324 " {int{-1}, 93463, \"world\"},\n" 19325 " {int{7}, 5, \"!!\" }\n" 19326 "};\n", 19327 Style); 19328 verifyFormat("struct test demo[] = {\n" 19329 " {56, 23, \"hello\"},\n" 19330 " {-1, 93463, \"world\"},\n" 19331 " {7, 5, \"!!\" },\n" 19332 "};\n", 19333 Style); 19334 verifyFormat("test demo[] = {\n" 19335 " {56, 23, \"hello\"},\n" 19336 " {-1, 93463, \"world\"},\n" 19337 " {7, 5, \"!!\" },\n" 19338 "};\n", 19339 Style); 19340 verifyFormat("demo = std::array<struct test, 3>{\n" 19341 " test{56, 23, \"hello\"},\n" 19342 " test{-1, 93463, \"world\"},\n" 19343 " test{7, 5, \"!!\" },\n" 19344 "};\n", 19345 Style); 19346 verifyFormat("test demo[] = {\n" 19347 " {56, 23, \"hello\"},\n" 19348 "#if X\n" 19349 " {-1, 93463, \"world\"},\n" 19350 "#endif\n" 19351 " {7, 5, \"!!\" }\n" 19352 "};\n", 19353 Style); 19354 verifyFormat( 19355 "test demo[] = {\n" 19356 " {7, 23,\n" 19357 " \"hello world i am a very long line that really, in any\"\n" 19358 " \"just world, ought to be split over multiple lines\"},\n" 19359 " {-1, 93463, \"world\" },\n" 19360 " {56, 5, \"!!\" }\n" 19361 "};\n", 19362 Style); 19363 19364 verifyFormat("return GradForUnaryCwise(g, {\n" 19365 " {{\"sign\"}, \"Sign\", {\"x\", " 19366 "\"dy\"} },\n" 19367 " {{\"dx\"}, \"Mul\", " 19368 "{\"dy\", \"sign\"}},\n" 19369 "});\n", 19370 Style); 19371 19372 Style.ColumnLimit = 0; 19373 EXPECT_EQ( 19374 "test demo[] = {\n" 19375 " {56, 23, \"hello world i am a very long line that really, in any " 19376 "just world, ought to be split over multiple lines\"},\n" 19377 " {-1, 93463, \"world\" " 19378 " },\n" 19379 " {7, 5, \"!!\" " 19380 " },\n" 19381 "};", 19382 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19383 "that really, in any just world, ought to be split over multiple " 19384 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19385 Style)); 19386 19387 Style.ColumnLimit = 80; 19388 verifyFormat("test demo[] = {\n" 19389 " {56, 23, /* a comment */ \"hello\"},\n" 19390 " {-1, 93463, \"world\" },\n" 19391 " {7, 5, \"!!\" }\n" 19392 "};\n", 19393 Style); 19394 19395 verifyFormat("test demo[] = {\n" 19396 " {56, 23, \"hello\" },\n" 19397 " {-1, 93463, \"world\" /* comment here */},\n" 19398 " {7, 5, \"!!\" }\n" 19399 "};\n", 19400 Style); 19401 19402 verifyFormat("test demo[] = {\n" 19403 " {56, /* a comment */ 23, \"hello\"},\n" 19404 " {-1, 93463, \"world\"},\n" 19405 " {7, 5, \"!!\" }\n" 19406 "};\n", 19407 Style); 19408 19409 Style.ColumnLimit = 20; 19410 EXPECT_EQ( 19411 "demo = std::array<\n" 19412 " struct test, 3>{\n" 19413 " test{\n" 19414 " 56, 23,\n" 19415 " \"hello \"\n" 19416 " \"world i \"\n" 19417 " \"am a very \"\n" 19418 " \"long line \"\n" 19419 " \"that \"\n" 19420 " \"really, \"\n" 19421 " \"in any \"\n" 19422 " \"just \"\n" 19423 " \"world, \"\n" 19424 " \"ought to \"\n" 19425 " \"be split \"\n" 19426 " \"over \"\n" 19427 " \"multiple \"\n" 19428 " \"lines\"},\n" 19429 " test{-1, 93463,\n" 19430 " \"world\"},\n" 19431 " test{7, 5,\n" 19432 " \"!!\" },\n" 19433 "};", 19434 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19435 "i am a very long line that really, in any just world, ought " 19436 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19437 "test{7, 5, \"!!\"},};", 19438 Style)); 19439 19440 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19441 Style = getLLVMStyleWithColumns(50); 19442 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19443 verifyFormat("static A x = {\n" 19444 " {{init1, init2, init3, init4},\n" 19445 " {init1, init2, init3, init4}}\n" 19446 "};", 19447 Style); 19448 Style.ColumnLimit = 100; 19449 EXPECT_EQ( 19450 "test demo[] = {\n" 19451 " {56, 23,\n" 19452 " \"hello world i am a very long line that really, in any just world" 19453 ", ought to be split over \"\n" 19454 " \"multiple lines\" },\n" 19455 " {-1, 93463, \"world\"},\n" 19456 " {7, 5, \"!!\" },\n" 19457 "};", 19458 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19459 "that really, in any just world, ought to be split over multiple " 19460 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19461 Style)); 19462 } 19463 19464 TEST_F(FormatTest, UnderstandsPragmas) { 19465 verifyFormat("#pragma omp reduction(| : var)"); 19466 verifyFormat("#pragma omp reduction(+ : var)"); 19467 19468 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19469 "(including parentheses).", 19470 format("#pragma mark Any non-hyphenated or hyphenated string " 19471 "(including parentheses).")); 19472 } 19473 19474 TEST_F(FormatTest, UnderstandPragmaOption) { 19475 verifyFormat("#pragma option -C -A"); 19476 19477 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19478 } 19479 19480 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19481 FormatStyle Style = getLLVMStyleWithColumns(20); 19482 19483 // See PR41213 19484 EXPECT_EQ("/*\n" 19485 " *\t9012345\n" 19486 " * /8901\n" 19487 " */", 19488 format("/*\n" 19489 " *\t9012345 /8901\n" 19490 " */", 19491 Style)); 19492 EXPECT_EQ("/*\n" 19493 " *345678\n" 19494 " *\t/8901\n" 19495 " */", 19496 format("/*\n" 19497 " *345678\t/8901\n" 19498 " */", 19499 Style)); 19500 19501 verifyFormat("int a; // the\n" 19502 " // comment", 19503 Style); 19504 EXPECT_EQ("int a; /* first line\n" 19505 " * second\n" 19506 " * line third\n" 19507 " * line\n" 19508 " */", 19509 format("int a; /* first line\n" 19510 " * second\n" 19511 " * line third\n" 19512 " * line\n" 19513 " */", 19514 Style)); 19515 EXPECT_EQ("int a; // first line\n" 19516 " // second\n" 19517 " // line third\n" 19518 " // line", 19519 format("int a; // first line\n" 19520 " // second line\n" 19521 " // third line", 19522 Style)); 19523 19524 Style.PenaltyExcessCharacter = 90; 19525 verifyFormat("int a; // the comment", Style); 19526 EXPECT_EQ("int a; // the comment\n" 19527 " // aaa", 19528 format("int a; // the comment aaa", Style)); 19529 EXPECT_EQ("int a; /* first line\n" 19530 " * second line\n" 19531 " * third line\n" 19532 " */", 19533 format("int a; /* first line\n" 19534 " * second line\n" 19535 " * third line\n" 19536 " */", 19537 Style)); 19538 EXPECT_EQ("int a; // first line\n" 19539 " // second line\n" 19540 " // third line", 19541 format("int a; // first line\n" 19542 " // second line\n" 19543 " // third line", 19544 Style)); 19545 // FIXME: Investigate why this is not getting the same layout as the test 19546 // above. 19547 EXPECT_EQ("int a; /* first line\n" 19548 " * second line\n" 19549 " * third line\n" 19550 " */", 19551 format("int a; /* first line second line third line" 19552 "\n*/", 19553 Style)); 19554 19555 EXPECT_EQ("// foo bar baz bazfoo\n" 19556 "// foo bar foo bar\n", 19557 format("// foo bar baz bazfoo\n" 19558 "// foo bar foo bar\n", 19559 Style)); 19560 EXPECT_EQ("// foo bar baz bazfoo\n" 19561 "// foo bar foo bar\n", 19562 format("// foo bar baz bazfoo\n" 19563 "// foo bar foo bar\n", 19564 Style)); 19565 19566 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19567 // next one. 19568 EXPECT_EQ("// foo bar baz bazfoo\n" 19569 "// bar foo bar\n", 19570 format("// foo bar baz bazfoo bar\n" 19571 "// foo bar\n", 19572 Style)); 19573 19574 EXPECT_EQ("// foo bar baz bazfoo\n" 19575 "// foo bar baz bazfoo\n" 19576 "// bar foo bar\n", 19577 format("// foo bar baz bazfoo\n" 19578 "// foo bar baz bazfoo bar\n" 19579 "// foo bar\n", 19580 Style)); 19581 19582 EXPECT_EQ("// foo bar baz bazfoo\n" 19583 "// foo bar baz bazfoo\n" 19584 "// bar foo bar\n", 19585 format("// foo bar baz bazfoo\n" 19586 "// foo bar baz bazfoo bar\n" 19587 "// foo bar\n", 19588 Style)); 19589 19590 // Make sure we do not keep protruding characters if strict mode reflow is 19591 // cheaper than keeping protruding characters. 19592 Style.ColumnLimit = 21; 19593 EXPECT_EQ( 19594 "// foo foo foo foo\n" 19595 "// foo foo foo foo\n" 19596 "// foo foo foo foo\n", 19597 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19598 19599 EXPECT_EQ("int a = /* long block\n" 19600 " comment */\n" 19601 " 42;", 19602 format("int a = /* long block comment */ 42;", Style)); 19603 } 19604 19605 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19606 FormatStyle Style = getLLVMStyle(); 19607 Style.ColumnLimit = 8; 19608 Style.PenaltyExcessCharacter = 15; 19609 verifyFormat("int foo(\n" 19610 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19611 Style); 19612 Style.PenaltyBreakOpenParenthesis = 200; 19613 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19614 format("int foo(\n" 19615 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19616 Style)); 19617 } 19618 19619 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19620 FormatStyle Style = getLLVMStyle(); 19621 Style.ColumnLimit = 5; 19622 Style.PenaltyExcessCharacter = 150; 19623 verifyFormat("foo((\n" 19624 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19625 19626 Style); 19627 Style.PenaltyBreakOpenParenthesis = 100000; 19628 EXPECT_EQ("foo((int)\n" 19629 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19630 format("foo((\n" 19631 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19632 Style)); 19633 } 19634 19635 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19636 FormatStyle Style = getLLVMStyle(); 19637 Style.ColumnLimit = 4; 19638 Style.PenaltyExcessCharacter = 100; 19639 verifyFormat("for (\n" 19640 " int iiiiiiiiiiiiiiiii =\n" 19641 " 0;\n" 19642 " iiiiiiiiiiiiiiiii <\n" 19643 " 2;\n" 19644 " iiiiiiiiiiiiiiiii++) {\n" 19645 "}", 19646 19647 Style); 19648 Style.PenaltyBreakOpenParenthesis = 1250; 19649 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19650 " 0;\n" 19651 " iiiiiiiiiiiiiiiii <\n" 19652 " 2;\n" 19653 " iiiiiiiiiiiiiiiii++) {\n" 19654 "}", 19655 format("for (\n" 19656 " int iiiiiiiiiiiiiiiii =\n" 19657 " 0;\n" 19658 " iiiiiiiiiiiiiiiii <\n" 19659 " 2;\n" 19660 " iiiiiiiiiiiiiiiii++) {\n" 19661 "}", 19662 Style)); 19663 } 19664 19665 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19666 for (size_t i = 1; i < Styles.size(); ++i) \ 19667 EXPECT_EQ(Styles[0], Styles[i]) \ 19668 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19669 19670 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19671 SmallVector<FormatStyle, 3> Styles; 19672 Styles.resize(3); 19673 19674 Styles[0] = getLLVMStyle(); 19675 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19676 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19677 EXPECT_ALL_STYLES_EQUAL(Styles); 19678 19679 Styles[0] = getGoogleStyle(); 19680 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19681 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19682 EXPECT_ALL_STYLES_EQUAL(Styles); 19683 19684 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19685 EXPECT_TRUE( 19686 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19687 EXPECT_TRUE( 19688 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19689 EXPECT_ALL_STYLES_EQUAL(Styles); 19690 19691 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19692 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19693 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19694 EXPECT_ALL_STYLES_EQUAL(Styles); 19695 19696 Styles[0] = getMozillaStyle(); 19697 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19698 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19699 EXPECT_ALL_STYLES_EQUAL(Styles); 19700 19701 Styles[0] = getWebKitStyle(); 19702 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19703 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19704 EXPECT_ALL_STYLES_EQUAL(Styles); 19705 19706 Styles[0] = getGNUStyle(); 19707 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19708 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19709 EXPECT_ALL_STYLES_EQUAL(Styles); 19710 19711 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19712 } 19713 19714 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19715 SmallVector<FormatStyle, 8> Styles; 19716 Styles.resize(2); 19717 19718 Styles[0] = getGoogleStyle(); 19719 Styles[1] = getLLVMStyle(); 19720 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19721 EXPECT_ALL_STYLES_EQUAL(Styles); 19722 19723 Styles.resize(5); 19724 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19725 Styles[1] = getLLVMStyle(); 19726 Styles[1].Language = FormatStyle::LK_JavaScript; 19727 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19728 19729 Styles[2] = getLLVMStyle(); 19730 Styles[2].Language = FormatStyle::LK_JavaScript; 19731 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19732 "BasedOnStyle: Google", 19733 &Styles[2]) 19734 .value()); 19735 19736 Styles[3] = getLLVMStyle(); 19737 Styles[3].Language = FormatStyle::LK_JavaScript; 19738 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19739 "Language: JavaScript", 19740 &Styles[3]) 19741 .value()); 19742 19743 Styles[4] = getLLVMStyle(); 19744 Styles[4].Language = FormatStyle::LK_JavaScript; 19745 EXPECT_EQ(0, parseConfiguration("---\n" 19746 "BasedOnStyle: LLVM\n" 19747 "IndentWidth: 123\n" 19748 "---\n" 19749 "BasedOnStyle: Google\n" 19750 "Language: JavaScript", 19751 &Styles[4]) 19752 .value()); 19753 EXPECT_ALL_STYLES_EQUAL(Styles); 19754 } 19755 19756 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19757 Style.FIELD = false; \ 19758 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19759 EXPECT_TRUE(Style.FIELD); \ 19760 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19761 EXPECT_FALSE(Style.FIELD); 19762 19763 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19764 19765 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19766 Style.STRUCT.FIELD = false; \ 19767 EXPECT_EQ(0, \ 19768 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19769 .value()); \ 19770 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19771 EXPECT_EQ(0, \ 19772 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19773 .value()); \ 19774 EXPECT_FALSE(Style.STRUCT.FIELD); 19775 19776 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19777 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19778 19779 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19780 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19781 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19782 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19783 19784 TEST_F(FormatTest, ParsesConfigurationBools) { 19785 FormatStyle Style = {}; 19786 Style.Language = FormatStyle::LK_Cpp; 19787 CHECK_PARSE_BOOL(AlignTrailingComments); 19788 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19789 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19790 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19791 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19792 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19793 CHECK_PARSE_BOOL(BinPackArguments); 19794 CHECK_PARSE_BOOL(BinPackParameters); 19795 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19796 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19797 CHECK_PARSE_BOOL(BreakStringLiterals); 19798 CHECK_PARSE_BOOL(CompactNamespaces); 19799 CHECK_PARSE_BOOL(DeriveLineEnding); 19800 CHECK_PARSE_BOOL(DerivePointerAlignment); 19801 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19802 CHECK_PARSE_BOOL(DisableFormat); 19803 CHECK_PARSE_BOOL(IndentAccessModifiers); 19804 CHECK_PARSE_BOOL(IndentCaseLabels); 19805 CHECK_PARSE_BOOL(IndentCaseBlocks); 19806 CHECK_PARSE_BOOL(IndentGotoLabels); 19807 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19808 CHECK_PARSE_BOOL(IndentRequiresClause); 19809 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19810 CHECK_PARSE_BOOL(InsertBraces); 19811 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19812 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19813 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19814 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19815 CHECK_PARSE_BOOL(ReflowComments); 19816 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19817 CHECK_PARSE_BOOL(SortUsingDeclarations); 19818 CHECK_PARSE_BOOL(SpacesInParentheses); 19819 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19820 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19821 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19822 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19823 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19824 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19825 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19826 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19827 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19828 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19829 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19830 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19831 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19832 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19833 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19834 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19835 CHECK_PARSE_BOOL(UseCRLF); 19836 19837 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19838 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19839 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19840 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19841 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19842 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19843 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19844 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19845 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19846 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19847 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19848 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19849 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19850 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19851 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19852 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19853 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19854 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19855 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19856 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19857 AfterFunctionDeclarationName); 19858 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19859 AfterFunctionDefinitionName); 19860 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19861 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19862 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19863 } 19864 19865 #undef CHECK_PARSE_BOOL 19866 19867 TEST_F(FormatTest, ParsesConfiguration) { 19868 FormatStyle Style = {}; 19869 Style.Language = FormatStyle::LK_Cpp; 19870 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19871 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19872 ConstructorInitializerIndentWidth, 1234u); 19873 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19874 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19875 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19876 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19877 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19878 PenaltyBreakBeforeFirstCallParameter, 1234u); 19879 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19880 PenaltyBreakTemplateDeclaration, 1234u); 19881 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19882 1234u); 19883 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19884 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19885 PenaltyReturnTypeOnItsOwnLine, 1234u); 19886 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19887 SpacesBeforeTrailingComments, 1234u); 19888 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19889 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19890 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19891 19892 Style.QualifierAlignment = FormatStyle::QAS_Right; 19893 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19894 FormatStyle::QAS_Leave); 19895 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19896 FormatStyle::QAS_Right); 19897 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19898 FormatStyle::QAS_Left); 19899 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19900 FormatStyle::QAS_Custom); 19901 19902 Style.QualifierOrder.clear(); 19903 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19904 std::vector<std::string>({"const", "volatile", "type"})); 19905 Style.QualifierOrder.clear(); 19906 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19907 std::vector<std::string>({"const", "type"})); 19908 Style.QualifierOrder.clear(); 19909 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19910 std::vector<std::string>({"volatile", "type"})); 19911 19912 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 19913 do { \ 19914 Style.FIELD.Enabled = true; \ 19915 CHECK_PARSE(#FIELD ": None", FIELD, \ 19916 FormatStyle::AlignConsecutiveStyle( \ 19917 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19918 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19919 /*PadOperators=*/true})); \ 19920 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 19921 FormatStyle::AlignConsecutiveStyle( \ 19922 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19923 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19924 /*PadOperators=*/true})); \ 19925 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 19926 FormatStyle::AlignConsecutiveStyle( \ 19927 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19928 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19929 /*PadOperators=*/true})); \ 19930 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 19931 FormatStyle::AlignConsecutiveStyle( \ 19932 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19933 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 19934 /*PadOperators=*/true})); \ 19935 /* For backwards compability, false / true should still parse */ \ 19936 CHECK_PARSE(#FIELD ": false", FIELD, \ 19937 FormatStyle::AlignConsecutiveStyle( \ 19938 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19939 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19940 /*PadOperators=*/true})); \ 19941 CHECK_PARSE(#FIELD ": true", FIELD, \ 19942 FormatStyle::AlignConsecutiveStyle( \ 19943 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19944 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19945 /*PadOperators=*/true})); \ 19946 \ 19947 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 19948 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 19949 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 19950 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 19951 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 19952 } while (false) 19953 19954 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 19955 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 19956 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 19957 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 19958 19959 #undef CHECK_ALIGN_CONSECUTIVE 19960 19961 Style.PointerAlignment = FormatStyle::PAS_Middle; 19962 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19963 FormatStyle::PAS_Left); 19964 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19965 FormatStyle::PAS_Right); 19966 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19967 FormatStyle::PAS_Middle); 19968 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19969 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19970 FormatStyle::RAS_Pointer); 19971 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19972 FormatStyle::RAS_Left); 19973 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19974 FormatStyle::RAS_Right); 19975 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19976 FormatStyle::RAS_Middle); 19977 // For backward compatibility: 19978 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19979 FormatStyle::PAS_Left); 19980 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19981 FormatStyle::PAS_Right); 19982 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19983 FormatStyle::PAS_Middle); 19984 19985 Style.Standard = FormatStyle::LS_Auto; 19986 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19987 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19988 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19989 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19990 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19991 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19992 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19993 // Legacy aliases: 19994 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19995 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19996 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19997 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19998 19999 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 20000 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 20001 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 20002 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 20003 FormatStyle::BOS_None); 20004 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 20005 FormatStyle::BOS_All); 20006 // For backward compatibility: 20007 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 20008 FormatStyle::BOS_None); 20009 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 20010 FormatStyle::BOS_All); 20011 20012 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20013 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20014 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20015 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20016 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20017 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20018 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20019 // For backward compatibility: 20020 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20021 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20022 20023 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20024 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20025 FormatStyle::BILS_AfterComma); 20026 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20027 FormatStyle::BILS_BeforeComma); 20028 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20029 FormatStyle::BILS_AfterColon); 20030 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20031 FormatStyle::BILS_BeforeColon); 20032 // For backward compatibility: 20033 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20034 FormatStyle::BILS_BeforeComma); 20035 20036 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20037 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20038 FormatStyle::PCIS_Never); 20039 CHECK_PARSE("PackConstructorInitializers: BinPack", 20040 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20041 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20042 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20043 CHECK_PARSE("PackConstructorInitializers: NextLine", 20044 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20045 // For backward compatibility: 20046 CHECK_PARSE("BasedOnStyle: Google\n" 20047 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20048 "AllowAllConstructorInitializersOnNextLine: false", 20049 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20050 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20051 CHECK_PARSE("BasedOnStyle: Google\n" 20052 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20053 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20054 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20055 "AllowAllConstructorInitializersOnNextLine: true", 20056 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20057 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20058 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20059 "AllowAllConstructorInitializersOnNextLine: false", 20060 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20061 20062 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20063 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20064 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20065 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20066 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20067 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20068 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20069 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20070 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20071 20072 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20073 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20074 FormatStyle::BAS_Align); 20075 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20076 FormatStyle::BAS_DontAlign); 20077 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20078 FormatStyle::BAS_AlwaysBreak); 20079 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20080 FormatStyle::BAS_BlockIndent); 20081 // For backward compatibility: 20082 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20083 FormatStyle::BAS_DontAlign); 20084 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20085 FormatStyle::BAS_Align); 20086 20087 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20088 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20089 FormatStyle::ENAS_DontAlign); 20090 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20091 FormatStyle::ENAS_Left); 20092 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20093 FormatStyle::ENAS_Right); 20094 // For backward compatibility: 20095 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20096 FormatStyle::ENAS_Left); 20097 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20098 FormatStyle::ENAS_Right); 20099 20100 Style.AlignOperands = FormatStyle::OAS_Align; 20101 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20102 FormatStyle::OAS_DontAlign); 20103 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20104 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20105 FormatStyle::OAS_AlignAfterOperator); 20106 // For backward compatibility: 20107 CHECK_PARSE("AlignOperands: false", AlignOperands, 20108 FormatStyle::OAS_DontAlign); 20109 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20110 20111 Style.UseTab = FormatStyle::UT_ForIndentation; 20112 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20113 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20114 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20115 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20116 FormatStyle::UT_ForContinuationAndIndentation); 20117 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20118 FormatStyle::UT_AlignWithSpaces); 20119 // For backward compatibility: 20120 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20121 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20122 20123 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20124 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20125 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20126 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20127 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20128 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20129 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20130 // For backward compatibility: 20131 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20132 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20133 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20134 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20135 20136 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20137 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20138 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20139 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20140 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20141 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20142 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20143 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20144 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20145 // For backward compatibility: 20146 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20147 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20148 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20149 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20150 20151 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20152 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20153 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20154 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20155 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20156 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20157 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20158 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20159 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20160 20161 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20162 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20163 FormatStyle::SBPO_Never); 20164 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20165 FormatStyle::SBPO_Always); 20166 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20167 FormatStyle::SBPO_ControlStatements); 20168 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20169 SpaceBeforeParens, 20170 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20171 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20172 FormatStyle::SBPO_NonEmptyParentheses); 20173 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20174 FormatStyle::SBPO_Custom); 20175 // For backward compatibility: 20176 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20177 FormatStyle::SBPO_Never); 20178 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20179 FormatStyle::SBPO_ControlStatements); 20180 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20181 SpaceBeforeParens, 20182 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20183 20184 Style.ColumnLimit = 123; 20185 FormatStyle BaseStyle = getLLVMStyle(); 20186 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20187 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20188 20189 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20190 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20191 FormatStyle::BS_Attach); 20192 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20193 FormatStyle::BS_Linux); 20194 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20195 FormatStyle::BS_Mozilla); 20196 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20197 FormatStyle::BS_Stroustrup); 20198 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20199 FormatStyle::BS_Allman); 20200 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20201 FormatStyle::BS_Whitesmiths); 20202 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20203 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20204 FormatStyle::BS_WebKit); 20205 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20206 FormatStyle::BS_Custom); 20207 20208 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20209 CHECK_PARSE("BraceWrapping:\n" 20210 " AfterControlStatement: MultiLine", 20211 BraceWrapping.AfterControlStatement, 20212 FormatStyle::BWACS_MultiLine); 20213 CHECK_PARSE("BraceWrapping:\n" 20214 " AfterControlStatement: Always", 20215 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20216 CHECK_PARSE("BraceWrapping:\n" 20217 " AfterControlStatement: Never", 20218 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20219 // For backward compatibility: 20220 CHECK_PARSE("BraceWrapping:\n" 20221 " AfterControlStatement: true", 20222 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20223 CHECK_PARSE("BraceWrapping:\n" 20224 " AfterControlStatement: false", 20225 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20226 20227 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20228 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20229 FormatStyle::RTBS_None); 20230 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20231 FormatStyle::RTBS_All); 20232 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20233 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20234 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20235 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20236 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20237 AlwaysBreakAfterReturnType, 20238 FormatStyle::RTBS_TopLevelDefinitions); 20239 20240 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20241 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20242 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20243 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20244 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20245 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20246 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20247 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20248 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20249 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20250 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20251 20252 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20253 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20254 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20255 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20256 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20257 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20258 AlwaysBreakAfterDefinitionReturnType, 20259 FormatStyle::DRTBS_TopLevel); 20260 20261 Style.NamespaceIndentation = FormatStyle::NI_All; 20262 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20263 FormatStyle::NI_None); 20264 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20265 FormatStyle::NI_Inner); 20266 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20267 FormatStyle::NI_All); 20268 20269 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20270 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20271 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20272 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20273 AllowShortIfStatementsOnASingleLine, 20274 FormatStyle::SIS_WithoutElse); 20275 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20276 AllowShortIfStatementsOnASingleLine, 20277 FormatStyle::SIS_OnlyFirstIf); 20278 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20279 AllowShortIfStatementsOnASingleLine, 20280 FormatStyle::SIS_AllIfsAndElse); 20281 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20282 AllowShortIfStatementsOnASingleLine, 20283 FormatStyle::SIS_OnlyFirstIf); 20284 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20285 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20286 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20287 AllowShortIfStatementsOnASingleLine, 20288 FormatStyle::SIS_WithoutElse); 20289 20290 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20291 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20292 FormatStyle::IEBS_AfterExternBlock); 20293 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20294 FormatStyle::IEBS_Indent); 20295 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20296 FormatStyle::IEBS_NoIndent); 20297 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20298 FormatStyle::IEBS_Indent); 20299 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20300 FormatStyle::IEBS_NoIndent); 20301 20302 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20303 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20304 FormatStyle::BFCS_Both); 20305 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20306 FormatStyle::BFCS_None); 20307 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20308 FormatStyle::BFCS_Before); 20309 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20310 FormatStyle::BFCS_After); 20311 20312 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20313 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20314 FormatStyle::SJSIO_After); 20315 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20316 FormatStyle::SJSIO_Before); 20317 20318 // FIXME: This is required because parsing a configuration simply overwrites 20319 // the first N elements of the list instead of resetting it. 20320 Style.ForEachMacros.clear(); 20321 std::vector<std::string> BoostForeach; 20322 BoostForeach.push_back("BOOST_FOREACH"); 20323 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20324 std::vector<std::string> BoostAndQForeach; 20325 BoostAndQForeach.push_back("BOOST_FOREACH"); 20326 BoostAndQForeach.push_back("Q_FOREACH"); 20327 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20328 BoostAndQForeach); 20329 20330 Style.IfMacros.clear(); 20331 std::vector<std::string> CustomIfs; 20332 CustomIfs.push_back("MYIF"); 20333 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20334 20335 Style.AttributeMacros.clear(); 20336 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20337 std::vector<std::string>{"__capability"}); 20338 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20339 std::vector<std::string>({"attr1", "attr2"})); 20340 20341 Style.StatementAttributeLikeMacros.clear(); 20342 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20343 StatementAttributeLikeMacros, 20344 std::vector<std::string>({"emit", "Q_EMIT"})); 20345 20346 Style.StatementMacros.clear(); 20347 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20348 std::vector<std::string>{"QUNUSED"}); 20349 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20350 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20351 20352 Style.NamespaceMacros.clear(); 20353 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20354 std::vector<std::string>{"TESTSUITE"}); 20355 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20356 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20357 20358 Style.WhitespaceSensitiveMacros.clear(); 20359 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20360 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20361 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20362 WhitespaceSensitiveMacros, 20363 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20364 Style.WhitespaceSensitiveMacros.clear(); 20365 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20366 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20367 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20368 WhitespaceSensitiveMacros, 20369 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20370 20371 Style.IncludeStyle.IncludeCategories.clear(); 20372 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20373 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20374 CHECK_PARSE("IncludeCategories:\n" 20375 " - Regex: abc/.*\n" 20376 " Priority: 2\n" 20377 " - Regex: .*\n" 20378 " Priority: 1\n" 20379 " CaseSensitive: true\n", 20380 IncludeStyle.IncludeCategories, ExpectedCategories); 20381 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20382 "abc$"); 20383 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20384 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20385 20386 Style.SortIncludes = FormatStyle::SI_Never; 20387 CHECK_PARSE("SortIncludes: true", SortIncludes, 20388 FormatStyle::SI_CaseSensitive); 20389 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20390 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20391 FormatStyle::SI_CaseInsensitive); 20392 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20393 FormatStyle::SI_CaseSensitive); 20394 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20395 20396 Style.RawStringFormats.clear(); 20397 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20398 { 20399 FormatStyle::LK_TextProto, 20400 {"pb", "proto"}, 20401 {"PARSE_TEXT_PROTO"}, 20402 /*CanonicalDelimiter=*/"", 20403 "llvm", 20404 }, 20405 { 20406 FormatStyle::LK_Cpp, 20407 {"cc", "cpp"}, 20408 {"C_CODEBLOCK", "CPPEVAL"}, 20409 /*CanonicalDelimiter=*/"cc", 20410 /*BasedOnStyle=*/"", 20411 }, 20412 }; 20413 20414 CHECK_PARSE("RawStringFormats:\n" 20415 " - Language: TextProto\n" 20416 " Delimiters:\n" 20417 " - 'pb'\n" 20418 " - 'proto'\n" 20419 " EnclosingFunctions:\n" 20420 " - 'PARSE_TEXT_PROTO'\n" 20421 " BasedOnStyle: llvm\n" 20422 " - Language: Cpp\n" 20423 " Delimiters:\n" 20424 " - 'cc'\n" 20425 " - 'cpp'\n" 20426 " EnclosingFunctions:\n" 20427 " - 'C_CODEBLOCK'\n" 20428 " - 'CPPEVAL'\n" 20429 " CanonicalDelimiter: 'cc'", 20430 RawStringFormats, ExpectedRawStringFormats); 20431 20432 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20433 " Minimum: 0\n" 20434 " Maximum: 0", 20435 SpacesInLineCommentPrefix.Minimum, 0u); 20436 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20437 Style.SpacesInLineCommentPrefix.Minimum = 1; 20438 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20439 " Minimum: 2", 20440 SpacesInLineCommentPrefix.Minimum, 0u); 20441 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20442 " Maximum: -1", 20443 SpacesInLineCommentPrefix.Maximum, -1u); 20444 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20445 " Minimum: 2", 20446 SpacesInLineCommentPrefix.Minimum, 2u); 20447 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20448 " Maximum: 1", 20449 SpacesInLineCommentPrefix.Maximum, 1u); 20450 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20451 20452 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20453 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20454 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20455 FormatStyle::SIAS_Always); 20456 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20457 // For backward compatibility: 20458 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20459 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20460 20461 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20462 FormatStyle::RCPS_WithPreceding); 20463 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20464 FormatStyle::RCPS_WithFollowing); 20465 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20466 FormatStyle::RCPS_SingleLine); 20467 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20468 FormatStyle::RCPS_OwnLine); 20469 20470 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20471 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20472 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20473 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20474 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20475 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20476 // For backward compatibility: 20477 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20478 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20479 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20480 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20481 } 20482 20483 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20484 FormatStyle Style = {}; 20485 Style.Language = FormatStyle::LK_Cpp; 20486 CHECK_PARSE("Language: Cpp\n" 20487 "IndentWidth: 12", 20488 IndentWidth, 12u); 20489 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20490 "IndentWidth: 34", 20491 &Style), 20492 ParseError::Unsuitable); 20493 FormatStyle BinPackedTCS = {}; 20494 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20495 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20496 "InsertTrailingCommas: Wrapped", 20497 &BinPackedTCS), 20498 ParseError::BinPackTrailingCommaConflict); 20499 EXPECT_EQ(12u, Style.IndentWidth); 20500 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20501 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20502 20503 Style.Language = FormatStyle::LK_JavaScript; 20504 CHECK_PARSE("Language: JavaScript\n" 20505 "IndentWidth: 12", 20506 IndentWidth, 12u); 20507 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20508 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20509 "IndentWidth: 34", 20510 &Style), 20511 ParseError::Unsuitable); 20512 EXPECT_EQ(23u, Style.IndentWidth); 20513 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20514 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20515 20516 CHECK_PARSE("BasedOnStyle: LLVM\n" 20517 "IndentWidth: 67", 20518 IndentWidth, 67u); 20519 20520 CHECK_PARSE("---\n" 20521 "Language: JavaScript\n" 20522 "IndentWidth: 12\n" 20523 "---\n" 20524 "Language: Cpp\n" 20525 "IndentWidth: 34\n" 20526 "...\n", 20527 IndentWidth, 12u); 20528 20529 Style.Language = FormatStyle::LK_Cpp; 20530 CHECK_PARSE("---\n" 20531 "Language: JavaScript\n" 20532 "IndentWidth: 12\n" 20533 "---\n" 20534 "Language: Cpp\n" 20535 "IndentWidth: 34\n" 20536 "...\n", 20537 IndentWidth, 34u); 20538 CHECK_PARSE("---\n" 20539 "IndentWidth: 78\n" 20540 "---\n" 20541 "Language: JavaScript\n" 20542 "IndentWidth: 56\n" 20543 "...\n", 20544 IndentWidth, 78u); 20545 20546 Style.ColumnLimit = 123; 20547 Style.IndentWidth = 234; 20548 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20549 Style.TabWidth = 345; 20550 EXPECT_FALSE(parseConfiguration("---\n" 20551 "IndentWidth: 456\n" 20552 "BreakBeforeBraces: Allman\n" 20553 "---\n" 20554 "Language: JavaScript\n" 20555 "IndentWidth: 111\n" 20556 "TabWidth: 111\n" 20557 "---\n" 20558 "Language: Cpp\n" 20559 "BreakBeforeBraces: Stroustrup\n" 20560 "TabWidth: 789\n" 20561 "...\n", 20562 &Style)); 20563 EXPECT_EQ(123u, Style.ColumnLimit); 20564 EXPECT_EQ(456u, Style.IndentWidth); 20565 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20566 EXPECT_EQ(789u, Style.TabWidth); 20567 20568 EXPECT_EQ(parseConfiguration("---\n" 20569 "Language: JavaScript\n" 20570 "IndentWidth: 56\n" 20571 "---\n" 20572 "IndentWidth: 78\n" 20573 "...\n", 20574 &Style), 20575 ParseError::Error); 20576 EXPECT_EQ(parseConfiguration("---\n" 20577 "Language: JavaScript\n" 20578 "IndentWidth: 56\n" 20579 "---\n" 20580 "Language: JavaScript\n" 20581 "IndentWidth: 78\n" 20582 "...\n", 20583 &Style), 20584 ParseError::Error); 20585 20586 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20587 } 20588 20589 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20590 FormatStyle Style = {}; 20591 Style.Language = FormatStyle::LK_JavaScript; 20592 Style.BreakBeforeTernaryOperators = true; 20593 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20594 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20595 20596 Style.BreakBeforeTernaryOperators = true; 20597 EXPECT_EQ(0, parseConfiguration("---\n" 20598 "BasedOnStyle: Google\n" 20599 "---\n" 20600 "Language: JavaScript\n" 20601 "IndentWidth: 76\n" 20602 "...\n", 20603 &Style) 20604 .value()); 20605 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20606 EXPECT_EQ(76u, Style.IndentWidth); 20607 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20608 } 20609 20610 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20611 FormatStyle Style = getLLVMStyle(); 20612 std::string YAML = configurationAsText(Style); 20613 FormatStyle ParsedStyle = {}; 20614 ParsedStyle.Language = FormatStyle::LK_Cpp; 20615 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20616 EXPECT_EQ(Style, ParsedStyle); 20617 } 20618 20619 TEST_F(FormatTest, WorksFor8bitEncodings) { 20620 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20621 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20622 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20623 "\"\xef\xee\xf0\xf3...\"", 20624 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20625 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20626 "\xef\xee\xf0\xf3...\"", 20627 getLLVMStyleWithColumns(12))); 20628 } 20629 20630 TEST_F(FormatTest, HandlesUTF8BOM) { 20631 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20632 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20633 format("\xef\xbb\xbf#include <iostream>")); 20634 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20635 format("\xef\xbb\xbf\n#include <iostream>")); 20636 } 20637 20638 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20639 #if !defined(_MSC_VER) 20640 20641 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20642 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20643 getLLVMStyleWithColumns(35)); 20644 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20645 getLLVMStyleWithColumns(31)); 20646 verifyFormat("// Однажды в студёную зимнюю пору...", 20647 getLLVMStyleWithColumns(36)); 20648 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20649 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20650 getLLVMStyleWithColumns(39)); 20651 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20652 getLLVMStyleWithColumns(35)); 20653 } 20654 20655 TEST_F(FormatTest, SplitsUTF8Strings) { 20656 // Non-printable characters' width is currently considered to be the length in 20657 // bytes in UTF8. The characters can be displayed in very different manner 20658 // (zero-width, single width with a substitution glyph, expanded to their code 20659 // (e.g. "<8d>"), so there's no single correct way to handle them. 20660 EXPECT_EQ("\"aaaaÄ\"\n" 20661 "\"\xc2\x8d\";", 20662 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20663 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20664 "\"\xc2\x8d\";", 20665 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20666 EXPECT_EQ("\"Однажды, в \"\n" 20667 "\"студёную \"\n" 20668 "\"зимнюю \"\n" 20669 "\"пору,\"", 20670 format("\"Однажды, в студёную зимнюю пору,\"", 20671 getLLVMStyleWithColumns(13))); 20672 EXPECT_EQ( 20673 "\"一 二 三 \"\n" 20674 "\"四 五六 \"\n" 20675 "\"七 八 九 \"\n" 20676 "\"十\"", 20677 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20678 EXPECT_EQ("\"一\t\"\n" 20679 "\"二 \t\"\n" 20680 "\"三 四 \"\n" 20681 "\"五\t\"\n" 20682 "\"六 \t\"\n" 20683 "\"七 \"\n" 20684 "\"八九十\tqq\"", 20685 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20686 getLLVMStyleWithColumns(11))); 20687 20688 // UTF8 character in an escape sequence. 20689 EXPECT_EQ("\"aaaaaa\"\n" 20690 "\"\\\xC2\x8D\"", 20691 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20692 } 20693 20694 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20695 EXPECT_EQ("const char *sssss =\n" 20696 " \"一二三四五六七八\\\n" 20697 " 九 十\";", 20698 format("const char *sssss = \"一二三四五六七八\\\n" 20699 " 九 十\";", 20700 getLLVMStyleWithColumns(30))); 20701 } 20702 20703 TEST_F(FormatTest, SplitsUTF8LineComments) { 20704 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20705 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20706 EXPECT_EQ("// Я из лесу\n" 20707 "// вышел; был\n" 20708 "// сильный\n" 20709 "// мороз.", 20710 format("// Я из лесу вышел; был сильный мороз.", 20711 getLLVMStyleWithColumns(13))); 20712 EXPECT_EQ("// 一二三\n" 20713 "// 四五六七\n" 20714 "// 八 九\n" 20715 "// 十", 20716 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20717 } 20718 20719 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20720 EXPECT_EQ("/* Гляжу,\n" 20721 " * поднимается\n" 20722 " * медленно в\n" 20723 " * гору\n" 20724 " * Лошадка,\n" 20725 " * везущая\n" 20726 " * хворосту\n" 20727 " * воз. */", 20728 format("/* Гляжу, поднимается медленно в гору\n" 20729 " * Лошадка, везущая хворосту воз. */", 20730 getLLVMStyleWithColumns(13))); 20731 EXPECT_EQ( 20732 "/* 一二三\n" 20733 " * 四五六七\n" 20734 " * 八 九\n" 20735 " * 十 */", 20736 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20737 EXPECT_EQ("/* \n" 20738 " * \n" 20739 " * - */", 20740 format("/* - */", getLLVMStyleWithColumns(12))); 20741 } 20742 20743 #endif // _MSC_VER 20744 20745 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20746 FormatStyle Style = getLLVMStyle(); 20747 20748 Style.ConstructorInitializerIndentWidth = 4; 20749 verifyFormat( 20750 "SomeClass::Constructor()\n" 20751 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20752 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20753 Style); 20754 20755 Style.ConstructorInitializerIndentWidth = 2; 20756 verifyFormat( 20757 "SomeClass::Constructor()\n" 20758 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20759 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20760 Style); 20761 20762 Style.ConstructorInitializerIndentWidth = 0; 20763 verifyFormat( 20764 "SomeClass::Constructor()\n" 20765 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20766 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20767 Style); 20768 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20769 verifyFormat( 20770 "SomeLongTemplateVariableName<\n" 20771 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20772 Style); 20773 verifyFormat("bool smaller = 1 < " 20774 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20775 " " 20776 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20777 Style); 20778 20779 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20780 verifyFormat("SomeClass::Constructor() :\n" 20781 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20782 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20783 Style); 20784 } 20785 20786 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20787 FormatStyle Style = getLLVMStyle(); 20788 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20789 Style.ConstructorInitializerIndentWidth = 4; 20790 verifyFormat("SomeClass::Constructor()\n" 20791 " : a(a)\n" 20792 " , b(b)\n" 20793 " , c(c) {}", 20794 Style); 20795 verifyFormat("SomeClass::Constructor()\n" 20796 " : a(a) {}", 20797 Style); 20798 20799 Style.ColumnLimit = 0; 20800 verifyFormat("SomeClass::Constructor()\n" 20801 " : a(a) {}", 20802 Style); 20803 verifyFormat("SomeClass::Constructor() noexcept\n" 20804 " : a(a) {}", 20805 Style); 20806 verifyFormat("SomeClass::Constructor()\n" 20807 " : a(a)\n" 20808 " , b(b)\n" 20809 " , c(c) {}", 20810 Style); 20811 verifyFormat("SomeClass::Constructor()\n" 20812 " : a(a) {\n" 20813 " foo();\n" 20814 " bar();\n" 20815 "}", 20816 Style); 20817 20818 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20819 verifyFormat("SomeClass::Constructor()\n" 20820 " : a(a)\n" 20821 " , b(b)\n" 20822 " , c(c) {\n}", 20823 Style); 20824 verifyFormat("SomeClass::Constructor()\n" 20825 " : a(a) {\n}", 20826 Style); 20827 20828 Style.ColumnLimit = 80; 20829 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20830 Style.ConstructorInitializerIndentWidth = 2; 20831 verifyFormat("SomeClass::Constructor()\n" 20832 " : a(a)\n" 20833 " , b(b)\n" 20834 " , c(c) {}", 20835 Style); 20836 20837 Style.ConstructorInitializerIndentWidth = 0; 20838 verifyFormat("SomeClass::Constructor()\n" 20839 ": a(a)\n" 20840 ", b(b)\n" 20841 ", c(c) {}", 20842 Style); 20843 20844 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20845 Style.ConstructorInitializerIndentWidth = 4; 20846 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20847 verifyFormat( 20848 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20849 Style); 20850 verifyFormat( 20851 "SomeClass::Constructor()\n" 20852 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20853 Style); 20854 Style.ConstructorInitializerIndentWidth = 4; 20855 Style.ColumnLimit = 60; 20856 verifyFormat("SomeClass::Constructor()\n" 20857 " : aaaaaaaa(aaaaaaaa)\n" 20858 " , aaaaaaaa(aaaaaaaa)\n" 20859 " , aaaaaaaa(aaaaaaaa) {}", 20860 Style); 20861 } 20862 20863 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20864 FormatStyle Style = getLLVMStyle(); 20865 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20866 Style.ConstructorInitializerIndentWidth = 4; 20867 verifyFormat("SomeClass::Constructor()\n" 20868 " : a{a}\n" 20869 " , b{b} {}", 20870 Style); 20871 verifyFormat("SomeClass::Constructor()\n" 20872 " : a{a}\n" 20873 "#if CONDITION\n" 20874 " , b{b}\n" 20875 "#endif\n" 20876 "{\n}", 20877 Style); 20878 Style.ConstructorInitializerIndentWidth = 2; 20879 verifyFormat("SomeClass::Constructor()\n" 20880 "#if CONDITION\n" 20881 " : a{a}\n" 20882 "#endif\n" 20883 " , b{b}\n" 20884 " , c{c} {\n}", 20885 Style); 20886 Style.ConstructorInitializerIndentWidth = 0; 20887 verifyFormat("SomeClass::Constructor()\n" 20888 ": a{a}\n" 20889 "#ifdef CONDITION\n" 20890 ", b{b}\n" 20891 "#else\n" 20892 ", c{c}\n" 20893 "#endif\n" 20894 ", d{d} {\n}", 20895 Style); 20896 Style.ConstructorInitializerIndentWidth = 4; 20897 verifyFormat("SomeClass::Constructor()\n" 20898 " : a{a}\n" 20899 "#if WINDOWS\n" 20900 "#if DEBUG\n" 20901 " , b{0}\n" 20902 "#else\n" 20903 " , b{1}\n" 20904 "#endif\n" 20905 "#else\n" 20906 "#if DEBUG\n" 20907 " , b{2}\n" 20908 "#else\n" 20909 " , b{3}\n" 20910 "#endif\n" 20911 "#endif\n" 20912 "{\n}", 20913 Style); 20914 verifyFormat("SomeClass::Constructor()\n" 20915 " : a{a}\n" 20916 "#if WINDOWS\n" 20917 " , b{0}\n" 20918 "#if DEBUG\n" 20919 " , c{0}\n" 20920 "#else\n" 20921 " , c{1}\n" 20922 "#endif\n" 20923 "#else\n" 20924 "#if DEBUG\n" 20925 " , c{2}\n" 20926 "#else\n" 20927 " , c{3}\n" 20928 "#endif\n" 20929 " , b{1}\n" 20930 "#endif\n" 20931 "{\n}", 20932 Style); 20933 } 20934 20935 TEST_F(FormatTest, Destructors) { 20936 verifyFormat("void F(int &i) { i.~int(); }"); 20937 verifyFormat("void F(int &i) { i->~int(); }"); 20938 } 20939 20940 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20941 FormatStyle Style = getWebKitStyle(); 20942 20943 // Don't indent in outer namespaces. 20944 verifyFormat("namespace outer {\n" 20945 "int i;\n" 20946 "namespace inner {\n" 20947 " int i;\n" 20948 "} // namespace inner\n" 20949 "} // namespace outer\n" 20950 "namespace other_outer {\n" 20951 "int i;\n" 20952 "}", 20953 Style); 20954 20955 // Don't indent case labels. 20956 verifyFormat("switch (variable) {\n" 20957 "case 1:\n" 20958 "case 2:\n" 20959 " doSomething();\n" 20960 " break;\n" 20961 "default:\n" 20962 " ++variable;\n" 20963 "}", 20964 Style); 20965 20966 // Wrap before binary operators. 20967 EXPECT_EQ("void f()\n" 20968 "{\n" 20969 " if (aaaaaaaaaaaaaaaa\n" 20970 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20971 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20972 " return;\n" 20973 "}", 20974 format("void f() {\n" 20975 "if (aaaaaaaaaaaaaaaa\n" 20976 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20977 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20978 "return;\n" 20979 "}", 20980 Style)); 20981 20982 // Allow functions on a single line. 20983 verifyFormat("void f() { return; }", Style); 20984 20985 // Allow empty blocks on a single line and insert a space in empty blocks. 20986 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20987 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20988 // However, don't merge non-empty short loops. 20989 EXPECT_EQ("while (true) {\n" 20990 " continue;\n" 20991 "}", 20992 format("while (true) { continue; }", Style)); 20993 20994 // Constructor initializers are formatted one per line with the "," on the 20995 // new line. 20996 verifyFormat("Constructor()\n" 20997 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20998 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20999 " aaaaaaaaaaaaaa)\n" 21000 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 21001 "{\n" 21002 "}", 21003 Style); 21004 verifyFormat("SomeClass::Constructor()\n" 21005 " : a(a)\n" 21006 "{\n" 21007 "}", 21008 Style); 21009 EXPECT_EQ("SomeClass::Constructor()\n" 21010 " : a(a)\n" 21011 "{\n" 21012 "}", 21013 format("SomeClass::Constructor():a(a){}", Style)); 21014 verifyFormat("SomeClass::Constructor()\n" 21015 " : a(a)\n" 21016 " , b(b)\n" 21017 " , c(c)\n" 21018 "{\n" 21019 "}", 21020 Style); 21021 verifyFormat("SomeClass::Constructor()\n" 21022 " : a(a)\n" 21023 "{\n" 21024 " foo();\n" 21025 " bar();\n" 21026 "}", 21027 Style); 21028 21029 // Access specifiers should be aligned left. 21030 verifyFormat("class C {\n" 21031 "public:\n" 21032 " int i;\n" 21033 "};", 21034 Style); 21035 21036 // Do not align comments. 21037 verifyFormat("int a; // Do not\n" 21038 "double b; // align comments.", 21039 Style); 21040 21041 // Do not align operands. 21042 EXPECT_EQ("ASSERT(aaaa\n" 21043 " || bbbb);", 21044 format("ASSERT ( aaaa\n||bbbb);", Style)); 21045 21046 // Accept input's line breaks. 21047 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21048 " || bbbbbbbbbbbbbbb) {\n" 21049 " i++;\n" 21050 "}", 21051 format("if (aaaaaaaaaaaaaaa\n" 21052 "|| bbbbbbbbbbbbbbb) { i++; }", 21053 Style)); 21054 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21055 " i++;\n" 21056 "}", 21057 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21058 21059 // Don't automatically break all macro definitions (llvm.org/PR17842). 21060 verifyFormat("#define aNumber 10", Style); 21061 // However, generally keep the line breaks that the user authored. 21062 EXPECT_EQ("#define aNumber \\\n" 21063 " 10", 21064 format("#define aNumber \\\n" 21065 " 10", 21066 Style)); 21067 21068 // Keep empty and one-element array literals on a single line. 21069 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21070 " copyItems:YES];", 21071 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21072 "copyItems:YES];", 21073 Style)); 21074 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21075 " copyItems:YES];", 21076 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21077 " copyItems:YES];", 21078 Style)); 21079 // FIXME: This does not seem right, there should be more indentation before 21080 // the array literal's entries. Nested blocks have the same problem. 21081 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21082 " @\"a\",\n" 21083 " @\"a\"\n" 21084 "]\n" 21085 " copyItems:YES];", 21086 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21087 " @\"a\",\n" 21088 " @\"a\"\n" 21089 " ]\n" 21090 " copyItems:YES];", 21091 Style)); 21092 EXPECT_EQ( 21093 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21094 " copyItems:YES];", 21095 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21096 " copyItems:YES];", 21097 Style)); 21098 21099 verifyFormat("[self.a b:c c:d];", Style); 21100 EXPECT_EQ("[self.a b:c\n" 21101 " c:d];", 21102 format("[self.a b:c\n" 21103 "c:d];", 21104 Style)); 21105 } 21106 21107 TEST_F(FormatTest, FormatsLambdas) { 21108 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21109 verifyFormat( 21110 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21111 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21112 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21113 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21114 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21115 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21116 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21117 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21118 verifyFormat("int x = f(*+[] {});"); 21119 verifyFormat("void f() {\n" 21120 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21121 "}\n"); 21122 verifyFormat("void f() {\n" 21123 " other(x.begin(), //\n" 21124 " x.end(), //\n" 21125 " [&](int, int) { return 1; });\n" 21126 "}\n"); 21127 verifyFormat("void f() {\n" 21128 " other.other.other.other.other(\n" 21129 " x.begin(), x.end(),\n" 21130 " [something, rather](int, int, int, int, int, int, int) { " 21131 "return 1; });\n" 21132 "}\n"); 21133 verifyFormat( 21134 "void f() {\n" 21135 " other.other.other.other.other(\n" 21136 " x.begin(), x.end(),\n" 21137 " [something, rather](int, int, int, int, int, int, int) {\n" 21138 " //\n" 21139 " });\n" 21140 "}\n"); 21141 verifyFormat("SomeFunction([]() { // A cool function...\n" 21142 " return 43;\n" 21143 "});"); 21144 EXPECT_EQ("SomeFunction([]() {\n" 21145 "#define A a\n" 21146 " return 43;\n" 21147 "});", 21148 format("SomeFunction([](){\n" 21149 "#define A a\n" 21150 "return 43;\n" 21151 "});")); 21152 verifyFormat("void f() {\n" 21153 " SomeFunction([](decltype(x), A *a) {});\n" 21154 " SomeFunction([](typeof(x), A *a) {});\n" 21155 " SomeFunction([](_Atomic(x), A *a) {});\n" 21156 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21157 "}"); 21158 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21159 " [](const aaaaaaaaaa &a) { return a; });"); 21160 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21161 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21162 "});"); 21163 verifyFormat("Constructor()\n" 21164 " : Field([] { // comment\n" 21165 " int i;\n" 21166 " }) {}"); 21167 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21168 " return some_parameter.size();\n" 21169 "};"); 21170 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21171 " [](const string &s) { return s; };"); 21172 verifyFormat("int i = aaaaaa ? 1 //\n" 21173 " : [] {\n" 21174 " return 2; //\n" 21175 " }();"); 21176 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21177 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21178 " return x == 2; // force break\n" 21179 " });"); 21180 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21181 " [=](int iiiiiiiiiiii) {\n" 21182 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21183 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21184 " });", 21185 getLLVMStyleWithColumns(60)); 21186 21187 verifyFormat("SomeFunction({[&] {\n" 21188 " // comment\n" 21189 " },\n" 21190 " [&] {\n" 21191 " // comment\n" 21192 " }});"); 21193 verifyFormat("SomeFunction({[&] {\n" 21194 " // comment\n" 21195 "}});"); 21196 verifyFormat( 21197 "virtual aaaaaaaaaaaaaaaa(\n" 21198 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21199 " aaaaa aaaaaaaaa);"); 21200 21201 // Lambdas with return types. 21202 verifyFormat("int c = []() -> int { return 2; }();\n"); 21203 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21204 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21205 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21206 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21207 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21208 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21209 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21210 verifyFormat("[a, a]() -> a<1> {};"); 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<!5> { return {}; };"); 21218 verifyFormat("[]() -> foo<~5> { return {}; };"); 21219 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21220 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21221 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21222 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21223 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21224 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21225 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21226 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21227 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21228 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21229 verifyFormat("namespace bar {\n" 21230 "// broken:\n" 21231 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21232 "} // namespace bar"); 21233 verifyFormat("namespace bar {\n" 21234 "// broken:\n" 21235 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21236 "} // namespace bar"); 21237 verifyFormat("namespace bar {\n" 21238 "// broken:\n" 21239 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21240 "} // namespace bar"); 21241 verifyFormat("namespace bar {\n" 21242 "// broken:\n" 21243 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21244 "} // namespace bar"); 21245 verifyFormat("namespace bar {\n" 21246 "// broken:\n" 21247 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21248 "} // namespace bar"); 21249 verifyFormat("namespace bar {\n" 21250 "// broken:\n" 21251 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21252 "} // namespace bar"); 21253 verifyFormat("namespace bar {\n" 21254 "// broken:\n" 21255 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21256 "} // namespace bar"); 21257 verifyFormat("namespace bar {\n" 21258 "// broken:\n" 21259 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21260 "} // namespace bar"); 21261 verifyFormat("namespace bar {\n" 21262 "// broken:\n" 21263 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21264 "} // namespace bar"); 21265 verifyFormat("namespace bar {\n" 21266 "// broken:\n" 21267 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21268 "} // namespace bar"); 21269 verifyFormat("namespace bar {\n" 21270 "// broken:\n" 21271 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21272 "} // namespace bar"); 21273 verifyFormat("namespace bar {\n" 21274 "// broken:\n" 21275 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21276 "} // namespace bar"); 21277 verifyFormat("namespace bar {\n" 21278 "// broken:\n" 21279 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21280 "} // namespace bar"); 21281 verifyFormat("namespace bar {\n" 21282 "// broken:\n" 21283 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21284 "} // namespace bar"); 21285 verifyFormat("namespace bar {\n" 21286 "// broken:\n" 21287 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21288 "} // namespace bar"); 21289 verifyFormat("namespace bar {\n" 21290 "// broken:\n" 21291 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21292 "} // namespace bar"); 21293 verifyFormat("namespace bar {\n" 21294 "// broken:\n" 21295 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21296 "} // namespace bar"); 21297 verifyFormat("namespace bar {\n" 21298 "// broken:\n" 21299 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21300 "} // namespace bar"); 21301 verifyFormat("[]() -> a<1> {};"); 21302 verifyFormat("[]() -> a<1> { ; };"); 21303 verifyFormat("[]() -> a<1> { ; }();"); 21304 verifyFormat("[a, a]() -> a<true> {};"); 21305 verifyFormat("[]() -> a<true> {};"); 21306 verifyFormat("[]() -> a<true> { ; };"); 21307 verifyFormat("[]() -> a<true> { ; }();"); 21308 verifyFormat("[a, a]() -> a<false> {};"); 21309 verifyFormat("[]() -> a<false> {};"); 21310 verifyFormat("[]() -> a<false> { ; };"); 21311 verifyFormat("[]() -> a<false> { ; }();"); 21312 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21313 verifyFormat("namespace bar {\n" 21314 "auto foo{[]() -> foo<false> { ; }};\n" 21315 "} // namespace bar"); 21316 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21317 " int j) -> int {\n" 21318 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21319 "};"); 21320 verifyFormat( 21321 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21322 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21323 " return aaaaaaaaaaaaaaaaa;\n" 21324 " });", 21325 getLLVMStyleWithColumns(70)); 21326 verifyFormat("[]() //\n" 21327 " -> int {\n" 21328 " return 1; //\n" 21329 "};"); 21330 verifyFormat("[]() -> Void<T...> {};"); 21331 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21332 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21333 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21334 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21335 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21336 verifyFormat("return int{[x = x]() { return x; }()};"); 21337 21338 // Lambdas with explicit template argument lists. 21339 verifyFormat( 21340 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21341 verifyFormat("auto L = []<class T>(T) {\n" 21342 " {\n" 21343 " f();\n" 21344 " g();\n" 21345 " }\n" 21346 "};\n"); 21347 verifyFormat("auto L = []<class... T>(T...) {\n" 21348 " {\n" 21349 " f();\n" 21350 " g();\n" 21351 " }\n" 21352 "};\n"); 21353 verifyFormat("auto L = []<typename... T>(T...) {\n" 21354 " {\n" 21355 " f();\n" 21356 " g();\n" 21357 " }\n" 21358 "};\n"); 21359 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21360 " {\n" 21361 " f();\n" 21362 " g();\n" 21363 " }\n" 21364 "};\n"); 21365 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21366 " {\n" 21367 " f();\n" 21368 " g();\n" 21369 " }\n" 21370 "};\n"); 21371 21372 // Multiple lambdas in the same parentheses change indentation rules. These 21373 // lambdas are forced to start on new lines. 21374 verifyFormat("SomeFunction(\n" 21375 " []() {\n" 21376 " //\n" 21377 " },\n" 21378 " []() {\n" 21379 " //\n" 21380 " });"); 21381 21382 // A lambda passed as arg0 is always pushed to the next line. 21383 verifyFormat("SomeFunction(\n" 21384 " [this] {\n" 21385 " //\n" 21386 " },\n" 21387 " 1);\n"); 21388 21389 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21390 // the arg0 case above. 21391 auto Style = getGoogleStyle(); 21392 Style.BinPackArguments = false; 21393 verifyFormat("SomeFunction(\n" 21394 " a,\n" 21395 " [this] {\n" 21396 " //\n" 21397 " },\n" 21398 " b);\n", 21399 Style); 21400 verifyFormat("SomeFunction(\n" 21401 " a,\n" 21402 " [this] {\n" 21403 " //\n" 21404 " },\n" 21405 " b);\n"); 21406 21407 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21408 // the BinPackArguments value (as long as the code is wide enough). 21409 verifyFormat( 21410 "something->SomeFunction(\n" 21411 " a,\n" 21412 " [this] {\n" 21413 " " 21414 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21415 " },\n" 21416 " b);\n"); 21417 21418 // A multi-line lambda is pulled up as long as the introducer fits on the 21419 // previous line and there are no further args. 21420 verifyFormat("function(1, [this, that] {\n" 21421 " //\n" 21422 "});\n"); 21423 verifyFormat("function([this, that] {\n" 21424 " //\n" 21425 "});\n"); 21426 // FIXME: this format is not ideal and we should consider forcing the first 21427 // arg onto its own line. 21428 verifyFormat("function(a, b, c, //\n" 21429 " d, [this, that] {\n" 21430 " //\n" 21431 " });\n"); 21432 21433 // Multiple lambdas are treated correctly even when there is a short arg0. 21434 verifyFormat("SomeFunction(\n" 21435 " 1,\n" 21436 " [this] {\n" 21437 " //\n" 21438 " },\n" 21439 " [this] {\n" 21440 " //\n" 21441 " },\n" 21442 " 1);\n"); 21443 21444 // More complex introducers. 21445 verifyFormat("return [i, args...] {};"); 21446 21447 // Not lambdas. 21448 verifyFormat("constexpr char hello[]{\"hello\"};"); 21449 verifyFormat("double &operator[](int i) { return 0; }\n" 21450 "int i;"); 21451 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21452 verifyFormat("int i = a[a][a]->f();"); 21453 verifyFormat("int i = (*b)[a]->f();"); 21454 21455 // Other corner cases. 21456 verifyFormat("void f() {\n" 21457 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21458 " );\n" 21459 "}"); 21460 21461 // Lambdas created through weird macros. 21462 verifyFormat("void f() {\n" 21463 " MACRO((const AA &a) { return 1; });\n" 21464 " MACRO((AA &a) { return 1; });\n" 21465 "}"); 21466 21467 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21468 " doo_dah();\n" 21469 " doo_dah();\n" 21470 " })) {\n" 21471 "}"); 21472 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21473 " doo_dah();\n" 21474 " doo_dah();\n" 21475 " })) {\n" 21476 "}"); 21477 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21478 " doo_dah();\n" 21479 " doo_dah();\n" 21480 " })) {\n" 21481 "}"); 21482 verifyFormat("auto lambda = []() {\n" 21483 " int a = 2\n" 21484 "#if A\n" 21485 " + 2\n" 21486 "#endif\n" 21487 " ;\n" 21488 "};"); 21489 21490 // Lambdas with complex multiline introducers. 21491 verifyFormat( 21492 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21493 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21494 " -> ::std::unordered_set<\n" 21495 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21496 " //\n" 21497 " });"); 21498 21499 FormatStyle DoNotMerge = getLLVMStyle(); 21500 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21501 verifyFormat("auto c = []() {\n" 21502 " return b;\n" 21503 "};", 21504 "auto c = []() { return b; };", DoNotMerge); 21505 verifyFormat("auto c = []() {\n" 21506 "};", 21507 " auto c = []() {};", DoNotMerge); 21508 21509 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21510 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21511 verifyFormat("auto c = []() {\n" 21512 " return b;\n" 21513 "};", 21514 "auto c = []() {\n" 21515 " return b;\n" 21516 " };", 21517 MergeEmptyOnly); 21518 verifyFormat("auto c = []() {};", 21519 "auto c = []() {\n" 21520 "};", 21521 MergeEmptyOnly); 21522 21523 FormatStyle MergeInline = getLLVMStyle(); 21524 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21525 verifyFormat("auto c = []() {\n" 21526 " return b;\n" 21527 "};", 21528 "auto c = []() { return b; };", MergeInline); 21529 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21530 MergeInline); 21531 verifyFormat("function([]() { return b; }, a)", 21532 "function([]() { return b; }, a)", MergeInline); 21533 verifyFormat("function(a, []() { return b; })", 21534 "function(a, []() { return b; })", MergeInline); 21535 21536 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21537 // AllowShortLambdasOnASingleLine 21538 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21539 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21540 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21541 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21542 FormatStyle::ShortLambdaStyle::SLS_None; 21543 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21544 " []()\n" 21545 " {\n" 21546 " return 17;\n" 21547 " });", 21548 LLVMWithBeforeLambdaBody); 21549 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21550 " []()\n" 21551 " {\n" 21552 " });", 21553 LLVMWithBeforeLambdaBody); 21554 verifyFormat("auto fct_SLS_None = []()\n" 21555 "{\n" 21556 " return 17;\n" 21557 "};", 21558 LLVMWithBeforeLambdaBody); 21559 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21560 " []()\n" 21561 " {\n" 21562 " return Call(\n" 21563 " []()\n" 21564 " {\n" 21565 " return 17;\n" 21566 " });\n" 21567 " });", 21568 LLVMWithBeforeLambdaBody); 21569 verifyFormat("void Fct() {\n" 21570 " return {[]()\n" 21571 " {\n" 21572 " return 17;\n" 21573 " }};\n" 21574 "}", 21575 LLVMWithBeforeLambdaBody); 21576 21577 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21578 FormatStyle::ShortLambdaStyle::SLS_Empty; 21579 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21580 " []()\n" 21581 " {\n" 21582 " return 17;\n" 21583 " });", 21584 LLVMWithBeforeLambdaBody); 21585 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21586 LLVMWithBeforeLambdaBody); 21587 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21588 "ongFunctionName_SLS_Empty(\n" 21589 " []() {});", 21590 LLVMWithBeforeLambdaBody); 21591 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21592 " []()\n" 21593 " {\n" 21594 " return 17;\n" 21595 " });", 21596 LLVMWithBeforeLambdaBody); 21597 verifyFormat("auto fct_SLS_Empty = []()\n" 21598 "{\n" 21599 " return 17;\n" 21600 "};", 21601 LLVMWithBeforeLambdaBody); 21602 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21603 " []()\n" 21604 " {\n" 21605 " return Call([]() {});\n" 21606 " });", 21607 LLVMWithBeforeLambdaBody); 21608 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21609 " []()\n" 21610 " {\n" 21611 " return Call([]() {});\n" 21612 " });", 21613 LLVMWithBeforeLambdaBody); 21614 verifyFormat( 21615 "FctWithLongLineInLambda_SLS_Empty(\n" 21616 " []()\n" 21617 " {\n" 21618 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21619 " AndShouldNotBeConsiderAsInline,\n" 21620 " LambdaBodyMustBeBreak);\n" 21621 " });", 21622 LLVMWithBeforeLambdaBody); 21623 21624 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21625 FormatStyle::ShortLambdaStyle::SLS_Inline; 21626 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21627 LLVMWithBeforeLambdaBody); 21628 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21629 LLVMWithBeforeLambdaBody); 21630 verifyFormat("auto fct_SLS_Inline = []()\n" 21631 "{\n" 21632 " return 17;\n" 21633 "};", 21634 LLVMWithBeforeLambdaBody); 21635 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21636 "17; }); });", 21637 LLVMWithBeforeLambdaBody); 21638 verifyFormat( 21639 "FctWithLongLineInLambda_SLS_Inline(\n" 21640 " []()\n" 21641 " {\n" 21642 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21643 " AndShouldNotBeConsiderAsInline,\n" 21644 " LambdaBodyMustBeBreak);\n" 21645 " });", 21646 LLVMWithBeforeLambdaBody); 21647 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21648 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21649 " []() { return 17; });", 21650 LLVMWithBeforeLambdaBody); 21651 verifyFormat( 21652 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21653 LLVMWithBeforeLambdaBody); 21654 21655 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21656 FormatStyle::ShortLambdaStyle::SLS_All; 21657 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21658 LLVMWithBeforeLambdaBody); 21659 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21660 LLVMWithBeforeLambdaBody); 21661 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21662 LLVMWithBeforeLambdaBody); 21663 verifyFormat("FctWithOneParam_SLS_All(\n" 21664 " []()\n" 21665 " {\n" 21666 " // A cool function...\n" 21667 " return 43;\n" 21668 " });", 21669 LLVMWithBeforeLambdaBody); 21670 verifyFormat("FctWithMultipleParams_SLS_All(" 21671 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21672 " []() { return 17; });", 21673 LLVMWithBeforeLambdaBody); 21674 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21675 LLVMWithBeforeLambdaBody); 21676 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21677 LLVMWithBeforeLambdaBody); 21678 verifyFormat( 21679 "FctWithLongLineInLambda_SLS_All(\n" 21680 " []()\n" 21681 " {\n" 21682 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21683 " AndShouldNotBeConsiderAsInline,\n" 21684 " LambdaBodyMustBeBreak);\n" 21685 " });", 21686 LLVMWithBeforeLambdaBody); 21687 verifyFormat( 21688 "auto fct_SLS_All = []()\n" 21689 "{\n" 21690 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21691 " AndShouldNotBeConsiderAsInline,\n" 21692 " LambdaBodyMustBeBreak);\n" 21693 "};", 21694 LLVMWithBeforeLambdaBody); 21695 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21696 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21697 LLVMWithBeforeLambdaBody); 21698 verifyFormat( 21699 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21700 " FirstParam,\n" 21701 " SecondParam,\n" 21702 " ThirdParam,\n" 21703 " FourthParam);", 21704 LLVMWithBeforeLambdaBody); 21705 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21706 " []() { return " 21707 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21708 " FirstParam,\n" 21709 " SecondParam,\n" 21710 " ThirdParam,\n" 21711 " FourthParam);", 21712 LLVMWithBeforeLambdaBody); 21713 verifyFormat( 21714 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21715 " SecondParam,\n" 21716 " ThirdParam,\n" 21717 " FourthParam,\n" 21718 " []() { return SomeValueNotSoLong; });", 21719 LLVMWithBeforeLambdaBody); 21720 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21721 " []()\n" 21722 " {\n" 21723 " return " 21724 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21725 "eConsiderAsInline;\n" 21726 " });", 21727 LLVMWithBeforeLambdaBody); 21728 verifyFormat( 21729 "FctWithLongLineInLambda_SLS_All(\n" 21730 " []()\n" 21731 " {\n" 21732 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21733 " AndShouldNotBeConsiderAsInline,\n" 21734 " LambdaBodyMustBeBreak);\n" 21735 " });", 21736 LLVMWithBeforeLambdaBody); 21737 verifyFormat("FctWithTwoParams_SLS_All(\n" 21738 " []()\n" 21739 " {\n" 21740 " // A cool function...\n" 21741 " return 43;\n" 21742 " },\n" 21743 " 87);", 21744 LLVMWithBeforeLambdaBody); 21745 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21746 LLVMWithBeforeLambdaBody); 21747 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21748 LLVMWithBeforeLambdaBody); 21749 verifyFormat( 21750 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21751 LLVMWithBeforeLambdaBody); 21752 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21753 "}); }, x);", 21754 LLVMWithBeforeLambdaBody); 21755 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21756 " []()\n" 21757 " {\n" 21758 " // A cool function...\n" 21759 " return Call([]() { return 17; });\n" 21760 " });", 21761 LLVMWithBeforeLambdaBody); 21762 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21763 " []()\n" 21764 " {\n" 21765 " return Call(\n" 21766 " []()\n" 21767 " {\n" 21768 " // A cool function...\n" 21769 " return 17;\n" 21770 " });\n" 21771 " });", 21772 LLVMWithBeforeLambdaBody); 21773 21774 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21775 FormatStyle::ShortLambdaStyle::SLS_None; 21776 21777 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21778 "{\n" 21779 " return MyAssignment::SelectFromList(this);\n" 21780 "};\n", 21781 LLVMWithBeforeLambdaBody); 21782 21783 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21784 "{\n" 21785 " return MyAssignment::SelectFromList(this);\n" 21786 "};\n", 21787 LLVMWithBeforeLambdaBody); 21788 21789 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21790 "{\n" 21791 " return MyAssignment::SelectFromList(this);\n" 21792 "};\n", 21793 LLVMWithBeforeLambdaBody); 21794 21795 verifyFormat("namespace test {\n" 21796 "class Test {\n" 21797 "public:\n" 21798 " Test() = default;\n" 21799 "};\n" 21800 "} // namespace test", 21801 LLVMWithBeforeLambdaBody); 21802 21803 // Lambdas with different indentation styles. 21804 Style = getLLVMStyleWithColumns(100); 21805 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21806 " return promise.then(\n" 21807 " [this, &someVariable, someObject = " 21808 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21809 " return someObject.startAsyncAction().then(\n" 21810 " [this, &someVariable](AsyncActionResult result) " 21811 "mutable { result.processMore(); });\n" 21812 " });\n" 21813 "}\n", 21814 format("SomeResult doSomething(SomeObject promise) {\n" 21815 " return promise.then([this, &someVariable, someObject = " 21816 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21817 " return someObject.startAsyncAction().then([this, " 21818 "&someVariable](AsyncActionResult result) mutable {\n" 21819 " result.processMore();\n" 21820 " });\n" 21821 " });\n" 21822 "}\n", 21823 Style)); 21824 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21825 verifyFormat("test() {\n" 21826 " ([]() -> {\n" 21827 " int b = 32;\n" 21828 " return 3;\n" 21829 " }).foo();\n" 21830 "}", 21831 Style); 21832 verifyFormat("test() {\n" 21833 " []() -> {\n" 21834 " int b = 32;\n" 21835 " return 3;\n" 21836 " }\n" 21837 "}", 21838 Style); 21839 verifyFormat("std::sort(v.begin(), v.end(),\n" 21840 " [](const auto &someLongArgumentName, const auto " 21841 "&someOtherLongArgumentName) {\n" 21842 " return someLongArgumentName.someMemberVariable < " 21843 "someOtherLongArgumentName.someMemberVariable;\n" 21844 "});", 21845 Style); 21846 verifyFormat("test() {\n" 21847 " (\n" 21848 " []() -> {\n" 21849 " int b = 32;\n" 21850 " return 3;\n" 21851 " },\n" 21852 " foo, bar)\n" 21853 " .foo();\n" 21854 "}", 21855 Style); 21856 verifyFormat("test() {\n" 21857 " ([]() -> {\n" 21858 " int b = 32;\n" 21859 " return 3;\n" 21860 " })\n" 21861 " .foo()\n" 21862 " .bar();\n" 21863 "}", 21864 Style); 21865 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21866 " return promise.then(\n" 21867 " [this, &someVariable, someObject = " 21868 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21869 " return someObject.startAsyncAction().then(\n" 21870 " [this, &someVariable](AsyncActionResult result) mutable { " 21871 "result.processMore(); });\n" 21872 " });\n" 21873 "}\n", 21874 format("SomeResult doSomething(SomeObject promise) {\n" 21875 " return promise.then([this, &someVariable, someObject = " 21876 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21877 " return someObject.startAsyncAction().then([this, " 21878 "&someVariable](AsyncActionResult result) mutable {\n" 21879 " result.processMore();\n" 21880 " });\n" 21881 " });\n" 21882 "}\n", 21883 Style)); 21884 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21885 " return promise.then([this, &someVariable] {\n" 21886 " return someObject.startAsyncAction().then(\n" 21887 " [this, &someVariable](AsyncActionResult result) mutable { " 21888 "result.processMore(); });\n" 21889 " });\n" 21890 "}\n", 21891 format("SomeResult doSomething(SomeObject promise) {\n" 21892 " return promise.then([this, &someVariable] {\n" 21893 " return someObject.startAsyncAction().then([this, " 21894 "&someVariable](AsyncActionResult result) mutable {\n" 21895 " result.processMore();\n" 21896 " });\n" 21897 " });\n" 21898 "}\n", 21899 Style)); 21900 Style = getGoogleStyle(); 21901 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21902 EXPECT_EQ("#define A \\\n" 21903 " [] { \\\n" 21904 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21905 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21906 " }", 21907 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21908 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21909 Style)); 21910 // TODO: The current formatting has a minor issue that's not worth fixing 21911 // right now whereby the closing brace is indented relative to the signature 21912 // instead of being aligned. This only happens with macros. 21913 } 21914 21915 TEST_F(FormatTest, LambdaWithLineComments) { 21916 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21917 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21918 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21919 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21920 FormatStyle::ShortLambdaStyle::SLS_All; 21921 21922 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21923 verifyFormat("auto k = []() // comment\n" 21924 "{ return; }", 21925 LLVMWithBeforeLambdaBody); 21926 verifyFormat("auto k = []() /* comment */ { return; }", 21927 LLVMWithBeforeLambdaBody); 21928 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21929 LLVMWithBeforeLambdaBody); 21930 verifyFormat("auto k = []() // X\n" 21931 "{ return; }", 21932 LLVMWithBeforeLambdaBody); 21933 verifyFormat( 21934 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21935 "{ return; }", 21936 LLVMWithBeforeLambdaBody); 21937 } 21938 21939 TEST_F(FormatTest, EmptyLinesInLambdas) { 21940 verifyFormat("auto lambda = []() {\n" 21941 " x(); //\n" 21942 "};", 21943 "auto lambda = []() {\n" 21944 "\n" 21945 " x(); //\n" 21946 "\n" 21947 "};"); 21948 } 21949 21950 TEST_F(FormatTest, FormatsBlocks) { 21951 FormatStyle ShortBlocks = getLLVMStyle(); 21952 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21953 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21954 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21955 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21956 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21957 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21958 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21959 21960 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21961 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21962 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21963 21964 verifyFormat("[operation setCompletionBlock:^{\n" 21965 " [self onOperationDone];\n" 21966 "}];"); 21967 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21968 " [self onOperationDone];\n" 21969 "}]};"); 21970 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21971 " f();\n" 21972 "}];"); 21973 verifyFormat("int a = [operation block:^int(int *i) {\n" 21974 " return 1;\n" 21975 "}];"); 21976 verifyFormat("[myObject doSomethingWith:arg1\n" 21977 " aaa:^int(int *a) {\n" 21978 " return 1;\n" 21979 " }\n" 21980 " bbb:f(a * bbbbbbbb)];"); 21981 21982 verifyFormat("[operation setCompletionBlock:^{\n" 21983 " [self.delegate newDataAvailable];\n" 21984 "}];", 21985 getLLVMStyleWithColumns(60)); 21986 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21987 " NSString *path = [self sessionFilePath];\n" 21988 " if (path) {\n" 21989 " // ...\n" 21990 " }\n" 21991 "});"); 21992 verifyFormat("[[SessionService sharedService]\n" 21993 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21994 " if (window) {\n" 21995 " [self windowDidLoad:window];\n" 21996 " } else {\n" 21997 " [self errorLoadingWindow];\n" 21998 " }\n" 21999 " }];"); 22000 verifyFormat("void (^largeBlock)(void) = ^{\n" 22001 " // ...\n" 22002 "};\n", 22003 getLLVMStyleWithColumns(40)); 22004 verifyFormat("[[SessionService sharedService]\n" 22005 " loadWindowWithCompletionBlock: //\n" 22006 " ^(SessionWindow *window) {\n" 22007 " if (window) {\n" 22008 " [self windowDidLoad:window];\n" 22009 " } else {\n" 22010 " [self errorLoadingWindow];\n" 22011 " }\n" 22012 " }];", 22013 getLLVMStyleWithColumns(60)); 22014 verifyFormat("[myObject doSomethingWith:arg1\n" 22015 " firstBlock:^(Foo *a) {\n" 22016 " // ...\n" 22017 " int i;\n" 22018 " }\n" 22019 " secondBlock:^(Bar *b) {\n" 22020 " // ...\n" 22021 " int i;\n" 22022 " }\n" 22023 " thirdBlock:^Foo(Bar *b) {\n" 22024 " // ...\n" 22025 " int i;\n" 22026 " }];"); 22027 verifyFormat("[myObject doSomethingWith:arg1\n" 22028 " firstBlock:-1\n" 22029 " secondBlock:^(Bar *b) {\n" 22030 " // ...\n" 22031 " int i;\n" 22032 " }];"); 22033 22034 verifyFormat("f(^{\n" 22035 " @autoreleasepool {\n" 22036 " if (a) {\n" 22037 " g();\n" 22038 " }\n" 22039 " }\n" 22040 "});"); 22041 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22042 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22043 "};"); 22044 22045 FormatStyle FourIndent = getLLVMStyle(); 22046 FourIndent.ObjCBlockIndentWidth = 4; 22047 verifyFormat("[operation setCompletionBlock:^{\n" 22048 " [self onOperationDone];\n" 22049 "}];", 22050 FourIndent); 22051 } 22052 22053 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22054 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22055 22056 verifyFormat("[[SessionService sharedService] " 22057 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22058 " if (window) {\n" 22059 " [self windowDidLoad:window];\n" 22060 " } else {\n" 22061 " [self errorLoadingWindow];\n" 22062 " }\n" 22063 "}];", 22064 ZeroColumn); 22065 EXPECT_EQ("[[SessionService sharedService]\n" 22066 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22067 " if (window) {\n" 22068 " [self windowDidLoad:window];\n" 22069 " } else {\n" 22070 " [self errorLoadingWindow];\n" 22071 " }\n" 22072 " }];", 22073 format("[[SessionService sharedService]\n" 22074 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22075 " if (window) {\n" 22076 " [self windowDidLoad:window];\n" 22077 " } else {\n" 22078 " [self errorLoadingWindow];\n" 22079 " }\n" 22080 "}];", 22081 ZeroColumn)); 22082 verifyFormat("[myObject doSomethingWith:arg1\n" 22083 " firstBlock:^(Foo *a) {\n" 22084 " // ...\n" 22085 " int i;\n" 22086 " }\n" 22087 " secondBlock:^(Bar *b) {\n" 22088 " // ...\n" 22089 " int i;\n" 22090 " }\n" 22091 " thirdBlock:^Foo(Bar *b) {\n" 22092 " // ...\n" 22093 " int i;\n" 22094 " }];", 22095 ZeroColumn); 22096 verifyFormat("f(^{\n" 22097 " @autoreleasepool {\n" 22098 " if (a) {\n" 22099 " g();\n" 22100 " }\n" 22101 " }\n" 22102 "});", 22103 ZeroColumn); 22104 verifyFormat("void (^largeBlock)(void) = ^{\n" 22105 " // ...\n" 22106 "};", 22107 ZeroColumn); 22108 22109 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22110 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22111 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22112 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22113 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22114 " int i;\n" 22115 "};", 22116 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22117 } 22118 22119 TEST_F(FormatTest, SupportsCRLF) { 22120 EXPECT_EQ("int a;\r\n" 22121 "int b;\r\n" 22122 "int c;\r\n", 22123 format("int a;\r\n" 22124 " int b;\r\n" 22125 " int c;\r\n", 22126 getLLVMStyle())); 22127 EXPECT_EQ("int a;\r\n" 22128 "int b;\r\n" 22129 "int c;\r\n", 22130 format("int a;\r\n" 22131 " int b;\n" 22132 " int c;\r\n", 22133 getLLVMStyle())); 22134 EXPECT_EQ("int a;\n" 22135 "int b;\n" 22136 "int c;\n", 22137 format("int a;\r\n" 22138 " int b;\n" 22139 " int c;\n", 22140 getLLVMStyle())); 22141 EXPECT_EQ("\"aaaaaaa \"\r\n" 22142 "\"bbbbbbb\";\r\n", 22143 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22144 EXPECT_EQ("#define A \\\r\n" 22145 " b; \\\r\n" 22146 " c; \\\r\n" 22147 " d;\r\n", 22148 format("#define A \\\r\n" 22149 " b; \\\r\n" 22150 " c; d; \r\n", 22151 getGoogleStyle())); 22152 22153 EXPECT_EQ("/*\r\n" 22154 "multi line block comments\r\n" 22155 "should not introduce\r\n" 22156 "an extra carriage return\r\n" 22157 "*/\r\n", 22158 format("/*\r\n" 22159 "multi line block comments\r\n" 22160 "should not introduce\r\n" 22161 "an extra carriage return\r\n" 22162 "*/\r\n")); 22163 EXPECT_EQ("/*\r\n" 22164 "\r\n" 22165 "*/", 22166 format("/*\r\n" 22167 " \r\r\r\n" 22168 "*/")); 22169 22170 FormatStyle style = getLLVMStyle(); 22171 22172 style.DeriveLineEnding = true; 22173 style.UseCRLF = false; 22174 EXPECT_EQ("union FooBarBazQux {\n" 22175 " int foo;\n" 22176 " int bar;\n" 22177 " int baz;\n" 22178 "};", 22179 format("union FooBarBazQux {\r\n" 22180 " int foo;\n" 22181 " int bar;\r\n" 22182 " int baz;\n" 22183 "};", 22184 style)); 22185 style.UseCRLF = true; 22186 EXPECT_EQ("union FooBarBazQux {\r\n" 22187 " int foo;\r\n" 22188 " int bar;\r\n" 22189 " int baz;\r\n" 22190 "};", 22191 format("union FooBarBazQux {\r\n" 22192 " int foo;\n" 22193 " int bar;\r\n" 22194 " int baz;\n" 22195 "};", 22196 style)); 22197 22198 style.DeriveLineEnding = false; 22199 style.UseCRLF = false; 22200 EXPECT_EQ("union FooBarBazQux {\n" 22201 " int foo;\n" 22202 " int bar;\n" 22203 " int baz;\n" 22204 " int qux;\n" 22205 "};", 22206 format("union FooBarBazQux {\r\n" 22207 " int foo;\n" 22208 " int bar;\r\n" 22209 " int baz;\n" 22210 " int qux;\r\n" 22211 "};", 22212 style)); 22213 style.UseCRLF = true; 22214 EXPECT_EQ("union FooBarBazQux {\r\n" 22215 " int foo;\r\n" 22216 " int bar;\r\n" 22217 " int baz;\r\n" 22218 " int qux;\r\n" 22219 "};", 22220 format("union FooBarBazQux {\r\n" 22221 " int foo;\n" 22222 " int bar;\r\n" 22223 " int baz;\n" 22224 " int qux;\n" 22225 "};", 22226 style)); 22227 22228 style.DeriveLineEnding = true; 22229 style.UseCRLF = false; 22230 EXPECT_EQ("union FooBarBazQux {\r\n" 22231 " int foo;\r\n" 22232 " int bar;\r\n" 22233 " int baz;\r\n" 22234 " int qux;\r\n" 22235 "};", 22236 format("union FooBarBazQux {\r\n" 22237 " int foo;\n" 22238 " int bar;\r\n" 22239 " int baz;\n" 22240 " int qux;\r\n" 22241 "};", 22242 style)); 22243 style.UseCRLF = true; 22244 EXPECT_EQ("union FooBarBazQux {\n" 22245 " int foo;\n" 22246 " int bar;\n" 22247 " int baz;\n" 22248 " int qux;\n" 22249 "};", 22250 format("union FooBarBazQux {\r\n" 22251 " int foo;\n" 22252 " int bar;\r\n" 22253 " int baz;\n" 22254 " int qux;\n" 22255 "};", 22256 style)); 22257 } 22258 22259 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22260 verifyFormat("MY_CLASS(C) {\n" 22261 " int i;\n" 22262 " int j;\n" 22263 "};"); 22264 } 22265 22266 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22267 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22268 TwoIndent.ContinuationIndentWidth = 2; 22269 22270 EXPECT_EQ("int i =\n" 22271 " longFunction(\n" 22272 " arg);", 22273 format("int i = longFunction(arg);", TwoIndent)); 22274 22275 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22276 SixIndent.ContinuationIndentWidth = 6; 22277 22278 EXPECT_EQ("int i =\n" 22279 " longFunction(\n" 22280 " arg);", 22281 format("int i = longFunction(arg);", SixIndent)); 22282 } 22283 22284 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22285 FormatStyle Style = getLLVMStyle(); 22286 verifyFormat("int Foo::getter(\n" 22287 " //\n" 22288 ") const {\n" 22289 " return foo;\n" 22290 "}", 22291 Style); 22292 verifyFormat("void Foo::setter(\n" 22293 " //\n" 22294 ") {\n" 22295 " foo = 1;\n" 22296 "}", 22297 Style); 22298 } 22299 22300 TEST_F(FormatTest, SpacesInAngles) { 22301 FormatStyle Spaces = getLLVMStyle(); 22302 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22303 22304 verifyFormat("vector< ::std::string > x1;", Spaces); 22305 verifyFormat("Foo< int, Bar > x2;", Spaces); 22306 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22307 22308 verifyFormat("static_cast< int >(arg);", Spaces); 22309 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22310 verifyFormat("f< int, float >();", Spaces); 22311 verifyFormat("template <> g() {}", Spaces); 22312 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22313 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22314 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22315 Spaces); 22316 22317 Spaces.Standard = FormatStyle::LS_Cpp03; 22318 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22319 verifyFormat("A< A< int > >();", Spaces); 22320 22321 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22322 verifyFormat("A<A<int> >();", Spaces); 22323 22324 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22325 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22326 Spaces); 22327 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22328 Spaces); 22329 22330 verifyFormat("A<A<int> >();", Spaces); 22331 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22332 verifyFormat("A< A< int > >();", Spaces); 22333 22334 Spaces.Standard = FormatStyle::LS_Cpp11; 22335 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22336 verifyFormat("A< A< int > >();", Spaces); 22337 22338 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22339 verifyFormat("vector<::std::string> x4;", Spaces); 22340 verifyFormat("vector<int> x5;", Spaces); 22341 verifyFormat("Foo<int, Bar> x6;", Spaces); 22342 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22343 22344 verifyFormat("A<A<int>>();", Spaces); 22345 22346 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22347 verifyFormat("vector<::std::string> x4;", Spaces); 22348 verifyFormat("vector< ::std::string > x4;", Spaces); 22349 verifyFormat("vector<int> x5;", Spaces); 22350 verifyFormat("vector< int > x5;", Spaces); 22351 verifyFormat("Foo<int, Bar> x6;", Spaces); 22352 verifyFormat("Foo< int, Bar > x6;", Spaces); 22353 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22354 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22355 22356 verifyFormat("A<A<int>>();", Spaces); 22357 verifyFormat("A< A< int > >();", Spaces); 22358 verifyFormat("A<A<int > >();", Spaces); 22359 verifyFormat("A< A< int>>();", Spaces); 22360 22361 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22362 verifyFormat("// clang-format off\n" 22363 "foo<<<1, 1>>>();\n" 22364 "// clang-format on\n", 22365 Spaces); 22366 verifyFormat("// clang-format off\n" 22367 "foo< < <1, 1> > >();\n" 22368 "// clang-format on\n", 22369 Spaces); 22370 } 22371 22372 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22373 FormatStyle Style = getLLVMStyle(); 22374 Style.SpaceAfterTemplateKeyword = false; 22375 verifyFormat("template<int> void foo();", Style); 22376 } 22377 22378 TEST_F(FormatTest, TripleAngleBrackets) { 22379 verifyFormat("f<<<1, 1>>>();"); 22380 verifyFormat("f<<<1, 1, 1, s>>>();"); 22381 verifyFormat("f<<<a, b, c, d>>>();"); 22382 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22383 verifyFormat("f<param><<<1, 1>>>();"); 22384 verifyFormat("f<1><<<1, 1>>>();"); 22385 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22386 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22387 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22388 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22389 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22390 } 22391 22392 TEST_F(FormatTest, MergeLessLessAtEnd) { 22393 verifyFormat("<<"); 22394 EXPECT_EQ("< < <", format("\\\n<<<")); 22395 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22396 "aaallvm::outs() <<"); 22397 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22398 "aaaallvm::outs()\n <<"); 22399 } 22400 22401 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22402 std::string code = "#if A\n" 22403 "#if B\n" 22404 "a.\n" 22405 "#endif\n" 22406 " a = 1;\n" 22407 "#else\n" 22408 "#endif\n" 22409 "#if C\n" 22410 "#else\n" 22411 "#endif\n"; 22412 EXPECT_EQ(code, format(code)); 22413 } 22414 22415 TEST_F(FormatTest, HandleConflictMarkers) { 22416 // Git/SVN conflict markers. 22417 EXPECT_EQ("int a;\n" 22418 "void f() {\n" 22419 " callme(some(parameter1,\n" 22420 "<<<<<<< text by the vcs\n" 22421 " parameter2),\n" 22422 "||||||| text by the vcs\n" 22423 " parameter2),\n" 22424 " parameter3,\n" 22425 "======= text by the vcs\n" 22426 " parameter2, parameter3),\n" 22427 ">>>>>>> text by the vcs\n" 22428 " otherparameter);\n", 22429 format("int a;\n" 22430 "void f() {\n" 22431 " callme(some(parameter1,\n" 22432 "<<<<<<< text by the vcs\n" 22433 " parameter2),\n" 22434 "||||||| text by the vcs\n" 22435 " parameter2),\n" 22436 " parameter3,\n" 22437 "======= text by the vcs\n" 22438 " parameter2,\n" 22439 " parameter3),\n" 22440 ">>>>>>> text by the vcs\n" 22441 " otherparameter);\n")); 22442 22443 // Perforce markers. 22444 EXPECT_EQ("void f() {\n" 22445 " function(\n" 22446 ">>>> text by the vcs\n" 22447 " parameter,\n" 22448 "==== text by the vcs\n" 22449 " parameter,\n" 22450 "==== text by the vcs\n" 22451 " parameter,\n" 22452 "<<<< text by the vcs\n" 22453 " parameter);\n", 22454 format("void f() {\n" 22455 " function(\n" 22456 ">>>> text by the vcs\n" 22457 " parameter,\n" 22458 "==== text by the vcs\n" 22459 " parameter,\n" 22460 "==== text by the vcs\n" 22461 " parameter,\n" 22462 "<<<< text by the vcs\n" 22463 " parameter);\n")); 22464 22465 EXPECT_EQ("<<<<<<<\n" 22466 "|||||||\n" 22467 "=======\n" 22468 ">>>>>>>", 22469 format("<<<<<<<\n" 22470 "|||||||\n" 22471 "=======\n" 22472 ">>>>>>>")); 22473 22474 EXPECT_EQ("<<<<<<<\n" 22475 "|||||||\n" 22476 "int i;\n" 22477 "=======\n" 22478 ">>>>>>>", 22479 format("<<<<<<<\n" 22480 "|||||||\n" 22481 "int i;\n" 22482 "=======\n" 22483 ">>>>>>>")); 22484 22485 // FIXME: Handle parsing of macros around conflict markers correctly: 22486 EXPECT_EQ("#define Macro \\\n" 22487 "<<<<<<<\n" 22488 "Something \\\n" 22489 "|||||||\n" 22490 "Else \\\n" 22491 "=======\n" 22492 "Other \\\n" 22493 ">>>>>>>\n" 22494 " End int i;\n", 22495 format("#define Macro \\\n" 22496 "<<<<<<<\n" 22497 " Something \\\n" 22498 "|||||||\n" 22499 " Else \\\n" 22500 "=======\n" 22501 " Other \\\n" 22502 ">>>>>>>\n" 22503 " End\n" 22504 "int i;\n")); 22505 22506 verifyFormat(R"(==== 22507 #ifdef A 22508 a 22509 #else 22510 b 22511 #endif 22512 )"); 22513 } 22514 22515 TEST_F(FormatTest, DisableRegions) { 22516 EXPECT_EQ("int i;\n" 22517 "// clang-format off\n" 22518 " int j;\n" 22519 "// clang-format on\n" 22520 "int k;", 22521 format(" int i;\n" 22522 " // clang-format off\n" 22523 " int j;\n" 22524 " // clang-format on\n" 22525 " int k;")); 22526 EXPECT_EQ("int i;\n" 22527 "/* clang-format off */\n" 22528 " int j;\n" 22529 "/* clang-format on */\n" 22530 "int k;", 22531 format(" int i;\n" 22532 " /* clang-format off */\n" 22533 " int j;\n" 22534 " /* clang-format on */\n" 22535 " int k;")); 22536 22537 // Don't reflow comments within disabled regions. 22538 EXPECT_EQ("// clang-format off\n" 22539 "// long long long long long long line\n" 22540 "/* clang-format on */\n" 22541 "/* long long long\n" 22542 " * long long long\n" 22543 " * line */\n" 22544 "int i;\n" 22545 "/* clang-format off */\n" 22546 "/* long long long long long long line */\n", 22547 format("// clang-format off\n" 22548 "// long long long long long long line\n" 22549 "/* clang-format on */\n" 22550 "/* long long long long long long line */\n" 22551 "int i;\n" 22552 "/* clang-format off */\n" 22553 "/* long long long long long long line */\n", 22554 getLLVMStyleWithColumns(20))); 22555 } 22556 22557 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22558 format("? ) ="); 22559 verifyNoCrash("#define a\\\n /**/}"); 22560 } 22561 22562 TEST_F(FormatTest, FormatsTableGenCode) { 22563 FormatStyle Style = getLLVMStyle(); 22564 Style.Language = FormatStyle::LK_TableGen; 22565 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22566 } 22567 22568 TEST_F(FormatTest, ArrayOfTemplates) { 22569 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22570 format("auto a = new unique_ptr<int > [ 10];")); 22571 22572 FormatStyle Spaces = getLLVMStyle(); 22573 Spaces.SpacesInSquareBrackets = true; 22574 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22575 format("auto a = new unique_ptr<int > [10];", Spaces)); 22576 } 22577 22578 TEST_F(FormatTest, ArrayAsTemplateType) { 22579 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22580 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22581 22582 FormatStyle Spaces = getLLVMStyle(); 22583 Spaces.SpacesInSquareBrackets = true; 22584 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22585 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22586 } 22587 22588 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22589 22590 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22591 llvm::vfs::InMemoryFileSystem FS; 22592 auto Style1 = getStyle("file", "", "Google", "", &FS); 22593 ASSERT_TRUE((bool)Style1); 22594 ASSERT_EQ(*Style1, getGoogleStyle()); 22595 } 22596 22597 TEST(FormatStyle, GetStyleOfFile) { 22598 llvm::vfs::InMemoryFileSystem FS; 22599 // Test 1: format file in the same directory. 22600 ASSERT_TRUE( 22601 FS.addFile("/a/.clang-format", 0, 22602 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22603 ASSERT_TRUE( 22604 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22605 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22606 ASSERT_TRUE((bool)Style1); 22607 ASSERT_EQ(*Style1, getLLVMStyle()); 22608 22609 // Test 2.1: fallback to default. 22610 ASSERT_TRUE( 22611 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22612 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22613 ASSERT_TRUE((bool)Style2); 22614 ASSERT_EQ(*Style2, getMozillaStyle()); 22615 22616 // Test 2.2: no format on 'none' fallback style. 22617 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22618 ASSERT_TRUE((bool)Style2); 22619 ASSERT_EQ(*Style2, getNoStyle()); 22620 22621 // Test 2.3: format if config is found with no based style while fallback is 22622 // 'none'. 22623 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22624 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22625 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22626 ASSERT_TRUE((bool)Style2); 22627 ASSERT_EQ(*Style2, getLLVMStyle()); 22628 22629 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22630 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22631 ASSERT_TRUE((bool)Style2); 22632 ASSERT_EQ(*Style2, getLLVMStyle()); 22633 22634 // Test 3: format file in parent directory. 22635 ASSERT_TRUE( 22636 FS.addFile("/c/.clang-format", 0, 22637 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22638 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22639 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22640 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22641 ASSERT_TRUE((bool)Style3); 22642 ASSERT_EQ(*Style3, getGoogleStyle()); 22643 22644 // Test 4: error on invalid fallback style 22645 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22646 ASSERT_FALSE((bool)Style4); 22647 llvm::consumeError(Style4.takeError()); 22648 22649 // Test 5: error on invalid yaml on command line 22650 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22651 ASSERT_FALSE((bool)Style5); 22652 llvm::consumeError(Style5.takeError()); 22653 22654 // Test 6: error on invalid style 22655 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22656 ASSERT_FALSE((bool)Style6); 22657 llvm::consumeError(Style6.takeError()); 22658 22659 // Test 7: found config file, error on parsing it 22660 ASSERT_TRUE( 22661 FS.addFile("/d/.clang-format", 0, 22662 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22663 "InvalidKey: InvalidValue"))); 22664 ASSERT_TRUE( 22665 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22666 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22667 ASSERT_FALSE((bool)Style7a); 22668 llvm::consumeError(Style7a.takeError()); 22669 22670 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22671 ASSERT_TRUE((bool)Style7b); 22672 22673 // Test 8: inferred per-language defaults apply. 22674 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22675 ASSERT_TRUE((bool)StyleTd); 22676 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22677 22678 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22679 // fallback style. 22680 ASSERT_TRUE(FS.addFile( 22681 "/e/sub/.clang-format", 0, 22682 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22683 "ColumnLimit: 20"))); 22684 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22685 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22686 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22687 ASSERT_TRUE(static_cast<bool>(Style9)); 22688 ASSERT_EQ(*Style9, [] { 22689 auto Style = getNoStyle(); 22690 Style.ColumnLimit = 20; 22691 return Style; 22692 }()); 22693 22694 // Test 9.1.2: propagate more than one level with no parent file. 22695 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22696 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22697 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22698 llvm::MemoryBuffer::getMemBuffer( 22699 "BasedOnStyle: InheritParentConfig\n" 22700 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22701 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22702 22703 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22704 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22705 ASSERT_TRUE(static_cast<bool>(Style9)); 22706 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22707 auto Style = getNoStyle(); 22708 Style.ColumnLimit = 20; 22709 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22710 return Style; 22711 }()); 22712 22713 // Test 9.2: with LLVM fallback style 22714 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22715 ASSERT_TRUE(static_cast<bool>(Style9)); 22716 ASSERT_EQ(*Style9, [] { 22717 auto Style = getLLVMStyle(); 22718 Style.ColumnLimit = 20; 22719 return Style; 22720 }()); 22721 22722 // Test 9.3: with a parent file 22723 ASSERT_TRUE( 22724 FS.addFile("/e/.clang-format", 0, 22725 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22726 "UseTab: Always"))); 22727 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22728 ASSERT_TRUE(static_cast<bool>(Style9)); 22729 ASSERT_EQ(*Style9, [] { 22730 auto Style = getGoogleStyle(); 22731 Style.ColumnLimit = 20; 22732 Style.UseTab = FormatStyle::UT_Always; 22733 return Style; 22734 }()); 22735 22736 // Test 9.4: propagate more than one level with a parent file. 22737 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22738 auto Style = getGoogleStyle(); 22739 Style.ColumnLimit = 20; 22740 Style.UseTab = FormatStyle::UT_Always; 22741 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22742 return Style; 22743 }(); 22744 22745 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22746 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22747 ASSERT_TRUE(static_cast<bool>(Style9)); 22748 ASSERT_EQ(*Style9, SubSubStyle); 22749 22750 // Test 9.5: use InheritParentConfig as style name 22751 Style9 = 22752 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22753 ASSERT_TRUE(static_cast<bool>(Style9)); 22754 ASSERT_EQ(*Style9, SubSubStyle); 22755 22756 // Test 9.6: use command line style with inheritance 22757 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22758 "none", "", &FS); 22759 ASSERT_TRUE(static_cast<bool>(Style9)); 22760 ASSERT_EQ(*Style9, SubSubStyle); 22761 22762 // Test 9.7: use command line style with inheritance and own config 22763 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22764 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22765 "/e/sub/code.cpp", "none", "", &FS); 22766 ASSERT_TRUE(static_cast<bool>(Style9)); 22767 ASSERT_EQ(*Style9, SubSubStyle); 22768 22769 // Test 9.8: use inheritance from a file without BasedOnStyle 22770 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22771 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22772 ASSERT_TRUE( 22773 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22774 llvm::MemoryBuffer::getMemBuffer( 22775 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22776 // Make sure we do not use the fallback style 22777 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22778 ASSERT_TRUE(static_cast<bool>(Style9)); 22779 ASSERT_EQ(*Style9, [] { 22780 auto Style = getLLVMStyle(); 22781 Style.ColumnLimit = 123; 22782 return Style; 22783 }()); 22784 22785 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22786 ASSERT_TRUE(static_cast<bool>(Style9)); 22787 ASSERT_EQ(*Style9, [] { 22788 auto Style = getLLVMStyle(); 22789 Style.ColumnLimit = 123; 22790 Style.IndentWidth = 7; 22791 return Style; 22792 }()); 22793 22794 // Test 9.9: use inheritance from a specific config file. 22795 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22796 "none", "", &FS); 22797 ASSERT_TRUE(static_cast<bool>(Style9)); 22798 ASSERT_EQ(*Style9, SubSubStyle); 22799 } 22800 22801 TEST(FormatStyle, GetStyleOfSpecificFile) { 22802 llvm::vfs::InMemoryFileSystem FS; 22803 // Specify absolute path to a format file in a parent directory. 22804 ASSERT_TRUE( 22805 FS.addFile("/e/.clang-format", 0, 22806 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22807 ASSERT_TRUE( 22808 FS.addFile("/e/explicit.clang-format", 0, 22809 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22810 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22811 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22812 auto Style = getStyle("file:/e/explicit.clang-format", 22813 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22814 ASSERT_TRUE(static_cast<bool>(Style)); 22815 ASSERT_EQ(*Style, getGoogleStyle()); 22816 22817 // Specify relative path to a format file. 22818 ASSERT_TRUE( 22819 FS.addFile("../../e/explicit.clang-format", 0, 22820 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22821 Style = getStyle("file:../../e/explicit.clang-format", 22822 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22823 ASSERT_TRUE(static_cast<bool>(Style)); 22824 ASSERT_EQ(*Style, getGoogleStyle()); 22825 22826 // Specify path to a format file that does not exist. 22827 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22828 "LLVM", "", &FS); 22829 ASSERT_FALSE(static_cast<bool>(Style)); 22830 llvm::consumeError(Style.takeError()); 22831 22832 // Specify path to a file on the filesystem. 22833 SmallString<128> FormatFilePath; 22834 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22835 "FormatFileTest", "tpl", FormatFilePath); 22836 EXPECT_FALSE((bool)ECF); 22837 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22838 EXPECT_FALSE((bool)ECF); 22839 FormatFileTest << "BasedOnStyle: Google\n"; 22840 FormatFileTest.close(); 22841 22842 SmallString<128> TestFilePath; 22843 std::error_code ECT = 22844 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22845 EXPECT_FALSE((bool)ECT); 22846 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22847 CodeFileTest << "int i;\n"; 22848 CodeFileTest.close(); 22849 22850 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22851 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22852 22853 llvm::sys::fs::remove(FormatFilePath.c_str()); 22854 llvm::sys::fs::remove(TestFilePath.c_str()); 22855 ASSERT_TRUE(static_cast<bool>(Style)); 22856 ASSERT_EQ(*Style, getGoogleStyle()); 22857 } 22858 22859 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22860 // Column limit is 20. 22861 std::string Code = "Type *a =\n" 22862 " new Type();\n" 22863 "g(iiiii, 0, jjjjj,\n" 22864 " 0, kkkkk, 0, mm);\n" 22865 "int bad = format ;"; 22866 std::string Expected = "auto a = new Type();\n" 22867 "g(iiiii, nullptr,\n" 22868 " jjjjj, nullptr,\n" 22869 " kkkkk, nullptr,\n" 22870 " mm);\n" 22871 "int bad = format ;"; 22872 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22873 tooling::Replacements Replaces = toReplacements( 22874 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22875 "auto "), 22876 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22877 "nullptr"), 22878 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22879 "nullptr"), 22880 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22881 "nullptr")}); 22882 22883 FormatStyle Style = getLLVMStyle(); 22884 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22885 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22886 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22887 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22888 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22889 EXPECT_TRUE(static_cast<bool>(Result)); 22890 EXPECT_EQ(Expected, *Result); 22891 } 22892 22893 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22894 std::string Code = "#include \"a.h\"\n" 22895 "#include \"c.h\"\n" 22896 "\n" 22897 "int main() {\n" 22898 " return 0;\n" 22899 "}"; 22900 std::string Expected = "#include \"a.h\"\n" 22901 "#include \"b.h\"\n" 22902 "#include \"c.h\"\n" 22903 "\n" 22904 "int main() {\n" 22905 " return 0;\n" 22906 "}"; 22907 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22908 tooling::Replacements Replaces = toReplacements( 22909 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22910 "#include \"b.h\"\n")}); 22911 22912 FormatStyle Style = getLLVMStyle(); 22913 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22914 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22915 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22916 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22917 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22918 EXPECT_TRUE(static_cast<bool>(Result)); 22919 EXPECT_EQ(Expected, *Result); 22920 } 22921 22922 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22923 EXPECT_EQ("using std::cin;\n" 22924 "using std::cout;", 22925 format("using std::cout;\n" 22926 "using std::cin;", 22927 getGoogleStyle())); 22928 } 22929 22930 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22931 FormatStyle Style = getLLVMStyle(); 22932 Style.Standard = FormatStyle::LS_Cpp03; 22933 // cpp03 recognize this string as identifier u8 and literal character 'a' 22934 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22935 } 22936 22937 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22938 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22939 // all modes, including C++11, C++14 and C++17 22940 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22941 } 22942 22943 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22944 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22945 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22946 } 22947 22948 TEST_F(FormatTest, StructuredBindings) { 22949 // Structured bindings is a C++17 feature. 22950 // all modes, including C++11, C++14 and C++17 22951 verifyFormat("auto [a, b] = f();"); 22952 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22953 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22954 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22955 EXPECT_EQ("auto const volatile [a, b] = f();", 22956 format("auto const volatile[a, b] = f();")); 22957 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22958 EXPECT_EQ("auto &[a, b, c] = f();", 22959 format("auto &[ a , b,c ] = f();")); 22960 EXPECT_EQ("auto &&[a, b, c] = f();", 22961 format("auto &&[ a , b,c ] = f();")); 22962 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22963 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22964 format("auto const volatile &&[a, b] = f();")); 22965 EXPECT_EQ("auto const &&[a, b] = f();", 22966 format("auto const && [a, b] = f();")); 22967 EXPECT_EQ("const auto &[a, b] = f();", 22968 format("const auto & [a, b] = f();")); 22969 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22970 format("const auto volatile &&[a, b] = f();")); 22971 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22972 format("volatile const auto &&[a, b] = f();")); 22973 EXPECT_EQ("const auto &&[a, b] = f();", 22974 format("const auto && [a, b] = f();")); 22975 22976 // Make sure we don't mistake structured bindings for lambdas. 22977 FormatStyle PointerMiddle = getLLVMStyle(); 22978 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22979 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22980 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22981 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22982 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22983 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22984 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22985 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22986 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22987 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22988 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22989 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22990 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22991 22992 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22993 format("for (const auto && [a, b] : some_range) {\n}")); 22994 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22995 format("for (const auto & [a, b] : some_range) {\n}")); 22996 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22997 format("for (const auto[a, b] : some_range) {\n}")); 22998 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22999 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 23000 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 23001 EXPECT_EQ("auto const &[x, y](expr);", 23002 format("auto const & [x,y] (expr);")); 23003 EXPECT_EQ("auto const &&[x, y](expr);", 23004 format("auto const && [x,y] (expr);")); 23005 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 23006 EXPECT_EQ("auto const &[x, y]{expr};", 23007 format("auto const & [x,y] {expr};")); 23008 EXPECT_EQ("auto const &&[x, y]{expr};", 23009 format("auto const && [x,y] {expr};")); 23010 23011 FormatStyle Spaces = getLLVMStyle(); 23012 Spaces.SpacesInSquareBrackets = true; 23013 verifyFormat("auto [ a, b ] = f();", Spaces); 23014 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23015 verifyFormat("auto &[ a, b ] = f();", Spaces); 23016 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23017 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23018 } 23019 23020 TEST_F(FormatTest, FileAndCode) { 23021 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23022 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23023 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23024 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23025 EXPECT_EQ(FormatStyle::LK_ObjC, 23026 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23027 EXPECT_EQ( 23028 FormatStyle::LK_ObjC, 23029 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23030 EXPECT_EQ(FormatStyle::LK_ObjC, 23031 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23032 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23033 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23034 EXPECT_EQ(FormatStyle::LK_ObjC, 23035 guessLanguage("foo", "@interface Foo\n@end\n")); 23036 EXPECT_EQ(FormatStyle::LK_ObjC, 23037 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23038 EXPECT_EQ( 23039 FormatStyle::LK_ObjC, 23040 guessLanguage("foo.h", 23041 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23042 EXPECT_EQ( 23043 FormatStyle::LK_Cpp, 23044 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23045 // Only one of the two preprocessor regions has ObjC-like code. 23046 EXPECT_EQ(FormatStyle::LK_ObjC, 23047 guessLanguage("foo.h", "#if A\n" 23048 "#define B() C\n" 23049 "#else\n" 23050 "#define B() [NSString a:@\"\"]\n" 23051 "#endif\n")); 23052 } 23053 23054 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23055 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23056 EXPECT_EQ(FormatStyle::LK_ObjC, 23057 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23058 EXPECT_EQ(FormatStyle::LK_Cpp, 23059 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23060 EXPECT_EQ( 23061 FormatStyle::LK_Cpp, 23062 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23063 EXPECT_EQ(FormatStyle::LK_ObjC, 23064 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23065 EXPECT_EQ(FormatStyle::LK_Cpp, 23066 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23067 EXPECT_EQ(FormatStyle::LK_ObjC, 23068 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23069 EXPECT_EQ(FormatStyle::LK_Cpp, 23070 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23071 EXPECT_EQ(FormatStyle::LK_Cpp, 23072 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23073 EXPECT_EQ(FormatStyle::LK_ObjC, 23074 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23075 EXPECT_EQ(FormatStyle::LK_Cpp, 23076 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23077 EXPECT_EQ( 23078 FormatStyle::LK_Cpp, 23079 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23080 EXPECT_EQ( 23081 FormatStyle::LK_Cpp, 23082 guessLanguage("foo.h", 23083 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23084 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23085 } 23086 23087 TEST_F(FormatTest, GuessLanguageWithCaret) { 23088 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23089 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23090 EXPECT_EQ(FormatStyle::LK_ObjC, 23091 guessLanguage("foo.h", "int(^)(char, float);")); 23092 EXPECT_EQ(FormatStyle::LK_ObjC, 23093 guessLanguage("foo.h", "int(^foo)(char, float);")); 23094 EXPECT_EQ(FormatStyle::LK_ObjC, 23095 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23096 EXPECT_EQ(FormatStyle::LK_ObjC, 23097 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23098 EXPECT_EQ( 23099 FormatStyle::LK_ObjC, 23100 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23101 } 23102 23103 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23104 EXPECT_EQ(FormatStyle::LK_Cpp, 23105 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23106 EXPECT_EQ(FormatStyle::LK_Cpp, 23107 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23108 EXPECT_EQ(FormatStyle::LK_Cpp, 23109 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23110 } 23111 23112 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23113 // ASM symbolic names are identifiers that must be surrounded by [] without 23114 // space in between: 23115 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23116 23117 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23118 verifyFormat(R"(// 23119 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23120 )"); 23121 23122 // A list of several ASM symbolic names. 23123 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23124 23125 // ASM symbolic names in inline ASM with inputs and outputs. 23126 verifyFormat(R"(// 23127 asm("cmoveq %1, %2, %[result]" 23128 : [result] "=r"(result) 23129 : "r"(test), "r"(new), "[result]"(old)); 23130 )"); 23131 23132 // ASM symbolic names in inline ASM with no outputs. 23133 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23134 } 23135 23136 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23137 EXPECT_EQ(FormatStyle::LK_Cpp, 23138 guessLanguage("foo.h", "void f() {\n" 23139 " asm (\"mov %[e], %[d]\"\n" 23140 " : [d] \"=rm\" (d)\n" 23141 " [e] \"rm\" (*e));\n" 23142 "}")); 23143 EXPECT_EQ(FormatStyle::LK_Cpp, 23144 guessLanguage("foo.h", "void f() {\n" 23145 " _asm (\"mov %[e], %[d]\"\n" 23146 " : [d] \"=rm\" (d)\n" 23147 " [e] \"rm\" (*e));\n" 23148 "}")); 23149 EXPECT_EQ(FormatStyle::LK_Cpp, 23150 guessLanguage("foo.h", "void f() {\n" 23151 " __asm (\"mov %[e], %[d]\"\n" 23152 " : [d] \"=rm\" (d)\n" 23153 " [e] \"rm\" (*e));\n" 23154 "}")); 23155 EXPECT_EQ(FormatStyle::LK_Cpp, 23156 guessLanguage("foo.h", "void f() {\n" 23157 " __asm__ (\"mov %[e], %[d]\"\n" 23158 " : [d] \"=rm\" (d)\n" 23159 " [e] \"rm\" (*e));\n" 23160 "}")); 23161 EXPECT_EQ(FormatStyle::LK_Cpp, 23162 guessLanguage("foo.h", "void f() {\n" 23163 " asm (\"mov %[e], %[d]\"\n" 23164 " : [d] \"=rm\" (d),\n" 23165 " [e] \"rm\" (*e));\n" 23166 "}")); 23167 EXPECT_EQ(FormatStyle::LK_Cpp, 23168 guessLanguage("foo.h", "void f() {\n" 23169 " asm volatile (\"mov %[e], %[d]\"\n" 23170 " : [d] \"=rm\" (d)\n" 23171 " [e] \"rm\" (*e));\n" 23172 "}")); 23173 } 23174 23175 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23176 EXPECT_EQ(FormatStyle::LK_Cpp, 23177 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23178 EXPECT_EQ(FormatStyle::LK_ObjC, 23179 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23180 EXPECT_EQ( 23181 FormatStyle::LK_Cpp, 23182 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23183 EXPECT_EQ( 23184 FormatStyle::LK_ObjC, 23185 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23186 } 23187 23188 TEST_F(FormatTest, TypenameMacros) { 23189 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23190 23191 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23192 FormatStyle Google = getGoogleStyleWithColumns(0); 23193 Google.TypenameMacros = TypenameMacros; 23194 verifyFormat("struct foo {\n" 23195 " int bar;\n" 23196 " TAILQ_ENTRY(a) bleh;\n" 23197 "};", 23198 Google); 23199 23200 FormatStyle Macros = getLLVMStyle(); 23201 Macros.TypenameMacros = TypenameMacros; 23202 23203 verifyFormat("STACK_OF(int) a;", Macros); 23204 verifyFormat("STACK_OF(int) *a;", Macros); 23205 verifyFormat("STACK_OF(int const *) *a;", Macros); 23206 verifyFormat("STACK_OF(int *const) *a;", Macros); 23207 verifyFormat("STACK_OF(int, string) a;", Macros); 23208 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23209 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23210 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23211 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23212 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23213 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23214 23215 Macros.PointerAlignment = FormatStyle::PAS_Left; 23216 verifyFormat("STACK_OF(int)* a;", Macros); 23217 verifyFormat("STACK_OF(int*)* a;", Macros); 23218 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23219 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23220 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23221 } 23222 23223 TEST_F(FormatTest, AtomicQualifier) { 23224 // Check that we treate _Atomic as a type and not a function call 23225 FormatStyle Google = getGoogleStyleWithColumns(0); 23226 verifyFormat("struct foo {\n" 23227 " int a1;\n" 23228 " _Atomic(a) a2;\n" 23229 " _Atomic(_Atomic(int) *const) a3;\n" 23230 "};", 23231 Google); 23232 verifyFormat("_Atomic(uint64_t) a;"); 23233 verifyFormat("_Atomic(uint64_t) *a;"); 23234 verifyFormat("_Atomic(uint64_t const *) *a;"); 23235 verifyFormat("_Atomic(uint64_t *const) *a;"); 23236 verifyFormat("_Atomic(const uint64_t *) *a;"); 23237 verifyFormat("_Atomic(uint64_t) a;"); 23238 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23239 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23240 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23241 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23242 23243 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23244 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23245 FormatStyle Style = getLLVMStyle(); 23246 Style.PointerAlignment = FormatStyle::PAS_Left; 23247 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23248 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23249 verifyFormat("_Atomic(int)* a;", Style); 23250 verifyFormat("_Atomic(int*)* a;", Style); 23251 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23252 23253 Style.SpacesInCStyleCastParentheses = true; 23254 Style.SpacesInParentheses = false; 23255 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23256 Style.SpacesInCStyleCastParentheses = false; 23257 Style.SpacesInParentheses = true; 23258 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23259 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23260 } 23261 23262 TEST_F(FormatTest, AmbersandInLamda) { 23263 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23264 FormatStyle AlignStyle = getLLVMStyle(); 23265 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23266 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23267 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23268 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23269 } 23270 23271 TEST_F(FormatTest, SpacesInConditionalStatement) { 23272 FormatStyle Spaces = getLLVMStyle(); 23273 Spaces.IfMacros.clear(); 23274 Spaces.IfMacros.push_back("MYIF"); 23275 Spaces.SpacesInConditionalStatement = true; 23276 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23277 verifyFormat("if ( !a )\n return;", Spaces); 23278 verifyFormat("if ( a )\n return;", Spaces); 23279 verifyFormat("if constexpr ( a )\n return;", Spaces); 23280 verifyFormat("MYIF ( a )\n return;", Spaces); 23281 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23282 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23283 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23284 verifyFormat("while ( a )\n return;", Spaces); 23285 verifyFormat("while ( (a && b) )\n return;", Spaces); 23286 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23287 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23288 // Check that space on the left of "::" is inserted as expected at beginning 23289 // of condition. 23290 verifyFormat("while ( ::func() )\n return;", Spaces); 23291 23292 // Check impact of ControlStatementsExceptControlMacros is honored. 23293 Spaces.SpaceBeforeParens = 23294 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23295 verifyFormat("MYIF( a )\n return;", Spaces); 23296 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23297 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23298 } 23299 23300 TEST_F(FormatTest, AlternativeOperators) { 23301 // Test case for ensuring alternate operators are not 23302 // combined with their right most neighbour. 23303 verifyFormat("int a and b;"); 23304 verifyFormat("int a and_eq b;"); 23305 verifyFormat("int a bitand b;"); 23306 verifyFormat("int a bitor b;"); 23307 verifyFormat("int a compl b;"); 23308 verifyFormat("int a not b;"); 23309 verifyFormat("int a not_eq b;"); 23310 verifyFormat("int a or b;"); 23311 verifyFormat("int a xor b;"); 23312 verifyFormat("int a xor_eq b;"); 23313 verifyFormat("return this not_eq bitand other;"); 23314 verifyFormat("bool operator not_eq(const X bitand other)"); 23315 23316 verifyFormat("int a and 5;"); 23317 verifyFormat("int a and_eq 5;"); 23318 verifyFormat("int a bitand 5;"); 23319 verifyFormat("int a bitor 5;"); 23320 verifyFormat("int a compl 5;"); 23321 verifyFormat("int a not 5;"); 23322 verifyFormat("int a not_eq 5;"); 23323 verifyFormat("int a or 5;"); 23324 verifyFormat("int a xor 5;"); 23325 verifyFormat("int a xor_eq 5;"); 23326 23327 verifyFormat("int a compl(5);"); 23328 verifyFormat("int a not(5);"); 23329 23330 /* FIXME handle alternate tokens 23331 * https://en.cppreference.com/w/cpp/language/operator_alternative 23332 // alternative tokens 23333 verifyFormat("compl foo();"); // ~foo(); 23334 verifyFormat("foo() <%%>;"); // foo(); 23335 verifyFormat("void foo() <%%>;"); // void foo(){} 23336 verifyFormat("int a <:1:>;"); // int a[1];[ 23337 verifyFormat("%:define ABC abc"); // #define ABC abc 23338 verifyFormat("%:%:"); // ## 23339 */ 23340 } 23341 23342 TEST_F(FormatTest, STLWhileNotDefineChed) { 23343 verifyFormat("#if defined(while)\n" 23344 "#define while EMIT WARNING C4005\n" 23345 "#endif // while"); 23346 } 23347 23348 TEST_F(FormatTest, OperatorSpacing) { 23349 FormatStyle Style = getLLVMStyle(); 23350 Style.PointerAlignment = FormatStyle::PAS_Right; 23351 verifyFormat("Foo::operator*();", Style); 23352 verifyFormat("Foo::operator void *();", Style); 23353 verifyFormat("Foo::operator void **();", Style); 23354 verifyFormat("Foo::operator void *&();", Style); 23355 verifyFormat("Foo::operator void *&&();", Style); 23356 verifyFormat("Foo::operator void const *();", Style); 23357 verifyFormat("Foo::operator void const **();", Style); 23358 verifyFormat("Foo::operator void const *&();", Style); 23359 verifyFormat("Foo::operator void const *&&();", Style); 23360 verifyFormat("Foo::operator()(void *);", Style); 23361 verifyFormat("Foo::operator*(void *);", Style); 23362 verifyFormat("Foo::operator*();", Style); 23363 verifyFormat("Foo::operator**();", Style); 23364 verifyFormat("Foo::operator&();", Style); 23365 verifyFormat("Foo::operator<int> *();", Style); 23366 verifyFormat("Foo::operator<Foo> *();", Style); 23367 verifyFormat("Foo::operator<int> **();", Style); 23368 verifyFormat("Foo::operator<Foo> **();", Style); 23369 verifyFormat("Foo::operator<int> &();", Style); 23370 verifyFormat("Foo::operator<Foo> &();", Style); 23371 verifyFormat("Foo::operator<int> &&();", Style); 23372 verifyFormat("Foo::operator<Foo> &&();", Style); 23373 verifyFormat("Foo::operator<int> *&();", Style); 23374 verifyFormat("Foo::operator<Foo> *&();", Style); 23375 verifyFormat("Foo::operator<int> *&&();", Style); 23376 verifyFormat("Foo::operator<Foo> *&&();", Style); 23377 verifyFormat("operator*(int (*)(), class Foo);", Style); 23378 23379 verifyFormat("Foo::operator&();", Style); 23380 verifyFormat("Foo::operator void &();", Style); 23381 verifyFormat("Foo::operator void const &();", Style); 23382 verifyFormat("Foo::operator()(void &);", Style); 23383 verifyFormat("Foo::operator&(void &);", Style); 23384 verifyFormat("Foo::operator&();", Style); 23385 verifyFormat("operator&(int (&)(), class Foo);", Style); 23386 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23387 23388 verifyFormat("Foo::operator&&();", Style); 23389 verifyFormat("Foo::operator**();", Style); 23390 verifyFormat("Foo::operator void &&();", Style); 23391 verifyFormat("Foo::operator void const &&();", Style); 23392 verifyFormat("Foo::operator()(void &&);", Style); 23393 verifyFormat("Foo::operator&&(void &&);", Style); 23394 verifyFormat("Foo::operator&&();", Style); 23395 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23396 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23397 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23398 Style); 23399 verifyFormat("operator void **()", Style); 23400 verifyFormat("operator const FooRight<Object> &()", Style); 23401 verifyFormat("operator const FooRight<Object> *()", Style); 23402 verifyFormat("operator const FooRight<Object> **()", Style); 23403 verifyFormat("operator const FooRight<Object> *&()", Style); 23404 verifyFormat("operator const FooRight<Object> *&&()", Style); 23405 23406 Style.PointerAlignment = FormatStyle::PAS_Left; 23407 verifyFormat("Foo::operator*();", Style); 23408 verifyFormat("Foo::operator**();", Style); 23409 verifyFormat("Foo::operator void*();", Style); 23410 verifyFormat("Foo::operator void**();", Style); 23411 verifyFormat("Foo::operator void*&();", Style); 23412 verifyFormat("Foo::operator void*&&();", Style); 23413 verifyFormat("Foo::operator void const*();", Style); 23414 verifyFormat("Foo::operator void const**();", Style); 23415 verifyFormat("Foo::operator void const*&();", Style); 23416 verifyFormat("Foo::operator void const*&&();", Style); 23417 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23418 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23419 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23420 verifyFormat("Foo::operator()(void*);", Style); 23421 verifyFormat("Foo::operator*(void*);", Style); 23422 verifyFormat("Foo::operator*();", Style); 23423 verifyFormat("Foo::operator<int>*();", Style); 23424 verifyFormat("Foo::operator<Foo>*();", Style); 23425 verifyFormat("Foo::operator<int>**();", Style); 23426 verifyFormat("Foo::operator<Foo>**();", Style); 23427 verifyFormat("Foo::operator<Foo>*&();", Style); 23428 verifyFormat("Foo::operator<int>&();", Style); 23429 verifyFormat("Foo::operator<Foo>&();", Style); 23430 verifyFormat("Foo::operator<int>&&();", Style); 23431 verifyFormat("Foo::operator<Foo>&&();", Style); 23432 verifyFormat("Foo::operator<int>*&();", Style); 23433 verifyFormat("Foo::operator<Foo>*&();", Style); 23434 verifyFormat("operator*(int (*)(), class Foo);", Style); 23435 23436 verifyFormat("Foo::operator&();", Style); 23437 verifyFormat("Foo::operator void&();", Style); 23438 verifyFormat("Foo::operator void const&();", Style); 23439 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23440 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23441 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23442 verifyFormat("Foo::operator()(void&);", Style); 23443 verifyFormat("Foo::operator&(void&);", Style); 23444 verifyFormat("Foo::operator&();", Style); 23445 verifyFormat("operator&(int (&)(), class Foo);", Style); 23446 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23447 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23448 23449 verifyFormat("Foo::operator&&();", Style); 23450 verifyFormat("Foo::operator void&&();", Style); 23451 verifyFormat("Foo::operator void const&&();", Style); 23452 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23453 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23454 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23455 verifyFormat("Foo::operator()(void&&);", Style); 23456 verifyFormat("Foo::operator&&(void&&);", Style); 23457 verifyFormat("Foo::operator&&();", Style); 23458 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23459 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23460 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23461 Style); 23462 verifyFormat("operator void**()", Style); 23463 verifyFormat("operator const FooLeft<Object>&()", Style); 23464 verifyFormat("operator const FooLeft<Object>*()", Style); 23465 verifyFormat("operator const FooLeft<Object>**()", Style); 23466 verifyFormat("operator const FooLeft<Object>*&()", Style); 23467 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23468 23469 // PR45107 23470 verifyFormat("operator Vector<String>&();", Style); 23471 verifyFormat("operator const Vector<String>&();", Style); 23472 verifyFormat("operator foo::Bar*();", Style); 23473 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23474 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23475 Style); 23476 23477 Style.PointerAlignment = FormatStyle::PAS_Middle; 23478 verifyFormat("Foo::operator*();", Style); 23479 verifyFormat("Foo::operator void *();", Style); 23480 verifyFormat("Foo::operator()(void *);", Style); 23481 verifyFormat("Foo::operator*(void *);", Style); 23482 verifyFormat("Foo::operator*();", Style); 23483 verifyFormat("operator*(int (*)(), class Foo);", Style); 23484 23485 verifyFormat("Foo::operator&();", Style); 23486 verifyFormat("Foo::operator void &();", Style); 23487 verifyFormat("Foo::operator void const &();", Style); 23488 verifyFormat("Foo::operator()(void &);", Style); 23489 verifyFormat("Foo::operator&(void &);", Style); 23490 verifyFormat("Foo::operator&();", Style); 23491 verifyFormat("operator&(int (&)(), class Foo);", Style); 23492 23493 verifyFormat("Foo::operator&&();", Style); 23494 verifyFormat("Foo::operator void &&();", Style); 23495 verifyFormat("Foo::operator void const &&();", Style); 23496 verifyFormat("Foo::operator()(void &&);", Style); 23497 verifyFormat("Foo::operator&&(void &&);", Style); 23498 verifyFormat("Foo::operator&&();", Style); 23499 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23500 } 23501 23502 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23503 FormatStyle Style = getLLVMStyle(); 23504 // PR46157 23505 verifyFormat("foo(operator+, -42);", Style); 23506 verifyFormat("foo(operator++, -42);", Style); 23507 verifyFormat("foo(operator--, -42);", Style); 23508 verifyFormat("foo(-42, operator--);", Style); 23509 verifyFormat("foo(-42, operator, );", Style); 23510 verifyFormat("foo(operator, , -42);", Style); 23511 } 23512 23513 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23514 FormatStyle Style = getLLVMStyle(); 23515 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23516 23517 // Don't use the helpers here, since 'mess up' will change the whitespace 23518 // and these are all whitespace sensitive by definition 23519 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23520 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23521 EXPECT_EQ( 23522 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23523 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23524 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23525 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23526 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23527 " Still=Intentional);", 23528 format("FOO(String-ized&Messy+But,: :\n" 23529 " Still=Intentional);", 23530 Style)); 23531 Style.AlignConsecutiveAssignments.Enabled = true; 23532 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23533 " Still=Intentional);", 23534 format("FOO(String-ized=&Messy+But,: :\n" 23535 " Still=Intentional);", 23536 Style)); 23537 23538 Style.ColumnLimit = 21; 23539 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23540 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23541 } 23542 23543 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23544 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23545 // test its interaction with line wrapping 23546 FormatStyle Style = getLLVMStyleWithColumns(80); 23547 verifyFormat("namespace {\n" 23548 "int i;\n" 23549 "int j;\n" 23550 "} // namespace", 23551 Style); 23552 23553 verifyFormat("namespace AAA {\n" 23554 "int i;\n" 23555 "int j;\n" 23556 "} // namespace AAA", 23557 Style); 23558 23559 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23560 "int i;\n" 23561 "int j;\n" 23562 "} // namespace Averyveryveryverylongnamespace", 23563 format("namespace Averyveryveryverylongnamespace {\n" 23564 "int i;\n" 23565 "int j;\n" 23566 "}", 23567 Style)); 23568 23569 EXPECT_EQ( 23570 "namespace " 23571 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23572 " went::mad::now {\n" 23573 "int i;\n" 23574 "int j;\n" 23575 "} // namespace\n" 23576 " // " 23577 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23578 "went::mad::now", 23579 format("namespace " 23580 "would::it::save::you::a::lot::of::time::if_::i::" 23581 "just::gave::up::and_::went::mad::now {\n" 23582 "int i;\n" 23583 "int j;\n" 23584 "}", 23585 Style)); 23586 23587 // This used to duplicate the comment again and again on subsequent runs 23588 EXPECT_EQ( 23589 "namespace " 23590 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23591 " went::mad::now {\n" 23592 "int i;\n" 23593 "int j;\n" 23594 "} // namespace\n" 23595 " // " 23596 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23597 "went::mad::now", 23598 format("namespace " 23599 "would::it::save::you::a::lot::of::time::if_::i::" 23600 "just::gave::up::and_::went::mad::now {\n" 23601 "int i;\n" 23602 "int j;\n" 23603 "} // namespace\n" 23604 " // " 23605 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23606 "and_::went::mad::now", 23607 Style)); 23608 } 23609 23610 TEST_F(FormatTest, LikelyUnlikely) { 23611 FormatStyle Style = getLLVMStyle(); 23612 23613 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23614 " return 29;\n" 23615 "}", 23616 Style); 23617 23618 verifyFormat("if (argc > 5) [[likely]] {\n" 23619 " return 29;\n" 23620 "}", 23621 Style); 23622 23623 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23624 " return 29;\n" 23625 "} else [[likely]] {\n" 23626 " return 42;\n" 23627 "}\n", 23628 Style); 23629 23630 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23631 " return 29;\n" 23632 "} else if (argc > 10) [[likely]] {\n" 23633 " return 99;\n" 23634 "} else {\n" 23635 " return 42;\n" 23636 "}\n", 23637 Style); 23638 23639 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23640 " return 29;\n" 23641 "}", 23642 Style); 23643 23644 verifyFormat("if (argc > 5) [[unlikely]]\n" 23645 " return 29;\n", 23646 Style); 23647 verifyFormat("if (argc > 5) [[likely]]\n" 23648 " return 29;\n", 23649 Style); 23650 23651 Style.AttributeMacros.push_back("UNLIKELY"); 23652 Style.AttributeMacros.push_back("LIKELY"); 23653 verifyFormat("if (argc > 5) UNLIKELY\n" 23654 " return 29;\n", 23655 Style); 23656 23657 verifyFormat("if (argc > 5) UNLIKELY {\n" 23658 " return 29;\n" 23659 "}", 23660 Style); 23661 verifyFormat("if (argc > 5) UNLIKELY {\n" 23662 " return 29;\n" 23663 "} else [[likely]] {\n" 23664 " return 42;\n" 23665 "}\n", 23666 Style); 23667 verifyFormat("if (argc > 5) UNLIKELY {\n" 23668 " return 29;\n" 23669 "} else LIKELY {\n" 23670 " return 42;\n" 23671 "}\n", 23672 Style); 23673 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23674 " return 29;\n" 23675 "} else LIKELY {\n" 23676 " return 42;\n" 23677 "}\n", 23678 Style); 23679 } 23680 23681 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23682 verifyFormat("Constructor()\n" 23683 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23684 " aaaa(aaaaaaaaaaaaaaaaaa, " 23685 "aaaaaaaaaaaaaaaaaat))"); 23686 verifyFormat("Constructor()\n" 23687 " : aaaaaaaaaaaaa(aaaaaa), " 23688 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23689 23690 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23691 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23692 verifyFormat("Constructor()\n" 23693 " : aaaaaa(aaaaaa),\n" 23694 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23695 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23696 StyleWithWhitespacePenalty); 23697 verifyFormat("Constructor()\n" 23698 " : aaaaaaaaaaaaa(aaaaaa), " 23699 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23700 StyleWithWhitespacePenalty); 23701 } 23702 23703 TEST_F(FormatTest, LLVMDefaultStyle) { 23704 FormatStyle Style = getLLVMStyle(); 23705 verifyFormat("extern \"C\" {\n" 23706 "int foo();\n" 23707 "}", 23708 Style); 23709 } 23710 TEST_F(FormatTest, GNUDefaultStyle) { 23711 FormatStyle Style = getGNUStyle(); 23712 verifyFormat("extern \"C\"\n" 23713 "{\n" 23714 " int foo ();\n" 23715 "}", 23716 Style); 23717 } 23718 TEST_F(FormatTest, MozillaDefaultStyle) { 23719 FormatStyle Style = getMozillaStyle(); 23720 verifyFormat("extern \"C\"\n" 23721 "{\n" 23722 " int foo();\n" 23723 "}", 23724 Style); 23725 } 23726 TEST_F(FormatTest, GoogleDefaultStyle) { 23727 FormatStyle Style = getGoogleStyle(); 23728 verifyFormat("extern \"C\" {\n" 23729 "int foo();\n" 23730 "}", 23731 Style); 23732 } 23733 TEST_F(FormatTest, ChromiumDefaultStyle) { 23734 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23735 verifyFormat("extern \"C\" {\n" 23736 "int foo();\n" 23737 "}", 23738 Style); 23739 } 23740 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23741 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23742 verifyFormat("extern \"C\"\n" 23743 "{\n" 23744 " int foo();\n" 23745 "}", 23746 Style); 23747 } 23748 TEST_F(FormatTest, WebKitDefaultStyle) { 23749 FormatStyle Style = getWebKitStyle(); 23750 verifyFormat("extern \"C\" {\n" 23751 "int foo();\n" 23752 "}", 23753 Style); 23754 } 23755 23756 TEST_F(FormatTest, Concepts) { 23757 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23758 FormatStyle::BBCDS_Always); 23759 verifyFormat("template <typename T>\n" 23760 "concept True = true;"); 23761 23762 verifyFormat("template <typename T>\n" 23763 "concept C = ((false || foo()) && C2<T>) ||\n" 23764 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23765 getLLVMStyleWithColumns(60)); 23766 23767 verifyFormat("template <typename T>\n" 23768 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23769 "sizeof(T) <= 8;"); 23770 23771 verifyFormat("template <typename T>\n" 23772 "concept DelayedCheck = true && requires(T t) {\n" 23773 " t.bar();\n" 23774 " t.baz();\n" 23775 " } && sizeof(T) <= 8;"); 23776 23777 verifyFormat("template <typename T>\n" 23778 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23779 " t.bar();\n" 23780 " t.baz();\n" 23781 " } && sizeof(T) <= 8;"); 23782 23783 verifyFormat("template <typename T>\n" 23784 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23785 "sizeof(T) <= 8;"); 23786 23787 verifyFormat("template <typename T>\n" 23788 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23789 "&& sizeof(T) <= 8;"); 23790 23791 verifyFormat( 23792 "template <typename T>\n" 23793 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23794 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23795 23796 verifyFormat("template <typename T>\n" 23797 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23798 "&& sizeof(T) <= 8;"); 23799 23800 verifyFormat( 23801 "template <typename T>\n" 23802 "concept DelayedCheck = (bool)(0) ||\n" 23803 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23804 23805 verifyFormat("template <typename T>\n" 23806 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23807 "&& sizeof(T) <= 8;"); 23808 23809 verifyFormat("template <typename T>\n" 23810 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23811 "sizeof(T) <= 8;"); 23812 23813 verifyFormat("template <typename T>\n" 23814 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23815 " requires(T t) {\n" 23816 " t.bar();\n" 23817 " t.baz();\n" 23818 " } && sizeof(T) <= 8 && !(4 < 3);", 23819 getLLVMStyleWithColumns(60)); 23820 23821 verifyFormat("template <typename T>\n" 23822 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23823 23824 verifyFormat("template <typename T>\n" 23825 "concept C = foo();"); 23826 23827 verifyFormat("template <typename T>\n" 23828 "concept C = foo(T());"); 23829 23830 verifyFormat("template <typename T>\n" 23831 "concept C = foo(T{});"); 23832 23833 verifyFormat("template <typename T>\n" 23834 "concept Size = V<sizeof(T)>::Value > 5;"); 23835 23836 verifyFormat("template <typename T>\n" 23837 "concept True = S<T>::Value;"); 23838 23839 verifyFormat( 23840 "template <typename T>\n" 23841 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23842 " sizeof(T) <= 8;"); 23843 23844 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23845 // the lambda l square. 23846 verifyFormat("template <typename T>\n" 23847 "concept C = [] -> bool { return true; }() && requires(T t) { " 23848 "t.bar(); } &&\n" 23849 " sizeof(T) <= 8;"); 23850 23851 verifyFormat( 23852 "template <typename T>\n" 23853 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23854 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23855 23856 verifyFormat("template <typename T>\n" 23857 "concept C = decltype([]() { return std::true_type{}; " 23858 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23859 getLLVMStyleWithColumns(120)); 23860 23861 verifyFormat("template <typename T>\n" 23862 "concept C = decltype([]() -> std::true_type { return {}; " 23863 "}())::value &&\n" 23864 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23865 23866 verifyFormat("template <typename T>\n" 23867 "concept C = true;\n" 23868 "Foo Bar;"); 23869 23870 verifyFormat("template <typename T>\n" 23871 "concept Hashable = requires(T a) {\n" 23872 " { std::hash<T>{}(a) } -> " 23873 "std::convertible_to<std::size_t>;\n" 23874 " };"); 23875 23876 verifyFormat( 23877 "template <typename T>\n" 23878 "concept EqualityComparable = requires(T a, T b) {\n" 23879 " { a == b } -> std::same_as<bool>;\n" 23880 " };"); 23881 23882 verifyFormat( 23883 "template <typename T>\n" 23884 "concept EqualityComparable = requires(T a, T b) {\n" 23885 " { a == b } -> std::same_as<bool>;\n" 23886 " { a != b } -> std::same_as<bool>;\n" 23887 " };"); 23888 23889 verifyFormat("template <typename T>\n" 23890 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23891 " { a == b };\n" 23892 " { a != b };\n" 23893 " };"); 23894 23895 verifyFormat("template <typename T>\n" 23896 "concept HasSizeT = requires { typename T::size_t; };"); 23897 23898 verifyFormat("template <typename T>\n" 23899 "concept Semiregular =\n" 23900 " DefaultConstructible<T> && CopyConstructible<T> && " 23901 "CopyAssignable<T> &&\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 " };"); 23910 23911 verifyFormat("template <typename T>\n" 23912 "concept Semiregular =\n" 23913 " requires(T a, std::size_t n) {\n" 23914 " requires Same<T *, decltype(&a)>;\n" 23915 " { a.~T() } noexcept;\n" 23916 " requires Same<T *, decltype(new T)>;\n" 23917 " requires Same<T *, decltype(new T[n])>;\n" 23918 " { delete new T; };\n" 23919 " { delete new T[n]; };\n" 23920 " { new T } -> std::same_as<T *>;\n" 23921 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23922 "CopyAssignable<T>;"); 23923 23924 verifyFormat( 23925 "template <typename T>\n" 23926 "concept Semiregular =\n" 23927 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23928 " requires Same<T *, decltype(&a)>;\n" 23929 " { a.~T() } noexcept;\n" 23930 " requires Same<T *, decltype(new T)>;\n" 23931 " requires Same<T *, decltype(new " 23932 "T[n])>;\n" 23933 " { delete new T; };\n" 23934 " { delete new T[n]; };\n" 23935 " } && CopyConstructible<T> && " 23936 "CopyAssignable<T>;"); 23937 23938 verifyFormat("template <typename T>\n" 23939 "concept Two = requires(T t) {\n" 23940 " { t.foo() } -> std::same_as<Bar>;\n" 23941 " } && requires(T &&t) {\n" 23942 " { t.foo() } -> std::same_as<Bar &&>;\n" 23943 " };"); 23944 23945 verifyFormat( 23946 "template <typename T>\n" 23947 "concept C = requires(T x) {\n" 23948 " { *x } -> std::convertible_to<typename T::inner>;\n" 23949 " { x + 1 } noexcept -> std::same_as<int>;\n" 23950 " { x * 1 } -> std::convertible_to<T>;\n" 23951 " };"); 23952 23953 verifyFormat( 23954 "template <typename T, typename U = T>\n" 23955 "concept Swappable = requires(T &&t, U &&u) {\n" 23956 " swap(std::forward<T>(t), std::forward<U>(u));\n" 23957 " swap(std::forward<U>(u), std::forward<T>(t));\n" 23958 " };"); 23959 23960 verifyFormat("template <typename T, typename U>\n" 23961 "concept Common = requires(T &&t, U &&u) {\n" 23962 " typename CommonType<T, U>;\n" 23963 " { CommonType<T, U>(std::forward<T>(t)) };\n" 23964 " };"); 23965 23966 verifyFormat("template <typename T, typename U>\n" 23967 "concept Common = requires(T &&t, U &&u) {\n" 23968 " typename CommonType<T, U>;\n" 23969 " { CommonType<T, U>{std::forward<T>(t)} };\n" 23970 " };"); 23971 23972 verifyFormat( 23973 "template <typename T>\n" 23974 "concept C = requires(T t) {\n" 23975 " requires Bar<T> && Foo<T>;\n" 23976 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23977 " };"); 23978 23979 verifyFormat("template <typename T>\n" 23980 "concept HasFoo = requires(T t) {\n" 23981 " { t.foo() };\n" 23982 " t.foo();\n" 23983 " };\n" 23984 "template <typename T>\n" 23985 "concept HasBar = requires(T t) {\n" 23986 " { t.bar() };\n" 23987 " t.bar();\n" 23988 " };"); 23989 23990 verifyFormat("template <typename T>\n" 23991 "concept Large = sizeof(T) > 10;"); 23992 23993 verifyFormat("template <typename T, typename U>\n" 23994 "concept FooableWith = requires(T t, U u) {\n" 23995 " typename T::foo_type;\n" 23996 " { t.foo(u) } -> typename T::foo_type;\n" 23997 " t++;\n" 23998 " };\n" 23999 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 24000 24001 verifyFormat("template <typename T>\n" 24002 "concept Context = is_specialization_of_v<context, T>;"); 24003 24004 verifyFormat("template <typename T>\n" 24005 "concept Node = std::is_object_v<T>;"); 24006 24007 verifyFormat("template <class T>\n" 24008 "concept integral = __is_integral(T);"); 24009 24010 verifyFormat("template <class T>\n" 24011 "concept is2D = __array_extent(T, 1) == 2;"); 24012 24013 verifyFormat("template <class T>\n" 24014 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24015 24016 verifyFormat("template <class T, class T2>\n" 24017 "concept Same = __is_same_as<T, T2>;"); 24018 24019 auto Style = getLLVMStyle(); 24020 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24021 24022 verifyFormat( 24023 "template <typename T>\n" 24024 "concept C = requires(T t) {\n" 24025 " requires Bar<T> && Foo<T>;\n" 24026 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24027 " };", 24028 Style); 24029 24030 verifyFormat("template <typename T>\n" 24031 "concept HasFoo = requires(T t) {\n" 24032 " { t.foo() };\n" 24033 " t.foo();\n" 24034 " };\n" 24035 "template <typename T>\n" 24036 "concept HasBar = requires(T t) {\n" 24037 " { t.bar() };\n" 24038 " t.bar();\n" 24039 " };", 24040 Style); 24041 24042 verifyFormat("template <typename T> concept True = true;", Style); 24043 24044 verifyFormat("template <typename T>\n" 24045 "concept C = decltype([]() -> std::true_type { return {}; " 24046 "}())::value &&\n" 24047 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24048 Style); 24049 24050 verifyFormat("template <typename T>\n" 24051 "concept Semiregular =\n" 24052 " DefaultConstructible<T> && CopyConstructible<T> && " 24053 "CopyAssignable<T> &&\n" 24054 " requires(T a, std::size_t n) {\n" 24055 " requires Same<T *, decltype(&a)>;\n" 24056 " { a.~T() } noexcept;\n" 24057 " requires Same<T *, decltype(new T)>;\n" 24058 " requires Same<T *, decltype(new T[n])>;\n" 24059 " { delete new T; };\n" 24060 " { delete new T[n]; };\n" 24061 " };", 24062 Style); 24063 24064 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24065 24066 verifyFormat("template <typename T> concept C =\n" 24067 " requires(T t) {\n" 24068 " requires Bar<T> && Foo<T>;\n" 24069 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24070 " };", 24071 Style); 24072 24073 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24074 " { t.foo() };\n" 24075 " t.foo();\n" 24076 " };\n" 24077 "template <typename T> concept HasBar = requires(T t) {\n" 24078 " { t.bar() };\n" 24079 " t.bar();\n" 24080 " };", 24081 Style); 24082 24083 verifyFormat("template <typename T> concept True = true;", Style); 24084 24085 verifyFormat( 24086 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24087 " return {};\n" 24088 " }())::value &&\n" 24089 " requires(T t) { t.bar(); } && " 24090 "sizeof(T) <= 8;", 24091 Style); 24092 24093 verifyFormat("template <typename T> concept Semiregular =\n" 24094 " DefaultConstructible<T> && CopyConstructible<T> && " 24095 "CopyAssignable<T> &&\n" 24096 " requires(T a, std::size_t n) {\n" 24097 " requires Same<T *, decltype(&a)>;\n" 24098 " { a.~T() } noexcept;\n" 24099 " requires Same<T *, decltype(new T)>;\n" 24100 " requires Same<T *, decltype(new T[n])>;\n" 24101 " { delete new T; };\n" 24102 " { delete new T[n]; };\n" 24103 " };", 24104 Style); 24105 24106 // The following tests are invalid C++, we just want to make sure we don't 24107 // assert. 24108 verifyFormat("template <typename T>\n" 24109 "concept C = requires C2<T>;"); 24110 24111 verifyFormat("template <typename T>\n" 24112 "concept C = 5 + 4;"); 24113 24114 verifyFormat("template <typename T>\n" 24115 "concept C =\n" 24116 "class X;"); 24117 24118 verifyFormat("template <typename T>\n" 24119 "concept C = [] && true;"); 24120 24121 verifyFormat("template <typename T>\n" 24122 "concept C = [] && requires(T t) { typename T::size_type; };"); 24123 } 24124 24125 TEST_F(FormatTest, RequiresClausesPositions) { 24126 auto Style = getLLVMStyle(); 24127 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24128 EXPECT_EQ(Style.IndentRequiresClause, true); 24129 24130 verifyFormat("template <typename T>\n" 24131 " requires(Foo<T> && std::trait<T>)\n" 24132 "struct Bar;", 24133 Style); 24134 24135 verifyFormat("template <typename T>\n" 24136 " requires(Foo<T> && std::trait<T>)\n" 24137 "class Bar {\n" 24138 "public:\n" 24139 " Bar(T t);\n" 24140 " bool baz();\n" 24141 "};", 24142 Style); 24143 24144 verifyFormat( 24145 "template <typename T>\n" 24146 " requires requires(T &&t) {\n" 24147 " typename T::I;\n" 24148 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24149 " }\n" 24150 "Bar(T) -> Bar<typename T::I>;", 24151 Style); 24152 24153 verifyFormat("template <typename T>\n" 24154 " requires(Foo<T> && std::trait<T>)\n" 24155 "constexpr T MyGlobal;", 24156 Style); 24157 24158 verifyFormat("template <typename 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 "inline int bar(T t) {\n" 24164 " return t.baz() ? T::Factor : 5;\n" 24165 "}", 24166 Style); 24167 24168 verifyFormat("template <typename T>\n" 24169 "inline int bar(T t)\n" 24170 " requires Foo<T> && requires(T t) {\n" 24171 " { t.baz() } -> std::same_as<bool>;\n" 24172 " requires std::same_as<T::Factor, int>;\n" 24173 " }\n" 24174 "{\n" 24175 " return t.baz() ? T::Factor : 5;\n" 24176 "}", 24177 Style); 24178 24179 verifyFormat("template <typename T>\n" 24180 " requires F<T>\n" 24181 "int bar(T t) {\n" 24182 " return 5;\n" 24183 "}", 24184 Style); 24185 24186 verifyFormat("template <typename T>\n" 24187 "int bar(T t)\n" 24188 " requires F<T>\n" 24189 "{\n" 24190 " return 5;\n" 24191 "}", 24192 Style); 24193 24194 verifyFormat("template <typename T>\n" 24195 "int bar(T t)\n" 24196 " requires F<T>;", 24197 Style); 24198 24199 Style.IndentRequiresClause = false; 24200 verifyFormat("template <typename T>\n" 24201 "requires F<T>\n" 24202 "int bar(T t) {\n" 24203 " return 5;\n" 24204 "}", 24205 Style); 24206 24207 verifyFormat("template <typename T>\n" 24208 "int bar(T t)\n" 24209 "requires F<T>\n" 24210 "{\n" 24211 " return 5;\n" 24212 "}", 24213 Style); 24214 24215 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24216 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24217 "template <typename T> requires Foo<T> void bar() {}\n" 24218 "template <typename T> void bar() requires Foo<T> {}\n" 24219 "template <typename T> void bar() requires Foo<T>;\n" 24220 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24221 Style); 24222 24223 auto ColumnStyle = Style; 24224 ColumnStyle.ColumnLimit = 40; 24225 verifyFormat("template <typename AAAAAAA>\n" 24226 "requires Foo<T> struct Bar {};\n" 24227 "template <typename AAAAAAA>\n" 24228 "requires Foo<T> void bar() {}\n" 24229 "template <typename AAAAAAA>\n" 24230 "void bar() requires Foo<T> {}\n" 24231 "template <typename AAAAAAA>\n" 24232 "requires Foo<T> Baz(T) -> Baz<T>;", 24233 ColumnStyle); 24234 24235 verifyFormat("template <typename T>\n" 24236 "requires Foo<AAAAAAA> struct Bar {};\n" 24237 "template <typename T>\n" 24238 "requires Foo<AAAAAAA> void bar() {}\n" 24239 "template <typename T>\n" 24240 "void bar() requires Foo<AAAAAAA> {}\n" 24241 "template <typename T>\n" 24242 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24243 ColumnStyle); 24244 24245 verifyFormat("template <typename AAAAAAA>\n" 24246 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24247 "struct Bar {};\n" 24248 "template <typename AAAAAAA>\n" 24249 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24250 "void bar() {}\n" 24251 "template <typename AAAAAAA>\n" 24252 "void bar()\n" 24253 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24254 "template <typename AAAAAAA>\n" 24255 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24256 "template <typename AAAAAAA>\n" 24257 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24258 "Bar(T) -> Bar<T>;", 24259 ColumnStyle); 24260 24261 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24262 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24263 24264 verifyFormat("template <typename T>\n" 24265 "requires Foo<T> struct Bar {};\n" 24266 "template <typename T>\n" 24267 "requires Foo<T> void bar() {}\n" 24268 "template <typename T>\n" 24269 "void bar()\n" 24270 "requires Foo<T> {}\n" 24271 "template <typename T>\n" 24272 "void bar()\n" 24273 "requires Foo<T>;\n" 24274 "template <typename T>\n" 24275 "requires Foo<T> Bar(T) -> Bar<T>;", 24276 Style); 24277 24278 verifyFormat("template <typename AAAAAAA>\n" 24279 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24280 "struct Bar {};\n" 24281 "template <typename AAAAAAA>\n" 24282 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24283 "void bar() {}\n" 24284 "template <typename AAAAAAA>\n" 24285 "void bar()\n" 24286 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24287 "template <typename AAAAAAA>\n" 24288 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24289 "template <typename AAAAAAA>\n" 24290 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24291 "Bar(T) -> Bar<T>;", 24292 ColumnStyle); 24293 24294 Style.IndentRequiresClause = true; 24295 ColumnStyle.IndentRequiresClause = true; 24296 24297 verifyFormat("template <typename T>\n" 24298 " requires Foo<T> struct Bar {};\n" 24299 "template <typename T>\n" 24300 " requires Foo<T> void bar() {}\n" 24301 "template <typename T>\n" 24302 "void bar()\n" 24303 " requires Foo<T> {}\n" 24304 "template <typename T>\n" 24305 " requires Foo<T> Bar(T) -> Bar<T>;", 24306 Style); 24307 24308 verifyFormat("template <typename AAAAAAA>\n" 24309 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24310 "struct Bar {};\n" 24311 "template <typename AAAAAAA>\n" 24312 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24313 "void bar() {}\n" 24314 "template <typename AAAAAAA>\n" 24315 "void bar()\n" 24316 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24317 "template <typename AAAAAAA>\n" 24318 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24319 "template <typename AAAAAAA>\n" 24320 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24321 "Bar(T) -> Bar<T>;", 24322 ColumnStyle); 24323 24324 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24325 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24326 24327 verifyFormat("template <typename T> requires Foo<T>\n" 24328 "struct Bar {};\n" 24329 "template <typename T> requires Foo<T>\n" 24330 "void bar() {}\n" 24331 "template <typename T>\n" 24332 "void bar() requires Foo<T>\n" 24333 "{}\n" 24334 "template <typename T> void bar() requires Foo<T>;\n" 24335 "template <typename T> requires Foo<T>\n" 24336 "Bar(T) -> Bar<T>;", 24337 Style); 24338 24339 verifyFormat("template <typename AAAAAAA>\n" 24340 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24341 "struct Bar {};\n" 24342 "template <typename AAAAAAA>\n" 24343 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24344 "void bar() {}\n" 24345 "template <typename AAAAAAA>\n" 24346 "void bar()\n" 24347 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24348 "{}\n" 24349 "template <typename AAAAAAA>\n" 24350 "requires Foo<AAAAAAAA>\n" 24351 "Bar(T) -> Bar<T>;\n" 24352 "template <typename AAAAAAA>\n" 24353 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24354 "Bar(T) -> Bar<T>;", 24355 ColumnStyle); 24356 } 24357 24358 TEST_F(FormatTest, RequiresClauses) { 24359 verifyFormat("struct [[nodiscard]] zero_t {\n" 24360 " template <class T>\n" 24361 " requires requires { number_zero_v<T>; }\n" 24362 " [[nodiscard]] constexpr operator T() const {\n" 24363 " return number_zero_v<T>;\n" 24364 " }\n" 24365 "};"); 24366 24367 auto Style = getLLVMStyle(); 24368 24369 verifyFormat( 24370 "template <typename T>\n" 24371 " requires is_default_constructible_v<hash<T>> and\n" 24372 " is_copy_constructible_v<hash<T>> and\n" 24373 " is_move_constructible_v<hash<T>> and\n" 24374 " is_copy_assignable_v<hash<T>> and " 24375 "is_move_assignable_v<hash<T>> and\n" 24376 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24377 " is_callable_v<hash<T>(T)> and\n" 24378 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24379 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24380 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24381 "struct S {};", 24382 Style); 24383 24384 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24385 verifyFormat( 24386 "template <typename T>\n" 24387 " requires is_default_constructible_v<hash<T>>\n" 24388 " and is_copy_constructible_v<hash<T>>\n" 24389 " and is_move_constructible_v<hash<T>>\n" 24390 " and is_copy_assignable_v<hash<T>> and " 24391 "is_move_assignable_v<hash<T>>\n" 24392 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24393 " and is_callable_v<hash<T>(T)>\n" 24394 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24395 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24396 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24397 "&>()))>\n" 24398 "struct S {};", 24399 Style); 24400 24401 // Not a clause, but we once hit an assert. 24402 verifyFormat("#if 0\n" 24403 "#else\n" 24404 "foo();\n" 24405 "#endif\n" 24406 "bar(requires);"); 24407 } 24408 24409 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24410 FormatStyle Style = getLLVMStyle(); 24411 StringRef Source = "void Foo::slot() {\n" 24412 " unsigned char MyChar = 'x';\n" 24413 " emit signal(MyChar);\n" 24414 " Q_EMIT signal(MyChar);\n" 24415 "}"; 24416 24417 EXPECT_EQ(Source, format(Source, Style)); 24418 24419 Style.AlignConsecutiveDeclarations.Enabled = true; 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 Style.StatementAttributeLikeMacros.push_back("emit"); 24428 EXPECT_EQ(Source, format(Source, Style)); 24429 24430 Style.StatementAttributeLikeMacros = {}; 24431 EXPECT_EQ("void Foo::slot() {\n" 24432 " unsigned char MyChar = 'x';\n" 24433 " emit signal(MyChar);\n" 24434 " Q_EMIT signal(MyChar);\n" 24435 "}", 24436 format(Source, Style)); 24437 } 24438 24439 TEST_F(FormatTest, IndentAccessModifiers) { 24440 FormatStyle Style = getLLVMStyle(); 24441 Style.IndentAccessModifiers = true; 24442 // Members are *two* levels below the record; 24443 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24444 verifyFormat("class C {\n" 24445 " int i;\n" 24446 "};\n", 24447 Style); 24448 verifyFormat("union C {\n" 24449 " int i;\n" 24450 " unsigned u;\n" 24451 "};\n", 24452 Style); 24453 // Access modifiers should be indented one level below the record. 24454 verifyFormat("class C {\n" 24455 " public:\n" 24456 " int i;\n" 24457 "};\n", 24458 Style); 24459 verifyFormat("struct S {\n" 24460 " private:\n" 24461 " class C {\n" 24462 " int j;\n" 24463 "\n" 24464 " public:\n" 24465 " C();\n" 24466 " };\n" 24467 "\n" 24468 " public:\n" 24469 " int i;\n" 24470 "};\n", 24471 Style); 24472 // Enumerations are not records and should be unaffected. 24473 Style.AllowShortEnumsOnASingleLine = false; 24474 verifyFormat("enum class E {\n" 24475 " A,\n" 24476 " B\n" 24477 "};\n", 24478 Style); 24479 // Test with a different indentation width; 24480 // also proves that the result is Style.AccessModifierOffset agnostic. 24481 Style.IndentWidth = 3; 24482 verifyFormat("class C {\n" 24483 " public:\n" 24484 " int i;\n" 24485 "};\n", 24486 Style); 24487 } 24488 24489 TEST_F(FormatTest, LimitlessStringsAndComments) { 24490 auto Style = getLLVMStyleWithColumns(0); 24491 constexpr StringRef Code = 24492 "/**\n" 24493 " * This is a multiline comment with quite some long lines, at least for " 24494 "the LLVM Style.\n" 24495 " * We will redo this with strings and line comments. Just to check if " 24496 "everything is working.\n" 24497 " */\n" 24498 "bool foo() {\n" 24499 " /* Single line multi line comment. */\n" 24500 " const std::string String = \"This is a multiline string with quite " 24501 "some long lines, at least for the LLVM Style.\"\n" 24502 " \"We already did it with multi line " 24503 "comments, and we will do it with line comments. Just to check if " 24504 "everything is working.\";\n" 24505 " // This is a line comment (block) with quite some long lines, at " 24506 "least for the LLVM Style.\n" 24507 " // We already did this with multi line comments and strings. Just to " 24508 "check if everything is working.\n" 24509 " const std::string SmallString = \"Hello World\";\n" 24510 " // Small line comment\n" 24511 " return String.size() > SmallString.size();\n" 24512 "}"; 24513 EXPECT_EQ(Code, format(Code, Style)); 24514 } 24515 24516 TEST_F(FormatTest, FormatDecayCopy) { 24517 // error cases from unit tests 24518 verifyFormat("foo(auto())"); 24519 verifyFormat("foo(auto{})"); 24520 verifyFormat("foo(auto({}))"); 24521 verifyFormat("foo(auto{{}})"); 24522 24523 verifyFormat("foo(auto(1))"); 24524 verifyFormat("foo(auto{1})"); 24525 verifyFormat("foo(new auto(1))"); 24526 verifyFormat("foo(new auto{1})"); 24527 verifyFormat("decltype(auto(1)) x;"); 24528 verifyFormat("decltype(auto{1}) x;"); 24529 verifyFormat("auto(x);"); 24530 verifyFormat("auto{x};"); 24531 verifyFormat("new auto{x};"); 24532 verifyFormat("auto{x} = y;"); 24533 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24534 // the user's own fault 24535 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24536 // clearly the user's own fault 24537 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24538 } 24539 24540 TEST_F(FormatTest, Cpp20ModulesSupport) { 24541 FormatStyle Style = getLLVMStyle(); 24542 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24543 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24544 24545 verifyFormat("export import foo;", Style); 24546 verifyFormat("export import foo:bar;", Style); 24547 verifyFormat("export import foo.bar;", Style); 24548 verifyFormat("export import foo.bar:baz;", Style); 24549 verifyFormat("export import :bar;", Style); 24550 verifyFormat("export module foo:bar;", Style); 24551 verifyFormat("export module foo;", Style); 24552 verifyFormat("export module foo.bar;", Style); 24553 verifyFormat("export module foo.bar:baz;", Style); 24554 verifyFormat("export import <string_view>;", Style); 24555 24556 verifyFormat("export type_name var;", Style); 24557 verifyFormat("template <class T> export using A = B<T>;", Style); 24558 verifyFormat("export using A = B;", Style); 24559 verifyFormat("export int func() {\n" 24560 " foo();\n" 24561 "}", 24562 Style); 24563 verifyFormat("export struct {\n" 24564 " int foo;\n" 24565 "};", 24566 Style); 24567 verifyFormat("export {\n" 24568 " int foo;\n" 24569 "};", 24570 Style); 24571 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24572 24573 verifyFormat("import bar;", Style); 24574 verifyFormat("import foo.bar;", Style); 24575 verifyFormat("import foo:bar;", Style); 24576 verifyFormat("import :bar;", Style); 24577 verifyFormat("import <ctime>;", Style); 24578 verifyFormat("import \"header\";", Style); 24579 24580 verifyFormat("module foo;", Style); 24581 verifyFormat("module foo:bar;", Style); 24582 verifyFormat("module foo.bar;", Style); 24583 verifyFormat("module;", Style); 24584 24585 verifyFormat("export namespace hi {\n" 24586 "const char *sayhi();\n" 24587 "}", 24588 Style); 24589 24590 verifyFormat("module :private;", Style); 24591 verifyFormat("import <foo/bar.h>;", Style); 24592 verifyFormat("import foo...bar;", Style); 24593 verifyFormat("import ..........;", Style); 24594 verifyFormat("module foo:private;", Style); 24595 verifyFormat("import a", Style); 24596 verifyFormat("module a", Style); 24597 verifyFormat("export import a", Style); 24598 verifyFormat("export module a", Style); 24599 24600 verifyFormat("import", Style); 24601 verifyFormat("module", Style); 24602 verifyFormat("export", Style); 24603 } 24604 24605 TEST_F(FormatTest, CoroutineForCoawait) { 24606 FormatStyle Style = getLLVMStyle(); 24607 verifyFormat("for co_await (auto x : range())\n ;"); 24608 verifyFormat("for (auto i : arr) {\n" 24609 "}", 24610 Style); 24611 verifyFormat("for co_await (auto i : arr) {\n" 24612 "}", 24613 Style); 24614 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24615 "}", 24616 Style); 24617 } 24618 24619 TEST_F(FormatTest, CoroutineCoAwait) { 24620 verifyFormat("int x = co_await foo();"); 24621 verifyFormat("int x = (co_await foo());"); 24622 verifyFormat("co_await (42);"); 24623 verifyFormat("void operator co_await(int);"); 24624 verifyFormat("void operator co_await(a);"); 24625 verifyFormat("co_await a;"); 24626 verifyFormat("co_await missing_await_resume{};"); 24627 verifyFormat("co_await a; // comment"); 24628 verifyFormat("void test0() { co_await a; }"); 24629 verifyFormat("co_await co_await co_await foo();"); 24630 verifyFormat("co_await foo().bar();"); 24631 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24632 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24633 "foo(); }(x, y);"); 24634 24635 FormatStyle Style = getLLVMStyleWithColumns(40); 24636 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24637 " co_return co_await foo();\n" 24638 "}(x, y);", 24639 Style); 24640 verifyFormat("co_await;"); 24641 } 24642 24643 TEST_F(FormatTest, CoroutineCoYield) { 24644 verifyFormat("int x = co_yield foo();"); 24645 verifyFormat("int x = (co_yield foo());"); 24646 verifyFormat("co_yield (42);"); 24647 verifyFormat("co_yield {42};"); 24648 verifyFormat("co_yield 42;"); 24649 verifyFormat("co_yield n++;"); 24650 verifyFormat("co_yield ++n;"); 24651 verifyFormat("co_yield;"); 24652 } 24653 24654 TEST_F(FormatTest, CoroutineCoReturn) { 24655 verifyFormat("co_return (42);"); 24656 verifyFormat("co_return;"); 24657 verifyFormat("co_return {};"); 24658 verifyFormat("co_return x;"); 24659 verifyFormat("co_return co_await foo();"); 24660 verifyFormat("co_return co_yield foo();"); 24661 } 24662 24663 TEST_F(FormatTest, EmptyShortBlock) { 24664 auto Style = getLLVMStyle(); 24665 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24666 24667 verifyFormat("try {\n" 24668 " doA();\n" 24669 "} catch (Exception &e) {\n" 24670 " e.printStackTrace();\n" 24671 "}\n", 24672 Style); 24673 24674 verifyFormat("try {\n" 24675 " doA();\n" 24676 "} catch (Exception &e) {}\n", 24677 Style); 24678 } 24679 24680 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24681 auto Style = getLLVMStyle(); 24682 24683 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24684 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24685 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24686 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24687 24688 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24689 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24690 } 24691 24692 TEST_F(FormatTest, InsertBraces) { 24693 FormatStyle Style = getLLVMStyle(); 24694 Style.InsertBraces = true; 24695 24696 verifyFormat("// clang-format off\n" 24697 "// comment\n" 24698 "if (a) f();\n" 24699 "// clang-format on\n" 24700 "if (b) {\n" 24701 " g();\n" 24702 "}", 24703 "// clang-format off\n" 24704 "// comment\n" 24705 "if (a) f();\n" 24706 "// clang-format on\n" 24707 "if (b) g();", 24708 Style); 24709 24710 verifyFormat("if (a) {\n" 24711 " switch (b) {\n" 24712 " case 1:\n" 24713 " c = 0;\n" 24714 " break;\n" 24715 " default:\n" 24716 " c = 1;\n" 24717 " }\n" 24718 "}", 24719 "if (a)\n" 24720 " switch (b) {\n" 24721 " case 1:\n" 24722 " c = 0;\n" 24723 " break;\n" 24724 " default:\n" 24725 " c = 1;\n" 24726 " }", 24727 Style); 24728 24729 verifyFormat("for (auto node : nodes) {\n" 24730 " if (node) {\n" 24731 " break;\n" 24732 " }\n" 24733 "}", 24734 "for (auto node : nodes)\n" 24735 " if (node)\n" 24736 " break;", 24737 Style); 24738 24739 verifyFormat("for (auto node : nodes) {\n" 24740 " if (node)\n" 24741 "}", 24742 "for (auto node : nodes)\n" 24743 " if (node)", 24744 Style); 24745 24746 verifyFormat("do {\n" 24747 " --a;\n" 24748 "} while (a);", 24749 "do\n" 24750 " --a;\n" 24751 "while (a);", 24752 Style); 24753 24754 verifyFormat("if (i) {\n" 24755 " ++i;\n" 24756 "} else {\n" 24757 " --i;\n" 24758 "}", 24759 "if (i)\n" 24760 " ++i;\n" 24761 "else {\n" 24762 " --i;\n" 24763 "}", 24764 Style); 24765 24766 verifyFormat("void f() {\n" 24767 " while (j--) {\n" 24768 " while (i) {\n" 24769 " --i;\n" 24770 " }\n" 24771 " }\n" 24772 "}", 24773 "void f() {\n" 24774 " while (j--)\n" 24775 " while (i)\n" 24776 " --i;\n" 24777 "}", 24778 Style); 24779 24780 verifyFormat("f({\n" 24781 " if (a) {\n" 24782 " g();\n" 24783 " }\n" 24784 "});", 24785 "f({\n" 24786 " if (a)\n" 24787 " g();\n" 24788 "});", 24789 Style); 24790 24791 verifyFormat("if (a) {\n" 24792 " f();\n" 24793 "} else if (b) {\n" 24794 " g();\n" 24795 "} else {\n" 24796 " h();\n" 24797 "}", 24798 "if (a)\n" 24799 " f();\n" 24800 "else if (b)\n" 24801 " g();\n" 24802 "else\n" 24803 " h();", 24804 Style); 24805 24806 verifyFormat("if (a) {\n" 24807 " f();\n" 24808 "}\n" 24809 "// comment\n" 24810 "/* comment */", 24811 "if (a)\n" 24812 " f();\n" 24813 "// comment\n" 24814 "/* comment */", 24815 Style); 24816 24817 verifyFormat("if (a) {\n" 24818 " // foo\n" 24819 " // bar\n" 24820 " f();\n" 24821 "}", 24822 "if (a)\n" 24823 " // foo\n" 24824 " // bar\n" 24825 " f();", 24826 Style); 24827 24828 verifyFormat("if (a) { // comment\n" 24829 " // comment\n" 24830 " f();\n" 24831 "}", 24832 "if (a) // comment\n" 24833 " // comment\n" 24834 " f();", 24835 Style); 24836 24837 verifyFormat("if (a) {\n" 24838 " f(); // comment\n" 24839 "}", 24840 "if (a)\n" 24841 " f(); // comment", 24842 Style); 24843 24844 verifyFormat("if (a) {\n" 24845 " f();\n" 24846 "}\n" 24847 "#undef A\n" 24848 "#undef B", 24849 "if (a)\n" 24850 " f();\n" 24851 "#undef A\n" 24852 "#undef B", 24853 Style); 24854 24855 verifyFormat("if (a)\n" 24856 "#ifdef A\n" 24857 " f();\n" 24858 "#else\n" 24859 " g();\n" 24860 "#endif", 24861 Style); 24862 24863 verifyFormat("#if 0\n" 24864 "#elif 1\n" 24865 "#endif\n" 24866 "void f() {\n" 24867 " if (a) {\n" 24868 " g();\n" 24869 " }\n" 24870 "}", 24871 "#if 0\n" 24872 "#elif 1\n" 24873 "#endif\n" 24874 "void f() {\n" 24875 " if (a) g();\n" 24876 "}", 24877 Style); 24878 24879 Style.ColumnLimit = 15; 24880 24881 verifyFormat("#define A \\\n" 24882 " if (a) \\\n" 24883 " f();", 24884 Style); 24885 24886 verifyFormat("if (a + b >\n" 24887 " c) {\n" 24888 " f();\n" 24889 "}", 24890 "if (a + b > c)\n" 24891 " f();", 24892 Style); 24893 } 24894 24895 TEST_F(FormatTest, RemoveBraces) { 24896 FormatStyle Style = getLLVMStyle(); 24897 Style.RemoveBracesLLVM = true; 24898 24899 // The following eight test cases are fully-braced versions of the examples at 24900 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24901 // statement-bodies-of-if-else-loop-statements". 24902 24903 // 1. Omit the braces, since the body is simple and clearly associated with 24904 // the if. 24905 verifyFormat("if (isa<FunctionDecl>(D))\n" 24906 " handleFunctionDecl(D);\n" 24907 "else if (isa<VarDecl>(D))\n" 24908 " handleVarDecl(D);", 24909 "if (isa<FunctionDecl>(D)) {\n" 24910 " handleFunctionDecl(D);\n" 24911 "} else if (isa<VarDecl>(D)) {\n" 24912 " handleVarDecl(D);\n" 24913 "}", 24914 Style); 24915 24916 // 2. Here we document the condition itself and not the body. 24917 verifyFormat("if (isa<VarDecl>(D)) {\n" 24918 " // It is necessary that we explain the situation with this\n" 24919 " // surprisingly long comment, so it would be unclear\n" 24920 " // without the braces whether the following statement is in\n" 24921 " // the scope of the `if`.\n" 24922 " // Because the condition is documented, we can't really\n" 24923 " // hoist this comment that applies to the body above the\n" 24924 " // if.\n" 24925 " handleOtherDecl(D);\n" 24926 "}", 24927 Style); 24928 24929 // 3. Use braces on the outer `if` to avoid a potential dangling else 24930 // situation. 24931 verifyFormat("if (isa<VarDecl>(D)) {\n" 24932 " for (auto *A : D.attrs())\n" 24933 " if (shouldProcessAttr(A))\n" 24934 " handleAttr(A);\n" 24935 "}", 24936 "if (isa<VarDecl>(D)) {\n" 24937 " for (auto *A : D.attrs()) {\n" 24938 " if (shouldProcessAttr(A)) {\n" 24939 " handleAttr(A);\n" 24940 " }\n" 24941 " }\n" 24942 "}", 24943 Style); 24944 24945 // 4. Use braces for the `if` block to keep it uniform with the else block. 24946 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24947 " handleFunctionDecl(D);\n" 24948 "} else {\n" 24949 " // In this else case, it is necessary that we explain the\n" 24950 " // situation with this surprisingly long comment, so it\n" 24951 " // would be unclear without the braces whether the\n" 24952 " // following statement is in the scope of the `if`.\n" 24953 " handleOtherDecl(D);\n" 24954 "}", 24955 Style); 24956 24957 // 5. This should also omit braces. The `for` loop contains only a single 24958 // statement, so it shouldn't have braces. The `if` also only contains a 24959 // single simple statement (the for loop), so it also should omit braces. 24960 verifyFormat("if (isa<FunctionDecl>(D))\n" 24961 " for (auto *A : D.attrs())\n" 24962 " handleAttr(A);", 24963 "if (isa<FunctionDecl>(D)) {\n" 24964 " for (auto *A : D.attrs()) {\n" 24965 " handleAttr(A);\n" 24966 " }\n" 24967 "}", 24968 Style); 24969 24970 // 6. Use braces for the outer `if` since the nested `for` is braced. 24971 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24972 " for (auto *A : D.attrs()) {\n" 24973 " // In this for loop body, it is necessary that we explain\n" 24974 " // the situation with this surprisingly long comment,\n" 24975 " // forcing braces on the `for` block.\n" 24976 " handleAttr(A);\n" 24977 " }\n" 24978 "}", 24979 Style); 24980 24981 // 7. Use braces on the outer block because there are more than two levels of 24982 // nesting. 24983 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24984 " for (auto *A : D.attrs())\n" 24985 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 24986 " handleAttrOnDecl(D, A, i);\n" 24987 "}", 24988 "if (isa<FunctionDecl>(D)) {\n" 24989 " for (auto *A : D.attrs()) {\n" 24990 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 24991 " handleAttrOnDecl(D, A, i);\n" 24992 " }\n" 24993 " }\n" 24994 "}", 24995 Style); 24996 24997 // 8. Use braces on the outer block because of a nested `if`, otherwise the 24998 // compiler would warn: `add explicit braces to avoid dangling else` 24999 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25000 " if (shouldProcess(D))\n" 25001 " handleVarDecl(D);\n" 25002 " else\n" 25003 " markAsIgnored(D);\n" 25004 "}", 25005 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25006 " if (shouldProcess(D)) {\n" 25007 " handleVarDecl(D);\n" 25008 " } else {\n" 25009 " markAsIgnored(D);\n" 25010 " }\n" 25011 "}", 25012 Style); 25013 25014 verifyFormat("// clang-format off\n" 25015 "// comment\n" 25016 "while (i > 0) { --i; }\n" 25017 "// clang-format on\n" 25018 "while (j < 0)\n" 25019 " ++j;", 25020 "// clang-format off\n" 25021 "// comment\n" 25022 "while (i > 0) { --i; }\n" 25023 "// clang-format on\n" 25024 "while (j < 0) { ++j; }", 25025 Style); 25026 25027 verifyFormat("if (a)\n" 25028 " b; // comment\n" 25029 "else if (c)\n" 25030 " d; /* comment */\n" 25031 "else\n" 25032 " e;", 25033 "if (a) {\n" 25034 " b; // comment\n" 25035 "} else if (c) {\n" 25036 " d; /* comment */\n" 25037 "} else {\n" 25038 " e;\n" 25039 "}", 25040 Style); 25041 25042 verifyFormat("if (a) {\n" 25043 " b;\n" 25044 " c;\n" 25045 "} else if (d) {\n" 25046 " e;\n" 25047 "}", 25048 Style); 25049 25050 verifyFormat("if (a) {\n" 25051 "#undef NDEBUG\n" 25052 " b;\n" 25053 "} else {\n" 25054 " c;\n" 25055 "}", 25056 Style); 25057 25058 verifyFormat("if (a) {\n" 25059 " // comment\n" 25060 "} else if (b) {\n" 25061 " c;\n" 25062 "}", 25063 Style); 25064 25065 verifyFormat("if (a) {\n" 25066 " b;\n" 25067 "} else {\n" 25068 " { c; }\n" 25069 "}", 25070 Style); 25071 25072 verifyFormat("if (a) {\n" 25073 " if (b) // comment\n" 25074 " c;\n" 25075 "} else if (d) {\n" 25076 " e;\n" 25077 "}", 25078 "if (a) {\n" 25079 " if (b) { // comment\n" 25080 " c;\n" 25081 " }\n" 25082 "} else if (d) {\n" 25083 " e;\n" 25084 "}", 25085 Style); 25086 25087 verifyFormat("if (a) {\n" 25088 " if (b) {\n" 25089 " c;\n" 25090 " // comment\n" 25091 " } else if (d) {\n" 25092 " e;\n" 25093 " }\n" 25094 "}", 25095 Style); 25096 25097 verifyFormat("if (a) {\n" 25098 " if (b)\n" 25099 " c;\n" 25100 "}", 25101 "if (a) {\n" 25102 " if (b) {\n" 25103 " c;\n" 25104 " }\n" 25105 "}", 25106 Style); 25107 25108 verifyFormat("if (a)\n" 25109 " if (b)\n" 25110 " c;\n" 25111 " else\n" 25112 " d;\n" 25113 "else\n" 25114 " e;", 25115 "if (a) {\n" 25116 " if (b) {\n" 25117 " c;\n" 25118 " } else {\n" 25119 " d;\n" 25120 " }\n" 25121 "} else {\n" 25122 " e;\n" 25123 "}", 25124 Style); 25125 25126 verifyFormat("if (a) {\n" 25127 " // comment\n" 25128 " if (b)\n" 25129 " c;\n" 25130 " else if (d)\n" 25131 " e;\n" 25132 "} else {\n" 25133 " g;\n" 25134 "}", 25135 "if (a) {\n" 25136 " // comment\n" 25137 " if (b) {\n" 25138 " c;\n" 25139 " } else if (d) {\n" 25140 " e;\n" 25141 " }\n" 25142 "} else {\n" 25143 " g;\n" 25144 "}", 25145 Style); 25146 25147 verifyFormat("if (a)\n" 25148 " b;\n" 25149 "else if (c)\n" 25150 " d;\n" 25151 "else\n" 25152 " e;", 25153 "if (a) {\n" 25154 " b;\n" 25155 "} else {\n" 25156 " if (c) {\n" 25157 " d;\n" 25158 " } else {\n" 25159 " e;\n" 25160 " }\n" 25161 "}", 25162 Style); 25163 25164 verifyFormat("if (a) {\n" 25165 " if (b)\n" 25166 " c;\n" 25167 " else if (d)\n" 25168 " e;\n" 25169 "} else {\n" 25170 " g;\n" 25171 "}", 25172 "if (a) {\n" 25173 " if (b)\n" 25174 " c;\n" 25175 " else {\n" 25176 " if (d)\n" 25177 " e;\n" 25178 " }\n" 25179 "} else {\n" 25180 " g;\n" 25181 "}", 25182 Style); 25183 25184 verifyFormat("if (a)\n" 25185 " b;\n" 25186 "else if (c)\n" 25187 " while (d)\n" 25188 " e;\n" 25189 "// comment", 25190 "if (a)\n" 25191 "{\n" 25192 " b;\n" 25193 "} else if (c) {\n" 25194 " while (d) {\n" 25195 " e;\n" 25196 " }\n" 25197 "}\n" 25198 "// comment", 25199 Style); 25200 25201 verifyFormat("if (a) {\n" 25202 " b;\n" 25203 "} else if (c) {\n" 25204 " d;\n" 25205 "} else {\n" 25206 " e;\n" 25207 " g;\n" 25208 "}", 25209 Style); 25210 25211 verifyFormat("if (a) {\n" 25212 " b;\n" 25213 "} else if (c) {\n" 25214 " d;\n" 25215 "} else {\n" 25216 " e;\n" 25217 "} // comment", 25218 Style); 25219 25220 verifyFormat("int abs = [](int i) {\n" 25221 " if (i >= 0)\n" 25222 " return i;\n" 25223 " return -i;\n" 25224 "};", 25225 "int abs = [](int i) {\n" 25226 " if (i >= 0) {\n" 25227 " return i;\n" 25228 " }\n" 25229 " return -i;\n" 25230 "};", 25231 Style); 25232 25233 verifyFormat("if (a)\n" 25234 " foo();\n" 25235 "else\n" 25236 " bar();", 25237 "if (a)\n" 25238 "{\n" 25239 " foo();\n" 25240 "}\n" 25241 "else\n" 25242 "{\n" 25243 " bar();\n" 25244 "}", 25245 Style); 25246 25247 verifyFormat("if (a) {\n" 25248 "Label:\n" 25249 "}", 25250 Style); 25251 25252 verifyFormat("if (a) {\n" 25253 "Label:\n" 25254 " f();\n" 25255 "}", 25256 Style); 25257 25258 verifyFormat("if (a) {\n" 25259 " f();\n" 25260 "Label:\n" 25261 "}", 25262 Style); 25263 25264 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 25265 #if 0 25266 Style.ColumnLimit = 65; 25267 25268 verifyFormat("if (condition) {\n" 25269 " ff(Indices,\n" 25270 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25271 "} else {\n" 25272 " ff(Indices,\n" 25273 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25274 "}", 25275 Style); 25276 25277 Style.ColumnLimit = 20; 25278 25279 verifyFormat("if (a) {\n" 25280 " b = c + // 1 -\n" 25281 " d;\n" 25282 "}", 25283 Style); 25284 25285 verifyFormat("if (a) {\n" 25286 " b = c >= 0 ? d\n" 25287 " : e;\n" 25288 "}", 25289 "if (a) {\n" 25290 " b = c >= 0 ? d : e;\n" 25291 "}", 25292 Style); 25293 #endif 25294 25295 Style.ColumnLimit = 20; 25296 25297 verifyFormat("if (a)\n" 25298 " b = c > 0 ? d : e;", 25299 "if (a) {\n" 25300 " b = c > 0 ? d : e;\n" 25301 "}", 25302 Style); 25303 25304 Style.ColumnLimit = 0; 25305 25306 verifyFormat("if (a)\n" 25307 " b234567890223456789032345678904234567890 = " 25308 "c234567890223456789032345678904234567890;", 25309 "if (a) {\n" 25310 " b234567890223456789032345678904234567890 = " 25311 "c234567890223456789032345678904234567890;\n" 25312 "}", 25313 Style); 25314 } 25315 25316 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25317 auto Style = getLLVMStyle(); 25318 25319 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25320 "void functionDecl(int a, int b, int c);"; 25321 25322 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25323 "paramF, paramG, paramH, paramI);\n" 25324 "void functionDecl(int argumentA, int argumentB, int " 25325 "argumentC, int argumentD, int argumentE);"; 25326 25327 verifyFormat(Short, Style); 25328 25329 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25330 "paramF, paramG, paramH,\n" 25331 " paramI);\n" 25332 "void functionDecl(int argumentA, int argumentB, int " 25333 "argumentC, int argumentD,\n" 25334 " int argumentE);"; 25335 25336 verifyFormat(NoBreak, Medium, Style); 25337 verifyFormat(NoBreak, 25338 "functionCall(\n" 25339 " paramA,\n" 25340 " paramB,\n" 25341 " paramC,\n" 25342 " paramD,\n" 25343 " paramE,\n" 25344 " paramF,\n" 25345 " paramG,\n" 25346 " paramH,\n" 25347 " paramI\n" 25348 ");\n" 25349 "void functionDecl(\n" 25350 " int argumentA,\n" 25351 " int argumentB,\n" 25352 " int argumentC,\n" 25353 " int argumentD,\n" 25354 " int argumentE\n" 25355 ");", 25356 Style); 25357 25358 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25359 " nestedLongFunctionCall(argument1, " 25360 "argument2, argument3,\n" 25361 " argument4, " 25362 "argument5));", 25363 Style); 25364 25365 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25366 25367 verifyFormat(Short, Style); 25368 verifyFormat( 25369 "functionCall(\n" 25370 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25371 "paramI\n" 25372 ");\n" 25373 "void functionDecl(\n" 25374 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25375 "argumentE\n" 25376 ");", 25377 Medium, Style); 25378 25379 Style.AllowAllArgumentsOnNextLine = false; 25380 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25381 25382 verifyFormat(Short, Style); 25383 verifyFormat( 25384 "functionCall(\n" 25385 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25386 "paramI\n" 25387 ");\n" 25388 "void functionDecl(\n" 25389 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25390 "argumentE\n" 25391 ");", 25392 Medium, Style); 25393 25394 Style.BinPackArguments = false; 25395 Style.BinPackParameters = false; 25396 25397 verifyFormat(Short, Style); 25398 25399 verifyFormat("functionCall(\n" 25400 " paramA,\n" 25401 " paramB,\n" 25402 " paramC,\n" 25403 " paramD,\n" 25404 " paramE,\n" 25405 " paramF,\n" 25406 " paramG,\n" 25407 " paramH,\n" 25408 " paramI\n" 25409 ");\n" 25410 "void functionDecl(\n" 25411 " int argumentA,\n" 25412 " int argumentB,\n" 25413 " int argumentC,\n" 25414 " int argumentD,\n" 25415 " int argumentE\n" 25416 ");", 25417 Medium, Style); 25418 25419 verifyFormat("outerFunctionCall(\n" 25420 " nestedFunctionCall(argument1),\n" 25421 " nestedLongFunctionCall(\n" 25422 " argument1,\n" 25423 " argument2,\n" 25424 " argument3,\n" 25425 " argument4,\n" 25426 " argument5\n" 25427 " )\n" 25428 ");", 25429 Style); 25430 25431 verifyFormat("int a = (int)b;", Style); 25432 verifyFormat("int a = (int)b;", 25433 "int a = (\n" 25434 " int\n" 25435 ") b;", 25436 Style); 25437 25438 verifyFormat("return (true);", Style); 25439 verifyFormat("return (true);", 25440 "return (\n" 25441 " true\n" 25442 ");", 25443 Style); 25444 25445 verifyFormat("void foo();", Style); 25446 verifyFormat("void foo();", 25447 "void foo(\n" 25448 ");", 25449 Style); 25450 25451 verifyFormat("void foo() {}", Style); 25452 verifyFormat("void foo() {}", 25453 "void foo(\n" 25454 ") {\n" 25455 "}", 25456 Style); 25457 25458 verifyFormat("auto string = std::string();", Style); 25459 verifyFormat("auto string = std::string();", 25460 "auto string = std::string(\n" 25461 ");", 25462 Style); 25463 25464 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25465 verifyFormat("void (*functionPointer)() = nullptr;", 25466 "void (\n" 25467 " *functionPointer\n" 25468 ")\n" 25469 "(\n" 25470 ") = nullptr;", 25471 Style); 25472 } 25473 25474 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25475 auto Style = getLLVMStyle(); 25476 25477 verifyFormat("if (foo()) {\n" 25478 " return;\n" 25479 "}", 25480 Style); 25481 25482 verifyFormat("if (quitelongarg !=\n" 25483 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25484 "comment\n" 25485 " return;\n" 25486 "}", 25487 Style); 25488 25489 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25490 25491 verifyFormat("if (foo()) {\n" 25492 " return;\n" 25493 "}", 25494 Style); 25495 25496 verifyFormat("if (quitelongarg !=\n" 25497 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25498 "comment\n" 25499 " return;\n" 25500 "}", 25501 Style); 25502 } 25503 25504 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25505 auto Style = getLLVMStyle(); 25506 25507 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25508 " doSomething();\n" 25509 "}", 25510 Style); 25511 25512 verifyFormat("for (int myReallyLongCountVariable = 0; " 25513 "myReallyLongCountVariable < count;\n" 25514 " myReallyLongCountVariable++) {\n" 25515 " doSomething();\n" 25516 "}", 25517 Style); 25518 25519 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25520 25521 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25522 " doSomething();\n" 25523 "}", 25524 Style); 25525 25526 verifyFormat("for (int myReallyLongCountVariable = 0; " 25527 "myReallyLongCountVariable < count;\n" 25528 " myReallyLongCountVariable++) {\n" 25529 " doSomething();\n" 25530 "}", 25531 Style); 25532 } 25533 25534 TEST_F(FormatTest, UnderstandsDigraphs) { 25535 verifyFormat("int arr<:5:> = {};"); 25536 verifyFormat("int arr[5] = <%%>;"); 25537 verifyFormat("int arr<:::qualified_variable:> = {};"); 25538 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25539 verifyFormat("%:include <header>"); 25540 verifyFormat("%:define A x##y"); 25541 verifyFormat("#define A x%:%:y"); 25542 } 25543 25544 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 25545 auto Style = getLLVMStyle(); 25546 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 25547 Style.AlignConsecutiveAssignments.Enabled = true; 25548 Style.AlignConsecutiveDeclarations.Enabled = true; 25549 25550 // The AlignArray code is incorrect for non square Arrays and can cause 25551 // crashes, these tests assert that the array is not changed but will 25552 // also act as regression tests for when it is properly fixed 25553 verifyFormat("struct test demo[] = {\n" 25554 " {1, 2},\n" 25555 " {3, 4, 5},\n" 25556 " {6, 7, 8}\n" 25557 "};", 25558 Style); 25559 verifyFormat("struct test demo[] = {\n" 25560 " {1, 2, 3, 4, 5},\n" 25561 " {3, 4, 5},\n" 25562 " {6, 7, 8}\n" 25563 "};", 25564 Style); 25565 verifyFormat("struct test demo[] = {\n" 25566 " {1, 2, 3, 4, 5},\n" 25567 " {3, 4, 5},\n" 25568 " {6, 7, 8, 9, 10, 11, 12}\n" 25569 "};", 25570 Style); 25571 verifyFormat("struct test demo[] = {\n" 25572 " {1, 2, 3},\n" 25573 " {3, 4, 5},\n" 25574 " {6, 7, 8, 9, 10, 11, 12}\n" 25575 "};", 25576 Style); 25577 25578 verifyFormat("S{\n" 25579 " {},\n" 25580 " {},\n" 25581 " {a, b}\n" 25582 "};", 25583 Style); 25584 verifyFormat("S{\n" 25585 " {},\n" 25586 " {},\n" 25587 " {a, b},\n" 25588 "};", 25589 Style); 25590 verifyFormat("void foo() {\n" 25591 " auto thing = test{\n" 25592 " {\n" 25593 " {13}, {something}, // A\n" 25594 " }\n" 25595 " };\n" 25596 "}", 25597 "void foo() {\n" 25598 " auto thing = test{\n" 25599 " {\n" 25600 " {13},\n" 25601 " {something}, // A\n" 25602 " }\n" 25603 " };\n" 25604 "}", 25605 Style); 25606 } 25607 25608 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 25609 auto Style = getLLVMStyle(); 25610 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 25611 Style.AlignConsecutiveAssignments.Enabled = true; 25612 Style.AlignConsecutiveDeclarations.Enabled = true; 25613 25614 // The AlignArray code is incorrect for non square Arrays and can cause 25615 // crashes, these tests assert that the array is not changed but will 25616 // also act as regression tests for when it is properly fixed 25617 verifyFormat("struct test demo[] = {\n" 25618 " {1, 2},\n" 25619 " {3, 4, 5},\n" 25620 " {6, 7, 8}\n" 25621 "};", 25622 Style); 25623 verifyFormat("struct test demo[] = {\n" 25624 " {1, 2, 3, 4, 5},\n" 25625 " {3, 4, 5},\n" 25626 " {6, 7, 8}\n" 25627 "};", 25628 Style); 25629 verifyFormat("struct test demo[] = {\n" 25630 " {1, 2, 3, 4, 5},\n" 25631 " {3, 4, 5},\n" 25632 " {6, 7, 8, 9, 10, 11, 12}\n" 25633 "};", 25634 Style); 25635 verifyFormat("struct test demo[] = {\n" 25636 " {1, 2, 3},\n" 25637 " {3, 4, 5},\n" 25638 " {6, 7, 8, 9, 10, 11, 12}\n" 25639 "};", 25640 Style); 25641 25642 verifyFormat("S{\n" 25643 " {},\n" 25644 " {},\n" 25645 " {a, b}\n" 25646 "};", 25647 Style); 25648 verifyFormat("S{\n" 25649 " {},\n" 25650 " {},\n" 25651 " {a, b},\n" 25652 "};", 25653 Style); 25654 verifyFormat("void foo() {\n" 25655 " auto thing = test{\n" 25656 " {\n" 25657 " {13}, {something}, // A\n" 25658 " }\n" 25659 " };\n" 25660 "}", 25661 "void foo() {\n" 25662 " auto thing = test{\n" 25663 " {\n" 25664 " {13},\n" 25665 " {something}, // A\n" 25666 " }\n" 25667 " };\n" 25668 "}", 25669 Style); 25670 } 25671 25672 TEST_F(FormatTest, FormatsVariableTemplates) { 25673 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 25674 verifyFormat("template <typename T> " 25675 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 25676 } 25677 25678 } // namespace 25679 } // namespace format 25680 } // namespace clang 25681