1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Format/Format.h" 10 11 #include "../Tooling/ReplacementTest.h" 12 #include "FormatTestUtils.h" 13 14 #include "llvm/Support/Debug.h" 15 #include "llvm/Support/MemoryBuffer.h" 16 #include "gtest/gtest.h" 17 18 #define DEBUG_TYPE "format-test" 19 20 using clang::tooling::ReplacementTest; 21 using clang::tooling::toReplacements; 22 using testing::ScopedTrace; 23 24 namespace clang { 25 namespace format { 26 namespace { 27 28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); } 29 30 class FormatTest : public ::testing::Test { 31 protected: 32 enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck }; 33 34 std::string format(llvm::StringRef Code, 35 const FormatStyle &Style = getLLVMStyle(), 36 StatusCheck CheckComplete = SC_ExpectComplete) { 37 LLVM_DEBUG(llvm::errs() << "---\n"); 38 LLVM_DEBUG(llvm::errs() << Code << "\n\n"); 39 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size())); 40 FormattingAttemptStatus Status; 41 tooling::Replacements Replaces = 42 reformat(Style, Code, Ranges, "<stdin>", &Status); 43 if (CheckComplete != SC_DoNotCheck) { 44 bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete; 45 EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete) 46 << Code << "\n\n"; 47 } 48 ReplacementCount = Replaces.size(); 49 auto Result = applyAllReplacements(Code, Replaces); 50 EXPECT_TRUE(static_cast<bool>(Result)); 51 LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); 52 return *Result; 53 } 54 55 FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) { 56 Style.ColumnLimit = ColumnLimit; 57 return Style; 58 } 59 60 FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) { 61 return getStyleWithColumns(getLLVMStyle(), ColumnLimit); 62 } 63 64 FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) { 65 return getStyleWithColumns(getGoogleStyle(), ColumnLimit); 66 } 67 68 void _verifyFormat(const char *File, int Line, llvm::StringRef Expected, 69 llvm::StringRef Code, 70 const FormatStyle &Style = getLLVMStyle()) { 71 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 72 EXPECT_EQ(Expected.str(), format(Expected, Style)) 73 << "Expected code is not stable"; 74 EXPECT_EQ(Expected.str(), format(Code, Style)); 75 if (Style.Language == FormatStyle::LK_Cpp) { 76 // Objective-C++ is a superset of C++, so everything checked for C++ 77 // needs to be checked for Objective-C++ as well. 78 FormatStyle ObjCStyle = Style; 79 ObjCStyle.Language = FormatStyle::LK_ObjC; 80 EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle)); 81 } 82 } 83 84 void _verifyFormat(const char *File, int Line, llvm::StringRef Code, 85 const FormatStyle &Style = getLLVMStyle()) { 86 _verifyFormat(File, Line, Code, test::messUp(Code), Style); 87 } 88 89 void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code, 90 const FormatStyle &Style = getLLVMStyle()) { 91 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 92 EXPECT_EQ(Code.str(), 93 format(test::messUp(Code), Style, SC_ExpectIncomplete)); 94 } 95 96 void _verifyIndependentOfContext(const char *File, int Line, 97 llvm::StringRef Text, 98 const FormatStyle &Style = getLLVMStyle()) { 99 _verifyFormat(File, Line, Text, Style); 100 _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(), 101 Style); 102 } 103 104 /// \brief Verify that clang-format does not crash on the given input. 105 void verifyNoCrash(llvm::StringRef Code, 106 const FormatStyle &Style = getLLVMStyle()) { 107 format(Code, Style, SC_DoNotCheck); 108 } 109 110 int ReplacementCount; 111 }; 112 113 #define verifyIndependentOfContext(...) \ 114 _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__) 115 #define verifyIncompleteFormat(...) \ 116 _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__) 117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__) 118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle()) 119 120 TEST_F(FormatTest, MessUp) { 121 EXPECT_EQ("1 2 3", test::messUp("1 2 3")); 122 EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n")); 123 EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc")); 124 EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc")); 125 EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne")); 126 } 127 128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) { 129 EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language); 130 } 131 132 TEST_F(FormatTest, LLVMStyleOverride) { 133 EXPECT_EQ(FormatStyle::LK_Proto, 134 getLLVMStyle(FormatStyle::LK_Proto).Language); 135 } 136 137 //===----------------------------------------------------------------------===// 138 // Basic function tests. 139 //===----------------------------------------------------------------------===// 140 141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { 142 EXPECT_EQ(";", format(";")); 143 } 144 145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) { 146 EXPECT_EQ("int i;", format(" int i;")); 147 EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;")); 148 EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); 149 EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); 150 } 151 152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { 153 EXPECT_EQ("int i;", format("int\ni;")); 154 } 155 156 TEST_F(FormatTest, FormatsNestedBlockStatements) { 157 EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); 158 } 159 160 TEST_F(FormatTest, FormatsNestedCall) { 161 verifyFormat("Method(f1, f2(f3));"); 162 verifyFormat("Method(f1(f2, f3()));"); 163 verifyFormat("Method(f1(f2, (f3())));"); 164 } 165 166 TEST_F(FormatTest, NestedNameSpecifiers) { 167 verifyFormat("vector<::Type> v;"); 168 verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); 169 verifyFormat("static constexpr bool Bar = decltype(bar())::value;"); 170 verifyFormat("static constexpr bool Bar = typeof(bar())::value;"); 171 verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;"); 172 verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;"); 173 verifyFormat("bool a = 2 < ::SomeFunction();"); 174 verifyFormat("ALWAYS_INLINE ::std::string getName();"); 175 verifyFormat("some::string getName();"); 176 } 177 178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { 179 EXPECT_EQ("if (a) {\n" 180 " f();\n" 181 "}", 182 format("if(a){f();}")); 183 EXPECT_EQ(4, ReplacementCount); 184 EXPECT_EQ("if (a) {\n" 185 " f();\n" 186 "}", 187 format("if (a) {\n" 188 " f();\n" 189 "}")); 190 EXPECT_EQ(0, ReplacementCount); 191 EXPECT_EQ("/*\r\n" 192 "\r\n" 193 "*/\r\n", 194 format("/*\r\n" 195 "\r\n" 196 "*/\r\n")); 197 EXPECT_EQ(0, ReplacementCount); 198 } 199 200 TEST_F(FormatTest, RemovesEmptyLines) { 201 EXPECT_EQ("class C {\n" 202 " int i;\n" 203 "};", 204 format("class C {\n" 205 " int i;\n" 206 "\n" 207 "};")); 208 209 // Don't remove empty lines at the start of namespaces or extern "C" blocks. 210 EXPECT_EQ("namespace N {\n" 211 "\n" 212 "int i;\n" 213 "}", 214 format("namespace N {\n" 215 "\n" 216 "int i;\n" 217 "}", 218 getGoogleStyle())); 219 EXPECT_EQ("/* something */ namespace N {\n" 220 "\n" 221 "int i;\n" 222 "}", 223 format("/* something */ namespace N {\n" 224 "\n" 225 "int i;\n" 226 "}", 227 getGoogleStyle())); 228 EXPECT_EQ("inline namespace N {\n" 229 "\n" 230 "int i;\n" 231 "}", 232 format("inline namespace N {\n" 233 "\n" 234 "int i;\n" 235 "}", 236 getGoogleStyle())); 237 EXPECT_EQ("/* something */ inline namespace N {\n" 238 "\n" 239 "int i;\n" 240 "}", 241 format("/* something */ inline namespace N {\n" 242 "\n" 243 "int i;\n" 244 "}", 245 getGoogleStyle())); 246 EXPECT_EQ("export namespace N {\n" 247 "\n" 248 "int i;\n" 249 "}", 250 format("export namespace N {\n" 251 "\n" 252 "int i;\n" 253 "}", 254 getGoogleStyle())); 255 EXPECT_EQ("extern /**/ \"C\" /**/ {\n" 256 "\n" 257 "int i;\n" 258 "}", 259 format("extern /**/ \"C\" /**/ {\n" 260 "\n" 261 "int i;\n" 262 "}", 263 getGoogleStyle())); 264 265 auto CustomStyle = getLLVMStyle(); 266 CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom; 267 CustomStyle.BraceWrapping.AfterNamespace = true; 268 CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false; 269 EXPECT_EQ("namespace N\n" 270 "{\n" 271 "\n" 272 "int i;\n" 273 "}", 274 format("namespace N\n" 275 "{\n" 276 "\n" 277 "\n" 278 "int i;\n" 279 "}", 280 CustomStyle)); 281 EXPECT_EQ("/* something */ namespace N\n" 282 "{\n" 283 "\n" 284 "int i;\n" 285 "}", 286 format("/* something */ namespace N {\n" 287 "\n" 288 "\n" 289 "int i;\n" 290 "}", 291 CustomStyle)); 292 EXPECT_EQ("inline namespace N\n" 293 "{\n" 294 "\n" 295 "int i;\n" 296 "}", 297 format("inline namespace N\n" 298 "{\n" 299 "\n" 300 "\n" 301 "int i;\n" 302 "}", 303 CustomStyle)); 304 EXPECT_EQ("/* something */ inline namespace N\n" 305 "{\n" 306 "\n" 307 "int i;\n" 308 "}", 309 format("/* something */ inline namespace N\n" 310 "{\n" 311 "\n" 312 "int i;\n" 313 "}", 314 CustomStyle)); 315 EXPECT_EQ("export namespace N\n" 316 "{\n" 317 "\n" 318 "int i;\n" 319 "}", 320 format("export namespace N\n" 321 "{\n" 322 "\n" 323 "int i;\n" 324 "}", 325 CustomStyle)); 326 EXPECT_EQ("namespace a\n" 327 "{\n" 328 "namespace b\n" 329 "{\n" 330 "\n" 331 "class AA {};\n" 332 "\n" 333 "} // namespace b\n" 334 "} // namespace a\n", 335 format("namespace a\n" 336 "{\n" 337 "namespace b\n" 338 "{\n" 339 "\n" 340 "\n" 341 "class AA {};\n" 342 "\n" 343 "\n" 344 "}\n" 345 "}\n", 346 CustomStyle)); 347 EXPECT_EQ("namespace A /* comment */\n" 348 "{\n" 349 "class B {}\n" 350 "} // namespace A", 351 format("namespace A /* comment */ { class B {} }", CustomStyle)); 352 EXPECT_EQ("namespace A\n" 353 "{ /* comment */\n" 354 "class B {}\n" 355 "} // namespace A", 356 format("namespace A {/* comment */ class B {} }", CustomStyle)); 357 EXPECT_EQ("namespace A\n" 358 "{ /* comment */\n" 359 "\n" 360 "class B {}\n" 361 "\n" 362 "" 363 "} // namespace A", 364 format("namespace A { /* comment */\n" 365 "\n" 366 "\n" 367 "class B {}\n" 368 "\n" 369 "\n" 370 "}", 371 CustomStyle)); 372 EXPECT_EQ("namespace A /* comment */\n" 373 "{\n" 374 "\n" 375 "class B {}\n" 376 "\n" 377 "} // namespace A", 378 format("namespace A/* comment */ {\n" 379 "\n" 380 "\n" 381 "class B {}\n" 382 "\n" 383 "\n" 384 "}", 385 CustomStyle)); 386 387 // ...but do keep inlining and removing empty lines for non-block extern "C" 388 // functions. 389 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); 390 EXPECT_EQ("extern \"C\" int f() {\n" 391 " int i = 42;\n" 392 " return i;\n" 393 "}", 394 format("extern \"C\" int f() {\n" 395 "\n" 396 " int i = 42;\n" 397 " return i;\n" 398 "}", 399 getGoogleStyle())); 400 401 // Remove empty lines at the beginning and end of blocks. 402 EXPECT_EQ("void f() {\n" 403 "\n" 404 " if (a) {\n" 405 "\n" 406 " f();\n" 407 " }\n" 408 "}", 409 format("void f() {\n" 410 "\n" 411 " if (a) {\n" 412 "\n" 413 " f();\n" 414 "\n" 415 " }\n" 416 "\n" 417 "}", 418 getLLVMStyle())); 419 EXPECT_EQ("void f() {\n" 420 " if (a) {\n" 421 " f();\n" 422 " }\n" 423 "}", 424 format("void f() {\n" 425 "\n" 426 " if (a) {\n" 427 "\n" 428 " f();\n" 429 "\n" 430 " }\n" 431 "\n" 432 "}", 433 getGoogleStyle())); 434 435 // Don't remove empty lines in more complex control statements. 436 EXPECT_EQ("void f() {\n" 437 " if (a) {\n" 438 " f();\n" 439 "\n" 440 " } else if (b) {\n" 441 " f();\n" 442 " }\n" 443 "}", 444 format("void f() {\n" 445 " if (a) {\n" 446 " f();\n" 447 "\n" 448 " } else if (b) {\n" 449 " f();\n" 450 "\n" 451 " }\n" 452 "\n" 453 "}")); 454 455 // Don't remove empty lines before namespace endings. 456 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 457 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 458 EXPECT_EQ("namespace {\n" 459 "int i;\n" 460 "\n" 461 "}", 462 format("namespace {\n" 463 "int i;\n" 464 "\n" 465 "}", 466 LLVMWithNoNamespaceFix)); 467 EXPECT_EQ("namespace {\n" 468 "int i;\n" 469 "}", 470 format("namespace {\n" 471 "int i;\n" 472 "}", 473 LLVMWithNoNamespaceFix)); 474 EXPECT_EQ("namespace {\n" 475 "int i;\n" 476 "\n" 477 "};", 478 format("namespace {\n" 479 "int i;\n" 480 "\n" 481 "};", 482 LLVMWithNoNamespaceFix)); 483 EXPECT_EQ("namespace {\n" 484 "int i;\n" 485 "};", 486 format("namespace {\n" 487 "int i;\n" 488 "};", 489 LLVMWithNoNamespaceFix)); 490 EXPECT_EQ("namespace {\n" 491 "int i;\n" 492 "\n" 493 "}", 494 format("namespace {\n" 495 "int i;\n" 496 "\n" 497 "}")); 498 EXPECT_EQ("namespace {\n" 499 "int i;\n" 500 "\n" 501 "} // namespace", 502 format("namespace {\n" 503 "int i;\n" 504 "\n" 505 "} // namespace")); 506 507 FormatStyle Style = getLLVMStyle(); 508 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 509 Style.MaxEmptyLinesToKeep = 2; 510 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 511 Style.BraceWrapping.AfterClass = true; 512 Style.BraceWrapping.AfterFunction = true; 513 Style.KeepEmptyLinesAtTheStartOfBlocks = false; 514 515 EXPECT_EQ("class Foo\n" 516 "{\n" 517 " Foo() {}\n" 518 "\n" 519 " void funk() {}\n" 520 "};", 521 format("class Foo\n" 522 "{\n" 523 " Foo()\n" 524 " {\n" 525 " }\n" 526 "\n" 527 " void funk() {}\n" 528 "};", 529 Style)); 530 } 531 532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { 533 verifyFormat("x = (a) and (b);"); 534 verifyFormat("x = (a) or (b);"); 535 verifyFormat("x = (a) bitand (b);"); 536 verifyFormat("x = (a) bitor (b);"); 537 verifyFormat("x = (a) not_eq (b);"); 538 verifyFormat("x = (a) and_eq (b);"); 539 verifyFormat("x = (a) or_eq (b);"); 540 verifyFormat("x = (a) xor (b);"); 541 } 542 543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { 544 verifyFormat("x = compl(a);"); 545 verifyFormat("x = not(a);"); 546 verifyFormat("x = bitand(a);"); 547 // Unary operator must not be merged with the next identifier 548 verifyFormat("x = compl a;"); 549 verifyFormat("x = not a;"); 550 verifyFormat("x = bitand a;"); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // Tests for control statements. 555 //===----------------------------------------------------------------------===// 556 557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { 558 verifyFormat("if (true)\n f();\ng();"); 559 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); 560 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); 561 verifyFormat("if constexpr (true)\n" 562 " f();\ng();"); 563 verifyFormat("if CONSTEXPR (true)\n" 564 " f();\ng();"); 565 verifyFormat("if constexpr (a)\n" 566 " if constexpr (b)\n" 567 " if constexpr (c)\n" 568 " g();\n" 569 "h();"); 570 verifyFormat("if CONSTEXPR (a)\n" 571 " if CONSTEXPR (b)\n" 572 " if CONSTEXPR (c)\n" 573 " g();\n" 574 "h();"); 575 verifyFormat("if constexpr (a)\n" 576 " if constexpr (b) {\n" 577 " f();\n" 578 " }\n" 579 "g();"); 580 verifyFormat("if CONSTEXPR (a)\n" 581 " if CONSTEXPR (b) {\n" 582 " f();\n" 583 " }\n" 584 "g();"); 585 586 verifyFormat("if consteval {\n}"); 587 verifyFormat("if !consteval {\n}"); 588 verifyFormat("if not consteval {\n}"); 589 verifyFormat("if consteval {\n} else {\n}"); 590 verifyFormat("if !consteval {\n} else {\n}"); 591 verifyFormat("if consteval {\n" 592 " f();\n" 593 "}"); 594 verifyFormat("if !consteval {\n" 595 " f();\n" 596 "}"); 597 verifyFormat("if consteval {\n" 598 " f();\n" 599 "} else {\n" 600 " g();\n" 601 "}"); 602 verifyFormat("if CONSTEVAL {\n" 603 " f();\n" 604 "}"); 605 verifyFormat("if !CONSTEVAL {\n" 606 " f();\n" 607 "}"); 608 609 verifyFormat("if (a)\n" 610 " g();"); 611 verifyFormat("if (a) {\n" 612 " g()\n" 613 "};"); 614 verifyFormat("if (a)\n" 615 " g();\n" 616 "else\n" 617 " g();"); 618 verifyFormat("if (a) {\n" 619 " g();\n" 620 "} else\n" 621 " g();"); 622 verifyFormat("if (a)\n" 623 " g();\n" 624 "else {\n" 625 " g();\n" 626 "}"); 627 verifyFormat("if (a) {\n" 628 " g();\n" 629 "} else {\n" 630 " g();\n" 631 "}"); 632 verifyFormat("if (a)\n" 633 " g();\n" 634 "else if (b)\n" 635 " g();\n" 636 "else\n" 637 " g();"); 638 verifyFormat("if (a) {\n" 639 " g();\n" 640 "} else if (b)\n" 641 " g();\n" 642 "else\n" 643 " g();"); 644 verifyFormat("if (a)\n" 645 " g();\n" 646 "else if (b) {\n" 647 " g();\n" 648 "} else\n" 649 " g();"); 650 verifyFormat("if (a)\n" 651 " g();\n" 652 "else if (b)\n" 653 " g();\n" 654 "else {\n" 655 " g();\n" 656 "}"); 657 verifyFormat("if (a)\n" 658 " g();\n" 659 "else if (b) {\n" 660 " g();\n" 661 "} else {\n" 662 " g();\n" 663 "}"); 664 verifyFormat("if (a) {\n" 665 " g();\n" 666 "} else if (b) {\n" 667 " g();\n" 668 "} else {\n" 669 " g();\n" 670 "}"); 671 672 FormatStyle AllowsMergedIf = getLLVMStyle(); 673 AllowsMergedIf.IfMacros.push_back("MYIF"); 674 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 675 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 676 FormatStyle::SIS_WithoutElse; 677 verifyFormat("if (a)\n" 678 " // comment\n" 679 " f();", 680 AllowsMergedIf); 681 verifyFormat("{\n" 682 " if (a)\n" 683 " label:\n" 684 " f();\n" 685 "}", 686 AllowsMergedIf); 687 verifyFormat("#define A \\\n" 688 " if (a) \\\n" 689 " label: \\\n" 690 " f()", 691 AllowsMergedIf); 692 verifyFormat("if (a)\n" 693 " ;", 694 AllowsMergedIf); 695 verifyFormat("if (a)\n" 696 " if (b) return;", 697 AllowsMergedIf); 698 699 verifyFormat("if (a) // Can't merge this\n" 700 " f();\n", 701 AllowsMergedIf); 702 verifyFormat("if (a) /* still don't merge */\n" 703 " f();", 704 AllowsMergedIf); 705 verifyFormat("if (a) { // Never merge this\n" 706 " f();\n" 707 "}", 708 AllowsMergedIf); 709 verifyFormat("if (a) { /* Never merge this */\n" 710 " f();\n" 711 "}", 712 AllowsMergedIf); 713 verifyFormat("MYIF (a)\n" 714 " // comment\n" 715 " f();", 716 AllowsMergedIf); 717 verifyFormat("{\n" 718 " MYIF (a)\n" 719 " label:\n" 720 " f();\n" 721 "}", 722 AllowsMergedIf); 723 verifyFormat("#define A \\\n" 724 " MYIF (a) \\\n" 725 " label: \\\n" 726 " f()", 727 AllowsMergedIf); 728 verifyFormat("MYIF (a)\n" 729 " ;", 730 AllowsMergedIf); 731 verifyFormat("MYIF (a)\n" 732 " MYIF (b) return;", 733 AllowsMergedIf); 734 735 verifyFormat("MYIF (a) // Can't merge this\n" 736 " f();\n", 737 AllowsMergedIf); 738 verifyFormat("MYIF (a) /* still don't merge */\n" 739 " f();", 740 AllowsMergedIf); 741 verifyFormat("MYIF (a) { // Never merge this\n" 742 " f();\n" 743 "}", 744 AllowsMergedIf); 745 verifyFormat("MYIF (a) { /* Never merge this */\n" 746 " f();\n" 747 "}", 748 AllowsMergedIf); 749 750 AllowsMergedIf.ColumnLimit = 14; 751 // Where line-lengths matter, a 2-letter synonym that maintains line length. 752 // Not IF to avoid any confusion that IF is somehow special. 753 AllowsMergedIf.IfMacros.push_back("FI"); 754 verifyFormat("if (a) return;", AllowsMergedIf); 755 verifyFormat("if (aaaaaaaaa)\n" 756 " return;", 757 AllowsMergedIf); 758 verifyFormat("FI (a) return;", AllowsMergedIf); 759 verifyFormat("FI (aaaaaaaaa)\n" 760 " return;", 761 AllowsMergedIf); 762 763 AllowsMergedIf.ColumnLimit = 13; 764 verifyFormat("if (a)\n return;", AllowsMergedIf); 765 verifyFormat("FI (a)\n return;", AllowsMergedIf); 766 767 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 768 AllowsMergedIfElse.IfMacros.push_back("MYIF"); 769 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 770 FormatStyle::SIS_AllIfsAndElse; 771 verifyFormat("if (a)\n" 772 " // comment\n" 773 " f();\n" 774 "else\n" 775 " // comment\n" 776 " f();", 777 AllowsMergedIfElse); 778 verifyFormat("{\n" 779 " if (a)\n" 780 " label:\n" 781 " f();\n" 782 " else\n" 783 " label:\n" 784 " f();\n" 785 "}", 786 AllowsMergedIfElse); 787 verifyFormat("if (a)\n" 788 " ;\n" 789 "else\n" 790 " ;", 791 AllowsMergedIfElse); 792 verifyFormat("if (a) {\n" 793 "} else {\n" 794 "}", 795 AllowsMergedIfElse); 796 verifyFormat("if (a) return;\n" 797 "else if (b) return;\n" 798 "else return;", 799 AllowsMergedIfElse); 800 verifyFormat("if (a) {\n" 801 "} else return;", 802 AllowsMergedIfElse); 803 verifyFormat("if (a) {\n" 804 "} else if (b) return;\n" 805 "else return;", 806 AllowsMergedIfElse); 807 verifyFormat("if (a) return;\n" 808 "else if (b) {\n" 809 "} else return;", 810 AllowsMergedIfElse); 811 verifyFormat("if (a)\n" 812 " if (b) return;\n" 813 " else return;", 814 AllowsMergedIfElse); 815 verifyFormat("if constexpr (a)\n" 816 " if constexpr (b) return;\n" 817 " else if constexpr (c) return;\n" 818 " else return;", 819 AllowsMergedIfElse); 820 verifyFormat("MYIF (a)\n" 821 " // comment\n" 822 " f();\n" 823 "else\n" 824 " // comment\n" 825 " f();", 826 AllowsMergedIfElse); 827 verifyFormat("{\n" 828 " MYIF (a)\n" 829 " label:\n" 830 " f();\n" 831 " else\n" 832 " label:\n" 833 " f();\n" 834 "}", 835 AllowsMergedIfElse); 836 verifyFormat("MYIF (a)\n" 837 " ;\n" 838 "else\n" 839 " ;", 840 AllowsMergedIfElse); 841 verifyFormat("MYIF (a) {\n" 842 "} else {\n" 843 "}", 844 AllowsMergedIfElse); 845 verifyFormat("MYIF (a) return;\n" 846 "else MYIF (b) return;\n" 847 "else return;", 848 AllowsMergedIfElse); 849 verifyFormat("MYIF (a) {\n" 850 "} else return;", 851 AllowsMergedIfElse); 852 verifyFormat("MYIF (a) {\n" 853 "} else MYIF (b) return;\n" 854 "else return;", 855 AllowsMergedIfElse); 856 verifyFormat("MYIF (a) return;\n" 857 "else MYIF (b) {\n" 858 "} else return;", 859 AllowsMergedIfElse); 860 verifyFormat("MYIF (a)\n" 861 " MYIF (b) return;\n" 862 " else return;", 863 AllowsMergedIfElse); 864 verifyFormat("MYIF constexpr (a)\n" 865 " MYIF constexpr (b) return;\n" 866 " else MYIF constexpr (c) return;\n" 867 " else return;", 868 AllowsMergedIfElse); 869 } 870 871 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 872 FormatStyle AllowsMergedIf = getLLVMStyle(); 873 AllowsMergedIf.IfMacros.push_back("MYIF"); 874 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 875 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 876 FormatStyle::SIS_WithoutElse; 877 verifyFormat("if (a)\n" 878 " f();\n" 879 "else {\n" 880 " g();\n" 881 "}", 882 AllowsMergedIf); 883 verifyFormat("if (a)\n" 884 " f();\n" 885 "else\n" 886 " g();\n", 887 AllowsMergedIf); 888 889 verifyFormat("if (a) g();", AllowsMergedIf); 890 verifyFormat("if (a) {\n" 891 " g()\n" 892 "};", 893 AllowsMergedIf); 894 verifyFormat("if (a)\n" 895 " g();\n" 896 "else\n" 897 " g();", 898 AllowsMergedIf); 899 verifyFormat("if (a) {\n" 900 " g();\n" 901 "} else\n" 902 " g();", 903 AllowsMergedIf); 904 verifyFormat("if (a)\n" 905 " g();\n" 906 "else {\n" 907 " g();\n" 908 "}", 909 AllowsMergedIf); 910 verifyFormat("if (a) {\n" 911 " g();\n" 912 "} else {\n" 913 " g();\n" 914 "}", 915 AllowsMergedIf); 916 verifyFormat("if (a)\n" 917 " g();\n" 918 "else if (b)\n" 919 " g();\n" 920 "else\n" 921 " g();", 922 AllowsMergedIf); 923 verifyFormat("if (a) {\n" 924 " g();\n" 925 "} else if (b)\n" 926 " g();\n" 927 "else\n" 928 " g();", 929 AllowsMergedIf); 930 verifyFormat("if (a)\n" 931 " g();\n" 932 "else if (b) {\n" 933 " g();\n" 934 "} else\n" 935 " g();", 936 AllowsMergedIf); 937 verifyFormat("if (a)\n" 938 " g();\n" 939 "else if (b)\n" 940 " g();\n" 941 "else {\n" 942 " g();\n" 943 "}", 944 AllowsMergedIf); 945 verifyFormat("if (a)\n" 946 " g();\n" 947 "else if (b) {\n" 948 " g();\n" 949 "} else {\n" 950 " g();\n" 951 "}", 952 AllowsMergedIf); 953 verifyFormat("if (a) {\n" 954 " g();\n" 955 "} else if (b) {\n" 956 " g();\n" 957 "} else {\n" 958 " g();\n" 959 "}", 960 AllowsMergedIf); 961 verifyFormat("MYIF (a)\n" 962 " f();\n" 963 "else {\n" 964 " g();\n" 965 "}", 966 AllowsMergedIf); 967 verifyFormat("MYIF (a)\n" 968 " f();\n" 969 "else\n" 970 " g();\n", 971 AllowsMergedIf); 972 973 verifyFormat("MYIF (a) g();", AllowsMergedIf); 974 verifyFormat("MYIF (a) {\n" 975 " g()\n" 976 "};", 977 AllowsMergedIf); 978 verifyFormat("MYIF (a)\n" 979 " g();\n" 980 "else\n" 981 " g();", 982 AllowsMergedIf); 983 verifyFormat("MYIF (a) {\n" 984 " g();\n" 985 "} else\n" 986 " g();", 987 AllowsMergedIf); 988 verifyFormat("MYIF (a)\n" 989 " g();\n" 990 "else {\n" 991 " g();\n" 992 "}", 993 AllowsMergedIf); 994 verifyFormat("MYIF (a) {\n" 995 " g();\n" 996 "} else {\n" 997 " g();\n" 998 "}", 999 AllowsMergedIf); 1000 verifyFormat("MYIF (a)\n" 1001 " g();\n" 1002 "else MYIF (b)\n" 1003 " g();\n" 1004 "else\n" 1005 " g();", 1006 AllowsMergedIf); 1007 verifyFormat("MYIF (a)\n" 1008 " g();\n" 1009 "else if (b)\n" 1010 " g();\n" 1011 "else\n" 1012 " g();", 1013 AllowsMergedIf); 1014 verifyFormat("MYIF (a) {\n" 1015 " g();\n" 1016 "} else MYIF (b)\n" 1017 " g();\n" 1018 "else\n" 1019 " g();", 1020 AllowsMergedIf); 1021 verifyFormat("MYIF (a) {\n" 1022 " g();\n" 1023 "} else if (b)\n" 1024 " g();\n" 1025 "else\n" 1026 " g();", 1027 AllowsMergedIf); 1028 verifyFormat("MYIF (a)\n" 1029 " g();\n" 1030 "else MYIF (b) {\n" 1031 " g();\n" 1032 "} else\n" 1033 " g();", 1034 AllowsMergedIf); 1035 verifyFormat("MYIF (a)\n" 1036 " g();\n" 1037 "else if (b) {\n" 1038 " g();\n" 1039 "} else\n" 1040 " g();", 1041 AllowsMergedIf); 1042 verifyFormat("MYIF (a)\n" 1043 " g();\n" 1044 "else MYIF (b)\n" 1045 " g();\n" 1046 "else {\n" 1047 " g();\n" 1048 "}", 1049 AllowsMergedIf); 1050 verifyFormat("MYIF (a)\n" 1051 " g();\n" 1052 "else if (b)\n" 1053 " g();\n" 1054 "else {\n" 1055 " g();\n" 1056 "}", 1057 AllowsMergedIf); 1058 verifyFormat("MYIF (a)\n" 1059 " g();\n" 1060 "else MYIF (b) {\n" 1061 " g();\n" 1062 "} else {\n" 1063 " g();\n" 1064 "}", 1065 AllowsMergedIf); 1066 verifyFormat("MYIF (a)\n" 1067 " g();\n" 1068 "else if (b) {\n" 1069 " g();\n" 1070 "} else {\n" 1071 " g();\n" 1072 "}", 1073 AllowsMergedIf); 1074 verifyFormat("MYIF (a) {\n" 1075 " g();\n" 1076 "} else MYIF (b) {\n" 1077 " g();\n" 1078 "} else {\n" 1079 " g();\n" 1080 "}", 1081 AllowsMergedIf); 1082 verifyFormat("MYIF (a) {\n" 1083 " g();\n" 1084 "} else if (b) {\n" 1085 " g();\n" 1086 "} else {\n" 1087 " g();\n" 1088 "}", 1089 AllowsMergedIf); 1090 1091 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1092 FormatStyle::SIS_OnlyFirstIf; 1093 1094 verifyFormat("if (a) f();\n" 1095 "else {\n" 1096 " g();\n" 1097 "}", 1098 AllowsMergedIf); 1099 verifyFormat("if (a) f();\n" 1100 "else {\n" 1101 " if (a) f();\n" 1102 " else {\n" 1103 " g();\n" 1104 " }\n" 1105 " g();\n" 1106 "}", 1107 AllowsMergedIf); 1108 1109 verifyFormat("if (a) g();", AllowsMergedIf); 1110 verifyFormat("if (a) {\n" 1111 " g()\n" 1112 "};", 1113 AllowsMergedIf); 1114 verifyFormat("if (a) g();\n" 1115 "else\n" 1116 " g();", 1117 AllowsMergedIf); 1118 verifyFormat("if (a) {\n" 1119 " g();\n" 1120 "} else\n" 1121 " g();", 1122 AllowsMergedIf); 1123 verifyFormat("if (a) g();\n" 1124 "else {\n" 1125 " g();\n" 1126 "}", 1127 AllowsMergedIf); 1128 verifyFormat("if (a) {\n" 1129 " g();\n" 1130 "} else {\n" 1131 " g();\n" 1132 "}", 1133 AllowsMergedIf); 1134 verifyFormat("if (a) g();\n" 1135 "else if (b)\n" 1136 " g();\n" 1137 "else\n" 1138 " g();", 1139 AllowsMergedIf); 1140 verifyFormat("if (a) {\n" 1141 " g();\n" 1142 "} else if (b)\n" 1143 " g();\n" 1144 "else\n" 1145 " g();", 1146 AllowsMergedIf); 1147 verifyFormat("if (a) g();\n" 1148 "else if (b) {\n" 1149 " g();\n" 1150 "} else\n" 1151 " g();", 1152 AllowsMergedIf); 1153 verifyFormat("if (a) g();\n" 1154 "else if (b)\n" 1155 " g();\n" 1156 "else {\n" 1157 " g();\n" 1158 "}", 1159 AllowsMergedIf); 1160 verifyFormat("if (a) g();\n" 1161 "else if (b) {\n" 1162 " g();\n" 1163 "} else {\n" 1164 " g();\n" 1165 "}", 1166 AllowsMergedIf); 1167 verifyFormat("if (a) {\n" 1168 " g();\n" 1169 "} else if (b) {\n" 1170 " g();\n" 1171 "} else {\n" 1172 " g();\n" 1173 "}", 1174 AllowsMergedIf); 1175 verifyFormat("MYIF (a) f();\n" 1176 "else {\n" 1177 " g();\n" 1178 "}", 1179 AllowsMergedIf); 1180 verifyFormat("MYIF (a) f();\n" 1181 "else {\n" 1182 " if (a) f();\n" 1183 " else {\n" 1184 " g();\n" 1185 " }\n" 1186 " g();\n" 1187 "}", 1188 AllowsMergedIf); 1189 1190 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1191 verifyFormat("MYIF (a) {\n" 1192 " g()\n" 1193 "};", 1194 AllowsMergedIf); 1195 verifyFormat("MYIF (a) g();\n" 1196 "else\n" 1197 " g();", 1198 AllowsMergedIf); 1199 verifyFormat("MYIF (a) {\n" 1200 " g();\n" 1201 "} else\n" 1202 " g();", 1203 AllowsMergedIf); 1204 verifyFormat("MYIF (a) g();\n" 1205 "else {\n" 1206 " g();\n" 1207 "}", 1208 AllowsMergedIf); 1209 verifyFormat("MYIF (a) {\n" 1210 " g();\n" 1211 "} else {\n" 1212 " g();\n" 1213 "}", 1214 AllowsMergedIf); 1215 verifyFormat("MYIF (a) g();\n" 1216 "else MYIF (b)\n" 1217 " g();\n" 1218 "else\n" 1219 " g();", 1220 AllowsMergedIf); 1221 verifyFormat("MYIF (a) g();\n" 1222 "else if (b)\n" 1223 " g();\n" 1224 "else\n" 1225 " g();", 1226 AllowsMergedIf); 1227 verifyFormat("MYIF (a) {\n" 1228 " g();\n" 1229 "} else MYIF (b)\n" 1230 " g();\n" 1231 "else\n" 1232 " g();", 1233 AllowsMergedIf); 1234 verifyFormat("MYIF (a) {\n" 1235 " g();\n" 1236 "} else if (b)\n" 1237 " g();\n" 1238 "else\n" 1239 " g();", 1240 AllowsMergedIf); 1241 verifyFormat("MYIF (a) g();\n" 1242 "else MYIF (b) {\n" 1243 " g();\n" 1244 "} else\n" 1245 " g();", 1246 AllowsMergedIf); 1247 verifyFormat("MYIF (a) g();\n" 1248 "else if (b) {\n" 1249 " g();\n" 1250 "} else\n" 1251 " g();", 1252 AllowsMergedIf); 1253 verifyFormat("MYIF (a) g();\n" 1254 "else MYIF (b)\n" 1255 " g();\n" 1256 "else {\n" 1257 " g();\n" 1258 "}", 1259 AllowsMergedIf); 1260 verifyFormat("MYIF (a) g();\n" 1261 "else if (b)\n" 1262 " g();\n" 1263 "else {\n" 1264 " g();\n" 1265 "}", 1266 AllowsMergedIf); 1267 verifyFormat("MYIF (a) g();\n" 1268 "else MYIF (b) {\n" 1269 " g();\n" 1270 "} else {\n" 1271 " g();\n" 1272 "}", 1273 AllowsMergedIf); 1274 verifyFormat("MYIF (a) g();\n" 1275 "else if (b) {\n" 1276 " g();\n" 1277 "} else {\n" 1278 " g();\n" 1279 "}", 1280 AllowsMergedIf); 1281 verifyFormat("MYIF (a) {\n" 1282 " g();\n" 1283 "} else MYIF (b) {\n" 1284 " g();\n" 1285 "} else {\n" 1286 " g();\n" 1287 "}", 1288 AllowsMergedIf); 1289 verifyFormat("MYIF (a) {\n" 1290 " g();\n" 1291 "} else if (b) {\n" 1292 " g();\n" 1293 "} else {\n" 1294 " g();\n" 1295 "}", 1296 AllowsMergedIf); 1297 1298 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1299 FormatStyle::SIS_AllIfsAndElse; 1300 1301 verifyFormat("if (a) f();\n" 1302 "else {\n" 1303 " g();\n" 1304 "}", 1305 AllowsMergedIf); 1306 verifyFormat("if (a) f();\n" 1307 "else {\n" 1308 " if (a) f();\n" 1309 " else {\n" 1310 " g();\n" 1311 " }\n" 1312 " g();\n" 1313 "}", 1314 AllowsMergedIf); 1315 1316 verifyFormat("if (a) g();", AllowsMergedIf); 1317 verifyFormat("if (a) {\n" 1318 " g()\n" 1319 "};", 1320 AllowsMergedIf); 1321 verifyFormat("if (a) g();\n" 1322 "else g();", 1323 AllowsMergedIf); 1324 verifyFormat("if (a) {\n" 1325 " g();\n" 1326 "} else g();", 1327 AllowsMergedIf); 1328 verifyFormat("if (a) g();\n" 1329 "else {\n" 1330 " g();\n" 1331 "}", 1332 AllowsMergedIf); 1333 verifyFormat("if (a) {\n" 1334 " g();\n" 1335 "} else {\n" 1336 " g();\n" 1337 "}", 1338 AllowsMergedIf); 1339 verifyFormat("if (a) g();\n" 1340 "else if (b) g();\n" 1341 "else g();", 1342 AllowsMergedIf); 1343 verifyFormat("if (a) {\n" 1344 " g();\n" 1345 "} else if (b) g();\n" 1346 "else g();", 1347 AllowsMergedIf); 1348 verifyFormat("if (a) g();\n" 1349 "else if (b) {\n" 1350 " g();\n" 1351 "} else g();", 1352 AllowsMergedIf); 1353 verifyFormat("if (a) g();\n" 1354 "else if (b) g();\n" 1355 "else {\n" 1356 " g();\n" 1357 "}", 1358 AllowsMergedIf); 1359 verifyFormat("if (a) g();\n" 1360 "else if (b) {\n" 1361 " g();\n" 1362 "} else {\n" 1363 " g();\n" 1364 "}", 1365 AllowsMergedIf); 1366 verifyFormat("if (a) {\n" 1367 " g();\n" 1368 "} else if (b) {\n" 1369 " g();\n" 1370 "} else {\n" 1371 " g();\n" 1372 "}", 1373 AllowsMergedIf); 1374 verifyFormat("MYIF (a) f();\n" 1375 "else {\n" 1376 " g();\n" 1377 "}", 1378 AllowsMergedIf); 1379 verifyFormat("MYIF (a) f();\n" 1380 "else {\n" 1381 " if (a) f();\n" 1382 " else {\n" 1383 " g();\n" 1384 " }\n" 1385 " g();\n" 1386 "}", 1387 AllowsMergedIf); 1388 1389 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1390 verifyFormat("MYIF (a) {\n" 1391 " g()\n" 1392 "};", 1393 AllowsMergedIf); 1394 verifyFormat("MYIF (a) g();\n" 1395 "else g();", 1396 AllowsMergedIf); 1397 verifyFormat("MYIF (a) {\n" 1398 " g();\n" 1399 "} else g();", 1400 AllowsMergedIf); 1401 verifyFormat("MYIF (a) g();\n" 1402 "else {\n" 1403 " g();\n" 1404 "}", 1405 AllowsMergedIf); 1406 verifyFormat("MYIF (a) {\n" 1407 " g();\n" 1408 "} else {\n" 1409 " g();\n" 1410 "}", 1411 AllowsMergedIf); 1412 verifyFormat("MYIF (a) g();\n" 1413 "else MYIF (b) g();\n" 1414 "else g();", 1415 AllowsMergedIf); 1416 verifyFormat("MYIF (a) g();\n" 1417 "else if (b) g();\n" 1418 "else g();", 1419 AllowsMergedIf); 1420 verifyFormat("MYIF (a) {\n" 1421 " g();\n" 1422 "} else MYIF (b) g();\n" 1423 "else g();", 1424 AllowsMergedIf); 1425 verifyFormat("MYIF (a) {\n" 1426 " g();\n" 1427 "} else if (b) g();\n" 1428 "else g();", 1429 AllowsMergedIf); 1430 verifyFormat("MYIF (a) g();\n" 1431 "else MYIF (b) {\n" 1432 " g();\n" 1433 "} else g();", 1434 AllowsMergedIf); 1435 verifyFormat("MYIF (a) g();\n" 1436 "else if (b) {\n" 1437 " g();\n" 1438 "} else g();", 1439 AllowsMergedIf); 1440 verifyFormat("MYIF (a) g();\n" 1441 "else MYIF (b) g();\n" 1442 "else {\n" 1443 " g();\n" 1444 "}", 1445 AllowsMergedIf); 1446 verifyFormat("MYIF (a) g();\n" 1447 "else if (b) g();\n" 1448 "else {\n" 1449 " g();\n" 1450 "}", 1451 AllowsMergedIf); 1452 verifyFormat("MYIF (a) g();\n" 1453 "else MYIF (b) {\n" 1454 " g();\n" 1455 "} else {\n" 1456 " g();\n" 1457 "}", 1458 AllowsMergedIf); 1459 verifyFormat("MYIF (a) g();\n" 1460 "else if (b) {\n" 1461 " g();\n" 1462 "} else {\n" 1463 " g();\n" 1464 "}", 1465 AllowsMergedIf); 1466 verifyFormat("MYIF (a) {\n" 1467 " g();\n" 1468 "} else MYIF (b) {\n" 1469 " g();\n" 1470 "} else {\n" 1471 " g();\n" 1472 "}", 1473 AllowsMergedIf); 1474 verifyFormat("MYIF (a) {\n" 1475 " g();\n" 1476 "} else if (b) {\n" 1477 " g();\n" 1478 "} else {\n" 1479 " g();\n" 1480 "}", 1481 AllowsMergedIf); 1482 } 1483 1484 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 1485 FormatStyle AllowsMergedLoops = getLLVMStyle(); 1486 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 1487 verifyFormat("while (true) continue;", AllowsMergedLoops); 1488 verifyFormat("for (;;) continue;", AllowsMergedLoops); 1489 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 1490 verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops); 1491 verifyFormat("while (true)\n" 1492 " ;", 1493 AllowsMergedLoops); 1494 verifyFormat("for (;;)\n" 1495 " ;", 1496 AllowsMergedLoops); 1497 verifyFormat("for (;;)\n" 1498 " for (;;) continue;", 1499 AllowsMergedLoops); 1500 verifyFormat("for (;;)\n" 1501 " while (true) continue;", 1502 AllowsMergedLoops); 1503 verifyFormat("while (true)\n" 1504 " for (;;) continue;", 1505 AllowsMergedLoops); 1506 verifyFormat("BOOST_FOREACH (int &v, vec)\n" 1507 " for (;;) continue;", 1508 AllowsMergedLoops); 1509 verifyFormat("for (;;)\n" 1510 " BOOST_FOREACH (int &v, vec) continue;", 1511 AllowsMergedLoops); 1512 verifyFormat("for (;;) // Can't merge this\n" 1513 " continue;", 1514 AllowsMergedLoops); 1515 verifyFormat("for (;;) /* still don't merge */\n" 1516 " continue;", 1517 AllowsMergedLoops); 1518 verifyFormat("do a++;\n" 1519 "while (true);", 1520 AllowsMergedLoops); 1521 verifyFormat("do /* Don't merge */\n" 1522 " a++;\n" 1523 "while (true);", 1524 AllowsMergedLoops); 1525 verifyFormat("do // Don't merge\n" 1526 " a++;\n" 1527 "while (true);", 1528 AllowsMergedLoops); 1529 verifyFormat("do\n" 1530 " // Don't merge\n" 1531 " a++;\n" 1532 "while (true);", 1533 AllowsMergedLoops); 1534 // Without braces labels are interpreted differently. 1535 verifyFormat("{\n" 1536 " do\n" 1537 " label:\n" 1538 " a++;\n" 1539 " while (true);\n" 1540 "}", 1541 AllowsMergedLoops); 1542 } 1543 1544 TEST_F(FormatTest, FormatShortBracedStatements) { 1545 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1546 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false); 1547 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine, 1548 FormatStyle::SIS_Never); 1549 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false); 1550 EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false); 1551 verifyFormat("for (;;) {\n" 1552 " f();\n" 1553 "}"); 1554 verifyFormat("/*comment*/ for (;;) {\n" 1555 " f();\n" 1556 "}"); 1557 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1558 " f();\n" 1559 "}"); 1560 verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n" 1561 " f();\n" 1562 "}"); 1563 verifyFormat("while (true) {\n" 1564 " f();\n" 1565 "}"); 1566 verifyFormat("/*comment*/ while (true) {\n" 1567 " f();\n" 1568 "}"); 1569 verifyFormat("if (true) {\n" 1570 " f();\n" 1571 "}"); 1572 verifyFormat("/*comment*/ if (true) {\n" 1573 " f();\n" 1574 "}"); 1575 1576 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1577 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1578 // Not IF to avoid any confusion that IF is somehow special. 1579 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1580 AllowSimpleBracedStatements.ColumnLimit = 40; 1581 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1582 FormatStyle::SBS_Always; 1583 1584 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1585 FormatStyle::SIS_WithoutElse; 1586 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1587 1588 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1589 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1590 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1591 1592 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1593 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1594 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1595 verifyFormat("if consteval {}", AllowSimpleBracedStatements); 1596 verifyFormat("if !consteval {}", AllowSimpleBracedStatements); 1597 verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements); 1598 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1599 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1600 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1601 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1602 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1603 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1604 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1605 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1606 verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements); 1607 verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1608 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1609 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1610 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1611 verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements); 1612 verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1613 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1614 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1615 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1616 AllowSimpleBracedStatements); 1617 verifyFormat("if (true) {\n" 1618 " ffffffffffffffffffffffff();\n" 1619 "}", 1620 AllowSimpleBracedStatements); 1621 verifyFormat("if (true) {\n" 1622 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1623 "}", 1624 AllowSimpleBracedStatements); 1625 verifyFormat("if (true) { //\n" 1626 " f();\n" 1627 "}", 1628 AllowSimpleBracedStatements); 1629 verifyFormat("if (true) {\n" 1630 " f();\n" 1631 " f();\n" 1632 "}", 1633 AllowSimpleBracedStatements); 1634 verifyFormat("if (true) {\n" 1635 " f();\n" 1636 "} else {\n" 1637 " f();\n" 1638 "}", 1639 AllowSimpleBracedStatements); 1640 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1641 AllowSimpleBracedStatements); 1642 verifyFormat("MYIF (true) {\n" 1643 " ffffffffffffffffffffffff();\n" 1644 "}", 1645 AllowSimpleBracedStatements); 1646 verifyFormat("MYIF (true) {\n" 1647 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1648 "}", 1649 AllowSimpleBracedStatements); 1650 verifyFormat("MYIF (true) { //\n" 1651 " f();\n" 1652 "}", 1653 AllowSimpleBracedStatements); 1654 verifyFormat("MYIF (true) {\n" 1655 " f();\n" 1656 " f();\n" 1657 "}", 1658 AllowSimpleBracedStatements); 1659 verifyFormat("MYIF (true) {\n" 1660 " f();\n" 1661 "} else {\n" 1662 " f();\n" 1663 "}", 1664 AllowSimpleBracedStatements); 1665 1666 verifyFormat("struct A2 {\n" 1667 " int X;\n" 1668 "};", 1669 AllowSimpleBracedStatements); 1670 verifyFormat("typedef struct A2 {\n" 1671 " int X;\n" 1672 "} A2_t;", 1673 AllowSimpleBracedStatements); 1674 verifyFormat("template <int> struct A2 {\n" 1675 " struct B {};\n" 1676 "};", 1677 AllowSimpleBracedStatements); 1678 1679 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1680 FormatStyle::SIS_Never; 1681 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1682 verifyFormat("if (true) {\n" 1683 " f();\n" 1684 "}", 1685 AllowSimpleBracedStatements); 1686 verifyFormat("if (true) {\n" 1687 " f();\n" 1688 "} else {\n" 1689 " f();\n" 1690 "}", 1691 AllowSimpleBracedStatements); 1692 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1693 verifyFormat("MYIF (true) {\n" 1694 " f();\n" 1695 "}", 1696 AllowSimpleBracedStatements); 1697 verifyFormat("MYIF (true) {\n" 1698 " f();\n" 1699 "} else {\n" 1700 " f();\n" 1701 "}", 1702 AllowSimpleBracedStatements); 1703 1704 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1705 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1706 verifyFormat("while (true) {\n" 1707 " f();\n" 1708 "}", 1709 AllowSimpleBracedStatements); 1710 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1711 verifyFormat("for (;;) {\n" 1712 " f();\n" 1713 "}", 1714 AllowSimpleBracedStatements); 1715 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1716 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1717 " f();\n" 1718 "}", 1719 AllowSimpleBracedStatements); 1720 1721 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1722 FormatStyle::SIS_WithoutElse; 1723 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1724 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1725 FormatStyle::BWACS_Always; 1726 1727 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1728 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1729 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1730 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1731 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1732 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1733 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1734 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1735 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1736 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1737 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1738 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1739 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1740 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1741 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1742 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1743 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1744 AllowSimpleBracedStatements); 1745 verifyFormat("if (true)\n" 1746 "{\n" 1747 " ffffffffffffffffffffffff();\n" 1748 "}", 1749 AllowSimpleBracedStatements); 1750 verifyFormat("if (true)\n" 1751 "{\n" 1752 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1753 "}", 1754 AllowSimpleBracedStatements); 1755 verifyFormat("if (true)\n" 1756 "{ //\n" 1757 " f();\n" 1758 "}", 1759 AllowSimpleBracedStatements); 1760 verifyFormat("if (true)\n" 1761 "{\n" 1762 " f();\n" 1763 " f();\n" 1764 "}", 1765 AllowSimpleBracedStatements); 1766 verifyFormat("if (true)\n" 1767 "{\n" 1768 " f();\n" 1769 "} else\n" 1770 "{\n" 1771 " f();\n" 1772 "}", 1773 AllowSimpleBracedStatements); 1774 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1775 AllowSimpleBracedStatements); 1776 verifyFormat("MYIF (true)\n" 1777 "{\n" 1778 " ffffffffffffffffffffffff();\n" 1779 "}", 1780 AllowSimpleBracedStatements); 1781 verifyFormat("MYIF (true)\n" 1782 "{\n" 1783 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1784 "}", 1785 AllowSimpleBracedStatements); 1786 verifyFormat("MYIF (true)\n" 1787 "{ //\n" 1788 " f();\n" 1789 "}", 1790 AllowSimpleBracedStatements); 1791 verifyFormat("MYIF (true)\n" 1792 "{\n" 1793 " f();\n" 1794 " f();\n" 1795 "}", 1796 AllowSimpleBracedStatements); 1797 verifyFormat("MYIF (true)\n" 1798 "{\n" 1799 " f();\n" 1800 "} else\n" 1801 "{\n" 1802 " f();\n" 1803 "}", 1804 AllowSimpleBracedStatements); 1805 1806 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1807 FormatStyle::SIS_Never; 1808 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1809 verifyFormat("if (true)\n" 1810 "{\n" 1811 " f();\n" 1812 "}", 1813 AllowSimpleBracedStatements); 1814 verifyFormat("if (true)\n" 1815 "{\n" 1816 " f();\n" 1817 "} else\n" 1818 "{\n" 1819 " f();\n" 1820 "}", 1821 AllowSimpleBracedStatements); 1822 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1823 verifyFormat("MYIF (true)\n" 1824 "{\n" 1825 " f();\n" 1826 "}", 1827 AllowSimpleBracedStatements); 1828 verifyFormat("MYIF (true)\n" 1829 "{\n" 1830 " f();\n" 1831 "} else\n" 1832 "{\n" 1833 " f();\n" 1834 "}", 1835 AllowSimpleBracedStatements); 1836 1837 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1838 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1839 verifyFormat("while (true)\n" 1840 "{\n" 1841 " f();\n" 1842 "}", 1843 AllowSimpleBracedStatements); 1844 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1845 verifyFormat("for (;;)\n" 1846 "{\n" 1847 " f();\n" 1848 "}", 1849 AllowSimpleBracedStatements); 1850 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1851 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1852 "{\n" 1853 " f();\n" 1854 "}", 1855 AllowSimpleBracedStatements); 1856 } 1857 1858 TEST_F(FormatTest, UnderstandsMacros) { 1859 verifyFormat("#define A (parentheses)"); 1860 verifyFormat("/* comment */ #define A (parentheses)"); 1861 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1862 // Even the partial code should never be merged. 1863 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1864 "#", 1865 format("/* comment */ #define A (parentheses)\n" 1866 "#")); 1867 verifyFormat("/* comment */ #define A (parentheses)\n" 1868 "#\n"); 1869 verifyFormat("/* comment */ #define A (parentheses)\n" 1870 "#define B (parentheses)"); 1871 verifyFormat("#define true ((int)1)"); 1872 verifyFormat("#define and(x)"); 1873 verifyFormat("#define if(x) x"); 1874 verifyFormat("#define return(x) (x)"); 1875 verifyFormat("#define while(x) for (; x;)"); 1876 verifyFormat("#define xor(x) (^(x))"); 1877 verifyFormat("#define __except(x)"); 1878 verifyFormat("#define __try(x)"); 1879 1880 // https://llvm.org/PR54348. 1881 verifyFormat( 1882 "#define A" 1883 " " 1884 "\\\n" 1885 " class & {}"); 1886 1887 FormatStyle Style = getLLVMStyle(); 1888 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1889 Style.BraceWrapping.AfterFunction = true; 1890 // Test that a macro definition never gets merged with the following 1891 // definition. 1892 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1893 verifyFormat("#define AAA " 1894 " \\\n" 1895 " N " 1896 " \\\n" 1897 " {\n" 1898 "#define BBB }\n", 1899 Style); 1900 // verifyFormat("#define AAA N { //\n", Style); 1901 1902 verifyFormat("MACRO(return)"); 1903 verifyFormat("MACRO(co_await)"); 1904 verifyFormat("MACRO(co_return)"); 1905 verifyFormat("MACRO(co_yield)"); 1906 verifyFormat("MACRO(return, something)"); 1907 verifyFormat("MACRO(co_return, something)"); 1908 verifyFormat("MACRO(something##something)"); 1909 verifyFormat("MACRO(return##something)"); 1910 verifyFormat("MACRO(co_return##something)"); 1911 } 1912 1913 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1914 FormatStyle Style = getLLVMStyleWithColumns(60); 1915 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1916 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1917 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1918 EXPECT_EQ("#define A \\\n" 1919 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1920 " { \\\n" 1921 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1922 " }\n" 1923 "X;", 1924 format("#define A \\\n" 1925 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1926 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1927 " }\n" 1928 "X;", 1929 Style)); 1930 } 1931 1932 TEST_F(FormatTest, ParseIfElse) { 1933 verifyFormat("if (true)\n" 1934 " if (true)\n" 1935 " if (true)\n" 1936 " f();\n" 1937 " else\n" 1938 " g();\n" 1939 " else\n" 1940 " h();\n" 1941 "else\n" 1942 " i();"); 1943 verifyFormat("if (true)\n" 1944 " if (true)\n" 1945 " if (true) {\n" 1946 " if (true)\n" 1947 " f();\n" 1948 " } else {\n" 1949 " g();\n" 1950 " }\n" 1951 " else\n" 1952 " h();\n" 1953 "else {\n" 1954 " i();\n" 1955 "}"); 1956 verifyFormat("if (true)\n" 1957 " if constexpr (true)\n" 1958 " if (true) {\n" 1959 " if constexpr (true)\n" 1960 " f();\n" 1961 " } else {\n" 1962 " g();\n" 1963 " }\n" 1964 " else\n" 1965 " h();\n" 1966 "else {\n" 1967 " i();\n" 1968 "}"); 1969 verifyFormat("if (true)\n" 1970 " if CONSTEXPR (true)\n" 1971 " if (true) {\n" 1972 " if CONSTEXPR (true)\n" 1973 " f();\n" 1974 " } else {\n" 1975 " g();\n" 1976 " }\n" 1977 " else\n" 1978 " h();\n" 1979 "else {\n" 1980 " i();\n" 1981 "}"); 1982 verifyFormat("void f() {\n" 1983 " if (a) {\n" 1984 " } else {\n" 1985 " }\n" 1986 "}"); 1987 } 1988 1989 TEST_F(FormatTest, ElseIf) { 1990 verifyFormat("if (a) {\n} else if (b) {\n}"); 1991 verifyFormat("if (a)\n" 1992 " f();\n" 1993 "else if (b)\n" 1994 " g();\n" 1995 "else\n" 1996 " h();"); 1997 verifyFormat("if (a)\n" 1998 " f();\n" 1999 "else // comment\n" 2000 " if (b) {\n" 2001 " g();\n" 2002 " h();\n" 2003 " }"); 2004 verifyFormat("if constexpr (a)\n" 2005 " f();\n" 2006 "else if constexpr (b)\n" 2007 " g();\n" 2008 "else\n" 2009 " h();"); 2010 verifyFormat("if CONSTEXPR (a)\n" 2011 " f();\n" 2012 "else if CONSTEXPR (b)\n" 2013 " g();\n" 2014 "else\n" 2015 " h();"); 2016 verifyFormat("if (a) {\n" 2017 " f();\n" 2018 "}\n" 2019 "// or else ..\n" 2020 "else {\n" 2021 " g()\n" 2022 "}"); 2023 2024 verifyFormat("if (a) {\n" 2025 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2026 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2027 "}"); 2028 verifyFormat("if (a) {\n" 2029 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2030 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2031 "}"); 2032 verifyFormat("if (a) {\n" 2033 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2034 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2035 "}"); 2036 verifyFormat("if (a) {\n" 2037 "} else if (\n" 2038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2039 "}", 2040 getLLVMStyleWithColumns(62)); 2041 verifyFormat("if (a) {\n" 2042 "} else if constexpr (\n" 2043 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2044 "}", 2045 getLLVMStyleWithColumns(62)); 2046 verifyFormat("if (a) {\n" 2047 "} else if CONSTEXPR (\n" 2048 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2049 "}", 2050 getLLVMStyleWithColumns(62)); 2051 } 2052 2053 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2054 FormatStyle Style = getLLVMStyle(); 2055 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2056 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2057 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2058 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2059 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2060 verifyFormat("int *f1(int &a) const &;", Style); 2061 verifyFormat("int *f1(int &a) const & = 0;", Style); 2062 verifyFormat("int *a = f1();", Style); 2063 verifyFormat("int &b = f2();", Style); 2064 verifyFormat("int &&c = f3();", Style); 2065 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2066 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2067 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2068 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2069 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2070 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2071 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2072 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2073 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2074 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2075 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2076 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2077 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2078 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2079 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2080 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2081 verifyFormat( 2082 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2083 " res2 = [](int &a) { return 0000000000000; };", 2084 Style); 2085 2086 Style.AlignConsecutiveDeclarations.Enabled = true; 2087 verifyFormat("Const unsigned int *c;\n" 2088 "const unsigned int *d;\n" 2089 "Const unsigned int &e;\n" 2090 "const unsigned int &f;\n" 2091 "const unsigned &&g;\n" 2092 "Const unsigned h;", 2093 Style); 2094 2095 Style.PointerAlignment = FormatStyle::PAS_Left; 2096 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2097 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2098 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2099 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2100 verifyFormat("int* f1(int& a) const& = 0;", Style); 2101 verifyFormat("int* a = f1();", Style); 2102 verifyFormat("int& b = f2();", Style); 2103 verifyFormat("int&& c = f3();", Style); 2104 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2105 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2106 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2107 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2108 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2109 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2110 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2111 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2112 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2113 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2114 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2115 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2116 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2117 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2118 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2119 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2120 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2121 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2122 verifyFormat( 2123 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2124 " res2 = [](int& a) { return 0000000000000; };", 2125 Style); 2126 2127 Style.AlignConsecutiveDeclarations.Enabled = true; 2128 verifyFormat("Const unsigned int* c;\n" 2129 "const unsigned int* d;\n" 2130 "Const unsigned int& e;\n" 2131 "const unsigned int& f;\n" 2132 "const unsigned&& g;\n" 2133 "Const unsigned h;", 2134 Style); 2135 2136 Style.PointerAlignment = FormatStyle::PAS_Right; 2137 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2138 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2139 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2140 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2141 verifyFormat("int *a = f1();", Style); 2142 verifyFormat("int& b = f2();", Style); 2143 verifyFormat("int&& c = f3();", Style); 2144 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2145 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2146 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2147 2148 Style.AlignConsecutiveDeclarations.Enabled = true; 2149 verifyFormat("Const unsigned int *c;\n" 2150 "const unsigned int *d;\n" 2151 "Const unsigned int& e;\n" 2152 "const unsigned int& f;\n" 2153 "const unsigned g;\n" 2154 "Const unsigned h;", 2155 Style); 2156 2157 Style.PointerAlignment = FormatStyle::PAS_Left; 2158 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2159 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2160 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2161 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2162 verifyFormat("int* a = f1();", Style); 2163 verifyFormat("int & b = f2();", Style); 2164 verifyFormat("int && c = f3();", Style); 2165 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2166 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2167 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2168 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2169 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2170 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2171 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2172 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2173 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2174 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2175 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2176 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2177 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2178 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2179 verifyFormat( 2180 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2181 " res2 = [](int & a) { return 0000000000000; };", 2182 Style); 2183 2184 Style.AlignConsecutiveDeclarations.Enabled = true; 2185 verifyFormat("Const unsigned int* c;\n" 2186 "const unsigned int* d;\n" 2187 "Const unsigned int & e;\n" 2188 "const unsigned int & f;\n" 2189 "const unsigned && g;\n" 2190 "Const unsigned h;", 2191 Style); 2192 2193 Style.PointerAlignment = FormatStyle::PAS_Middle; 2194 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2195 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2196 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2197 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2198 verifyFormat("int * a = f1();", Style); 2199 verifyFormat("int &b = f2();", Style); 2200 verifyFormat("int &&c = f3();", Style); 2201 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2202 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2203 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2204 2205 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2206 // specifically handled 2207 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2208 } 2209 2210 TEST_F(FormatTest, FormatsForLoop) { 2211 verifyFormat( 2212 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2213 " ++VeryVeryLongLoopVariable)\n" 2214 " ;"); 2215 verifyFormat("for (;;)\n" 2216 " f();"); 2217 verifyFormat("for (;;) {\n}"); 2218 verifyFormat("for (;;) {\n" 2219 " f();\n" 2220 "}"); 2221 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2222 2223 verifyFormat( 2224 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2225 " E = UnwrappedLines.end();\n" 2226 " I != E; ++I) {\n}"); 2227 2228 verifyFormat( 2229 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2230 " ++IIIII) {\n}"); 2231 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2232 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2233 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2234 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2235 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2236 " E = FD->getDeclsInPrototypeScope().end();\n" 2237 " I != E; ++I) {\n}"); 2238 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2239 " I = Container.begin(),\n" 2240 " E = Container.end();\n" 2241 " I != E; ++I) {\n}", 2242 getLLVMStyleWithColumns(76)); 2243 2244 verifyFormat( 2245 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2246 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2247 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2248 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2249 " ++aaaaaaaaaaa) {\n}"); 2250 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2251 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2252 " ++i) {\n}"); 2253 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2254 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2255 "}"); 2256 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2257 " aaaaaaaaaa);\n" 2258 " iter; ++iter) {\n" 2259 "}"); 2260 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2261 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2262 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2263 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2264 2265 // These should not be formatted as Objective-C for-in loops. 2266 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2267 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2268 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2269 verifyFormat( 2270 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2271 2272 FormatStyle NoBinPacking = getLLVMStyle(); 2273 NoBinPacking.BinPackParameters = false; 2274 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2275 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2276 " aaaaaaaaaaaaaaaa,\n" 2277 " aaaaaaaaaaaaaaaa,\n" 2278 " aaaaaaaaaaaaaaaa);\n" 2279 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2280 "}", 2281 NoBinPacking); 2282 verifyFormat( 2283 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2284 " E = UnwrappedLines.end();\n" 2285 " I != E;\n" 2286 " ++I) {\n}", 2287 NoBinPacking); 2288 2289 FormatStyle AlignLeft = getLLVMStyle(); 2290 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2291 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2292 } 2293 2294 TEST_F(FormatTest, RangeBasedForLoops) { 2295 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2296 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2297 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2298 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2299 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2300 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2301 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2302 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2303 } 2304 2305 TEST_F(FormatTest, ForEachLoops) { 2306 FormatStyle Style = getLLVMStyle(); 2307 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2308 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2309 verifyFormat("void f() {\n" 2310 " for (;;) {\n" 2311 " }\n" 2312 " foreach (Item *item, itemlist) {\n" 2313 " }\n" 2314 " Q_FOREACH (Item *item, itemlist) {\n" 2315 " }\n" 2316 " BOOST_FOREACH (Item *item, itemlist) {\n" 2317 " }\n" 2318 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2319 "}", 2320 Style); 2321 verifyFormat("void f() {\n" 2322 " for (;;)\n" 2323 " int j = 1;\n" 2324 " Q_FOREACH (int v, vec)\n" 2325 " v *= 2;\n" 2326 " for (;;) {\n" 2327 " int j = 1;\n" 2328 " }\n" 2329 " Q_FOREACH (int v, vec) {\n" 2330 " v *= 2;\n" 2331 " }\n" 2332 "}", 2333 Style); 2334 2335 FormatStyle ShortBlocks = getLLVMStyle(); 2336 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2337 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2338 verifyFormat("void f() {\n" 2339 " for (;;)\n" 2340 " int j = 1;\n" 2341 " Q_FOREACH (int &v, vec)\n" 2342 " v *= 2;\n" 2343 " for (;;) {\n" 2344 " int j = 1;\n" 2345 " }\n" 2346 " Q_FOREACH (int &v, vec) {\n" 2347 " int j = 1;\n" 2348 " }\n" 2349 "}", 2350 ShortBlocks); 2351 2352 FormatStyle ShortLoops = getLLVMStyle(); 2353 ShortLoops.AllowShortLoopsOnASingleLine = true; 2354 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2355 verifyFormat("void f() {\n" 2356 " for (;;) int j = 1;\n" 2357 " Q_FOREACH (int &v, vec) int j = 1;\n" 2358 " for (;;) {\n" 2359 " int j = 1;\n" 2360 " }\n" 2361 " Q_FOREACH (int &v, vec) {\n" 2362 " int j = 1;\n" 2363 " }\n" 2364 "}", 2365 ShortLoops); 2366 2367 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2368 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2369 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2370 verifyFormat("void f() {\n" 2371 " for (;;) int j = 1;\n" 2372 " Q_FOREACH (int &v, vec) int j = 1;\n" 2373 " for (;;) { int j = 1; }\n" 2374 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2375 "}", 2376 ShortBlocksAndLoops); 2377 2378 Style.SpaceBeforeParens = 2379 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2380 verifyFormat("void f() {\n" 2381 " for (;;) {\n" 2382 " }\n" 2383 " foreach(Item *item, itemlist) {\n" 2384 " }\n" 2385 " Q_FOREACH(Item *item, itemlist) {\n" 2386 " }\n" 2387 " BOOST_FOREACH(Item *item, itemlist) {\n" 2388 " }\n" 2389 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2390 "}", 2391 Style); 2392 2393 // As function-like macros. 2394 verifyFormat("#define foreach(x, y)\n" 2395 "#define Q_FOREACH(x, y)\n" 2396 "#define BOOST_FOREACH(x, y)\n" 2397 "#define UNKNOWN_FOREACH(x, y)\n"); 2398 2399 // Not as function-like macros. 2400 verifyFormat("#define foreach (x, y)\n" 2401 "#define Q_FOREACH (x, y)\n" 2402 "#define BOOST_FOREACH (x, y)\n" 2403 "#define UNKNOWN_FOREACH (x, y)\n"); 2404 2405 // handle microsoft non standard extension 2406 verifyFormat("for each (char c in x->MyStringProperty)"); 2407 } 2408 2409 TEST_F(FormatTest, FormatsWhileLoop) { 2410 verifyFormat("while (true) {\n}"); 2411 verifyFormat("while (true)\n" 2412 " f();"); 2413 verifyFormat("while () {\n}"); 2414 verifyFormat("while () {\n" 2415 " f();\n" 2416 "}"); 2417 } 2418 2419 TEST_F(FormatTest, FormatsDoWhile) { 2420 verifyFormat("do {\n" 2421 " do_something();\n" 2422 "} while (something());"); 2423 verifyFormat("do\n" 2424 " do_something();\n" 2425 "while (something());"); 2426 } 2427 2428 TEST_F(FormatTest, FormatsSwitchStatement) { 2429 verifyFormat("switch (x) {\n" 2430 "case 1:\n" 2431 " f();\n" 2432 " break;\n" 2433 "case kFoo:\n" 2434 "case ns::kBar:\n" 2435 "case kBaz:\n" 2436 " break;\n" 2437 "default:\n" 2438 " g();\n" 2439 " break;\n" 2440 "}"); 2441 verifyFormat("switch (x) {\n" 2442 "case 1: {\n" 2443 " f();\n" 2444 " break;\n" 2445 "}\n" 2446 "case 2: {\n" 2447 " break;\n" 2448 "}\n" 2449 "}"); 2450 verifyFormat("switch (x) {\n" 2451 "case 1: {\n" 2452 " f();\n" 2453 " {\n" 2454 " g();\n" 2455 " h();\n" 2456 " }\n" 2457 " break;\n" 2458 "}\n" 2459 "}"); 2460 verifyFormat("switch (x) {\n" 2461 "case 1: {\n" 2462 " f();\n" 2463 " if (foo) {\n" 2464 " g();\n" 2465 " h();\n" 2466 " }\n" 2467 " break;\n" 2468 "}\n" 2469 "}"); 2470 verifyFormat("switch (x) {\n" 2471 "case 1: {\n" 2472 " f();\n" 2473 " g();\n" 2474 "} break;\n" 2475 "}"); 2476 verifyFormat("switch (test)\n" 2477 " ;"); 2478 verifyFormat("switch (x) {\n" 2479 "default: {\n" 2480 " // Do nothing.\n" 2481 "}\n" 2482 "}"); 2483 verifyFormat("switch (x) {\n" 2484 "// comment\n" 2485 "// if 1, do f()\n" 2486 "case 1:\n" 2487 " f();\n" 2488 "}"); 2489 verifyFormat("switch (x) {\n" 2490 "case 1:\n" 2491 " // Do amazing stuff\n" 2492 " {\n" 2493 " f();\n" 2494 " g();\n" 2495 " }\n" 2496 " break;\n" 2497 "}"); 2498 verifyFormat("#define A \\\n" 2499 " switch (x) { \\\n" 2500 " case a: \\\n" 2501 " foo = b; \\\n" 2502 " }", 2503 getLLVMStyleWithColumns(20)); 2504 verifyFormat("#define OPERATION_CASE(name) \\\n" 2505 " case OP_name: \\\n" 2506 " return operations::Operation##name\n", 2507 getLLVMStyleWithColumns(40)); 2508 verifyFormat("switch (x) {\n" 2509 "case 1:;\n" 2510 "default:;\n" 2511 " int i;\n" 2512 "}"); 2513 2514 verifyGoogleFormat("switch (x) {\n" 2515 " case 1:\n" 2516 " f();\n" 2517 " break;\n" 2518 " case kFoo:\n" 2519 " case ns::kBar:\n" 2520 " case kBaz:\n" 2521 " break;\n" 2522 " default:\n" 2523 " g();\n" 2524 " break;\n" 2525 "}"); 2526 verifyGoogleFormat("switch (x) {\n" 2527 " case 1: {\n" 2528 " f();\n" 2529 " break;\n" 2530 " }\n" 2531 "}"); 2532 verifyGoogleFormat("switch (test)\n" 2533 " ;"); 2534 2535 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2536 " case OP_name: \\\n" 2537 " return operations::Operation##name\n"); 2538 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2539 " // Get the correction operation class.\n" 2540 " switch (OpCode) {\n" 2541 " CASE(Add);\n" 2542 " CASE(Subtract);\n" 2543 " default:\n" 2544 " return operations::Unknown;\n" 2545 " }\n" 2546 "#undef OPERATION_CASE\n" 2547 "}"); 2548 verifyFormat("DEBUG({\n" 2549 " switch (x) {\n" 2550 " case A:\n" 2551 " f();\n" 2552 " break;\n" 2553 " // fallthrough\n" 2554 " case B:\n" 2555 " g();\n" 2556 " break;\n" 2557 " }\n" 2558 "});"); 2559 EXPECT_EQ("DEBUG({\n" 2560 " switch (x) {\n" 2561 " case A:\n" 2562 " f();\n" 2563 " break;\n" 2564 " // On B:\n" 2565 " case B:\n" 2566 " g();\n" 2567 " break;\n" 2568 " }\n" 2569 "});", 2570 format("DEBUG({\n" 2571 " switch (x) {\n" 2572 " case A:\n" 2573 " f();\n" 2574 " break;\n" 2575 " // On B:\n" 2576 " case B:\n" 2577 " g();\n" 2578 " break;\n" 2579 " }\n" 2580 "});", 2581 getLLVMStyle())); 2582 EXPECT_EQ("switch (n) {\n" 2583 "case 0: {\n" 2584 " return false;\n" 2585 "}\n" 2586 "default: {\n" 2587 " return true;\n" 2588 "}\n" 2589 "}", 2590 format("switch (n)\n" 2591 "{\n" 2592 "case 0: {\n" 2593 " return false;\n" 2594 "}\n" 2595 "default: {\n" 2596 " return true;\n" 2597 "}\n" 2598 "}", 2599 getLLVMStyle())); 2600 verifyFormat("switch (a) {\n" 2601 "case (b):\n" 2602 " return;\n" 2603 "}"); 2604 2605 verifyFormat("switch (a) {\n" 2606 "case some_namespace::\n" 2607 " some_constant:\n" 2608 " return;\n" 2609 "}", 2610 getLLVMStyleWithColumns(34)); 2611 2612 verifyFormat("switch (a) {\n" 2613 "[[likely]] case 1:\n" 2614 " return;\n" 2615 "}"); 2616 verifyFormat("switch (a) {\n" 2617 "[[likely]] [[other::likely]] case 1:\n" 2618 " return;\n" 2619 "}"); 2620 verifyFormat("switch (x) {\n" 2621 "case 1:\n" 2622 " return;\n" 2623 "[[likely]] case 2:\n" 2624 " return;\n" 2625 "}"); 2626 verifyFormat("switch (a) {\n" 2627 "case 1:\n" 2628 "[[likely]] case 2:\n" 2629 " return;\n" 2630 "}"); 2631 FormatStyle Attributes = getLLVMStyle(); 2632 Attributes.AttributeMacros.push_back("LIKELY"); 2633 Attributes.AttributeMacros.push_back("OTHER_LIKELY"); 2634 verifyFormat("switch (a) {\n" 2635 "LIKELY case b:\n" 2636 " return;\n" 2637 "}", 2638 Attributes); 2639 verifyFormat("switch (a) {\n" 2640 "LIKELY OTHER_LIKELY() case b:\n" 2641 " return;\n" 2642 "}", 2643 Attributes); 2644 verifyFormat("switch (a) {\n" 2645 "case 1:\n" 2646 " return;\n" 2647 "LIKELY case 2:\n" 2648 " return;\n" 2649 "}", 2650 Attributes); 2651 verifyFormat("switch (a) {\n" 2652 "case 1:\n" 2653 "LIKELY case 2:\n" 2654 " return;\n" 2655 "}", 2656 Attributes); 2657 2658 FormatStyle Style = getLLVMStyle(); 2659 Style.IndentCaseLabels = true; 2660 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2661 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2662 Style.BraceWrapping.AfterCaseLabel = true; 2663 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2664 EXPECT_EQ("switch (n)\n" 2665 "{\n" 2666 " case 0:\n" 2667 " {\n" 2668 " return false;\n" 2669 " }\n" 2670 " default:\n" 2671 " {\n" 2672 " return true;\n" 2673 " }\n" 2674 "}", 2675 format("switch (n) {\n" 2676 " case 0: {\n" 2677 " return false;\n" 2678 " }\n" 2679 " default: {\n" 2680 " return true;\n" 2681 " }\n" 2682 "}", 2683 Style)); 2684 Style.BraceWrapping.AfterCaseLabel = false; 2685 EXPECT_EQ("switch (n)\n" 2686 "{\n" 2687 " case 0: {\n" 2688 " return false;\n" 2689 " }\n" 2690 " default: {\n" 2691 " return true;\n" 2692 " }\n" 2693 "}", 2694 format("switch (n) {\n" 2695 " case 0:\n" 2696 " {\n" 2697 " return false;\n" 2698 " }\n" 2699 " default:\n" 2700 " {\n" 2701 " return true;\n" 2702 " }\n" 2703 "}", 2704 Style)); 2705 Style.IndentCaseLabels = false; 2706 Style.IndentCaseBlocks = true; 2707 EXPECT_EQ("switch (n)\n" 2708 "{\n" 2709 "case 0:\n" 2710 " {\n" 2711 " return false;\n" 2712 " }\n" 2713 "case 1:\n" 2714 " break;\n" 2715 "default:\n" 2716 " {\n" 2717 " return true;\n" 2718 " }\n" 2719 "}", 2720 format("switch (n) {\n" 2721 "case 0: {\n" 2722 " return false;\n" 2723 "}\n" 2724 "case 1:\n" 2725 " break;\n" 2726 "default: {\n" 2727 " return true;\n" 2728 "}\n" 2729 "}", 2730 Style)); 2731 Style.IndentCaseLabels = true; 2732 Style.IndentCaseBlocks = true; 2733 EXPECT_EQ("switch (n)\n" 2734 "{\n" 2735 " case 0:\n" 2736 " {\n" 2737 " return false;\n" 2738 " }\n" 2739 " case 1:\n" 2740 " break;\n" 2741 " default:\n" 2742 " {\n" 2743 " return true;\n" 2744 " }\n" 2745 "}", 2746 format("switch (n) {\n" 2747 "case 0: {\n" 2748 " return false;\n" 2749 "}\n" 2750 "case 1:\n" 2751 " break;\n" 2752 "default: {\n" 2753 " return true;\n" 2754 "}\n" 2755 "}", 2756 Style)); 2757 } 2758 2759 TEST_F(FormatTest, CaseRanges) { 2760 verifyFormat("switch (x) {\n" 2761 "case 'A' ... 'Z':\n" 2762 "case 1 ... 5:\n" 2763 "case a ... b:\n" 2764 " break;\n" 2765 "}"); 2766 } 2767 2768 TEST_F(FormatTest, ShortEnums) { 2769 FormatStyle Style = getLLVMStyle(); 2770 Style.AllowShortEnumsOnASingleLine = true; 2771 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2772 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2773 Style.AllowShortEnumsOnASingleLine = false; 2774 verifyFormat("enum {\n" 2775 " A,\n" 2776 " B,\n" 2777 " C\n" 2778 "} ShortEnum1, ShortEnum2;", 2779 Style); 2780 verifyFormat("typedef enum {\n" 2781 " A,\n" 2782 " B,\n" 2783 " C\n" 2784 "} ShortEnum1, ShortEnum2;", 2785 Style); 2786 verifyFormat("enum {\n" 2787 " A,\n" 2788 "} ShortEnum1, ShortEnum2;", 2789 Style); 2790 verifyFormat("typedef enum {\n" 2791 " A,\n" 2792 "} ShortEnum1, ShortEnum2;", 2793 Style); 2794 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2795 Style.BraceWrapping.AfterEnum = true; 2796 verifyFormat("enum\n" 2797 "{\n" 2798 " A,\n" 2799 " B,\n" 2800 " C\n" 2801 "} ShortEnum1, ShortEnum2;", 2802 Style); 2803 verifyFormat("typedef enum\n" 2804 "{\n" 2805 " A,\n" 2806 " B,\n" 2807 " C\n" 2808 "} ShortEnum1, ShortEnum2;", 2809 Style); 2810 } 2811 2812 TEST_F(FormatTest, ShortCaseLabels) { 2813 FormatStyle Style = getLLVMStyle(); 2814 Style.AllowShortCaseLabelsOnASingleLine = true; 2815 verifyFormat("switch (a) {\n" 2816 "case 1: x = 1; break;\n" 2817 "case 2: return;\n" 2818 "case 3:\n" 2819 "case 4:\n" 2820 "case 5: return;\n" 2821 "case 6: // comment\n" 2822 " return;\n" 2823 "case 7:\n" 2824 " // comment\n" 2825 " return;\n" 2826 "case 8:\n" 2827 " x = 8; // comment\n" 2828 " break;\n" 2829 "default: y = 1; break;\n" 2830 "}", 2831 Style); 2832 verifyFormat("switch (a) {\n" 2833 "case 0: return; // comment\n" 2834 "case 1: break; // comment\n" 2835 "case 2: return;\n" 2836 "// comment\n" 2837 "case 3: return;\n" 2838 "// comment 1\n" 2839 "// comment 2\n" 2840 "// comment 3\n" 2841 "case 4: break; /* comment */\n" 2842 "case 5:\n" 2843 " // comment\n" 2844 " break;\n" 2845 "case 6: /* comment */ x = 1; break;\n" 2846 "case 7: x = /* comment */ 1; break;\n" 2847 "case 8:\n" 2848 " x = 1; /* comment */\n" 2849 " break;\n" 2850 "case 9:\n" 2851 " break; // comment line 1\n" 2852 " // comment line 2\n" 2853 "}", 2854 Style); 2855 EXPECT_EQ("switch (a) {\n" 2856 "case 1:\n" 2857 " x = 8;\n" 2858 " // fall through\n" 2859 "case 2: x = 8;\n" 2860 "// comment\n" 2861 "case 3:\n" 2862 " return; /* comment line 1\n" 2863 " * comment line 2 */\n" 2864 "case 4: i = 8;\n" 2865 "// something else\n" 2866 "#if FOO\n" 2867 "case 5: break;\n" 2868 "#endif\n" 2869 "}", 2870 format("switch (a) {\n" 2871 "case 1: x = 8;\n" 2872 " // fall through\n" 2873 "case 2:\n" 2874 " x = 8;\n" 2875 "// comment\n" 2876 "case 3:\n" 2877 " return; /* comment line 1\n" 2878 " * comment line 2 */\n" 2879 "case 4:\n" 2880 " i = 8;\n" 2881 "// something else\n" 2882 "#if FOO\n" 2883 "case 5: break;\n" 2884 "#endif\n" 2885 "}", 2886 Style)); 2887 EXPECT_EQ("switch (a) {\n" 2888 "case 0:\n" 2889 " return; // long long long long long long long long long long " 2890 "long long comment\n" 2891 " // line\n" 2892 "}", 2893 format("switch (a) {\n" 2894 "case 0: return; // long long long long long long long long " 2895 "long long long long comment line\n" 2896 "}", 2897 Style)); 2898 EXPECT_EQ("switch (a) {\n" 2899 "case 0:\n" 2900 " return; /* long long long long long long long long long long " 2901 "long long comment\n" 2902 " line */\n" 2903 "}", 2904 format("switch (a) {\n" 2905 "case 0: return; /* long long long long long long long long " 2906 "long long long long comment line */\n" 2907 "}", 2908 Style)); 2909 verifyFormat("switch (a) {\n" 2910 "#if FOO\n" 2911 "case 0: return 0;\n" 2912 "#endif\n" 2913 "}", 2914 Style); 2915 verifyFormat("switch (a) {\n" 2916 "case 1: {\n" 2917 "}\n" 2918 "case 2: {\n" 2919 " return;\n" 2920 "}\n" 2921 "case 3: {\n" 2922 " x = 1;\n" 2923 " return;\n" 2924 "}\n" 2925 "case 4:\n" 2926 " if (x)\n" 2927 " return;\n" 2928 "}", 2929 Style); 2930 Style.ColumnLimit = 21; 2931 verifyFormat("switch (a) {\n" 2932 "case 1: x = 1; break;\n" 2933 "case 2: return;\n" 2934 "case 3:\n" 2935 "case 4:\n" 2936 "case 5: return;\n" 2937 "default:\n" 2938 " y = 1;\n" 2939 " break;\n" 2940 "}", 2941 Style); 2942 Style.ColumnLimit = 80; 2943 Style.AllowShortCaseLabelsOnASingleLine = false; 2944 Style.IndentCaseLabels = true; 2945 EXPECT_EQ("switch (n) {\n" 2946 " default /*comments*/:\n" 2947 " return true;\n" 2948 " case 0:\n" 2949 " return false;\n" 2950 "}", 2951 format("switch (n) {\n" 2952 "default/*comments*/:\n" 2953 " return true;\n" 2954 "case 0:\n" 2955 " return false;\n" 2956 "}", 2957 Style)); 2958 Style.AllowShortCaseLabelsOnASingleLine = true; 2959 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2960 Style.BraceWrapping.AfterCaseLabel = true; 2961 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2962 EXPECT_EQ("switch (n)\n" 2963 "{\n" 2964 " case 0:\n" 2965 " {\n" 2966 " return false;\n" 2967 " }\n" 2968 " default:\n" 2969 " {\n" 2970 " return true;\n" 2971 " }\n" 2972 "}", 2973 format("switch (n) {\n" 2974 " case 0: {\n" 2975 " return false;\n" 2976 " }\n" 2977 " default:\n" 2978 " {\n" 2979 " return true;\n" 2980 " }\n" 2981 "}", 2982 Style)); 2983 } 2984 2985 TEST_F(FormatTest, FormatsLabels) { 2986 verifyFormat("void f() {\n" 2987 " some_code();\n" 2988 "test_label:\n" 2989 " some_other_code();\n" 2990 " {\n" 2991 " some_more_code();\n" 2992 " another_label:\n" 2993 " some_more_code();\n" 2994 " }\n" 2995 "}"); 2996 verifyFormat("{\n" 2997 " some_code();\n" 2998 "test_label:\n" 2999 " some_other_code();\n" 3000 "}"); 3001 verifyFormat("{\n" 3002 " some_code();\n" 3003 "test_label:;\n" 3004 " int i = 0;\n" 3005 "}"); 3006 FormatStyle Style = getLLVMStyle(); 3007 Style.IndentGotoLabels = false; 3008 verifyFormat("void f() {\n" 3009 " some_code();\n" 3010 "test_label:\n" 3011 " some_other_code();\n" 3012 " {\n" 3013 " some_more_code();\n" 3014 "another_label:\n" 3015 " some_more_code();\n" 3016 " }\n" 3017 "}", 3018 Style); 3019 verifyFormat("{\n" 3020 " some_code();\n" 3021 "test_label:\n" 3022 " some_other_code();\n" 3023 "}", 3024 Style); 3025 verifyFormat("{\n" 3026 " some_code();\n" 3027 "test_label:;\n" 3028 " int i = 0;\n" 3029 "}"); 3030 } 3031 3032 TEST_F(FormatTest, MultiLineControlStatements) { 3033 FormatStyle Style = getLLVMStyleWithColumns(20); 3034 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3035 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3036 // Short lines should keep opening brace on same line. 3037 EXPECT_EQ("if (foo) {\n" 3038 " bar();\n" 3039 "}", 3040 format("if(foo){bar();}", Style)); 3041 EXPECT_EQ("if (foo) {\n" 3042 " bar();\n" 3043 "} else {\n" 3044 " baz();\n" 3045 "}", 3046 format("if(foo){bar();}else{baz();}", Style)); 3047 EXPECT_EQ("if (foo && bar) {\n" 3048 " baz();\n" 3049 "}", 3050 format("if(foo&&bar){baz();}", Style)); 3051 EXPECT_EQ("if (foo) {\n" 3052 " bar();\n" 3053 "} else if (baz) {\n" 3054 " quux();\n" 3055 "}", 3056 format("if(foo){bar();}else if(baz){quux();}", Style)); 3057 EXPECT_EQ( 3058 "if (foo) {\n" 3059 " bar();\n" 3060 "} else if (baz) {\n" 3061 " quux();\n" 3062 "} else {\n" 3063 " foobar();\n" 3064 "}", 3065 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 3066 EXPECT_EQ("for (;;) {\n" 3067 " foo();\n" 3068 "}", 3069 format("for(;;){foo();}")); 3070 EXPECT_EQ("while (1) {\n" 3071 " foo();\n" 3072 "}", 3073 format("while(1){foo();}", Style)); 3074 EXPECT_EQ("switch (foo) {\n" 3075 "case bar:\n" 3076 " return;\n" 3077 "}", 3078 format("switch(foo){case bar:return;}", Style)); 3079 EXPECT_EQ("try {\n" 3080 " foo();\n" 3081 "} catch (...) {\n" 3082 " bar();\n" 3083 "}", 3084 format("try{foo();}catch(...){bar();}", Style)); 3085 EXPECT_EQ("do {\n" 3086 " foo();\n" 3087 "} while (bar &&\n" 3088 " baz);", 3089 format("do{foo();}while(bar&&baz);", Style)); 3090 // Long lines should put opening brace on new line. 3091 EXPECT_EQ("if (foo && bar &&\n" 3092 " baz)\n" 3093 "{\n" 3094 " quux();\n" 3095 "}", 3096 format("if(foo&&bar&&baz){quux();}", Style)); 3097 EXPECT_EQ("if (foo && bar &&\n" 3098 " baz)\n" 3099 "{\n" 3100 " quux();\n" 3101 "}", 3102 format("if (foo && bar &&\n" 3103 " baz) {\n" 3104 " quux();\n" 3105 "}", 3106 Style)); 3107 EXPECT_EQ("if (foo) {\n" 3108 " bar();\n" 3109 "} else if (baz ||\n" 3110 " quux)\n" 3111 "{\n" 3112 " foobar();\n" 3113 "}", 3114 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3115 EXPECT_EQ( 3116 "if (foo) {\n" 3117 " bar();\n" 3118 "} else if (baz ||\n" 3119 " quux)\n" 3120 "{\n" 3121 " foobar();\n" 3122 "} else {\n" 3123 " barbaz();\n" 3124 "}", 3125 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3126 Style)); 3127 EXPECT_EQ("for (int i = 0;\n" 3128 " i < 10; ++i)\n" 3129 "{\n" 3130 " foo();\n" 3131 "}", 3132 format("for(int i=0;i<10;++i){foo();}", Style)); 3133 EXPECT_EQ("foreach (int i,\n" 3134 " list)\n" 3135 "{\n" 3136 " foo();\n" 3137 "}", 3138 format("foreach(int i, list){foo();}", Style)); 3139 Style.ColumnLimit = 3140 40; // to concentrate at brace wrapping, not line wrap due to column limit 3141 EXPECT_EQ("foreach (int i, list) {\n" 3142 " foo();\n" 3143 "}", 3144 format("foreach(int i, list){foo();}", Style)); 3145 Style.ColumnLimit = 3146 20; // to concentrate at brace wrapping, not line wrap due to column limit 3147 EXPECT_EQ("while (foo || bar ||\n" 3148 " baz)\n" 3149 "{\n" 3150 " quux();\n" 3151 "}", 3152 format("while(foo||bar||baz){quux();}", Style)); 3153 EXPECT_EQ("switch (\n" 3154 " foo = barbaz)\n" 3155 "{\n" 3156 "case quux:\n" 3157 " return;\n" 3158 "}", 3159 format("switch(foo=barbaz){case quux:return;}", Style)); 3160 EXPECT_EQ("try {\n" 3161 " foo();\n" 3162 "} catch (\n" 3163 " Exception &bar)\n" 3164 "{\n" 3165 " baz();\n" 3166 "}", 3167 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3168 Style.ColumnLimit = 3169 40; // to concentrate at brace wrapping, not line wrap due to column limit 3170 EXPECT_EQ("try {\n" 3171 " foo();\n" 3172 "} catch (Exception &bar) {\n" 3173 " baz();\n" 3174 "}", 3175 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3176 Style.ColumnLimit = 3177 20; // to concentrate at brace wrapping, not line wrap due to column limit 3178 3179 Style.BraceWrapping.BeforeElse = true; 3180 EXPECT_EQ( 3181 "if (foo) {\n" 3182 " bar();\n" 3183 "}\n" 3184 "else if (baz ||\n" 3185 " quux)\n" 3186 "{\n" 3187 " foobar();\n" 3188 "}\n" 3189 "else {\n" 3190 " barbaz();\n" 3191 "}", 3192 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3193 Style)); 3194 3195 Style.BraceWrapping.BeforeCatch = true; 3196 EXPECT_EQ("try {\n" 3197 " foo();\n" 3198 "}\n" 3199 "catch (...) {\n" 3200 " baz();\n" 3201 "}", 3202 format("try{foo();}catch(...){baz();}", Style)); 3203 3204 Style.BraceWrapping.AfterFunction = true; 3205 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3206 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3207 Style.ColumnLimit = 80; 3208 verifyFormat("void shortfunction() { bar(); }", Style); 3209 3210 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3211 verifyFormat("void shortfunction()\n" 3212 "{\n" 3213 " bar();\n" 3214 "}", 3215 Style); 3216 } 3217 3218 TEST_F(FormatTest, BeforeWhile) { 3219 FormatStyle Style = getLLVMStyle(); 3220 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3221 3222 verifyFormat("do {\n" 3223 " foo();\n" 3224 "} while (1);", 3225 Style); 3226 Style.BraceWrapping.BeforeWhile = true; 3227 verifyFormat("do {\n" 3228 " foo();\n" 3229 "}\n" 3230 "while (1);", 3231 Style); 3232 } 3233 3234 //===----------------------------------------------------------------------===// 3235 // Tests for classes, namespaces, etc. 3236 //===----------------------------------------------------------------------===// 3237 3238 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3239 verifyFormat("class A {};"); 3240 } 3241 3242 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3243 verifyFormat("class A {\n" 3244 "public:\n" 3245 "public: // comment\n" 3246 "protected:\n" 3247 "private:\n" 3248 " void f() {}\n" 3249 "};"); 3250 verifyFormat("export class A {\n" 3251 "public:\n" 3252 "public: // comment\n" 3253 "protected:\n" 3254 "private:\n" 3255 " void f() {}\n" 3256 "};"); 3257 verifyGoogleFormat("class A {\n" 3258 " public:\n" 3259 " protected:\n" 3260 " private:\n" 3261 " void f() {}\n" 3262 "};"); 3263 verifyGoogleFormat("export class A {\n" 3264 " public:\n" 3265 " protected:\n" 3266 " private:\n" 3267 " void f() {}\n" 3268 "};"); 3269 verifyFormat("class A {\n" 3270 "public slots:\n" 3271 " void f1() {}\n" 3272 "public Q_SLOTS:\n" 3273 " void f2() {}\n" 3274 "protected slots:\n" 3275 " void f3() {}\n" 3276 "protected Q_SLOTS:\n" 3277 " void f4() {}\n" 3278 "private slots:\n" 3279 " void f5() {}\n" 3280 "private Q_SLOTS:\n" 3281 " void f6() {}\n" 3282 "signals:\n" 3283 " void g1();\n" 3284 "Q_SIGNALS:\n" 3285 " void g2();\n" 3286 "};"); 3287 3288 // Don't interpret 'signals' the wrong way. 3289 verifyFormat("signals.set();"); 3290 verifyFormat("for (Signals signals : f()) {\n}"); 3291 verifyFormat("{\n" 3292 " signals.set(); // This needs indentation.\n" 3293 "}"); 3294 verifyFormat("void f() {\n" 3295 "label:\n" 3296 " signals.baz();\n" 3297 "}"); 3298 verifyFormat("private[1];"); 3299 verifyFormat("testArray[public] = 1;"); 3300 verifyFormat("public();"); 3301 verifyFormat("myFunc(public);"); 3302 verifyFormat("std::vector<int> testVec = {private};"); 3303 verifyFormat("private.p = 1;"); 3304 verifyFormat("void function(private...){};"); 3305 verifyFormat("if (private && public)\n"); 3306 verifyFormat("private &= true;"); 3307 verifyFormat("int x = private * public;"); 3308 verifyFormat("public *= private;"); 3309 verifyFormat("int x = public + private;"); 3310 verifyFormat("private++;"); 3311 verifyFormat("++private;"); 3312 verifyFormat("public += private;"); 3313 verifyFormat("public = public - private;"); 3314 verifyFormat("public->foo();"); 3315 verifyFormat("private--;"); 3316 verifyFormat("--private;"); 3317 verifyFormat("public -= 1;"); 3318 verifyFormat("if (!private && !public)\n"); 3319 verifyFormat("public != private;"); 3320 verifyFormat("int x = public / private;"); 3321 verifyFormat("public /= 2;"); 3322 verifyFormat("public = public % 2;"); 3323 verifyFormat("public %= 2;"); 3324 verifyFormat("if (public < private)\n"); 3325 verifyFormat("public << private;"); 3326 verifyFormat("public <<= private;"); 3327 verifyFormat("if (public > private)\n"); 3328 verifyFormat("public >> private;"); 3329 verifyFormat("public >>= private;"); 3330 verifyFormat("public ^ private;"); 3331 verifyFormat("public ^= private;"); 3332 verifyFormat("public | private;"); 3333 verifyFormat("public |= private;"); 3334 verifyFormat("auto x = private ? 1 : 2;"); 3335 verifyFormat("if (public == private)\n"); 3336 verifyFormat("void foo(public, private)"); 3337 verifyFormat("public::foo();"); 3338 } 3339 3340 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3341 EXPECT_EQ("class A {\n" 3342 "public:\n" 3343 " void f();\n" 3344 "\n" 3345 "private:\n" 3346 " void g() {}\n" 3347 " // test\n" 3348 "protected:\n" 3349 " int h;\n" 3350 "};", 3351 format("class A {\n" 3352 "public:\n" 3353 "void f();\n" 3354 "private:\n" 3355 "void g() {}\n" 3356 "// test\n" 3357 "protected:\n" 3358 "int h;\n" 3359 "};")); 3360 EXPECT_EQ("class A {\n" 3361 "protected:\n" 3362 "public:\n" 3363 " void f();\n" 3364 "};", 3365 format("class A {\n" 3366 "protected:\n" 3367 "\n" 3368 "public:\n" 3369 "\n" 3370 " void f();\n" 3371 "};")); 3372 3373 // Even ensure proper spacing inside macros. 3374 EXPECT_EQ("#define B \\\n" 3375 " class A { \\\n" 3376 " protected: \\\n" 3377 " public: \\\n" 3378 " void f(); \\\n" 3379 " };", 3380 format("#define B \\\n" 3381 " class A { \\\n" 3382 " protected: \\\n" 3383 " \\\n" 3384 " public: \\\n" 3385 " \\\n" 3386 " void f(); \\\n" 3387 " };", 3388 getGoogleStyle())); 3389 // But don't remove empty lines after macros ending in access specifiers. 3390 EXPECT_EQ("#define A private:\n" 3391 "\n" 3392 "int i;", 3393 format("#define A private:\n" 3394 "\n" 3395 "int i;")); 3396 } 3397 3398 TEST_F(FormatTest, FormatsClasses) { 3399 verifyFormat("class A : public B {};"); 3400 verifyFormat("class A : public ::B {};"); 3401 3402 verifyFormat( 3403 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3404 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3405 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3406 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3407 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3408 verifyFormat( 3409 "class A : public B, public C, public D, public E, public F {};"); 3410 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3411 " public C,\n" 3412 " public D,\n" 3413 " public E,\n" 3414 " public F,\n" 3415 " public G {};"); 3416 3417 verifyFormat("class\n" 3418 " ReallyReallyLongClassName {\n" 3419 " int i;\n" 3420 "};", 3421 getLLVMStyleWithColumns(32)); 3422 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3423 " aaaaaaaaaaaaaaaa> {};"); 3424 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3425 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3426 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3427 verifyFormat("template <class R, class C>\n" 3428 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3429 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3430 verifyFormat("class ::A::B {};"); 3431 } 3432 3433 TEST_F(FormatTest, BreakInheritanceStyle) { 3434 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3435 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3436 FormatStyle::BILS_BeforeComma; 3437 verifyFormat("class MyClass : public X {};", 3438 StyleWithInheritanceBreakBeforeComma); 3439 verifyFormat("class MyClass\n" 3440 " : public X\n" 3441 " , public Y {};", 3442 StyleWithInheritanceBreakBeforeComma); 3443 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3444 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3445 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3446 StyleWithInheritanceBreakBeforeComma); 3447 verifyFormat("struct aaaaaaaaaaaaa\n" 3448 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3449 " aaaaaaaaaaaaaaaa> {};", 3450 StyleWithInheritanceBreakBeforeComma); 3451 3452 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3453 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3454 FormatStyle::BILS_AfterColon; 3455 verifyFormat("class MyClass : public X {};", 3456 StyleWithInheritanceBreakAfterColon); 3457 verifyFormat("class MyClass : public X, public Y {};", 3458 StyleWithInheritanceBreakAfterColon); 3459 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3460 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3461 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3462 StyleWithInheritanceBreakAfterColon); 3463 verifyFormat("struct aaaaaaaaaaaaa :\n" 3464 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3465 " aaaaaaaaaaaaaaaa> {};", 3466 StyleWithInheritanceBreakAfterColon); 3467 3468 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3469 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3470 FormatStyle::BILS_AfterComma; 3471 verifyFormat("class MyClass : public X {};", 3472 StyleWithInheritanceBreakAfterComma); 3473 verifyFormat("class MyClass : public X,\n" 3474 " public Y {};", 3475 StyleWithInheritanceBreakAfterComma); 3476 verifyFormat( 3477 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3478 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3479 "{};", 3480 StyleWithInheritanceBreakAfterComma); 3481 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3482 " aaaaaaaaaaaaaaaa> {};", 3483 StyleWithInheritanceBreakAfterComma); 3484 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3485 " : public OnceBreak,\n" 3486 " public AlwaysBreak,\n" 3487 " EvenBasesFitInOneLine {};", 3488 StyleWithInheritanceBreakAfterComma); 3489 } 3490 3491 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3492 verifyFormat("class A {\n} a, b;"); 3493 verifyFormat("struct A {\n} a, b;"); 3494 verifyFormat("union A {\n} a, b;"); 3495 3496 verifyFormat("constexpr class A {\n} a, b;"); 3497 verifyFormat("constexpr struct A {\n} a, b;"); 3498 verifyFormat("constexpr union A {\n} a, b;"); 3499 3500 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3501 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3502 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3503 3504 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3505 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3506 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3507 3508 verifyFormat("namespace ns {\n" 3509 "class {\n" 3510 "} a, b;\n" 3511 "} // namespace ns"); 3512 verifyFormat("namespace ns {\n" 3513 "const class {\n" 3514 "} a, b;\n" 3515 "} // namespace ns"); 3516 verifyFormat("namespace ns {\n" 3517 "constexpr class C {\n" 3518 "} a, b;\n" 3519 "} // namespace ns"); 3520 verifyFormat("namespace ns {\n" 3521 "class { /* comment */\n" 3522 "} a, b;\n" 3523 "} // namespace ns"); 3524 verifyFormat("namespace ns {\n" 3525 "const class { /* comment */\n" 3526 "} a, b;\n" 3527 "} // namespace ns"); 3528 } 3529 3530 TEST_F(FormatTest, FormatsEnum) { 3531 verifyFormat("enum {\n" 3532 " Zero,\n" 3533 " One = 1,\n" 3534 " Two = One + 1,\n" 3535 " Three = (One + Two),\n" 3536 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3537 " Five = (One, Two, Three, Four, 5)\n" 3538 "};"); 3539 verifyGoogleFormat("enum {\n" 3540 " Zero,\n" 3541 " One = 1,\n" 3542 " Two = One + 1,\n" 3543 " Three = (One + Two),\n" 3544 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3545 " Five = (One, Two, Three, Four, 5)\n" 3546 "};"); 3547 verifyFormat("enum Enum {};"); 3548 verifyFormat("enum {};"); 3549 verifyFormat("enum X E {} d;"); 3550 verifyFormat("enum __attribute__((...)) E {} d;"); 3551 verifyFormat("enum __declspec__((...)) E {} d;"); 3552 verifyFormat("enum {\n" 3553 " Bar = Foo<int, int>::value\n" 3554 "};", 3555 getLLVMStyleWithColumns(30)); 3556 3557 verifyFormat("enum ShortEnum { A, B, C };"); 3558 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3559 3560 EXPECT_EQ("enum KeepEmptyLines {\n" 3561 " ONE,\n" 3562 "\n" 3563 " TWO,\n" 3564 "\n" 3565 " THREE\n" 3566 "}", 3567 format("enum KeepEmptyLines {\n" 3568 " ONE,\n" 3569 "\n" 3570 " TWO,\n" 3571 "\n" 3572 "\n" 3573 " THREE\n" 3574 "}")); 3575 verifyFormat("enum E { // comment\n" 3576 " ONE,\n" 3577 " TWO\n" 3578 "};\n" 3579 "int i;"); 3580 3581 FormatStyle EightIndent = getLLVMStyle(); 3582 EightIndent.IndentWidth = 8; 3583 verifyFormat("enum {\n" 3584 " VOID,\n" 3585 " CHAR,\n" 3586 " SHORT,\n" 3587 " INT,\n" 3588 " LONG,\n" 3589 " SIGNED,\n" 3590 " UNSIGNED,\n" 3591 " BOOL,\n" 3592 " FLOAT,\n" 3593 " DOUBLE,\n" 3594 " COMPLEX\n" 3595 "};", 3596 EightIndent); 3597 3598 // Not enums. 3599 verifyFormat("enum X f() {\n" 3600 " a();\n" 3601 " return 42;\n" 3602 "}"); 3603 verifyFormat("enum X Type::f() {\n" 3604 " a();\n" 3605 " return 42;\n" 3606 "}"); 3607 verifyFormat("enum ::X f() {\n" 3608 " a();\n" 3609 " return 42;\n" 3610 "}"); 3611 verifyFormat("enum ns::X f() {\n" 3612 " a();\n" 3613 " return 42;\n" 3614 "}"); 3615 } 3616 3617 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3618 verifyFormat("enum Type {\n" 3619 " One = 0; // These semicolons should be commas.\n" 3620 " Two = 1;\n" 3621 "};"); 3622 verifyFormat("namespace n {\n" 3623 "enum Type {\n" 3624 " One,\n" 3625 " Two, // missing };\n" 3626 " int i;\n" 3627 "}\n" 3628 "void g() {}"); 3629 } 3630 3631 TEST_F(FormatTest, FormatsEnumStruct) { 3632 verifyFormat("enum struct {\n" 3633 " Zero,\n" 3634 " One = 1,\n" 3635 " Two = One + 1,\n" 3636 " Three = (One + Two),\n" 3637 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3638 " Five = (One, Two, Three, Four, 5)\n" 3639 "};"); 3640 verifyFormat("enum struct Enum {};"); 3641 verifyFormat("enum struct {};"); 3642 verifyFormat("enum struct X E {} d;"); 3643 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3644 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3645 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3646 } 3647 3648 TEST_F(FormatTest, FormatsEnumClass) { 3649 verifyFormat("enum class {\n" 3650 " Zero,\n" 3651 " One = 1,\n" 3652 " Two = One + 1,\n" 3653 " Three = (One + Two),\n" 3654 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3655 " Five = (One, Two, Three, Four, 5)\n" 3656 "};"); 3657 verifyFormat("enum class Enum {};"); 3658 verifyFormat("enum class {};"); 3659 verifyFormat("enum class X E {} d;"); 3660 verifyFormat("enum class __attribute__((...)) E {} d;"); 3661 verifyFormat("enum class __declspec__((...)) E {} d;"); 3662 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3663 } 3664 3665 TEST_F(FormatTest, FormatsEnumTypes) { 3666 verifyFormat("enum X : int {\n" 3667 " A, // Force multiple lines.\n" 3668 " B\n" 3669 "};"); 3670 verifyFormat("enum X : int { A, B };"); 3671 verifyFormat("enum X : std::uint32_t { A, B };"); 3672 } 3673 3674 TEST_F(FormatTest, FormatsTypedefEnum) { 3675 FormatStyle Style = getLLVMStyleWithColumns(40); 3676 verifyFormat("typedef enum {} EmptyEnum;"); 3677 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3678 verifyFormat("typedef enum {\n" 3679 " ZERO = 0,\n" 3680 " ONE = 1,\n" 3681 " TWO = 2,\n" 3682 " THREE = 3\n" 3683 "} LongEnum;", 3684 Style); 3685 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3686 Style.BraceWrapping.AfterEnum = true; 3687 verifyFormat("typedef enum {} EmptyEnum;"); 3688 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3689 verifyFormat("typedef enum\n" 3690 "{\n" 3691 " ZERO = 0,\n" 3692 " ONE = 1,\n" 3693 " TWO = 2,\n" 3694 " THREE = 3\n" 3695 "} LongEnum;", 3696 Style); 3697 } 3698 3699 TEST_F(FormatTest, FormatsNSEnums) { 3700 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3701 verifyGoogleFormat( 3702 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3703 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3704 " // Information about someDecentlyLongValue.\n" 3705 " someDecentlyLongValue,\n" 3706 " // Information about anotherDecentlyLongValue.\n" 3707 " anotherDecentlyLongValue,\n" 3708 " // Information about aThirdDecentlyLongValue.\n" 3709 " aThirdDecentlyLongValue\n" 3710 "};"); 3711 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3712 " // Information about someDecentlyLongValue.\n" 3713 " someDecentlyLongValue,\n" 3714 " // Information about anotherDecentlyLongValue.\n" 3715 " anotherDecentlyLongValue,\n" 3716 " // Information about aThirdDecentlyLongValue.\n" 3717 " aThirdDecentlyLongValue\n" 3718 "};"); 3719 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3720 " a = 1,\n" 3721 " b = 2,\n" 3722 " c = 3,\n" 3723 "};"); 3724 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3725 " a = 1,\n" 3726 " b = 2,\n" 3727 " c = 3,\n" 3728 "};"); 3729 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3730 " a = 1,\n" 3731 " b = 2,\n" 3732 " c = 3,\n" 3733 "};"); 3734 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3735 " a = 1,\n" 3736 " b = 2,\n" 3737 " c = 3,\n" 3738 "};"); 3739 } 3740 3741 TEST_F(FormatTest, FormatsBitfields) { 3742 verifyFormat("struct Bitfields {\n" 3743 " unsigned sClass : 8;\n" 3744 " unsigned ValueKind : 2;\n" 3745 "};"); 3746 verifyFormat("struct A {\n" 3747 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3748 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3749 "};"); 3750 verifyFormat("struct MyStruct {\n" 3751 " uchar data;\n" 3752 " uchar : 8;\n" 3753 " uchar : 8;\n" 3754 " uchar other;\n" 3755 "};"); 3756 FormatStyle Style = getLLVMStyle(); 3757 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3758 verifyFormat("struct Bitfields {\n" 3759 " unsigned sClass:8;\n" 3760 " unsigned ValueKind:2;\n" 3761 " uchar other;\n" 3762 "};", 3763 Style); 3764 verifyFormat("struct A {\n" 3765 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3766 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3767 "};", 3768 Style); 3769 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3770 verifyFormat("struct Bitfields {\n" 3771 " unsigned sClass :8;\n" 3772 " unsigned ValueKind :2;\n" 3773 " uchar other;\n" 3774 "};", 3775 Style); 3776 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3777 verifyFormat("struct Bitfields {\n" 3778 " unsigned sClass: 8;\n" 3779 " unsigned ValueKind: 2;\n" 3780 " uchar other;\n" 3781 "};", 3782 Style); 3783 } 3784 3785 TEST_F(FormatTest, FormatsNamespaces) { 3786 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3787 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3788 3789 verifyFormat("namespace some_namespace {\n" 3790 "class A {};\n" 3791 "void f() { f(); }\n" 3792 "}", 3793 LLVMWithNoNamespaceFix); 3794 verifyFormat("#define M(x) x##x\n" 3795 "namespace M(x) {\n" 3796 "class A {};\n" 3797 "void f() { f(); }\n" 3798 "}", 3799 LLVMWithNoNamespaceFix); 3800 verifyFormat("#define M(x) x##x\n" 3801 "namespace N::inline M(x) {\n" 3802 "class A {};\n" 3803 "void f() { f(); }\n" 3804 "}", 3805 LLVMWithNoNamespaceFix); 3806 verifyFormat("#define M(x) x##x\n" 3807 "namespace M(x)::inline N {\n" 3808 "class A {};\n" 3809 "void f() { f(); }\n" 3810 "}", 3811 LLVMWithNoNamespaceFix); 3812 verifyFormat("#define M(x) x##x\n" 3813 "namespace N::M(x) {\n" 3814 "class A {};\n" 3815 "void f() { f(); }\n" 3816 "}", 3817 LLVMWithNoNamespaceFix); 3818 verifyFormat("#define M(x) x##x\n" 3819 "namespace M::N(x) {\n" 3820 "class A {};\n" 3821 "void f() { f(); }\n" 3822 "}", 3823 LLVMWithNoNamespaceFix); 3824 verifyFormat("namespace N::inline D {\n" 3825 "class A {};\n" 3826 "void f() { f(); }\n" 3827 "}", 3828 LLVMWithNoNamespaceFix); 3829 verifyFormat("namespace N::inline D::E {\n" 3830 "class A {};\n" 3831 "void f() { f(); }\n" 3832 "}", 3833 LLVMWithNoNamespaceFix); 3834 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3835 "class A {};\n" 3836 "void f() { f(); }\n" 3837 "}", 3838 LLVMWithNoNamespaceFix); 3839 verifyFormat("/* something */ namespace some_namespace {\n" 3840 "class A {};\n" 3841 "void f() { f(); }\n" 3842 "}", 3843 LLVMWithNoNamespaceFix); 3844 verifyFormat("namespace {\n" 3845 "class A {};\n" 3846 "void f() { f(); }\n" 3847 "}", 3848 LLVMWithNoNamespaceFix); 3849 verifyFormat("/* something */ namespace {\n" 3850 "class A {};\n" 3851 "void f() { f(); }\n" 3852 "}", 3853 LLVMWithNoNamespaceFix); 3854 verifyFormat("inline namespace X {\n" 3855 "class A {};\n" 3856 "void f() { f(); }\n" 3857 "}", 3858 LLVMWithNoNamespaceFix); 3859 verifyFormat("/* something */ inline namespace X {\n" 3860 "class A {};\n" 3861 "void f() { f(); }\n" 3862 "}", 3863 LLVMWithNoNamespaceFix); 3864 verifyFormat("export namespace X {\n" 3865 "class A {};\n" 3866 "void f() { f(); }\n" 3867 "}", 3868 LLVMWithNoNamespaceFix); 3869 verifyFormat("using namespace some_namespace;\n" 3870 "class A {};\n" 3871 "void f() { f(); }", 3872 LLVMWithNoNamespaceFix); 3873 3874 // This code is more common than we thought; if we 3875 // layout this correctly the semicolon will go into 3876 // its own line, which is undesirable. 3877 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3878 verifyFormat("namespace {\n" 3879 "class A {};\n" 3880 "};", 3881 LLVMWithNoNamespaceFix); 3882 3883 verifyFormat("namespace {\n" 3884 "int SomeVariable = 0; // comment\n" 3885 "} // namespace", 3886 LLVMWithNoNamespaceFix); 3887 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3888 "#define HEADER_GUARD\n" 3889 "namespace my_namespace {\n" 3890 "int i;\n" 3891 "} // my_namespace\n" 3892 "#endif // HEADER_GUARD", 3893 format("#ifndef HEADER_GUARD\n" 3894 " #define HEADER_GUARD\n" 3895 " namespace my_namespace {\n" 3896 "int i;\n" 3897 "} // my_namespace\n" 3898 "#endif // HEADER_GUARD", 3899 LLVMWithNoNamespaceFix)); 3900 3901 EXPECT_EQ("namespace A::B {\n" 3902 "class C {};\n" 3903 "}", 3904 format("namespace A::B {\n" 3905 "class C {};\n" 3906 "}", 3907 LLVMWithNoNamespaceFix)); 3908 3909 FormatStyle Style = getLLVMStyle(); 3910 Style.NamespaceIndentation = FormatStyle::NI_All; 3911 EXPECT_EQ("namespace out {\n" 3912 " int i;\n" 3913 " namespace in {\n" 3914 " int i;\n" 3915 " } // namespace in\n" 3916 "} // namespace out", 3917 format("namespace out {\n" 3918 "int i;\n" 3919 "namespace in {\n" 3920 "int i;\n" 3921 "} // namespace in\n" 3922 "} // namespace out", 3923 Style)); 3924 3925 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3926 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3927 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3928 FormatStyle::SFS_Inline; 3929 verifyFormat("namespace {\n" 3930 " void f() {\n" 3931 " return;\n" 3932 " }\n" 3933 "} // namespace\n", 3934 ShortInlineFunctions); 3935 verifyFormat("namespace { /* comment */\n" 3936 " void f() {\n" 3937 " return;\n" 3938 " }\n" 3939 "} // namespace\n", 3940 ShortInlineFunctions); 3941 verifyFormat("namespace { // comment\n" 3942 " void f() {\n" 3943 " return;\n" 3944 " }\n" 3945 "} // namespace\n", 3946 ShortInlineFunctions); 3947 verifyFormat("namespace {\n" 3948 " int some_int;\n" 3949 " void f() {\n" 3950 " return;\n" 3951 " }\n" 3952 "} // namespace\n", 3953 ShortInlineFunctions); 3954 verifyFormat("namespace interface {\n" 3955 " void f() {\n" 3956 " return;\n" 3957 " }\n" 3958 "} // namespace interface\n", 3959 ShortInlineFunctions); 3960 verifyFormat("namespace {\n" 3961 " class X {\n" 3962 " void f() { return; }\n" 3963 " };\n" 3964 "} // namespace\n", 3965 ShortInlineFunctions); 3966 verifyFormat("namespace {\n" 3967 " class X { /* comment */\n" 3968 " void f() { return; }\n" 3969 " };\n" 3970 "} // namespace\n", 3971 ShortInlineFunctions); 3972 verifyFormat("namespace {\n" 3973 " class X { // comment\n" 3974 " void f() { return; }\n" 3975 " };\n" 3976 "} // namespace\n", 3977 ShortInlineFunctions); 3978 verifyFormat("namespace {\n" 3979 " struct X {\n" 3980 " void f() { return; }\n" 3981 " };\n" 3982 "} // namespace\n", 3983 ShortInlineFunctions); 3984 verifyFormat("namespace {\n" 3985 " union X {\n" 3986 " void f() { return; }\n" 3987 " };\n" 3988 "} // namespace\n", 3989 ShortInlineFunctions); 3990 verifyFormat("extern \"C\" {\n" 3991 "void f() {\n" 3992 " return;\n" 3993 "}\n" 3994 "} // namespace\n", 3995 ShortInlineFunctions); 3996 verifyFormat("namespace {\n" 3997 " class X {\n" 3998 " void f() { return; }\n" 3999 " } x;\n" 4000 "} // namespace\n", 4001 ShortInlineFunctions); 4002 verifyFormat("namespace {\n" 4003 " [[nodiscard]] class X {\n" 4004 " void f() { return; }\n" 4005 " };\n" 4006 "} // namespace\n", 4007 ShortInlineFunctions); 4008 verifyFormat("namespace {\n" 4009 " static class X {\n" 4010 " void f() { return; }\n" 4011 " } x;\n" 4012 "} // namespace\n", 4013 ShortInlineFunctions); 4014 verifyFormat("namespace {\n" 4015 " constexpr class X {\n" 4016 " void f() { return; }\n" 4017 " } x;\n" 4018 "} // namespace\n", 4019 ShortInlineFunctions); 4020 4021 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4022 verifyFormat("extern \"C\" {\n" 4023 " void f() {\n" 4024 " return;\n" 4025 " }\n" 4026 "} // namespace\n", 4027 ShortInlineFunctions); 4028 4029 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4030 EXPECT_EQ("namespace out {\n" 4031 "int i;\n" 4032 "namespace in {\n" 4033 " int i;\n" 4034 "} // namespace in\n" 4035 "} // namespace out", 4036 format("namespace out {\n" 4037 "int i;\n" 4038 "namespace in {\n" 4039 "int i;\n" 4040 "} // namespace in\n" 4041 "} // namespace out", 4042 Style)); 4043 4044 Style.NamespaceIndentation = FormatStyle::NI_None; 4045 verifyFormat("template <class T>\n" 4046 "concept a_concept = X<>;\n" 4047 "namespace B {\n" 4048 "struct b_struct {};\n" 4049 "} // namespace B\n", 4050 Style); 4051 verifyFormat("template <int I>\n" 4052 "constexpr void foo()\n" 4053 " requires(I == 42)\n" 4054 "{}\n" 4055 "namespace ns {\n" 4056 "void foo() {}\n" 4057 "} // namespace ns\n", 4058 Style); 4059 } 4060 4061 TEST_F(FormatTest, NamespaceMacros) { 4062 FormatStyle Style = getLLVMStyle(); 4063 Style.NamespaceMacros.push_back("TESTSUITE"); 4064 4065 verifyFormat("TESTSUITE(A) {\n" 4066 "int foo();\n" 4067 "} // TESTSUITE(A)", 4068 Style); 4069 4070 verifyFormat("TESTSUITE(A, B) {\n" 4071 "int foo();\n" 4072 "} // TESTSUITE(A)", 4073 Style); 4074 4075 // Properly indent according to NamespaceIndentation style 4076 Style.NamespaceIndentation = FormatStyle::NI_All; 4077 verifyFormat("TESTSUITE(A) {\n" 4078 " int foo();\n" 4079 "} // TESTSUITE(A)", 4080 Style); 4081 verifyFormat("TESTSUITE(A) {\n" 4082 " namespace B {\n" 4083 " int foo();\n" 4084 " } // namespace B\n" 4085 "} // TESTSUITE(A)", 4086 Style); 4087 verifyFormat("namespace A {\n" 4088 " TESTSUITE(B) {\n" 4089 " int foo();\n" 4090 " } // TESTSUITE(B)\n" 4091 "} // namespace A", 4092 Style); 4093 4094 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4095 verifyFormat("TESTSUITE(A) {\n" 4096 "TESTSUITE(B) {\n" 4097 " int foo();\n" 4098 "} // TESTSUITE(B)\n" 4099 "} // TESTSUITE(A)", 4100 Style); 4101 verifyFormat("TESTSUITE(A) {\n" 4102 "namespace B {\n" 4103 " int foo();\n" 4104 "} // namespace B\n" 4105 "} // TESTSUITE(A)", 4106 Style); 4107 verifyFormat("namespace A {\n" 4108 "TESTSUITE(B) {\n" 4109 " int foo();\n" 4110 "} // TESTSUITE(B)\n" 4111 "} // namespace A", 4112 Style); 4113 4114 // Properly merge namespace-macros blocks in CompactNamespaces mode 4115 Style.NamespaceIndentation = FormatStyle::NI_None; 4116 Style.CompactNamespaces = true; 4117 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4118 "}} // TESTSUITE(A::B)", 4119 Style); 4120 4121 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4122 "}} // TESTSUITE(out::in)", 4123 format("TESTSUITE(out) {\n" 4124 "TESTSUITE(in) {\n" 4125 "} // TESTSUITE(in)\n" 4126 "} // TESTSUITE(out)", 4127 Style)); 4128 4129 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4130 "}} // TESTSUITE(out::in)", 4131 format("TESTSUITE(out) {\n" 4132 "TESTSUITE(in) {\n" 4133 "} // TESTSUITE(in)\n" 4134 "} // TESTSUITE(out)", 4135 Style)); 4136 4137 // Do not merge different namespaces/macros 4138 EXPECT_EQ("namespace out {\n" 4139 "TESTSUITE(in) {\n" 4140 "} // TESTSUITE(in)\n" 4141 "} // namespace out", 4142 format("namespace out {\n" 4143 "TESTSUITE(in) {\n" 4144 "} // TESTSUITE(in)\n" 4145 "} // namespace out", 4146 Style)); 4147 EXPECT_EQ("TESTSUITE(out) {\n" 4148 "namespace in {\n" 4149 "} // namespace in\n" 4150 "} // TESTSUITE(out)", 4151 format("TESTSUITE(out) {\n" 4152 "namespace in {\n" 4153 "} // namespace in\n" 4154 "} // TESTSUITE(out)", 4155 Style)); 4156 Style.NamespaceMacros.push_back("FOOBAR"); 4157 EXPECT_EQ("TESTSUITE(out) {\n" 4158 "FOOBAR(in) {\n" 4159 "} // FOOBAR(in)\n" 4160 "} // TESTSUITE(out)", 4161 format("TESTSUITE(out) {\n" 4162 "FOOBAR(in) {\n" 4163 "} // FOOBAR(in)\n" 4164 "} // TESTSUITE(out)", 4165 Style)); 4166 } 4167 4168 TEST_F(FormatTest, FormatsCompactNamespaces) { 4169 FormatStyle Style = getLLVMStyle(); 4170 Style.CompactNamespaces = true; 4171 Style.NamespaceMacros.push_back("TESTSUITE"); 4172 4173 verifyFormat("namespace A { namespace B {\n" 4174 "}} // namespace A::B", 4175 Style); 4176 4177 EXPECT_EQ("namespace out { namespace in {\n" 4178 "}} // namespace out::in", 4179 format("namespace out {\n" 4180 "namespace in {\n" 4181 "} // namespace in\n" 4182 "} // namespace out", 4183 Style)); 4184 4185 // Only namespaces which have both consecutive opening and end get compacted 4186 EXPECT_EQ("namespace out {\n" 4187 "namespace in1 {\n" 4188 "} // namespace in1\n" 4189 "namespace in2 {\n" 4190 "} // namespace in2\n" 4191 "} // namespace out", 4192 format("namespace out {\n" 4193 "namespace in1 {\n" 4194 "} // namespace in1\n" 4195 "namespace in2 {\n" 4196 "} // namespace in2\n" 4197 "} // namespace out", 4198 Style)); 4199 4200 EXPECT_EQ("namespace out {\n" 4201 "int i;\n" 4202 "namespace in {\n" 4203 "int j;\n" 4204 "} // namespace in\n" 4205 "int k;\n" 4206 "} // namespace out", 4207 format("namespace out { int i;\n" 4208 "namespace in { int j; } // namespace in\n" 4209 "int k; } // namespace out", 4210 Style)); 4211 4212 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4213 "}}} // namespace A::B::C\n", 4214 format("namespace A { namespace B {\n" 4215 "namespace C {\n" 4216 "}} // namespace B::C\n" 4217 "} // namespace A\n", 4218 Style)); 4219 4220 Style.ColumnLimit = 40; 4221 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4222 "namespace bbbbbbbbbb {\n" 4223 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4224 format("namespace aaaaaaaaaa {\n" 4225 "namespace bbbbbbbbbb {\n" 4226 "} // namespace bbbbbbbbbb\n" 4227 "} // namespace aaaaaaaaaa", 4228 Style)); 4229 4230 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4231 "namespace cccccc {\n" 4232 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4233 format("namespace aaaaaa {\n" 4234 "namespace bbbbbb {\n" 4235 "namespace cccccc {\n" 4236 "} // namespace cccccc\n" 4237 "} // namespace bbbbbb\n" 4238 "} // namespace aaaaaa", 4239 Style)); 4240 Style.ColumnLimit = 80; 4241 4242 // Extra semicolon after 'inner' closing brace prevents merging 4243 EXPECT_EQ("namespace out { namespace in {\n" 4244 "}; } // namespace out::in", 4245 format("namespace out {\n" 4246 "namespace in {\n" 4247 "}; // namespace in\n" 4248 "} // namespace out", 4249 Style)); 4250 4251 // Extra semicolon after 'outer' closing brace is conserved 4252 EXPECT_EQ("namespace out { namespace in {\n" 4253 "}}; // namespace out::in", 4254 format("namespace out {\n" 4255 "namespace in {\n" 4256 "} // namespace in\n" 4257 "}; // namespace out", 4258 Style)); 4259 4260 Style.NamespaceIndentation = FormatStyle::NI_All; 4261 EXPECT_EQ("namespace out { namespace in {\n" 4262 " int i;\n" 4263 "}} // namespace out::in", 4264 format("namespace out {\n" 4265 "namespace in {\n" 4266 "int i;\n" 4267 "} // namespace in\n" 4268 "} // namespace out", 4269 Style)); 4270 EXPECT_EQ("namespace out { namespace mid {\n" 4271 " namespace in {\n" 4272 " int j;\n" 4273 " } // namespace in\n" 4274 " int k;\n" 4275 "}} // namespace out::mid", 4276 format("namespace out { namespace mid {\n" 4277 "namespace in { int j; } // namespace in\n" 4278 "int k; }} // namespace out::mid", 4279 Style)); 4280 4281 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4282 EXPECT_EQ("namespace out { namespace in {\n" 4283 " int i;\n" 4284 "}} // namespace out::in", 4285 format("namespace out {\n" 4286 "namespace in {\n" 4287 "int i;\n" 4288 "} // namespace in\n" 4289 "} // namespace out", 4290 Style)); 4291 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4292 " int i;\n" 4293 "}}} // namespace out::mid::in", 4294 format("namespace out {\n" 4295 "namespace mid {\n" 4296 "namespace in {\n" 4297 "int i;\n" 4298 "} // namespace in\n" 4299 "} // namespace mid\n" 4300 "} // namespace out", 4301 Style)); 4302 4303 Style.CompactNamespaces = true; 4304 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4305 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4306 Style.BraceWrapping.BeforeLambdaBody = true; 4307 verifyFormat("namespace out { namespace in {\n" 4308 "}} // namespace out::in", 4309 Style); 4310 EXPECT_EQ("namespace out { namespace in {\n" 4311 "}} // namespace out::in", 4312 format("namespace out {\n" 4313 "namespace in {\n" 4314 "} // namespace in\n" 4315 "} // namespace out", 4316 Style)); 4317 } 4318 4319 TEST_F(FormatTest, FormatsExternC) { 4320 verifyFormat("extern \"C\" {\nint a;"); 4321 verifyFormat("extern \"C\" {}"); 4322 verifyFormat("extern \"C\" {\n" 4323 "int foo();\n" 4324 "}"); 4325 verifyFormat("extern \"C\" int foo() {}"); 4326 verifyFormat("extern \"C\" int foo();"); 4327 verifyFormat("extern \"C\" int foo() {\n" 4328 " int i = 42;\n" 4329 " return i;\n" 4330 "}"); 4331 4332 FormatStyle Style = getLLVMStyle(); 4333 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4334 Style.BraceWrapping.AfterFunction = true; 4335 verifyFormat("extern \"C\" int foo() {}", Style); 4336 verifyFormat("extern \"C\" int foo();", Style); 4337 verifyFormat("extern \"C\" int foo()\n" 4338 "{\n" 4339 " int i = 42;\n" 4340 " return i;\n" 4341 "}", 4342 Style); 4343 4344 Style.BraceWrapping.AfterExternBlock = true; 4345 Style.BraceWrapping.SplitEmptyRecord = false; 4346 verifyFormat("extern \"C\"\n" 4347 "{}", 4348 Style); 4349 verifyFormat("extern \"C\"\n" 4350 "{\n" 4351 " int foo();\n" 4352 "}", 4353 Style); 4354 } 4355 4356 TEST_F(FormatTest, IndentExternBlockStyle) { 4357 FormatStyle Style = getLLVMStyle(); 4358 Style.IndentWidth = 2; 4359 4360 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4361 verifyFormat("extern \"C\" { /*9*/\n" 4362 "}", 4363 Style); 4364 verifyFormat("extern \"C\" {\n" 4365 " int foo10();\n" 4366 "}", 4367 Style); 4368 4369 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4370 verifyFormat("extern \"C\" { /*11*/\n" 4371 "}", 4372 Style); 4373 verifyFormat("extern \"C\" {\n" 4374 "int foo12();\n" 4375 "}", 4376 Style); 4377 4378 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4379 Style.BraceWrapping.AfterExternBlock = true; 4380 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4381 verifyFormat("extern \"C\"\n" 4382 "{ /*13*/\n" 4383 "}", 4384 Style); 4385 verifyFormat("extern \"C\"\n{\n" 4386 " int foo14();\n" 4387 "}", 4388 Style); 4389 4390 Style.BraceWrapping.AfterExternBlock = false; 4391 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4392 verifyFormat("extern \"C\" { /*15*/\n" 4393 "}", 4394 Style); 4395 verifyFormat("extern \"C\" {\n" 4396 "int foo16();\n" 4397 "}", 4398 Style); 4399 4400 Style.BraceWrapping.AfterExternBlock = true; 4401 verifyFormat("extern \"C\"\n" 4402 "{ /*13*/\n" 4403 "}", 4404 Style); 4405 verifyFormat("extern \"C\"\n" 4406 "{\n" 4407 "int foo14();\n" 4408 "}", 4409 Style); 4410 4411 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4412 verifyFormat("extern \"C\"\n" 4413 "{ /*13*/\n" 4414 "}", 4415 Style); 4416 verifyFormat("extern \"C\"\n" 4417 "{\n" 4418 " int foo14();\n" 4419 "}", 4420 Style); 4421 } 4422 4423 TEST_F(FormatTest, FormatsInlineASM) { 4424 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4425 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4426 verifyFormat( 4427 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4428 " \"cpuid\\n\\t\"\n" 4429 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4430 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4431 " : \"a\"(value));"); 4432 EXPECT_EQ( 4433 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4434 " __asm {\n" 4435 " mov edx,[that] // vtable in edx\n" 4436 " mov eax,methodIndex\n" 4437 " call [edx][eax*4] // stdcall\n" 4438 " }\n" 4439 "}", 4440 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4441 " __asm {\n" 4442 " mov edx,[that] // vtable in edx\n" 4443 " mov eax,methodIndex\n" 4444 " call [edx][eax*4] // stdcall\n" 4445 " }\n" 4446 "}")); 4447 EXPECT_EQ("_asm {\n" 4448 " xor eax, eax;\n" 4449 " cpuid;\n" 4450 "}", 4451 format("_asm {\n" 4452 " xor eax, eax;\n" 4453 " cpuid;\n" 4454 "}")); 4455 verifyFormat("void function() {\n" 4456 " // comment\n" 4457 " asm(\"\");\n" 4458 "}"); 4459 EXPECT_EQ("__asm {\n" 4460 "}\n" 4461 "int i;", 4462 format("__asm {\n" 4463 "}\n" 4464 "int i;")); 4465 } 4466 4467 TEST_F(FormatTest, FormatTryCatch) { 4468 verifyFormat("try {\n" 4469 " throw a * b;\n" 4470 "} catch (int a) {\n" 4471 " // Do nothing.\n" 4472 "} catch (...) {\n" 4473 " exit(42);\n" 4474 "}"); 4475 4476 // Function-level try statements. 4477 verifyFormat("int f() try { return 4; } catch (...) {\n" 4478 " return 5;\n" 4479 "}"); 4480 verifyFormat("class A {\n" 4481 " int a;\n" 4482 " A() try : a(0) {\n" 4483 " } catch (...) {\n" 4484 " throw;\n" 4485 " }\n" 4486 "};\n"); 4487 verifyFormat("class A {\n" 4488 " int a;\n" 4489 " A() try : a(0), b{1} {\n" 4490 " } catch (...) {\n" 4491 " throw;\n" 4492 " }\n" 4493 "};\n"); 4494 verifyFormat("class A {\n" 4495 " int a;\n" 4496 " A() try : a(0), b{1}, c{2} {\n" 4497 " } catch (...) {\n" 4498 " throw;\n" 4499 " }\n" 4500 "};\n"); 4501 verifyFormat("class A {\n" 4502 " int a;\n" 4503 " A() try : a(0), b{1}, c{2} {\n" 4504 " { // New scope.\n" 4505 " }\n" 4506 " } catch (...) {\n" 4507 " throw;\n" 4508 " }\n" 4509 "};\n"); 4510 4511 // Incomplete try-catch blocks. 4512 verifyIncompleteFormat("try {} catch ("); 4513 } 4514 4515 TEST_F(FormatTest, FormatTryAsAVariable) { 4516 verifyFormat("int try;"); 4517 verifyFormat("int try, size;"); 4518 verifyFormat("try = foo();"); 4519 verifyFormat("if (try < size) {\n return true;\n}"); 4520 4521 verifyFormat("int catch;"); 4522 verifyFormat("int catch, size;"); 4523 verifyFormat("catch = foo();"); 4524 verifyFormat("if (catch < size) {\n return true;\n}"); 4525 4526 FormatStyle Style = getLLVMStyle(); 4527 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4528 Style.BraceWrapping.AfterFunction = true; 4529 Style.BraceWrapping.BeforeCatch = true; 4530 verifyFormat("try {\n" 4531 " int bar = 1;\n" 4532 "}\n" 4533 "catch (...) {\n" 4534 " int bar = 1;\n" 4535 "}", 4536 Style); 4537 verifyFormat("#if NO_EX\n" 4538 "try\n" 4539 "#endif\n" 4540 "{\n" 4541 "}\n" 4542 "#if NO_EX\n" 4543 "catch (...) {\n" 4544 "}", 4545 Style); 4546 verifyFormat("try /* abc */ {\n" 4547 " int bar = 1;\n" 4548 "}\n" 4549 "catch (...) {\n" 4550 " int bar = 1;\n" 4551 "}", 4552 Style); 4553 verifyFormat("try\n" 4554 "// abc\n" 4555 "{\n" 4556 " int bar = 1;\n" 4557 "}\n" 4558 "catch (...) {\n" 4559 " int bar = 1;\n" 4560 "}", 4561 Style); 4562 } 4563 4564 TEST_F(FormatTest, FormatSEHTryCatch) { 4565 verifyFormat("__try {\n" 4566 " int a = b * c;\n" 4567 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4568 " // Do nothing.\n" 4569 "}"); 4570 4571 verifyFormat("__try {\n" 4572 " int a = b * c;\n" 4573 "} __finally {\n" 4574 " // Do nothing.\n" 4575 "}"); 4576 4577 verifyFormat("DEBUG({\n" 4578 " __try {\n" 4579 " } __finally {\n" 4580 " }\n" 4581 "});\n"); 4582 } 4583 4584 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4585 verifyFormat("try {\n" 4586 " f();\n" 4587 "} catch {\n" 4588 " g();\n" 4589 "}"); 4590 verifyFormat("try {\n" 4591 " f();\n" 4592 "} catch (A a) MACRO(x) {\n" 4593 " g();\n" 4594 "} catch (B b) MACRO(x) {\n" 4595 " g();\n" 4596 "}"); 4597 } 4598 4599 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4600 FormatStyle Style = getLLVMStyle(); 4601 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4602 FormatStyle::BS_WebKit}) { 4603 Style.BreakBeforeBraces = BraceStyle; 4604 verifyFormat("try {\n" 4605 " // something\n" 4606 "} catch (...) {\n" 4607 " // something\n" 4608 "}", 4609 Style); 4610 } 4611 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4612 verifyFormat("try {\n" 4613 " // something\n" 4614 "}\n" 4615 "catch (...) {\n" 4616 " // something\n" 4617 "}", 4618 Style); 4619 verifyFormat("__try {\n" 4620 " // something\n" 4621 "}\n" 4622 "__finally {\n" 4623 " // something\n" 4624 "}", 4625 Style); 4626 verifyFormat("@try {\n" 4627 " // something\n" 4628 "}\n" 4629 "@finally {\n" 4630 " // something\n" 4631 "}", 4632 Style); 4633 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4634 verifyFormat("try\n" 4635 "{\n" 4636 " // something\n" 4637 "}\n" 4638 "catch (...)\n" 4639 "{\n" 4640 " // something\n" 4641 "}", 4642 Style); 4643 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4644 verifyFormat("try\n" 4645 " {\n" 4646 " // something white\n" 4647 " }\n" 4648 "catch (...)\n" 4649 " {\n" 4650 " // something white\n" 4651 " }", 4652 Style); 4653 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4654 verifyFormat("try\n" 4655 " {\n" 4656 " // something\n" 4657 " }\n" 4658 "catch (...)\n" 4659 " {\n" 4660 " // something\n" 4661 " }", 4662 Style); 4663 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4664 Style.BraceWrapping.BeforeCatch = true; 4665 verifyFormat("try {\n" 4666 " // something\n" 4667 "}\n" 4668 "catch (...) {\n" 4669 " // something\n" 4670 "}", 4671 Style); 4672 } 4673 4674 TEST_F(FormatTest, StaticInitializers) { 4675 verifyFormat("static SomeClass SC = {1, 'a'};"); 4676 4677 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4678 " 100000000, " 4679 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4680 4681 // Here, everything other than the "}" would fit on a line. 4682 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4683 " 10000000000000000000000000};"); 4684 EXPECT_EQ("S s = {a,\n" 4685 "\n" 4686 " b};", 4687 format("S s = {\n" 4688 " a,\n" 4689 "\n" 4690 " b\n" 4691 "};")); 4692 4693 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4694 // line. However, the formatting looks a bit off and this probably doesn't 4695 // happen often in practice. 4696 verifyFormat("static int Variable[1] = {\n" 4697 " {1000000000000000000000000000000000000}};", 4698 getLLVMStyleWithColumns(40)); 4699 } 4700 4701 TEST_F(FormatTest, DesignatedInitializers) { 4702 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4703 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4704 " .bbbbbbbbbb = 2,\n" 4705 " .cccccccccc = 3,\n" 4706 " .dddddddddd = 4,\n" 4707 " .eeeeeeeeee = 5};"); 4708 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4709 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4710 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4711 " .ccccccccccccccccccccccccccc = 3,\n" 4712 " .ddddddddddddddddddddddddddd = 4,\n" 4713 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4714 4715 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4716 4717 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4718 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4719 " [2] = bbbbbbbbbb,\n" 4720 " [3] = cccccccccc,\n" 4721 " [4] = dddddddddd,\n" 4722 " [5] = eeeeeeeeee};"); 4723 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4724 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4725 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4726 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4727 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4728 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4729 } 4730 4731 TEST_F(FormatTest, NestedStaticInitializers) { 4732 verifyFormat("static A x = {{{}}};\n"); 4733 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4734 " {init1, init2, init3, init4}}};", 4735 getLLVMStyleWithColumns(50)); 4736 4737 verifyFormat("somes Status::global_reps[3] = {\n" 4738 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4739 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4740 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4741 getLLVMStyleWithColumns(60)); 4742 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4743 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4744 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4745 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4746 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4747 " {rect.fRight - rect.fLeft, rect.fBottom - " 4748 "rect.fTop}};"); 4749 4750 verifyFormat( 4751 "SomeArrayOfSomeType a = {\n" 4752 " {{1, 2, 3},\n" 4753 " {1, 2, 3},\n" 4754 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4755 " 333333333333333333333333333333},\n" 4756 " {1, 2, 3},\n" 4757 " {1, 2, 3}}};"); 4758 verifyFormat( 4759 "SomeArrayOfSomeType a = {\n" 4760 " {{1, 2, 3}},\n" 4761 " {{1, 2, 3}},\n" 4762 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4763 " 333333333333333333333333333333}},\n" 4764 " {{1, 2, 3}},\n" 4765 " {{1, 2, 3}}};"); 4766 4767 verifyFormat("struct {\n" 4768 " unsigned bit;\n" 4769 " const char *const name;\n" 4770 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4771 " {kOsWin, \"Windows\"},\n" 4772 " {kOsLinux, \"Linux\"},\n" 4773 " {kOsCrOS, \"Chrome OS\"}};"); 4774 verifyFormat("struct {\n" 4775 " unsigned bit;\n" 4776 " const char *const name;\n" 4777 "} kBitsToOs[] = {\n" 4778 " {kOsMac, \"Mac\"},\n" 4779 " {kOsWin, \"Windows\"},\n" 4780 " {kOsLinux, \"Linux\"},\n" 4781 " {kOsCrOS, \"Chrome OS\"},\n" 4782 "};"); 4783 } 4784 4785 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4786 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4787 " \\\n" 4788 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4789 } 4790 4791 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4792 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4793 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4794 4795 // Do break defaulted and deleted functions. 4796 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4797 " default;", 4798 getLLVMStyleWithColumns(40)); 4799 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4800 " delete;", 4801 getLLVMStyleWithColumns(40)); 4802 } 4803 4804 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4805 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4806 getLLVMStyleWithColumns(40)); 4807 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4808 getLLVMStyleWithColumns(40)); 4809 EXPECT_EQ("#define Q \\\n" 4810 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4811 " \"aaaaaaaa.cpp\"", 4812 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4813 getLLVMStyleWithColumns(40))); 4814 } 4815 4816 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4817 EXPECT_EQ("# 123 \"A string literal\"", 4818 format(" # 123 \"A string literal\"")); 4819 } 4820 4821 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4822 EXPECT_EQ("#;", format("#;")); 4823 verifyFormat("#\n;\n;\n;"); 4824 } 4825 4826 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4827 EXPECT_EQ("#line 42 \"test\"\n", 4828 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4829 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4830 getLLVMStyleWithColumns(12))); 4831 } 4832 4833 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4834 EXPECT_EQ("#line 42 \"test\"", 4835 format("# \\\n line \\\n 42 \\\n \"test\"")); 4836 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4837 } 4838 4839 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4840 verifyFormat("#define A \\x20"); 4841 verifyFormat("#define A \\ x20"); 4842 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4843 verifyFormat("#define A ''"); 4844 verifyFormat("#define A ''qqq"); 4845 verifyFormat("#define A `qqq"); 4846 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4847 EXPECT_EQ("const char *c = STRINGIFY(\n" 4848 "\\na : b);", 4849 format("const char * c = STRINGIFY(\n" 4850 "\\na : b);")); 4851 4852 verifyFormat("a\r\\"); 4853 verifyFormat("a\v\\"); 4854 verifyFormat("a\f\\"); 4855 } 4856 4857 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4858 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4859 style.IndentWidth = 4; 4860 style.PPIndentWidth = 1; 4861 4862 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4863 verifyFormat("#ifdef __linux__\n" 4864 "void foo() {\n" 4865 " int x = 0;\n" 4866 "}\n" 4867 "#define FOO\n" 4868 "#endif\n" 4869 "void bar() {\n" 4870 " int y = 0;\n" 4871 "}\n", 4872 style); 4873 4874 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4875 verifyFormat("#ifdef __linux__\n" 4876 "void foo() {\n" 4877 " int x = 0;\n" 4878 "}\n" 4879 "# define FOO foo\n" 4880 "#endif\n" 4881 "void bar() {\n" 4882 " int y = 0;\n" 4883 "}\n", 4884 style); 4885 4886 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4887 verifyFormat("#ifdef __linux__\n" 4888 "void foo() {\n" 4889 " int x = 0;\n" 4890 "}\n" 4891 " #define FOO foo\n" 4892 "#endif\n" 4893 "void bar() {\n" 4894 " int y = 0;\n" 4895 "}\n", 4896 style); 4897 } 4898 4899 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4900 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4901 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4902 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4903 // FIXME: We never break before the macro name. 4904 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4905 4906 verifyFormat("#define A A\n#define A A"); 4907 verifyFormat("#define A(X) A\n#define A A"); 4908 4909 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4910 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4911 } 4912 4913 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4914 EXPECT_EQ("// somecomment\n" 4915 "#include \"a.h\"\n" 4916 "#define A( \\\n" 4917 " A, B)\n" 4918 "#include \"b.h\"\n" 4919 "// somecomment\n", 4920 format(" // somecomment\n" 4921 " #include \"a.h\"\n" 4922 "#define A(A,\\\n" 4923 " B)\n" 4924 " #include \"b.h\"\n" 4925 " // somecomment\n", 4926 getLLVMStyleWithColumns(13))); 4927 } 4928 4929 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4930 4931 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4932 EXPECT_EQ("#define A \\\n" 4933 " c; \\\n" 4934 " e;\n" 4935 "f;", 4936 format("#define A c; e;\n" 4937 "f;", 4938 getLLVMStyleWithColumns(14))); 4939 } 4940 4941 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4942 4943 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4944 EXPECT_EQ("int x,\n" 4945 "#define A\n" 4946 " y;", 4947 format("int x,\n#define A\ny;")); 4948 } 4949 4950 TEST_F(FormatTest, HashInMacroDefinition) { 4951 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4952 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4953 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4954 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4955 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4956 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4957 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4958 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4959 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4960 verifyFormat("#define A \\\n" 4961 " { \\\n" 4962 " f(#c); \\\n" 4963 " }", 4964 getLLVMStyleWithColumns(11)); 4965 4966 verifyFormat("#define A(X) \\\n" 4967 " void function##X()", 4968 getLLVMStyleWithColumns(22)); 4969 4970 verifyFormat("#define A(a, b, c) \\\n" 4971 " void a##b##c()", 4972 getLLVMStyleWithColumns(22)); 4973 4974 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4975 } 4976 4977 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4978 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4979 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4980 4981 FormatStyle Style = getLLVMStyle(); 4982 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4983 verifyFormat("#define true ((foo)1)", Style); 4984 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4985 verifyFormat("#define false((foo)0)", Style); 4986 } 4987 4988 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4989 EXPECT_EQ("#define A b;", format("#define A \\\n" 4990 " \\\n" 4991 " b;", 4992 getLLVMStyleWithColumns(25))); 4993 EXPECT_EQ("#define A \\\n" 4994 " \\\n" 4995 " a; \\\n" 4996 " b;", 4997 format("#define A \\\n" 4998 " \\\n" 4999 " a; \\\n" 5000 " b;", 5001 getLLVMStyleWithColumns(11))); 5002 EXPECT_EQ("#define A \\\n" 5003 " a; \\\n" 5004 " \\\n" 5005 " b;", 5006 format("#define A \\\n" 5007 " a; \\\n" 5008 " \\\n" 5009 " b;", 5010 getLLVMStyleWithColumns(11))); 5011 } 5012 5013 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5014 verifyIncompleteFormat("#define A :"); 5015 verifyFormat("#define SOMECASES \\\n" 5016 " case 1: \\\n" 5017 " case 2\n", 5018 getLLVMStyleWithColumns(20)); 5019 verifyFormat("#define MACRO(a) \\\n" 5020 " if (a) \\\n" 5021 " f(); \\\n" 5022 " else \\\n" 5023 " g()", 5024 getLLVMStyleWithColumns(18)); 5025 verifyFormat("#define A template <typename T>"); 5026 verifyIncompleteFormat("#define STR(x) #x\n" 5027 "f(STR(this_is_a_string_literal{));"); 5028 verifyFormat("#pragma omp threadprivate( \\\n" 5029 " y)), // expected-warning", 5030 getLLVMStyleWithColumns(28)); 5031 verifyFormat("#d, = };"); 5032 verifyFormat("#if \"a"); 5033 verifyIncompleteFormat("({\n" 5034 "#define b \\\n" 5035 " } \\\n" 5036 " a\n" 5037 "a", 5038 getLLVMStyleWithColumns(15)); 5039 verifyFormat("#define A \\\n" 5040 " { \\\n" 5041 " {\n" 5042 "#define B \\\n" 5043 " } \\\n" 5044 " }", 5045 getLLVMStyleWithColumns(15)); 5046 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5047 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5048 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5049 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5050 } 5051 5052 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5053 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5054 EXPECT_EQ("class A : public QObject {\n" 5055 " Q_OBJECT\n" 5056 "\n" 5057 " A() {}\n" 5058 "};", 5059 format("class A : public QObject {\n" 5060 " Q_OBJECT\n" 5061 "\n" 5062 " A() {\n}\n" 5063 "} ;")); 5064 EXPECT_EQ("MACRO\n" 5065 "/*static*/ int i;", 5066 format("MACRO\n" 5067 " /*static*/ int i;")); 5068 EXPECT_EQ("SOME_MACRO\n" 5069 "namespace {\n" 5070 "void f();\n" 5071 "} // namespace", 5072 format("SOME_MACRO\n" 5073 " namespace {\n" 5074 "void f( );\n" 5075 "} // namespace")); 5076 // Only if the identifier contains at least 5 characters. 5077 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5078 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5079 // Only if everything is upper case. 5080 EXPECT_EQ("class A : public QObject {\n" 5081 " Q_Object A() {}\n" 5082 "};", 5083 format("class A : public QObject {\n" 5084 " Q_Object\n" 5085 " A() {\n}\n" 5086 "} ;")); 5087 5088 // Only if the next line can actually start an unwrapped line. 5089 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5090 format("SOME_WEIRD_LOG_MACRO\n" 5091 "<< SomeThing;")); 5092 5093 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5094 "(n, buffers))\n", 5095 getChromiumStyle(FormatStyle::LK_Cpp)); 5096 5097 // See PR41483 5098 EXPECT_EQ("/**/ FOO(a)\n" 5099 "FOO(b)", 5100 format("/**/ FOO(a)\n" 5101 "FOO(b)")); 5102 } 5103 5104 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5105 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5106 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5107 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5108 "class X {};\n" 5109 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5110 "int *createScopDetectionPass() { return 0; }", 5111 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5112 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5113 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5114 " class X {};\n" 5115 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5116 " int *createScopDetectionPass() { return 0; }")); 5117 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5118 // braces, so that inner block is indented one level more. 5119 EXPECT_EQ("int q() {\n" 5120 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5121 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5122 " IPC_END_MESSAGE_MAP()\n" 5123 "}", 5124 format("int q() {\n" 5125 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5126 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5127 " IPC_END_MESSAGE_MAP()\n" 5128 "}")); 5129 5130 // Same inside macros. 5131 EXPECT_EQ("#define LIST(L) \\\n" 5132 " L(A) \\\n" 5133 " L(B) \\\n" 5134 " L(C)", 5135 format("#define LIST(L) \\\n" 5136 " L(A) \\\n" 5137 " L(B) \\\n" 5138 " L(C)", 5139 getGoogleStyle())); 5140 5141 // These must not be recognized as macros. 5142 EXPECT_EQ("int q() {\n" 5143 " f(x);\n" 5144 " f(x) {}\n" 5145 " f(x)->g();\n" 5146 " f(x)->*g();\n" 5147 " f(x).g();\n" 5148 " f(x) = x;\n" 5149 " f(x) += x;\n" 5150 " f(x) -= x;\n" 5151 " f(x) *= x;\n" 5152 " f(x) /= x;\n" 5153 " f(x) %= x;\n" 5154 " f(x) &= x;\n" 5155 " f(x) |= x;\n" 5156 " f(x) ^= x;\n" 5157 " f(x) >>= x;\n" 5158 " f(x) <<= x;\n" 5159 " f(x)[y].z();\n" 5160 " LOG(INFO) << x;\n" 5161 " ifstream(x) >> x;\n" 5162 "}\n", 5163 format("int q() {\n" 5164 " f(x)\n;\n" 5165 " f(x)\n {}\n" 5166 " f(x)\n->g();\n" 5167 " f(x)\n->*g();\n" 5168 " f(x)\n.g();\n" 5169 " f(x)\n = x;\n" 5170 " f(x)\n += x;\n" 5171 " f(x)\n -= x;\n" 5172 " f(x)\n *= x;\n" 5173 " f(x)\n /= x;\n" 5174 " f(x)\n %= x;\n" 5175 " f(x)\n &= x;\n" 5176 " f(x)\n |= x;\n" 5177 " f(x)\n ^= x;\n" 5178 " f(x)\n >>= x;\n" 5179 " f(x)\n <<= x;\n" 5180 " f(x)\n[y].z();\n" 5181 " LOG(INFO)\n << x;\n" 5182 " ifstream(x)\n >> x;\n" 5183 "}\n")); 5184 EXPECT_EQ("int q() {\n" 5185 " F(x)\n" 5186 " if (1) {\n" 5187 " }\n" 5188 " F(x)\n" 5189 " while (1) {\n" 5190 " }\n" 5191 " F(x)\n" 5192 " G(x);\n" 5193 " F(x)\n" 5194 " try {\n" 5195 " Q();\n" 5196 " } catch (...) {\n" 5197 " }\n" 5198 "}\n", 5199 format("int q() {\n" 5200 "F(x)\n" 5201 "if (1) {}\n" 5202 "F(x)\n" 5203 "while (1) {}\n" 5204 "F(x)\n" 5205 "G(x);\n" 5206 "F(x)\n" 5207 "try { Q(); } catch (...) {}\n" 5208 "}\n")); 5209 EXPECT_EQ("class A {\n" 5210 " A() : t(0) {}\n" 5211 " A(int i) noexcept() : {}\n" 5212 " A(X x)\n" // FIXME: function-level try blocks are broken. 5213 " try : t(0) {\n" 5214 " } catch (...) {\n" 5215 " }\n" 5216 "};", 5217 format("class A {\n" 5218 " A()\n : t(0) {}\n" 5219 " A(int i)\n noexcept() : {}\n" 5220 " A(X x)\n" 5221 " try : t(0) {} catch (...) {}\n" 5222 "};")); 5223 FormatStyle Style = getLLVMStyle(); 5224 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5225 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5226 Style.BraceWrapping.AfterFunction = true; 5227 EXPECT_EQ("void f()\n" 5228 "try\n" 5229 "{\n" 5230 "}", 5231 format("void f() try {\n" 5232 "}", 5233 Style)); 5234 EXPECT_EQ("class SomeClass {\n" 5235 "public:\n" 5236 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5237 "};", 5238 format("class SomeClass {\n" 5239 "public:\n" 5240 " SomeClass()\n" 5241 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5242 "};")); 5243 EXPECT_EQ("class SomeClass {\n" 5244 "public:\n" 5245 " SomeClass()\n" 5246 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5247 "};", 5248 format("class SomeClass {\n" 5249 "public:\n" 5250 " SomeClass()\n" 5251 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5252 "};", 5253 getLLVMStyleWithColumns(40))); 5254 5255 verifyFormat("MACRO(>)"); 5256 5257 // Some macros contain an implicit semicolon. 5258 Style = getLLVMStyle(); 5259 Style.StatementMacros.push_back("FOO"); 5260 verifyFormat("FOO(a) int b = 0;"); 5261 verifyFormat("FOO(a)\n" 5262 "int b = 0;", 5263 Style); 5264 verifyFormat("FOO(a);\n" 5265 "int b = 0;", 5266 Style); 5267 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5268 "int b = 0;", 5269 Style); 5270 verifyFormat("FOO()\n" 5271 "int b = 0;", 5272 Style); 5273 verifyFormat("FOO\n" 5274 "int b = 0;", 5275 Style); 5276 verifyFormat("void f() {\n" 5277 " FOO(a)\n" 5278 " return a;\n" 5279 "}", 5280 Style); 5281 verifyFormat("FOO(a)\n" 5282 "FOO(b)", 5283 Style); 5284 verifyFormat("int a = 0;\n" 5285 "FOO(b)\n" 5286 "int c = 0;", 5287 Style); 5288 verifyFormat("int a = 0;\n" 5289 "int x = FOO(a)\n" 5290 "int b = 0;", 5291 Style); 5292 verifyFormat("void foo(int a) { FOO(a) }\n" 5293 "uint32_t bar() {}", 5294 Style); 5295 } 5296 5297 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5298 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5299 5300 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5301 ZeroColumn); 5302 } 5303 5304 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5305 verifyFormat("#define A \\\n" 5306 " f({ \\\n" 5307 " g(); \\\n" 5308 " });", 5309 getLLVMStyleWithColumns(11)); 5310 } 5311 5312 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5313 FormatStyle Style = getLLVMStyleWithColumns(40); 5314 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5315 verifyFormat("#ifdef _WIN32\n" 5316 "#define A 0\n" 5317 "#ifdef VAR2\n" 5318 "#define B 1\n" 5319 "#include <someheader.h>\n" 5320 "#define MACRO \\\n" 5321 " some_very_long_func_aaaaaaaaaa();\n" 5322 "#endif\n" 5323 "#else\n" 5324 "#define A 1\n" 5325 "#endif", 5326 Style); 5327 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5328 verifyFormat("#ifdef _WIN32\n" 5329 "# define A 0\n" 5330 "# ifdef VAR2\n" 5331 "# define B 1\n" 5332 "# include <someheader.h>\n" 5333 "# define MACRO \\\n" 5334 " some_very_long_func_aaaaaaaaaa();\n" 5335 "# endif\n" 5336 "#else\n" 5337 "# define A 1\n" 5338 "#endif", 5339 Style); 5340 verifyFormat("#if A\n" 5341 "# define MACRO \\\n" 5342 " void a(int x) { \\\n" 5343 " b(); \\\n" 5344 " c(); \\\n" 5345 " d(); \\\n" 5346 " e(); \\\n" 5347 " f(); \\\n" 5348 " }\n" 5349 "#endif", 5350 Style); 5351 // Comments before include guard. 5352 verifyFormat("// file comment\n" 5353 "// file comment\n" 5354 "#ifndef HEADER_H\n" 5355 "#define HEADER_H\n" 5356 "code();\n" 5357 "#endif", 5358 Style); 5359 // Test with include guards. 5360 verifyFormat("#ifndef HEADER_H\n" 5361 "#define HEADER_H\n" 5362 "code();\n" 5363 "#endif", 5364 Style); 5365 // Include guards must have a #define with the same variable immediately 5366 // after #ifndef. 5367 verifyFormat("#ifndef NOT_GUARD\n" 5368 "# define FOO\n" 5369 "code();\n" 5370 "#endif", 5371 Style); 5372 5373 // Include guards must cover the entire file. 5374 verifyFormat("code();\n" 5375 "code();\n" 5376 "#ifndef NOT_GUARD\n" 5377 "# define NOT_GUARD\n" 5378 "code();\n" 5379 "#endif", 5380 Style); 5381 verifyFormat("#ifndef NOT_GUARD\n" 5382 "# define NOT_GUARD\n" 5383 "code();\n" 5384 "#endif\n" 5385 "code();", 5386 Style); 5387 // Test with trailing blank lines. 5388 verifyFormat("#ifndef HEADER_H\n" 5389 "#define HEADER_H\n" 5390 "code();\n" 5391 "#endif\n", 5392 Style); 5393 // Include guards don't have #else. 5394 verifyFormat("#ifndef NOT_GUARD\n" 5395 "# define NOT_GUARD\n" 5396 "code();\n" 5397 "#else\n" 5398 "#endif", 5399 Style); 5400 verifyFormat("#ifndef NOT_GUARD\n" 5401 "# define NOT_GUARD\n" 5402 "code();\n" 5403 "#elif FOO\n" 5404 "#endif", 5405 Style); 5406 // Non-identifier #define after potential include guard. 5407 verifyFormat("#ifndef FOO\n" 5408 "# define 1\n" 5409 "#endif\n", 5410 Style); 5411 // #if closes past last non-preprocessor line. 5412 verifyFormat("#ifndef FOO\n" 5413 "#define FOO\n" 5414 "#if 1\n" 5415 "int i;\n" 5416 "# define A 0\n" 5417 "#endif\n" 5418 "#endif\n", 5419 Style); 5420 // Don't crash if there is an #elif directive without a condition. 5421 verifyFormat("#if 1\n" 5422 "int x;\n" 5423 "#elif\n" 5424 "int y;\n" 5425 "#else\n" 5426 "int z;\n" 5427 "#endif", 5428 Style); 5429 // FIXME: This doesn't handle the case where there's code between the 5430 // #ifndef and #define but all other conditions hold. This is because when 5431 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5432 // previous code line yet, so we can't detect it. 5433 EXPECT_EQ("#ifndef NOT_GUARD\n" 5434 "code();\n" 5435 "#define NOT_GUARD\n" 5436 "code();\n" 5437 "#endif", 5438 format("#ifndef NOT_GUARD\n" 5439 "code();\n" 5440 "# define NOT_GUARD\n" 5441 "code();\n" 5442 "#endif", 5443 Style)); 5444 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5445 // be outside an include guard. Examples are #pragma once and 5446 // #pragma GCC diagnostic, or anything else that does not change the meaning 5447 // of the file if it's included multiple times. 5448 EXPECT_EQ("#ifdef WIN32\n" 5449 "# pragma once\n" 5450 "#endif\n" 5451 "#ifndef HEADER_H\n" 5452 "# define HEADER_H\n" 5453 "code();\n" 5454 "#endif", 5455 format("#ifdef WIN32\n" 5456 "# pragma once\n" 5457 "#endif\n" 5458 "#ifndef HEADER_H\n" 5459 "#define HEADER_H\n" 5460 "code();\n" 5461 "#endif", 5462 Style)); 5463 // FIXME: This does not detect when there is a single non-preprocessor line 5464 // in front of an include-guard-like structure where other conditions hold 5465 // because ScopedLineState hides the line. 5466 EXPECT_EQ("code();\n" 5467 "#ifndef HEADER_H\n" 5468 "#define HEADER_H\n" 5469 "code();\n" 5470 "#endif", 5471 format("code();\n" 5472 "#ifndef HEADER_H\n" 5473 "# define HEADER_H\n" 5474 "code();\n" 5475 "#endif", 5476 Style)); 5477 // Keep comments aligned with #, otherwise indent comments normally. These 5478 // tests cannot use verifyFormat because messUp manipulates leading 5479 // whitespace. 5480 { 5481 const char *Expected = "" 5482 "void f() {\n" 5483 "#if 1\n" 5484 "// Preprocessor aligned.\n" 5485 "# define A 0\n" 5486 " // Code. Separated by blank line.\n" 5487 "\n" 5488 "# define B 0\n" 5489 " // Code. Not aligned with #\n" 5490 "# define C 0\n" 5491 "#endif"; 5492 const char *ToFormat = "" 5493 "void f() {\n" 5494 "#if 1\n" 5495 "// Preprocessor aligned.\n" 5496 "# define A 0\n" 5497 "// Code. Separated by blank line.\n" 5498 "\n" 5499 "# define B 0\n" 5500 " // Code. Not aligned with #\n" 5501 "# define C 0\n" 5502 "#endif"; 5503 EXPECT_EQ(Expected, format(ToFormat, Style)); 5504 EXPECT_EQ(Expected, format(Expected, Style)); 5505 } 5506 // Keep block quotes aligned. 5507 { 5508 const char *Expected = "" 5509 "void f() {\n" 5510 "#if 1\n" 5511 "/* Preprocessor aligned. */\n" 5512 "# define A 0\n" 5513 " /* Code. Separated by blank line. */\n" 5514 "\n" 5515 "# define B 0\n" 5516 " /* Code. Not aligned with # */\n" 5517 "# define C 0\n" 5518 "#endif"; 5519 const char *ToFormat = "" 5520 "void f() {\n" 5521 "#if 1\n" 5522 "/* Preprocessor aligned. */\n" 5523 "# define A 0\n" 5524 "/* Code. Separated by blank line. */\n" 5525 "\n" 5526 "# define B 0\n" 5527 " /* Code. Not aligned with # */\n" 5528 "# define C 0\n" 5529 "#endif"; 5530 EXPECT_EQ(Expected, format(ToFormat, Style)); 5531 EXPECT_EQ(Expected, format(Expected, Style)); 5532 } 5533 // Keep comments aligned with un-indented directives. 5534 { 5535 const char *Expected = "" 5536 "void f() {\n" 5537 "// Preprocessor aligned.\n" 5538 "#define A 0\n" 5539 " // Code. Separated by blank line.\n" 5540 "\n" 5541 "#define B 0\n" 5542 " // Code. Not aligned with #\n" 5543 "#define C 0\n"; 5544 const char *ToFormat = "" 5545 "void f() {\n" 5546 "// Preprocessor aligned.\n" 5547 "#define A 0\n" 5548 "// Code. Separated by blank line.\n" 5549 "\n" 5550 "#define B 0\n" 5551 " // Code. Not aligned with #\n" 5552 "#define C 0\n"; 5553 EXPECT_EQ(Expected, format(ToFormat, Style)); 5554 EXPECT_EQ(Expected, format(Expected, Style)); 5555 } 5556 // Test AfterHash with tabs. 5557 { 5558 FormatStyle Tabbed = Style; 5559 Tabbed.UseTab = FormatStyle::UT_Always; 5560 Tabbed.IndentWidth = 8; 5561 Tabbed.TabWidth = 8; 5562 verifyFormat("#ifdef _WIN32\n" 5563 "#\tdefine A 0\n" 5564 "#\tifdef VAR2\n" 5565 "#\t\tdefine B 1\n" 5566 "#\t\tinclude <someheader.h>\n" 5567 "#\t\tdefine MACRO \\\n" 5568 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5569 "#\tendif\n" 5570 "#else\n" 5571 "#\tdefine A 1\n" 5572 "#endif", 5573 Tabbed); 5574 } 5575 5576 // Regression test: Multiline-macro inside include guards. 5577 verifyFormat("#ifndef HEADER_H\n" 5578 "#define HEADER_H\n" 5579 "#define A() \\\n" 5580 " int i; \\\n" 5581 " int j;\n" 5582 "#endif // HEADER_H", 5583 getLLVMStyleWithColumns(20)); 5584 5585 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5586 // Basic before hash indent tests 5587 verifyFormat("#ifdef _WIN32\n" 5588 " #define A 0\n" 5589 " #ifdef VAR2\n" 5590 " #define B 1\n" 5591 " #include <someheader.h>\n" 5592 " #define MACRO \\\n" 5593 " some_very_long_func_aaaaaaaaaa();\n" 5594 " #endif\n" 5595 "#else\n" 5596 " #define A 1\n" 5597 "#endif", 5598 Style); 5599 verifyFormat("#if A\n" 5600 " #define MACRO \\\n" 5601 " void a(int x) { \\\n" 5602 " b(); \\\n" 5603 " c(); \\\n" 5604 " d(); \\\n" 5605 " e(); \\\n" 5606 " f(); \\\n" 5607 " }\n" 5608 "#endif", 5609 Style); 5610 // Keep comments aligned with indented directives. These 5611 // tests cannot use verifyFormat because messUp manipulates leading 5612 // whitespace. 5613 { 5614 const char *Expected = "void f() {\n" 5615 "// Aligned to preprocessor.\n" 5616 "#if 1\n" 5617 " // Aligned to code.\n" 5618 " int a;\n" 5619 " #if 1\n" 5620 " // Aligned to preprocessor.\n" 5621 " #define A 0\n" 5622 " // Aligned to code.\n" 5623 " int b;\n" 5624 " #endif\n" 5625 "#endif\n" 5626 "}"; 5627 const char *ToFormat = "void f() {\n" 5628 "// Aligned to preprocessor.\n" 5629 "#if 1\n" 5630 "// Aligned to code.\n" 5631 "int a;\n" 5632 "#if 1\n" 5633 "// Aligned to preprocessor.\n" 5634 "#define A 0\n" 5635 "// Aligned to code.\n" 5636 "int b;\n" 5637 "#endif\n" 5638 "#endif\n" 5639 "}"; 5640 EXPECT_EQ(Expected, format(ToFormat, Style)); 5641 EXPECT_EQ(Expected, format(Expected, Style)); 5642 } 5643 { 5644 const char *Expected = "void f() {\n" 5645 "/* Aligned to preprocessor. */\n" 5646 "#if 1\n" 5647 " /* Aligned to code. */\n" 5648 " int a;\n" 5649 " #if 1\n" 5650 " /* Aligned to preprocessor. */\n" 5651 " #define A 0\n" 5652 " /* Aligned to code. */\n" 5653 " int b;\n" 5654 " #endif\n" 5655 "#endif\n" 5656 "}"; 5657 const char *ToFormat = "void f() {\n" 5658 "/* Aligned to preprocessor. */\n" 5659 "#if 1\n" 5660 "/* Aligned to code. */\n" 5661 "int a;\n" 5662 "#if 1\n" 5663 "/* Aligned to preprocessor. */\n" 5664 "#define A 0\n" 5665 "/* Aligned to code. */\n" 5666 "int b;\n" 5667 "#endif\n" 5668 "#endif\n" 5669 "}"; 5670 EXPECT_EQ(Expected, format(ToFormat, Style)); 5671 EXPECT_EQ(Expected, format(Expected, Style)); 5672 } 5673 5674 // Test single comment before preprocessor 5675 verifyFormat("// Comment\n" 5676 "\n" 5677 "#if 1\n" 5678 "#endif", 5679 Style); 5680 } 5681 5682 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5683 verifyFormat("{\n { a #c; }\n}"); 5684 } 5685 5686 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5687 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5688 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5689 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5690 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5691 } 5692 5693 TEST_F(FormatTest, EscapedNewlines) { 5694 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5695 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5696 format("#define A \\\nint i;\\\n int j;", Narrow)); 5697 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5698 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5699 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5700 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5701 5702 FormatStyle AlignLeft = getLLVMStyle(); 5703 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5704 EXPECT_EQ("#define MACRO(x) \\\n" 5705 "private: \\\n" 5706 " int x(int a);\n", 5707 format("#define MACRO(x) \\\n" 5708 "private: \\\n" 5709 " int x(int a);\n", 5710 AlignLeft)); 5711 5712 // CRLF line endings 5713 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5714 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5715 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5716 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5717 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5718 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5719 EXPECT_EQ("#define MACRO(x) \\\r\n" 5720 "private: \\\r\n" 5721 " int x(int a);\r\n", 5722 format("#define MACRO(x) \\\r\n" 5723 "private: \\\r\n" 5724 " int x(int a);\r\n", 5725 AlignLeft)); 5726 5727 FormatStyle DontAlign = getLLVMStyle(); 5728 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5729 DontAlign.MaxEmptyLinesToKeep = 3; 5730 // FIXME: can't use verifyFormat here because the newline before 5731 // "public:" is not inserted the first time it's reformatted 5732 EXPECT_EQ("#define A \\\n" 5733 " class Foo { \\\n" 5734 " void bar(); \\\n" 5735 "\\\n" 5736 "\\\n" 5737 "\\\n" 5738 " public: \\\n" 5739 " void baz(); \\\n" 5740 " };", 5741 format("#define A \\\n" 5742 " class Foo { \\\n" 5743 " void bar(); \\\n" 5744 "\\\n" 5745 "\\\n" 5746 "\\\n" 5747 " public: \\\n" 5748 " void baz(); \\\n" 5749 " };", 5750 DontAlign)); 5751 } 5752 5753 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5754 verifyFormat("#define A \\\n" 5755 " int v( \\\n" 5756 " a); \\\n" 5757 " int i;", 5758 getLLVMStyleWithColumns(11)); 5759 } 5760 5761 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5762 EXPECT_EQ( 5763 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5764 " \\\n" 5765 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5766 "\n" 5767 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5768 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5769 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5770 "\\\n" 5771 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5772 " \n" 5773 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5774 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5775 } 5776 5777 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5778 EXPECT_EQ("int\n" 5779 "#define A\n" 5780 " a;", 5781 format("int\n#define A\na;")); 5782 verifyFormat("functionCallTo(\n" 5783 " someOtherFunction(\n" 5784 " withSomeParameters, whichInSequence,\n" 5785 " areLongerThanALine(andAnotherCall,\n" 5786 "#define A B\n" 5787 " withMoreParamters,\n" 5788 " whichStronglyInfluenceTheLayout),\n" 5789 " andMoreParameters),\n" 5790 " trailing);", 5791 getLLVMStyleWithColumns(69)); 5792 verifyFormat("Foo::Foo()\n" 5793 "#ifdef BAR\n" 5794 " : baz(0)\n" 5795 "#endif\n" 5796 "{\n" 5797 "}"); 5798 verifyFormat("void f() {\n" 5799 " if (true)\n" 5800 "#ifdef A\n" 5801 " f(42);\n" 5802 " x();\n" 5803 "#else\n" 5804 " g();\n" 5805 " x();\n" 5806 "#endif\n" 5807 "}"); 5808 verifyFormat("void f(param1, param2,\n" 5809 " param3,\n" 5810 "#ifdef A\n" 5811 " param4(param5,\n" 5812 "#ifdef A1\n" 5813 " param6,\n" 5814 "#ifdef A2\n" 5815 " param7),\n" 5816 "#else\n" 5817 " param8),\n" 5818 " param9,\n" 5819 "#endif\n" 5820 " param10,\n" 5821 "#endif\n" 5822 " param11)\n" 5823 "#else\n" 5824 " param12)\n" 5825 "#endif\n" 5826 "{\n" 5827 " x();\n" 5828 "}", 5829 getLLVMStyleWithColumns(28)); 5830 verifyFormat("#if 1\n" 5831 "int i;"); 5832 verifyFormat("#if 1\n" 5833 "#endif\n" 5834 "#if 1\n" 5835 "#else\n" 5836 "#endif\n"); 5837 verifyFormat("DEBUG({\n" 5838 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5839 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5840 "});\n" 5841 "#if a\n" 5842 "#else\n" 5843 "#endif"); 5844 5845 verifyIncompleteFormat("void f(\n" 5846 "#if A\n" 5847 ");\n" 5848 "#else\n" 5849 "#endif"); 5850 } 5851 5852 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5853 verifyFormat("#endif\n" 5854 "#if B"); 5855 } 5856 5857 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5858 FormatStyle SingleLine = getLLVMStyle(); 5859 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5860 verifyFormat("#if 0\n" 5861 "#elif 1\n" 5862 "#endif\n" 5863 "void foo() {\n" 5864 " if (test) foo2();\n" 5865 "}", 5866 SingleLine); 5867 } 5868 5869 TEST_F(FormatTest, LayoutBlockInsideParens) { 5870 verifyFormat("functionCall({ int i; });"); 5871 verifyFormat("functionCall({\n" 5872 " int i;\n" 5873 " int j;\n" 5874 "});"); 5875 verifyFormat("functionCall(\n" 5876 " {\n" 5877 " int i;\n" 5878 " int j;\n" 5879 " },\n" 5880 " aaaa, bbbb, cccc);"); 5881 verifyFormat("functionA(functionB({\n" 5882 " int i;\n" 5883 " int j;\n" 5884 " }),\n" 5885 " aaaa, bbbb, cccc);"); 5886 verifyFormat("functionCall(\n" 5887 " {\n" 5888 " int i;\n" 5889 " int j;\n" 5890 " },\n" 5891 " aaaa, bbbb, // comment\n" 5892 " cccc);"); 5893 verifyFormat("functionA(functionB({\n" 5894 " int i;\n" 5895 " int j;\n" 5896 " }),\n" 5897 " aaaa, bbbb, // comment\n" 5898 " cccc);"); 5899 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5900 verifyFormat("functionCall(aaaa, bbbb, {\n" 5901 " int i;\n" 5902 " int j;\n" 5903 "});"); 5904 verifyFormat( 5905 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5906 " {\n" 5907 " int i; // break\n" 5908 " },\n" 5909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5910 " ccccccccccccccccc));"); 5911 verifyFormat("DEBUG({\n" 5912 " if (a)\n" 5913 " f();\n" 5914 "});"); 5915 } 5916 5917 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5918 EXPECT_EQ("SOME_MACRO { int i; }\n" 5919 "int i;", 5920 format(" SOME_MACRO {int i;} int i;")); 5921 } 5922 5923 TEST_F(FormatTest, LayoutNestedBlocks) { 5924 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5925 " struct s {\n" 5926 " int i;\n" 5927 " };\n" 5928 " s kBitsToOs[] = {{10}};\n" 5929 " for (int i = 0; i < 10; ++i)\n" 5930 " return;\n" 5931 "}"); 5932 verifyFormat("call(parameter, {\n" 5933 " something();\n" 5934 " // Comment using all columns.\n" 5935 " somethingelse();\n" 5936 "});", 5937 getLLVMStyleWithColumns(40)); 5938 verifyFormat("DEBUG( //\n" 5939 " { f(); }, a);"); 5940 verifyFormat("DEBUG( //\n" 5941 " {\n" 5942 " f(); //\n" 5943 " },\n" 5944 " a);"); 5945 5946 EXPECT_EQ("call(parameter, {\n" 5947 " something();\n" 5948 " // Comment too\n" 5949 " // looooooooooong.\n" 5950 " somethingElse();\n" 5951 "});", 5952 format("call(parameter, {\n" 5953 " something();\n" 5954 " // Comment too looooooooooong.\n" 5955 " somethingElse();\n" 5956 "});", 5957 getLLVMStyleWithColumns(29))); 5958 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5959 EXPECT_EQ("DEBUG({ // comment\n" 5960 " int i;\n" 5961 "});", 5962 format("DEBUG({ // comment\n" 5963 "int i;\n" 5964 "});")); 5965 EXPECT_EQ("DEBUG({\n" 5966 " int i;\n" 5967 "\n" 5968 " // comment\n" 5969 " int j;\n" 5970 "});", 5971 format("DEBUG({\n" 5972 " int i;\n" 5973 "\n" 5974 " // comment\n" 5975 " int j;\n" 5976 "});")); 5977 5978 verifyFormat("DEBUG({\n" 5979 " if (a)\n" 5980 " return;\n" 5981 "});"); 5982 verifyGoogleFormat("DEBUG({\n" 5983 " if (a) return;\n" 5984 "});"); 5985 FormatStyle Style = getGoogleStyle(); 5986 Style.ColumnLimit = 45; 5987 verifyFormat("Debug(\n" 5988 " aaaaa,\n" 5989 " {\n" 5990 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5991 " },\n" 5992 " a);", 5993 Style); 5994 5995 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5996 5997 verifyNoCrash("^{v^{a}}"); 5998 } 5999 6000 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6001 EXPECT_EQ("#define MACRO() \\\n" 6002 " Debug(aaa, /* force line break */ \\\n" 6003 " { \\\n" 6004 " int i; \\\n" 6005 " int j; \\\n" 6006 " })", 6007 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6008 " { int i; int j; })", 6009 getGoogleStyle())); 6010 6011 EXPECT_EQ("#define A \\\n" 6012 " [] { \\\n" 6013 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6014 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6015 " }", 6016 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6017 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6018 getGoogleStyle())); 6019 } 6020 6021 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6022 EXPECT_EQ("{}", format("{}")); 6023 verifyFormat("enum E {};"); 6024 verifyFormat("enum E {}"); 6025 FormatStyle Style = getLLVMStyle(); 6026 Style.SpaceInEmptyBlock = true; 6027 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6028 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6029 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6030 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6031 Style.BraceWrapping.BeforeElse = false; 6032 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6033 verifyFormat("if (a)\n" 6034 "{\n" 6035 "} else if (b)\n" 6036 "{\n" 6037 "} else\n" 6038 "{ }", 6039 Style); 6040 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6041 verifyFormat("if (a) {\n" 6042 "} else if (b) {\n" 6043 "} else {\n" 6044 "}", 6045 Style); 6046 Style.BraceWrapping.BeforeElse = true; 6047 verifyFormat("if (a) { }\n" 6048 "else if (b) { }\n" 6049 "else { }", 6050 Style); 6051 } 6052 6053 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6054 FormatStyle Style = getLLVMStyle(); 6055 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6056 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6057 verifyFormat("FOO_BEGIN\n" 6058 " FOO_ENTRY\n" 6059 "FOO_END", 6060 Style); 6061 verifyFormat("FOO_BEGIN\n" 6062 " NESTED_FOO_BEGIN\n" 6063 " NESTED_FOO_ENTRY\n" 6064 " NESTED_FOO_END\n" 6065 "FOO_END", 6066 Style); 6067 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6068 " int x;\n" 6069 " x = 1;\n" 6070 "FOO_END(Baz)", 6071 Style); 6072 } 6073 6074 //===----------------------------------------------------------------------===// 6075 // Line break tests. 6076 //===----------------------------------------------------------------------===// 6077 6078 TEST_F(FormatTest, PreventConfusingIndents) { 6079 verifyFormat( 6080 "void f() {\n" 6081 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6082 " parameter, parameter, parameter)),\n" 6083 " SecondLongCall(parameter));\n" 6084 "}"); 6085 verifyFormat( 6086 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6087 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6088 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6089 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6090 verifyFormat( 6091 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6092 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6093 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6094 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6095 verifyFormat( 6096 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6097 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6098 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6099 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6100 verifyFormat("int a = bbbb && ccc &&\n" 6101 " fffff(\n" 6102 "#define A Just forcing a new line\n" 6103 " ddd);"); 6104 } 6105 6106 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6107 verifyFormat( 6108 "bool aaaaaaa =\n" 6109 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6110 " bbbbbbbb();"); 6111 verifyFormat( 6112 "bool aaaaaaa =\n" 6113 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6114 " bbbbbbbb();"); 6115 6116 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6117 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6118 " ccccccccc == ddddddddddd;"); 6119 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6120 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6121 " ccccccccc == ddddddddddd;"); 6122 verifyFormat( 6123 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6125 " ccccccccc == ddddddddddd;"); 6126 6127 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6128 " aaaaaa) &&\n" 6129 " bbbbbb && cccccc;"); 6130 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6131 " aaaaaa) >>\n" 6132 " bbbbbb;"); 6133 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6134 " SourceMgr.getSpellingColumnNumber(\n" 6135 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6136 " 1);"); 6137 6138 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6139 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6140 " cccccc) {\n}"); 6141 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6142 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6143 " cccccc) {\n}"); 6144 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6145 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6146 " cccccc) {\n}"); 6147 verifyFormat("b = a &&\n" 6148 " // Comment\n" 6149 " b.c && d;"); 6150 6151 // If the LHS of a comparison is not a binary expression itself, the 6152 // additional linebreak confuses many people. 6153 verifyFormat( 6154 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6155 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6156 "}"); 6157 verifyFormat( 6158 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6160 "}"); 6161 verifyFormat( 6162 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6163 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6164 "}"); 6165 verifyFormat( 6166 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6167 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6168 "}"); 6169 // Even explicit parentheses stress the precedence enough to make the 6170 // additional break unnecessary. 6171 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6172 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6173 "}"); 6174 // This cases is borderline, but with the indentation it is still readable. 6175 verifyFormat( 6176 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6177 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6178 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6179 "}", 6180 getLLVMStyleWithColumns(75)); 6181 6182 // If the LHS is a binary expression, we should still use the additional break 6183 // as otherwise the formatting hides the operator precedence. 6184 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6185 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6186 " 5) {\n" 6187 "}"); 6188 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6189 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6190 " 5) {\n" 6191 "}"); 6192 6193 FormatStyle OnePerLine = getLLVMStyle(); 6194 OnePerLine.BinPackParameters = false; 6195 verifyFormat( 6196 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6197 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6199 OnePerLine); 6200 6201 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6202 " .aaa(aaaaaaaaaaaaa) *\n" 6203 " aaaaaaa +\n" 6204 " aaaaaaa;", 6205 getLLVMStyleWithColumns(40)); 6206 } 6207 6208 TEST_F(FormatTest, ExpressionIndentation) { 6209 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6210 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6211 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6212 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6213 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6214 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6215 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6216 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6217 " ccccccccccccccccccccccccccccccccccccccccc;"); 6218 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6219 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6220 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6221 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6222 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6224 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6225 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6226 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6227 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6229 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6230 verifyFormat("if () {\n" 6231 "} else if (aaaaa && bbbbb > // break\n" 6232 " ccccc) {\n" 6233 "}"); 6234 verifyFormat("if () {\n" 6235 "} else if constexpr (aaaaa && bbbbb > // break\n" 6236 " ccccc) {\n" 6237 "}"); 6238 verifyFormat("if () {\n" 6239 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6240 " ccccc) {\n" 6241 "}"); 6242 verifyFormat("if () {\n" 6243 "} else if (aaaaa &&\n" 6244 " bbbbb > // break\n" 6245 " ccccc &&\n" 6246 " ddddd) {\n" 6247 "}"); 6248 6249 // Presence of a trailing comment used to change indentation of b. 6250 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6251 " b;\n" 6252 "return aaaaaaaaaaaaaaaaaaa +\n" 6253 " b; //", 6254 getLLVMStyleWithColumns(30)); 6255 } 6256 6257 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6258 // Not sure what the best system is here. Like this, the LHS can be found 6259 // immediately above an operator (everything with the same or a higher 6260 // indent). The RHS is aligned right of the operator and so compasses 6261 // everything until something with the same indent as the operator is found. 6262 // FIXME: Is this a good system? 6263 FormatStyle Style = getLLVMStyle(); 6264 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6265 verifyFormat( 6266 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6267 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6268 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6269 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6270 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6271 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6272 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6273 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6274 " > ccccccccccccccccccccccccccccccccccccccccc;", 6275 Style); 6276 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6277 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6278 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6279 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6280 Style); 6281 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6282 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6283 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6284 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6285 Style); 6286 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6287 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6288 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6289 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6290 Style); 6291 verifyFormat("if () {\n" 6292 "} else if (aaaaa\n" 6293 " && bbbbb // break\n" 6294 " > ccccc) {\n" 6295 "}", 6296 Style); 6297 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6298 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6299 Style); 6300 verifyFormat("return (a)\n" 6301 " // comment\n" 6302 " + b;", 6303 Style); 6304 verifyFormat( 6305 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6306 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6307 " + cc;", 6308 Style); 6309 6310 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6311 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6312 Style); 6313 6314 // Forced by comments. 6315 verifyFormat( 6316 "unsigned ContentSize =\n" 6317 " sizeof(int16_t) // DWARF ARange version number\n" 6318 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6319 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6320 " + sizeof(int8_t); // Segment Size (in bytes)"); 6321 6322 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6323 " == boost::fusion::at_c<1>(iiii).second;", 6324 Style); 6325 6326 Style.ColumnLimit = 60; 6327 verifyFormat("zzzzzzzzzz\n" 6328 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6329 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6330 Style); 6331 6332 Style.ColumnLimit = 80; 6333 Style.IndentWidth = 4; 6334 Style.TabWidth = 4; 6335 Style.UseTab = FormatStyle::UT_Always; 6336 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6337 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6338 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6339 "\t&& (someOtherLongishConditionPart1\n" 6340 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6341 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6342 "(someOtherLongishConditionPart1 || " 6343 "someOtherEvenLongerNestedConditionPart2);", 6344 Style)); 6345 } 6346 6347 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6348 FormatStyle Style = getLLVMStyle(); 6349 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6350 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6351 6352 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6353 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6354 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6355 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6356 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6357 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6358 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6359 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6360 " > ccccccccccccccccccccccccccccccccccccccccc;", 6361 Style); 6362 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6363 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6364 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6365 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6366 Style); 6367 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6368 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6369 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6370 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6371 Style); 6372 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6373 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6374 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6375 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6376 Style); 6377 verifyFormat("if () {\n" 6378 "} else if (aaaaa\n" 6379 " && bbbbb // break\n" 6380 " > ccccc) {\n" 6381 "}", 6382 Style); 6383 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6384 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6385 Style); 6386 verifyFormat("return (a)\n" 6387 " // comment\n" 6388 " + b;", 6389 Style); 6390 verifyFormat( 6391 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6392 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6393 " + cc;", 6394 Style); 6395 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6396 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6397 " : 3333333333333333;", 6398 Style); 6399 verifyFormat( 6400 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6401 " : ccccccccccccccc ? dddddddddddddddddd\n" 6402 " : eeeeeeeeeeeeeeeeee)\n" 6403 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6404 " : 3333333333333333;", 6405 Style); 6406 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6407 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6408 Style); 6409 6410 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6411 " == boost::fusion::at_c<1>(iiii).second;", 6412 Style); 6413 6414 Style.ColumnLimit = 60; 6415 verifyFormat("zzzzzzzzzzzzz\n" 6416 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6417 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6418 Style); 6419 6420 // Forced by comments. 6421 Style.ColumnLimit = 80; 6422 verifyFormat( 6423 "unsigned ContentSize\n" 6424 " = sizeof(int16_t) // DWARF ARange version number\n" 6425 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6426 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6427 " + sizeof(int8_t); // Segment Size (in bytes)", 6428 Style); 6429 6430 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6431 verifyFormat( 6432 "unsigned ContentSize =\n" 6433 " sizeof(int16_t) // DWARF ARange version number\n" 6434 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6435 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6436 " + sizeof(int8_t); // Segment Size (in bytes)", 6437 Style); 6438 6439 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6440 verifyFormat( 6441 "unsigned ContentSize =\n" 6442 " sizeof(int16_t) // DWARF ARange version number\n" 6443 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6444 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6445 " + sizeof(int8_t); // Segment Size (in bytes)", 6446 Style); 6447 } 6448 6449 TEST_F(FormatTest, EnforcedOperatorWraps) { 6450 // Here we'd like to wrap after the || operators, but a comment is forcing an 6451 // earlier wrap. 6452 verifyFormat("bool x = aaaaa //\n" 6453 " || bbbbb\n" 6454 " //\n" 6455 " || cccc;"); 6456 } 6457 6458 TEST_F(FormatTest, NoOperandAlignment) { 6459 FormatStyle Style = getLLVMStyle(); 6460 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6461 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6462 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6464 Style); 6465 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6466 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6467 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6468 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6469 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6470 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6471 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6472 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6473 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6474 " > ccccccccccccccccccccccccccccccccccccccccc;", 6475 Style); 6476 6477 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6478 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6479 " + cc;", 6480 Style); 6481 verifyFormat("int a = aa\n" 6482 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6483 " * cccccccccccccccccccccccccccccccccccc;\n", 6484 Style); 6485 6486 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6487 verifyFormat("return (a > b\n" 6488 " // comment1\n" 6489 " // comment2\n" 6490 " || c);", 6491 Style); 6492 } 6493 6494 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6495 FormatStyle Style = getLLVMStyle(); 6496 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6497 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6498 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6499 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6500 Style); 6501 } 6502 6503 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6504 FormatStyle Style = getLLVMStyleWithColumns(40); 6505 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6506 Style.BinPackArguments = false; 6507 verifyFormat("void test() {\n" 6508 " someFunction(\n" 6509 " this + argument + is + quite\n" 6510 " + long + so + it + gets + wrapped\n" 6511 " + but + remains + bin - packed);\n" 6512 "}", 6513 Style); 6514 verifyFormat("void test() {\n" 6515 " someFunction(arg1,\n" 6516 " this + argument + is\n" 6517 " + quite + long + so\n" 6518 " + it + gets + wrapped\n" 6519 " + but + remains + bin\n" 6520 " - packed,\n" 6521 " arg3);\n" 6522 "}", 6523 Style); 6524 verifyFormat("void test() {\n" 6525 " someFunction(\n" 6526 " arg1,\n" 6527 " this + argument + has\n" 6528 " + anotherFunc(nested,\n" 6529 " calls + whose\n" 6530 " + arguments\n" 6531 " + are + also\n" 6532 " + wrapped,\n" 6533 " in + addition)\n" 6534 " + to + being + bin - packed,\n" 6535 " arg3);\n" 6536 "}", 6537 Style); 6538 6539 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6540 verifyFormat("void test() {\n" 6541 " someFunction(\n" 6542 " arg1,\n" 6543 " this + argument + has +\n" 6544 " anotherFunc(nested,\n" 6545 " calls + whose +\n" 6546 " arguments +\n" 6547 " are + also +\n" 6548 " wrapped,\n" 6549 " in + addition) +\n" 6550 " to + being + bin - packed,\n" 6551 " arg3);\n" 6552 "}", 6553 Style); 6554 } 6555 6556 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6557 auto Style = getLLVMStyleWithColumns(45); 6558 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6559 verifyFormat("bool b =\n" 6560 " is_default_constructible_v<hash<T>> and\n" 6561 " is_copy_constructible_v<hash<T>> and\n" 6562 " is_move_constructible_v<hash<T>> and\n" 6563 " is_copy_assignable_v<hash<T>> and\n" 6564 " is_move_assignable_v<hash<T>> and\n" 6565 " is_destructible_v<hash<T>> and\n" 6566 " is_swappable_v<hash<T>> and\n" 6567 " is_callable_v<hash<T>(T)>;", 6568 Style); 6569 6570 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6571 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6572 " and is_copy_constructible_v<hash<T>>\n" 6573 " and is_move_constructible_v<hash<T>>\n" 6574 " and is_copy_assignable_v<hash<T>>\n" 6575 " and is_move_assignable_v<hash<T>>\n" 6576 " and is_destructible_v<hash<T>>\n" 6577 " and is_swappable_v<hash<T>>\n" 6578 " and is_callable_v<hash<T>(T)>;", 6579 Style); 6580 6581 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6582 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6583 " and is_copy_constructible_v<hash<T>>\n" 6584 " and is_move_constructible_v<hash<T>>\n" 6585 " and is_copy_assignable_v<hash<T>>\n" 6586 " and is_move_assignable_v<hash<T>>\n" 6587 " and is_destructible_v<hash<T>>\n" 6588 " and is_swappable_v<hash<T>>\n" 6589 " and is_callable_v<hash<T>(T)>;", 6590 Style); 6591 } 6592 6593 TEST_F(FormatTest, ConstructorInitializers) { 6594 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6595 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6596 getLLVMStyleWithColumns(45)); 6597 verifyFormat("Constructor()\n" 6598 " : Inttializer(FitsOnTheLine) {}", 6599 getLLVMStyleWithColumns(44)); 6600 verifyFormat("Constructor()\n" 6601 " : Inttializer(FitsOnTheLine) {}", 6602 getLLVMStyleWithColumns(43)); 6603 6604 verifyFormat("template <typename T>\n" 6605 "Constructor() : Initializer(FitsOnTheLine) {}", 6606 getLLVMStyleWithColumns(45)); 6607 6608 verifyFormat( 6609 "SomeClass::Constructor()\n" 6610 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6611 6612 verifyFormat( 6613 "SomeClass::Constructor()\n" 6614 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6615 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6616 verifyFormat( 6617 "SomeClass::Constructor()\n" 6618 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6619 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6620 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6621 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6622 " : aaaaaaaaaa(aaaaaa) {}"); 6623 6624 verifyFormat("Constructor()\n" 6625 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6626 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6627 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6628 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6629 6630 verifyFormat("Constructor()\n" 6631 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6632 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6633 6634 verifyFormat("Constructor(int Parameter = 0)\n" 6635 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6636 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6637 verifyFormat("Constructor()\n" 6638 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6639 "}", 6640 getLLVMStyleWithColumns(60)); 6641 verifyFormat("Constructor()\n" 6642 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6643 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6644 6645 // Here a line could be saved by splitting the second initializer onto two 6646 // lines, but that is not desirable. 6647 verifyFormat("Constructor()\n" 6648 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6649 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6650 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6651 6652 FormatStyle OnePerLine = getLLVMStyle(); 6653 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6654 verifyFormat("MyClass::MyClass()\n" 6655 " : a(a),\n" 6656 " b(b),\n" 6657 " c(c) {}", 6658 OnePerLine); 6659 verifyFormat("MyClass::MyClass()\n" 6660 " : a(a), // comment\n" 6661 " b(b),\n" 6662 " c(c) {}", 6663 OnePerLine); 6664 verifyFormat("MyClass::MyClass(int a)\n" 6665 " : b(a), // comment\n" 6666 " c(a + 1) { // lined up\n" 6667 "}", 6668 OnePerLine); 6669 verifyFormat("Constructor()\n" 6670 " : a(b, b, b) {}", 6671 OnePerLine); 6672 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6673 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6674 verifyFormat("SomeClass::Constructor()\n" 6675 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6676 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6677 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6678 OnePerLine); 6679 verifyFormat("SomeClass::Constructor()\n" 6680 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6681 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6682 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6683 OnePerLine); 6684 verifyFormat("MyClass::MyClass(int var)\n" 6685 " : some_var_(var), // 4 space indent\n" 6686 " some_other_var_(var + 1) { // lined up\n" 6687 "}", 6688 OnePerLine); 6689 verifyFormat("Constructor()\n" 6690 " : aaaaa(aaaaaa),\n" 6691 " aaaaa(aaaaaa),\n" 6692 " aaaaa(aaaaaa),\n" 6693 " aaaaa(aaaaaa),\n" 6694 " aaaaa(aaaaaa) {}", 6695 OnePerLine); 6696 verifyFormat("Constructor()\n" 6697 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6698 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6699 OnePerLine); 6700 OnePerLine.BinPackParameters = false; 6701 verifyFormat( 6702 "Constructor()\n" 6703 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6704 " aaaaaaaaaaa().aaa(),\n" 6705 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6706 OnePerLine); 6707 OnePerLine.ColumnLimit = 60; 6708 verifyFormat("Constructor()\n" 6709 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6710 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6711 OnePerLine); 6712 6713 EXPECT_EQ("Constructor()\n" 6714 " : // Comment forcing unwanted break.\n" 6715 " aaaa(aaaa) {}", 6716 format("Constructor() :\n" 6717 " // Comment forcing unwanted break.\n" 6718 " aaaa(aaaa) {}")); 6719 } 6720 6721 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6722 FormatStyle Style = getLLVMStyleWithColumns(60); 6723 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6724 Style.BinPackParameters = false; 6725 6726 for (int i = 0; i < 4; ++i) { 6727 // Test all combinations of parameters that should not have an effect. 6728 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6729 Style.AllowAllArgumentsOnNextLine = i & 2; 6730 6731 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6732 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6733 verifyFormat("Constructor()\n" 6734 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6735 Style); 6736 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6737 6738 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6739 verifyFormat("Constructor()\n" 6740 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6741 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6742 Style); 6743 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6744 6745 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6746 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6747 verifyFormat("Constructor()\n" 6748 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6749 Style); 6750 6751 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6752 verifyFormat("Constructor()\n" 6753 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6754 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6755 Style); 6756 6757 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6758 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6759 verifyFormat("Constructor() :\n" 6760 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6761 Style); 6762 6763 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6764 verifyFormat("Constructor() :\n" 6765 " aaaaaaaaaaaaaaaaaa(a),\n" 6766 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6767 Style); 6768 } 6769 6770 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6771 // AllowAllConstructorInitializersOnNextLine in all 6772 // BreakConstructorInitializers modes 6773 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6774 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6775 verifyFormat("SomeClassWithALongName::Constructor(\n" 6776 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6777 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6778 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6779 Style); 6780 6781 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6782 verifyFormat("SomeClassWithALongName::Constructor(\n" 6783 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6784 " int bbbbbbbbbbbbb,\n" 6785 " int cccccccccccccccc)\n" 6786 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6787 Style); 6788 6789 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6790 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6791 verifyFormat("SomeClassWithALongName::Constructor(\n" 6792 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6793 " int bbbbbbbbbbbbb)\n" 6794 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6795 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6796 Style); 6797 6798 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6799 6800 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6801 verifyFormat("SomeClassWithALongName::Constructor(\n" 6802 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6803 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6804 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6805 Style); 6806 6807 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6808 verifyFormat("SomeClassWithALongName::Constructor(\n" 6809 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6810 " int bbbbbbbbbbbbb,\n" 6811 " int cccccccccccccccc)\n" 6812 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6813 Style); 6814 6815 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6816 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6817 verifyFormat("SomeClassWithALongName::Constructor(\n" 6818 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6819 " int bbbbbbbbbbbbb)\n" 6820 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6821 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6822 Style); 6823 6824 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6825 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6826 verifyFormat("SomeClassWithALongName::Constructor(\n" 6827 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6828 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6829 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6830 Style); 6831 6832 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6833 verifyFormat("SomeClassWithALongName::Constructor(\n" 6834 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6835 " int bbbbbbbbbbbbb,\n" 6836 " int cccccccccccccccc) :\n" 6837 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6838 Style); 6839 6840 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6841 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6842 verifyFormat("SomeClassWithALongName::Constructor(\n" 6843 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6844 " int bbbbbbbbbbbbb) :\n" 6845 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6846 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6847 Style); 6848 } 6849 6850 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6851 FormatStyle Style = getLLVMStyleWithColumns(60); 6852 Style.BinPackArguments = false; 6853 for (int i = 0; i < 4; ++i) { 6854 // Test all combinations of parameters that should not have an effect. 6855 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6856 Style.PackConstructorInitializers = 6857 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6858 6859 Style.AllowAllArgumentsOnNextLine = true; 6860 verifyFormat("void foo() {\n" 6861 " FunctionCallWithReallyLongName(\n" 6862 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6863 "}", 6864 Style); 6865 Style.AllowAllArgumentsOnNextLine = false; 6866 verifyFormat("void foo() {\n" 6867 " FunctionCallWithReallyLongName(\n" 6868 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6869 " bbbbbbbbbbbb);\n" 6870 "}", 6871 Style); 6872 6873 Style.AllowAllArgumentsOnNextLine = true; 6874 verifyFormat("void foo() {\n" 6875 " auto VariableWithReallyLongName = {\n" 6876 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6877 "}", 6878 Style); 6879 Style.AllowAllArgumentsOnNextLine = false; 6880 verifyFormat("void foo() {\n" 6881 " auto VariableWithReallyLongName = {\n" 6882 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6883 " bbbbbbbbbbbb};\n" 6884 "}", 6885 Style); 6886 } 6887 6888 // This parameter should not affect declarations. 6889 Style.BinPackParameters = false; 6890 Style.AllowAllArgumentsOnNextLine = false; 6891 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6892 verifyFormat("void FunctionCallWithReallyLongName(\n" 6893 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6894 Style); 6895 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6896 verifyFormat("void FunctionCallWithReallyLongName(\n" 6897 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6898 " int bbbbbbbbbbbb);", 6899 Style); 6900 } 6901 6902 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6903 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6904 // and BAS_Align. 6905 FormatStyle Style = getLLVMStyleWithColumns(35); 6906 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6907 "void functionDecl(int A, int B, int C);"; 6908 Style.AllowAllArgumentsOnNextLine = false; 6909 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6910 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6911 " paramC);\n" 6912 "void functionDecl(int A, int B,\n" 6913 " int C);"), 6914 format(Input, Style)); 6915 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6916 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6917 " paramC);\n" 6918 "void functionDecl(int A, int B,\n" 6919 " int C);"), 6920 format(Input, Style)); 6921 // However, BAS_AlwaysBreak should take precedence over 6922 // AllowAllArgumentsOnNextLine. 6923 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6924 EXPECT_EQ(StringRef("functionCall(\n" 6925 " paramA, paramB, paramC);\n" 6926 "void functionDecl(\n" 6927 " int A, int B, int C);"), 6928 format(Input, Style)); 6929 6930 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6931 // first argument. 6932 Style.AllowAllArgumentsOnNextLine = true; 6933 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6934 EXPECT_EQ(StringRef("functionCall(\n" 6935 " paramA, paramB, paramC);\n" 6936 "void functionDecl(\n" 6937 " int A, int B, int C);"), 6938 format(Input, Style)); 6939 // It wouldn't fit on one line with aligned parameters so this setting 6940 // doesn't change anything for BAS_Align. 6941 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6942 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6943 " paramC);\n" 6944 "void functionDecl(int A, int B,\n" 6945 " int C);"), 6946 format(Input, Style)); 6947 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6948 EXPECT_EQ(StringRef("functionCall(\n" 6949 " paramA, paramB, paramC);\n" 6950 "void functionDecl(\n" 6951 " int A, int B, int C);"), 6952 format(Input, Style)); 6953 } 6954 6955 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6956 FormatStyle Style = getLLVMStyle(); 6957 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6958 6959 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6960 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6961 getStyleWithColumns(Style, 45)); 6962 verifyFormat("Constructor() :\n" 6963 " Initializer(FitsOnTheLine) {}", 6964 getStyleWithColumns(Style, 44)); 6965 verifyFormat("Constructor() :\n" 6966 " Initializer(FitsOnTheLine) {}", 6967 getStyleWithColumns(Style, 43)); 6968 6969 verifyFormat("template <typename T>\n" 6970 "Constructor() : Initializer(FitsOnTheLine) {}", 6971 getStyleWithColumns(Style, 50)); 6972 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6973 verifyFormat( 6974 "SomeClass::Constructor() :\n" 6975 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6976 Style); 6977 6978 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6979 verifyFormat( 6980 "SomeClass::Constructor() :\n" 6981 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6982 Style); 6983 6984 verifyFormat( 6985 "SomeClass::Constructor() :\n" 6986 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6987 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6988 Style); 6989 verifyFormat( 6990 "SomeClass::Constructor() :\n" 6991 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6992 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6993 Style); 6994 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6995 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6996 " aaaaaaaaaa(aaaaaa) {}", 6997 Style); 6998 6999 verifyFormat("Constructor() :\n" 7000 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7001 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7002 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7003 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7004 Style); 7005 7006 verifyFormat("Constructor() :\n" 7007 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7008 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7009 Style); 7010 7011 verifyFormat("Constructor(int Parameter = 0) :\n" 7012 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7013 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7014 Style); 7015 verifyFormat("Constructor() :\n" 7016 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7017 "}", 7018 getStyleWithColumns(Style, 60)); 7019 verifyFormat("Constructor() :\n" 7020 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7021 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7022 Style); 7023 7024 // Here a line could be saved by splitting the second initializer onto two 7025 // lines, but that is not desirable. 7026 verifyFormat("Constructor() :\n" 7027 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7028 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7029 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7030 Style); 7031 7032 FormatStyle OnePerLine = Style; 7033 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7034 verifyFormat("SomeClass::Constructor() :\n" 7035 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7036 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7037 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7038 OnePerLine); 7039 verifyFormat("SomeClass::Constructor() :\n" 7040 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7041 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7042 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7043 OnePerLine); 7044 verifyFormat("MyClass::MyClass(int var) :\n" 7045 " some_var_(var), // 4 space indent\n" 7046 " some_other_var_(var + 1) { // lined up\n" 7047 "}", 7048 OnePerLine); 7049 verifyFormat("Constructor() :\n" 7050 " aaaaa(aaaaaa),\n" 7051 " aaaaa(aaaaaa),\n" 7052 " aaaaa(aaaaaa),\n" 7053 " aaaaa(aaaaaa),\n" 7054 " aaaaa(aaaaaa) {}", 7055 OnePerLine); 7056 verifyFormat("Constructor() :\n" 7057 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7058 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7059 OnePerLine); 7060 OnePerLine.BinPackParameters = false; 7061 verifyFormat("Constructor() :\n" 7062 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7063 " aaaaaaaaaaa().aaa(),\n" 7064 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7065 OnePerLine); 7066 OnePerLine.ColumnLimit = 60; 7067 verifyFormat("Constructor() :\n" 7068 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7069 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7070 OnePerLine); 7071 7072 EXPECT_EQ("Constructor() :\n" 7073 " // Comment forcing unwanted break.\n" 7074 " aaaa(aaaa) {}", 7075 format("Constructor() :\n" 7076 " // Comment forcing unwanted break.\n" 7077 " aaaa(aaaa) {}", 7078 Style)); 7079 7080 Style.ColumnLimit = 0; 7081 verifyFormat("SomeClass::Constructor() :\n" 7082 " a(a) {}", 7083 Style); 7084 verifyFormat("SomeClass::Constructor() noexcept :\n" 7085 " a(a) {}", 7086 Style); 7087 verifyFormat("SomeClass::Constructor() :\n" 7088 " a(a), b(b), c(c) {}", 7089 Style); 7090 verifyFormat("SomeClass::Constructor() :\n" 7091 " a(a) {\n" 7092 " foo();\n" 7093 " bar();\n" 7094 "}", 7095 Style); 7096 7097 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7098 verifyFormat("SomeClass::Constructor() :\n" 7099 " a(a), b(b), c(c) {\n" 7100 "}", 7101 Style); 7102 verifyFormat("SomeClass::Constructor() :\n" 7103 " a(a) {\n" 7104 "}", 7105 Style); 7106 7107 Style.ColumnLimit = 80; 7108 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7109 Style.ConstructorInitializerIndentWidth = 2; 7110 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7111 verifyFormat("SomeClass::Constructor() :\n" 7112 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7113 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7114 Style); 7115 7116 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7117 // well 7118 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7119 verifyFormat( 7120 "class SomeClass\n" 7121 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7122 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7123 Style); 7124 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7125 verifyFormat( 7126 "class SomeClass\n" 7127 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7128 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7129 Style); 7130 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7131 verifyFormat( 7132 "class SomeClass :\n" 7133 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7134 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7135 Style); 7136 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7137 verifyFormat( 7138 "class SomeClass\n" 7139 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7140 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7141 Style); 7142 } 7143 7144 #ifndef EXPENSIVE_CHECKS 7145 // Expensive checks enables libstdc++ checking which includes validating the 7146 // state of ranges used in std::priority_queue - this blows out the 7147 // runtime/scalability of the function and makes this test unacceptably slow. 7148 TEST_F(FormatTest, MemoizationTests) { 7149 // This breaks if the memoization lookup does not take \c Indent and 7150 // \c LastSpace into account. 7151 verifyFormat( 7152 "extern CFRunLoopTimerRef\n" 7153 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7154 " CFTimeInterval interval, CFOptionFlags flags,\n" 7155 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7156 " CFRunLoopTimerContext *context) {}"); 7157 7158 // Deep nesting somewhat works around our memoization. 7159 verifyFormat( 7160 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7161 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7162 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7163 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7164 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7165 getLLVMStyleWithColumns(65)); 7166 verifyFormat( 7167 "aaaaa(\n" 7168 " aaaaa,\n" 7169 " aaaaa(\n" 7170 " aaaaa,\n" 7171 " aaaaa(\n" 7172 " aaaaa,\n" 7173 " aaaaa(\n" 7174 " aaaaa,\n" 7175 " aaaaa(\n" 7176 " aaaaa,\n" 7177 " aaaaa(\n" 7178 " aaaaa,\n" 7179 " aaaaa(\n" 7180 " aaaaa,\n" 7181 " aaaaa(\n" 7182 " aaaaa,\n" 7183 " aaaaa(\n" 7184 " aaaaa,\n" 7185 " aaaaa(\n" 7186 " aaaaa,\n" 7187 " aaaaa(\n" 7188 " aaaaa,\n" 7189 " aaaaa(\n" 7190 " aaaaa,\n" 7191 " aaaaa))))))))))));", 7192 getLLVMStyleWithColumns(65)); 7193 verifyFormat( 7194 "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n" 7195 " a),\n" 7196 " a),\n" 7197 " a),\n" 7198 " a),\n" 7199 " a),\n" 7200 " a),\n" 7201 " a),\n" 7202 " a),\n" 7203 " a),\n" 7204 " a),\n" 7205 " a),\n" 7206 " a),\n" 7207 " a),\n" 7208 " a),\n" 7209 " a),\n" 7210 " a),\n" 7211 " a)", 7212 getLLVMStyleWithColumns(65)); 7213 7214 // This test takes VERY long when memoization is broken. 7215 FormatStyle OnePerLine = getLLVMStyle(); 7216 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7217 OnePerLine.BinPackParameters = false; 7218 std::string input = "Constructor()\n" 7219 " : aaaa(a,\n"; 7220 for (unsigned i = 0, e = 80; i != e; ++i) { 7221 input += " a,\n"; 7222 } 7223 input += " a) {}"; 7224 verifyFormat(input, OnePerLine); 7225 } 7226 #endif 7227 7228 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7229 verifyFormat( 7230 "void f() {\n" 7231 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7232 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7233 " f();\n" 7234 "}"); 7235 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7236 " Intervals[i - 1].getRange().getLast()) {\n}"); 7237 } 7238 7239 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7240 // Principially, we break function declarations in a certain order: 7241 // 1) break amongst arguments. 7242 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7243 " Cccccccccccccc cccccccccccccc);"); 7244 verifyFormat("template <class TemplateIt>\n" 7245 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7246 " TemplateIt *stop) {}"); 7247 7248 // 2) break after return type. 7249 verifyFormat( 7250 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7251 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7252 getGoogleStyle()); 7253 7254 // 3) break after (. 7255 verifyFormat( 7256 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7257 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7258 getGoogleStyle()); 7259 7260 // 4) break before after nested name specifiers. 7261 verifyFormat( 7262 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7263 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7264 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7265 getGoogleStyle()); 7266 7267 // However, there are exceptions, if a sufficient amount of lines can be 7268 // saved. 7269 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7270 // more adjusting. 7271 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7272 " Cccccccccccccc cccccccccc,\n" 7273 " Cccccccccccccc cccccccccc,\n" 7274 " Cccccccccccccc cccccccccc,\n" 7275 " Cccccccccccccc cccccccccc);"); 7276 verifyFormat( 7277 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7278 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7279 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7280 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7281 getGoogleStyle()); 7282 verifyFormat( 7283 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7284 " Cccccccccccccc cccccccccc,\n" 7285 " Cccccccccccccc cccccccccc,\n" 7286 " Cccccccccccccc cccccccccc,\n" 7287 " Cccccccccccccc cccccccccc,\n" 7288 " Cccccccccccccc cccccccccc,\n" 7289 " Cccccccccccccc cccccccccc);"); 7290 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7291 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7292 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7293 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7294 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7295 7296 // Break after multi-line parameters. 7297 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7298 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7299 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7300 " bbbb bbbb);"); 7301 verifyFormat("void SomeLoooooooooooongFunction(\n" 7302 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7303 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7304 " int bbbbbbbbbbbbb);"); 7305 7306 // Treat overloaded operators like other functions. 7307 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7308 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7309 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7310 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7311 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7312 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7313 verifyGoogleFormat( 7314 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7315 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7316 verifyGoogleFormat( 7317 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7318 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7319 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7320 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7321 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7322 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7323 verifyGoogleFormat( 7324 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7325 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7326 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7327 verifyGoogleFormat("template <typename T>\n" 7328 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7329 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7330 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7331 7332 FormatStyle Style = getLLVMStyle(); 7333 Style.PointerAlignment = FormatStyle::PAS_Left; 7334 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7335 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7336 Style); 7337 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7338 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7339 Style); 7340 } 7341 7342 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7343 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7344 // Prefer keeping `::` followed by `operator` together. 7345 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7346 "ccccccccc::operator++() {\n" 7347 " stuff();\n" 7348 "}", 7349 format("const aaaa::bbbbbbb\n" 7350 "&ccccccccc::operator++() { stuff(); }", 7351 getLLVMStyleWithColumns(40))); 7352 } 7353 7354 TEST_F(FormatTest, TrailingReturnType) { 7355 verifyFormat("auto foo() -> int;\n"); 7356 // correct trailing return type spacing 7357 verifyFormat("auto operator->() -> int;\n"); 7358 verifyFormat("auto operator++(int) -> int;\n"); 7359 7360 verifyFormat("struct S {\n" 7361 " auto bar() const -> int;\n" 7362 "};"); 7363 verifyFormat("template <size_t Order, typename T>\n" 7364 "auto load_img(const std::string &filename)\n" 7365 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7366 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7367 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7368 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7369 verifyFormat("template <typename T>\n" 7370 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7371 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7372 7373 // Not trailing return types. 7374 verifyFormat("void f() { auto a = b->c(); }"); 7375 verifyFormat("auto a = p->foo();"); 7376 verifyFormat("int a = p->foo();"); 7377 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7378 } 7379 7380 TEST_F(FormatTest, DeductionGuides) { 7381 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7382 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7383 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7384 verifyFormat( 7385 "template <class... T>\n" 7386 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7387 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7388 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7389 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7390 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7391 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7392 verifyFormat("template <class T> x() -> x<1>;"); 7393 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7394 7395 // Ensure not deduction guides. 7396 verifyFormat("c()->f<int>();"); 7397 verifyFormat("x()->foo<1>;"); 7398 verifyFormat("x = p->foo<3>();"); 7399 verifyFormat("x()->x<1>();"); 7400 verifyFormat("x()->x<1>;"); 7401 } 7402 7403 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7404 // Avoid breaking before trailing 'const' or other trailing annotations, if 7405 // they are not function-like. 7406 FormatStyle Style = getGoogleStyleWithColumns(47); 7407 verifyFormat("void someLongFunction(\n" 7408 " int someLoooooooooooooongParameter) const {\n}", 7409 getLLVMStyleWithColumns(47)); 7410 verifyFormat("LoooooongReturnType\n" 7411 "someLoooooooongFunction() const {}", 7412 getLLVMStyleWithColumns(47)); 7413 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7414 " const {}", 7415 Style); 7416 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7417 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7418 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7419 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7420 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7421 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7422 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7423 " aaaaaaaaaaa aaaaa) const override;"); 7424 verifyGoogleFormat( 7425 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7426 " const override;"); 7427 7428 // Even if the first parameter has to be wrapped. 7429 verifyFormat("void someLongFunction(\n" 7430 " int someLongParameter) const {}", 7431 getLLVMStyleWithColumns(46)); 7432 verifyFormat("void someLongFunction(\n" 7433 " int someLongParameter) const {}", 7434 Style); 7435 verifyFormat("void someLongFunction(\n" 7436 " int someLongParameter) override {}", 7437 Style); 7438 verifyFormat("void someLongFunction(\n" 7439 " int someLongParameter) OVERRIDE {}", 7440 Style); 7441 verifyFormat("void someLongFunction(\n" 7442 " int someLongParameter) final {}", 7443 Style); 7444 verifyFormat("void someLongFunction(\n" 7445 " int someLongParameter) FINAL {}", 7446 Style); 7447 verifyFormat("void someLongFunction(\n" 7448 " int parameter) const override {}", 7449 Style); 7450 7451 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7452 verifyFormat("void someLongFunction(\n" 7453 " int someLongParameter) const\n" 7454 "{\n" 7455 "}", 7456 Style); 7457 7458 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7459 verifyFormat("void someLongFunction(\n" 7460 " int someLongParameter) const\n" 7461 " {\n" 7462 " }", 7463 Style); 7464 7465 // Unless these are unknown annotations. 7466 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7467 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7468 " LONG_AND_UGLY_ANNOTATION;"); 7469 7470 // Breaking before function-like trailing annotations is fine to keep them 7471 // close to their arguments. 7472 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7473 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7474 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7475 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7476 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7477 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7478 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7479 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7480 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7481 7482 verifyFormat( 7483 "void aaaaaaaaaaaaaaaaaa()\n" 7484 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7485 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7486 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7487 " __attribute__((unused));"); 7488 verifyGoogleFormat( 7489 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7490 " GUARDED_BY(aaaaaaaaaaaa);"); 7491 verifyGoogleFormat( 7492 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7493 " GUARDED_BY(aaaaaaaaaaaa);"); 7494 verifyGoogleFormat( 7495 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7496 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7497 verifyGoogleFormat( 7498 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7499 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7500 } 7501 7502 TEST_F(FormatTest, FunctionAnnotations) { 7503 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7504 "int OldFunction(const string ¶meter) {}"); 7505 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7506 "string OldFunction(const string ¶meter) {}"); 7507 verifyFormat("template <typename T>\n" 7508 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7509 "string OldFunction(const string ¶meter) {}"); 7510 7511 // Not function annotations. 7512 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7513 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7514 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7515 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7516 verifyFormat("MACRO(abc).function() // wrap\n" 7517 " << abc;"); 7518 verifyFormat("MACRO(abc)->function() // wrap\n" 7519 " << abc;"); 7520 verifyFormat("MACRO(abc)::function() // wrap\n" 7521 " << abc;"); 7522 } 7523 7524 TEST_F(FormatTest, BreaksDesireably) { 7525 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7526 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7527 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7528 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7529 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7530 "}"); 7531 7532 verifyFormat( 7533 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7534 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7535 7536 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7537 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7538 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7539 7540 verifyFormat( 7541 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7542 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7543 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7544 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7545 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7546 7547 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7548 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7549 7550 verifyFormat( 7551 "void f() {\n" 7552 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7553 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7554 "}"); 7555 verifyFormat( 7556 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7557 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7558 verifyFormat( 7559 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7560 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7561 verifyFormat( 7562 "aaaaaa(aaa,\n" 7563 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7564 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7565 " aaaa);"); 7566 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7567 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7568 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7569 7570 // Indent consistently independent of call expression and unary operator. 7571 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7572 " dddddddddddddddddddddddddddddd));"); 7573 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7574 " dddddddddddddddddddddddddddddd));"); 7575 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7576 " dddddddddddddddddddddddddddddd));"); 7577 7578 // This test case breaks on an incorrect memoization, i.e. an optimization not 7579 // taking into account the StopAt value. 7580 verifyFormat( 7581 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7582 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7583 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7584 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7585 7586 verifyFormat("{\n {\n {\n" 7587 " Annotation.SpaceRequiredBefore =\n" 7588 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7589 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7590 " }\n }\n}"); 7591 7592 // Break on an outer level if there was a break on an inner level. 7593 EXPECT_EQ("f(g(h(a, // comment\n" 7594 " b, c),\n" 7595 " d, e),\n" 7596 " x, y);", 7597 format("f(g(h(a, // comment\n" 7598 " b, c), d, e), x, y);")); 7599 7600 // Prefer breaking similar line breaks. 7601 verifyFormat( 7602 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7603 " NSTrackingMouseEnteredAndExited |\n" 7604 " NSTrackingActiveAlways;"); 7605 } 7606 7607 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7608 FormatStyle NoBinPacking = getGoogleStyle(); 7609 NoBinPacking.BinPackParameters = false; 7610 NoBinPacking.BinPackArguments = true; 7611 verifyFormat("void f() {\n" 7612 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7613 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7614 "}", 7615 NoBinPacking); 7616 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7617 " int aaaaaaaaaaaaaaaaaaaa,\n" 7618 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7619 NoBinPacking); 7620 7621 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7622 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7623 " vector<int> bbbbbbbbbbbbbbb);", 7624 NoBinPacking); 7625 // FIXME: This behavior difference is probably not wanted. However, currently 7626 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7627 // template arguments from BreakBeforeParameter being set because of the 7628 // one-per-line formatting. 7629 verifyFormat( 7630 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7631 " aaaaaaaaaa> aaaaaaaaaa);", 7632 NoBinPacking); 7633 verifyFormat( 7634 "void fffffffffff(\n" 7635 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7636 " aaaaaaaaaa);"); 7637 } 7638 7639 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7640 FormatStyle NoBinPacking = getGoogleStyle(); 7641 NoBinPacking.BinPackParameters = false; 7642 NoBinPacking.BinPackArguments = false; 7643 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7644 " aaaaaaaaaaaaaaaaaaaa,\n" 7645 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7646 NoBinPacking); 7647 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7648 " aaaaaaaaaaaaa,\n" 7649 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7650 NoBinPacking); 7651 verifyFormat( 7652 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7653 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7654 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7655 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7656 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7657 NoBinPacking); 7658 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7659 " .aaaaaaaaaaaaaaaaaa();", 7660 NoBinPacking); 7661 verifyFormat("void f() {\n" 7662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7663 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7664 "}", 7665 NoBinPacking); 7666 7667 verifyFormat( 7668 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7669 " aaaaaaaaaaaa,\n" 7670 " aaaaaaaaaaaa);", 7671 NoBinPacking); 7672 verifyFormat( 7673 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7674 " ddddddddddddddddddddddddddddd),\n" 7675 " test);", 7676 NoBinPacking); 7677 7678 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7679 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7680 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7681 " aaaaaaaaaaaaaaaaaa;", 7682 NoBinPacking); 7683 verifyFormat("a(\"a\"\n" 7684 " \"a\",\n" 7685 " a);"); 7686 7687 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7688 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7689 " aaaaaaaaa,\n" 7690 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7691 NoBinPacking); 7692 verifyFormat( 7693 "void f() {\n" 7694 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7695 " .aaaaaaa();\n" 7696 "}", 7697 NoBinPacking); 7698 verifyFormat( 7699 "template <class SomeType, class SomeOtherType>\n" 7700 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7701 NoBinPacking); 7702 } 7703 7704 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7705 FormatStyle Style = getLLVMStyleWithColumns(15); 7706 Style.ExperimentalAutoDetectBinPacking = true; 7707 EXPECT_EQ("aaa(aaaa,\n" 7708 " aaaa,\n" 7709 " aaaa);\n" 7710 "aaa(aaaa,\n" 7711 " aaaa,\n" 7712 " aaaa);", 7713 format("aaa(aaaa,\n" // one-per-line 7714 " aaaa,\n" 7715 " aaaa );\n" 7716 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7717 Style)); 7718 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7719 " aaaa);\n" 7720 "aaa(aaaa, aaaa,\n" 7721 " aaaa);", 7722 format("aaa(aaaa, aaaa,\n" // bin-packed 7723 " aaaa );\n" 7724 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7725 Style)); 7726 } 7727 7728 TEST_F(FormatTest, FormatsBuilderPattern) { 7729 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7730 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7731 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7732 " .StartsWith(\".init\", ORDER_INIT)\n" 7733 " .StartsWith(\".fini\", ORDER_FINI)\n" 7734 " .StartsWith(\".hash\", ORDER_HASH)\n" 7735 " .Default(ORDER_TEXT);\n"); 7736 7737 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7738 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7739 verifyFormat("aaaaaaa->aaaaaaa\n" 7740 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7741 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7742 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7743 verifyFormat( 7744 "aaaaaaa->aaaaaaa\n" 7745 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7746 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7747 verifyFormat( 7748 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7749 " aaaaaaaaaaaaaa);"); 7750 verifyFormat( 7751 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7752 " aaaaaa->aaaaaaaaaaaa()\n" 7753 " ->aaaaaaaaaaaaaaaa(\n" 7754 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7755 " ->aaaaaaaaaaaaaaaaa();"); 7756 verifyGoogleFormat( 7757 "void f() {\n" 7758 " someo->Add((new util::filetools::Handler(dir))\n" 7759 " ->OnEvent1(NewPermanentCallback(\n" 7760 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7761 " ->OnEvent2(NewPermanentCallback(\n" 7762 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7763 " ->OnEvent3(NewPermanentCallback(\n" 7764 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7765 " ->OnEvent5(NewPermanentCallback(\n" 7766 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7767 " ->OnEvent6(NewPermanentCallback(\n" 7768 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7769 "}"); 7770 7771 verifyFormat( 7772 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7773 verifyFormat("aaaaaaaaaaaaaaa()\n" 7774 " .aaaaaaaaaaaaaaa()\n" 7775 " .aaaaaaaaaaaaaaa()\n" 7776 " .aaaaaaaaaaaaaaa()\n" 7777 " .aaaaaaaaaaaaaaa();"); 7778 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7779 " .aaaaaaaaaaaaaaa()\n" 7780 " .aaaaaaaaaaaaaaa()\n" 7781 " .aaaaaaaaaaaaaaa();"); 7782 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7783 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7784 " .aaaaaaaaaaaaaaa();"); 7785 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7786 " ->aaaaaaaaaaaaaae(0)\n" 7787 " ->aaaaaaaaaaaaaaa();"); 7788 7789 // Don't linewrap after very short segments. 7790 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7791 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7792 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7793 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7794 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7795 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7796 verifyFormat("aaa()\n" 7797 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7798 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7799 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7800 7801 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7802 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7803 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7804 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7805 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7806 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7807 7808 // Prefer not to break after empty parentheses. 7809 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7810 " First->LastNewlineOffset);"); 7811 7812 // Prefer not to create "hanging" indents. 7813 verifyFormat( 7814 "return !soooooooooooooome_map\n" 7815 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7816 " .second;"); 7817 verifyFormat( 7818 "return aaaaaaaaaaaaaaaa\n" 7819 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7820 " .aaaa(aaaaaaaaaaaaaa);"); 7821 // No hanging indent here. 7822 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7823 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7824 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7825 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7826 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7827 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7828 getLLVMStyleWithColumns(60)); 7829 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7830 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7831 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7832 getLLVMStyleWithColumns(59)); 7833 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7834 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7835 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7836 7837 // Dont break if only closing statements before member call 7838 verifyFormat("test() {\n" 7839 " ([]() -> {\n" 7840 " int b = 32;\n" 7841 " return 3;\n" 7842 " }).foo();\n" 7843 "}"); 7844 verifyFormat("test() {\n" 7845 " (\n" 7846 " []() -> {\n" 7847 " int b = 32;\n" 7848 " return 3;\n" 7849 " },\n" 7850 " foo, bar)\n" 7851 " .foo();\n" 7852 "}"); 7853 verifyFormat("test() {\n" 7854 " ([]() -> {\n" 7855 " int b = 32;\n" 7856 " return 3;\n" 7857 " })\n" 7858 " .foo()\n" 7859 " .bar();\n" 7860 "}"); 7861 verifyFormat("test() {\n" 7862 " ([]() -> {\n" 7863 " int b = 32;\n" 7864 " return 3;\n" 7865 " })\n" 7866 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7867 " \"bbbb\");\n" 7868 "}", 7869 getLLVMStyleWithColumns(30)); 7870 } 7871 7872 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7873 verifyFormat( 7874 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7875 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7876 verifyFormat( 7877 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7878 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7879 7880 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7881 " ccccccccccccccccccccccccc) {\n}"); 7882 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7883 " ccccccccccccccccccccccccc) {\n}"); 7884 7885 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7886 " ccccccccccccccccccccccccc) {\n}"); 7887 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7888 " ccccccccccccccccccccccccc) {\n}"); 7889 7890 verifyFormat( 7891 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7892 " ccccccccccccccccccccccccc) {\n}"); 7893 verifyFormat( 7894 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7895 " ccccccccccccccccccccccccc) {\n}"); 7896 7897 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7898 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7899 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7900 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7901 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7902 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7903 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7904 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7905 7906 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7907 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7908 " aaaaaaaaaaaaaaa != aa) {\n}"); 7909 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7910 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7911 " aaaaaaaaaaaaaaa != aa) {\n}"); 7912 } 7913 7914 TEST_F(FormatTest, BreaksAfterAssignments) { 7915 verifyFormat( 7916 "unsigned Cost =\n" 7917 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7918 " SI->getPointerAddressSpaceee());\n"); 7919 verifyFormat( 7920 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7921 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7922 7923 verifyFormat( 7924 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7925 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7926 verifyFormat("unsigned OriginalStartColumn =\n" 7927 " SourceMgr.getSpellingColumnNumber(\n" 7928 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7929 " 1;"); 7930 } 7931 7932 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7933 FormatStyle Style = getLLVMStyle(); 7934 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7935 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7936 Style); 7937 7938 Style.PenaltyBreakAssignment = 20; 7939 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7940 " cccccccccccccccccccccccccc;", 7941 Style); 7942 } 7943 7944 TEST_F(FormatTest, AlignsAfterAssignments) { 7945 verifyFormat( 7946 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7947 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7948 verifyFormat( 7949 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7950 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7951 verifyFormat( 7952 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7953 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7954 verifyFormat( 7955 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7956 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7957 verifyFormat( 7958 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7959 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7960 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7961 } 7962 7963 TEST_F(FormatTest, AlignsAfterReturn) { 7964 verifyFormat( 7965 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7966 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7967 verifyFormat( 7968 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7969 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7970 verifyFormat( 7971 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7972 " aaaaaaaaaaaaaaaaaaaaaa();"); 7973 verifyFormat( 7974 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7975 " aaaaaaaaaaaaaaaaaaaaaa());"); 7976 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7977 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7978 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7979 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7980 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7981 verifyFormat("return\n" 7982 " // true if code is one of a or b.\n" 7983 " code == a || code == b;"); 7984 } 7985 7986 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7987 verifyFormat( 7988 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7989 " aaaaaaaaa aaaaaaa) {}"); 7990 verifyFormat( 7991 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7992 " aaaaaaaaaaa aaaaaaaaa);"); 7993 verifyFormat( 7994 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7995 " aaaaaaaaaaaaaaaaaaaaa));"); 7996 FormatStyle Style = getLLVMStyle(); 7997 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7998 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7999 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8000 Style); 8001 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8002 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8003 Style); 8004 verifyFormat("SomeLongVariableName->someFunction(\n" 8005 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8006 Style); 8007 verifyFormat( 8008 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8009 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8010 Style); 8011 verifyFormat( 8012 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8013 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8014 Style); 8015 verifyFormat( 8016 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8017 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8018 Style); 8019 8020 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8021 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8022 " b));", 8023 Style); 8024 8025 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8026 Style.BinPackArguments = false; 8027 Style.BinPackParameters = false; 8028 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8029 " aaaaaaaaaaa aaaaaaaa,\n" 8030 " aaaaaaaaa aaaaaaa,\n" 8031 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8032 Style); 8033 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8034 " aaaaaaaaaaa aaaaaaaaa,\n" 8035 " aaaaaaaaaaa aaaaaaaaa,\n" 8036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8037 Style); 8038 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8039 " aaaaaaaaaaaaaaa,\n" 8040 " aaaaaaaaaaaaaaaaaaaaa,\n" 8041 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8042 Style); 8043 verifyFormat( 8044 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8045 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8046 Style); 8047 verifyFormat( 8048 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8049 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8050 Style); 8051 verifyFormat( 8052 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8053 " aaaaaaaaaaaaaaaaaaaaa(\n" 8054 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8055 " aaaaaaaaaaaaaaaa);", 8056 Style); 8057 verifyFormat( 8058 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8059 " aaaaaaaaaaaaaaaaaaaaa(\n" 8060 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8061 " aaaaaaaaaaaaaaaa);", 8062 Style); 8063 } 8064 8065 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8066 FormatStyle Style = getLLVMStyleWithColumns(40); 8067 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8068 " bbbbbbbbbbbbbbbbbbbbbb);", 8069 Style); 8070 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8071 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8072 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8073 " bbbbbbbbbbbbbbbbbbbbbb);", 8074 Style); 8075 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8076 Style.AlignOperands = FormatStyle::OAS_Align; 8077 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8078 " bbbbbbbbbbbbbbbbbbbbbb);", 8079 Style); 8080 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8081 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8082 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8083 " bbbbbbbbbbbbbbbbbbbbbb);", 8084 Style); 8085 } 8086 8087 TEST_F(FormatTest, BreaksConditionalExpressions) { 8088 verifyFormat( 8089 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8090 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8091 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8092 verifyFormat( 8093 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8094 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8095 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8096 verifyFormat( 8097 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8098 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8099 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8100 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8101 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8102 verifyFormat( 8103 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8104 " : aaaaaaaaaaaaa);"); 8105 verifyFormat( 8106 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8107 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8108 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8109 " aaaaaaaaaaaaa);"); 8110 verifyFormat( 8111 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8112 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8113 " aaaaaaaaaaaaa);"); 8114 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8115 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8116 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8117 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8119 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8120 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8121 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8122 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8123 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8125 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8126 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8128 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8129 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8130 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8131 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8132 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8133 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8134 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8136 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8137 " : aaaaaaaaaaaaaaaa;"); 8138 verifyFormat( 8139 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8140 " ? aaaaaaaaaaaaaaa\n" 8141 " : aaaaaaaaaaaaaaa;"); 8142 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8143 " aaaaaaaaa\n" 8144 " ? b\n" 8145 " : c);"); 8146 verifyFormat("return aaaa == bbbb\n" 8147 " // comment\n" 8148 " ? aaaa\n" 8149 " : bbbb;"); 8150 verifyFormat("unsigned Indent =\n" 8151 " format(TheLine.First,\n" 8152 " IndentForLevel[TheLine.Level] >= 0\n" 8153 " ? IndentForLevel[TheLine.Level]\n" 8154 " : TheLine * 2,\n" 8155 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8156 getLLVMStyleWithColumns(60)); 8157 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8158 " ? aaaaaaaaaaaaaaa\n" 8159 " : bbbbbbbbbbbbbbb //\n" 8160 " ? ccccccccccccccc\n" 8161 " : ddddddddddddddd;"); 8162 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8163 " ? aaaaaaaaaaaaaaa\n" 8164 " : (bbbbbbbbbbbbbbb //\n" 8165 " ? ccccccccccccccc\n" 8166 " : ddddddddddddddd);"); 8167 verifyFormat( 8168 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8169 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8170 " aaaaaaaaaaaaaaaaaaaaa +\n" 8171 " aaaaaaaaaaaaaaaaaaaaa\n" 8172 " : aaaaaaaaaa;"); 8173 verifyFormat( 8174 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8175 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8176 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8177 8178 FormatStyle NoBinPacking = getLLVMStyle(); 8179 NoBinPacking.BinPackArguments = false; 8180 verifyFormat( 8181 "void f() {\n" 8182 " g(aaa,\n" 8183 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8184 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8185 " ? aaaaaaaaaaaaaaa\n" 8186 " : aaaaaaaaaaaaaaa);\n" 8187 "}", 8188 NoBinPacking); 8189 verifyFormat( 8190 "void f() {\n" 8191 " g(aaa,\n" 8192 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8193 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8194 " ?: aaaaaaaaaaaaaaa);\n" 8195 "}", 8196 NoBinPacking); 8197 8198 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8199 " // comment.\n" 8200 " ccccccccccccccccccccccccccccccccccccccc\n" 8201 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8202 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8203 8204 // Assignments in conditional expressions. Apparently not uncommon :-(. 8205 verifyFormat("return a != b\n" 8206 " // comment\n" 8207 " ? a = b\n" 8208 " : a = b;"); 8209 verifyFormat("return a != b\n" 8210 " // comment\n" 8211 " ? a = a != b\n" 8212 " // comment\n" 8213 " ? a = b\n" 8214 " : a\n" 8215 " : a;\n"); 8216 verifyFormat("return a != b\n" 8217 " // comment\n" 8218 " ? a\n" 8219 " : a = a != b\n" 8220 " // comment\n" 8221 " ? a = b\n" 8222 " : a;"); 8223 8224 // Chained conditionals 8225 FormatStyle Style = getLLVMStyleWithColumns(70); 8226 Style.AlignOperands = FormatStyle::OAS_Align; 8227 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8228 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8229 " : 3333333333333333;", 8230 Style); 8231 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8232 " : bbbbbbbbbb ? 2222222222222222\n" 8233 " : 3333333333333333;", 8234 Style); 8235 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8236 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8237 " : 3333333333333333;", 8238 Style); 8239 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8240 " : bbbbbbbbbbbbbb ? 222222\n" 8241 " : 333333;", 8242 Style); 8243 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8244 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8245 " : cccccccccccccc ? 3333333333333333\n" 8246 " : 4444444444444444;", 8247 Style); 8248 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8249 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8250 " : 3333333333333333;", 8251 Style); 8252 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8253 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8254 " : (aaa ? bbb : ccc);", 8255 Style); 8256 verifyFormat( 8257 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8258 " : cccccccccccccccccc)\n" 8259 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8260 " : 3333333333333333;", 8261 Style); 8262 verifyFormat( 8263 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8264 " : cccccccccccccccccc)\n" 8265 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8266 " : 3333333333333333;", 8267 Style); 8268 verifyFormat( 8269 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8270 " : dddddddddddddddddd)\n" 8271 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8272 " : 3333333333333333;", 8273 Style); 8274 verifyFormat( 8275 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8276 " : dddddddddddddddddd)\n" 8277 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8278 " : 3333333333333333;", 8279 Style); 8280 verifyFormat( 8281 "return aaaaaaaaa ? 1111111111111111\n" 8282 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8283 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8284 " : dddddddddddddddddd)\n", 8285 Style); 8286 verifyFormat( 8287 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8288 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8289 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8290 " : cccccccccccccccccc);", 8291 Style); 8292 verifyFormat( 8293 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8294 " : ccccccccccccccc ? dddddddddddddddddd\n" 8295 " : eeeeeeeeeeeeeeeeee)\n" 8296 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8297 " : 3333333333333333;", 8298 Style); 8299 verifyFormat( 8300 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8301 " : ccccccccccccccc ? dddddddddddddddddd\n" 8302 " : eeeeeeeeeeeeeeeeee)\n" 8303 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8304 " : 3333333333333333;", 8305 Style); 8306 verifyFormat( 8307 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8308 " : cccccccccccc ? dddddddddddddddddd\n" 8309 " : eeeeeeeeeeeeeeeeee)\n" 8310 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8311 " : 3333333333333333;", 8312 Style); 8313 verifyFormat( 8314 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8315 " : cccccccccccccccccc\n" 8316 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8317 " : 3333333333333333;", 8318 Style); 8319 verifyFormat( 8320 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8321 " : cccccccccccccccc ? dddddddddddddddddd\n" 8322 " : eeeeeeeeeeeeeeeeee\n" 8323 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8324 " : 3333333333333333;", 8325 Style); 8326 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8327 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8328 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8329 " : eeeeeeeeeeeeeeeeee)\n" 8330 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8331 " : 3333333333333333;", 8332 Style); 8333 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8334 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8335 " : cccccccccccccccc ? dddddddddddddddddd\n" 8336 " : eeeeeeeeeeeeeeeeee\n" 8337 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8338 " : 3333333333333333;", 8339 Style); 8340 8341 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8342 Style.BreakBeforeTernaryOperators = false; 8343 // FIXME: Aligning the question marks is weird given DontAlign. 8344 // Consider disabling this alignment in this case. Also check whether this 8345 // will render the adjustment from https://reviews.llvm.org/D82199 8346 // unnecessary. 8347 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8348 " bbbb ? cccccccccccccccccc :\n" 8349 " ddddd;\n", 8350 Style); 8351 8352 EXPECT_EQ( 8353 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8354 " /*\n" 8355 " */\n" 8356 " function() {\n" 8357 " try {\n" 8358 " return JJJJJJJJJJJJJJ(\n" 8359 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8360 " }\n" 8361 " } :\n" 8362 " function() {};", 8363 format( 8364 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8365 " /*\n" 8366 " */\n" 8367 " function() {\n" 8368 " try {\n" 8369 " return JJJJJJJJJJJJJJ(\n" 8370 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8371 " }\n" 8372 " } :\n" 8373 " function() {};", 8374 getGoogleStyle(FormatStyle::LK_JavaScript))); 8375 } 8376 8377 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8378 FormatStyle Style = getLLVMStyleWithColumns(70); 8379 Style.BreakBeforeTernaryOperators = false; 8380 verifyFormat( 8381 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8382 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8383 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8384 Style); 8385 verifyFormat( 8386 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8387 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8388 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8389 Style); 8390 verifyFormat( 8391 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8392 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8393 Style); 8394 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8395 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8396 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8397 Style); 8398 verifyFormat( 8399 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8400 " aaaaaaaaaaaaa);", 8401 Style); 8402 verifyFormat( 8403 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8404 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8405 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8406 " aaaaaaaaaaaaa);", 8407 Style); 8408 verifyFormat( 8409 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8410 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8411 " aaaaaaaaaaaaa);", 8412 Style); 8413 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8414 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8415 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8416 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8418 Style); 8419 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8420 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8421 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8422 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8423 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8424 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8425 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8426 Style); 8427 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8428 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8429 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8430 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8431 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8432 Style); 8433 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8434 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8435 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8436 Style); 8437 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8438 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8439 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8440 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8441 Style); 8442 verifyFormat( 8443 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8444 " aaaaaaaaaaaaaaa :\n" 8445 " aaaaaaaaaaaaaaa;", 8446 Style); 8447 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8448 " aaaaaaaaa ?\n" 8449 " b :\n" 8450 " c);", 8451 Style); 8452 verifyFormat("unsigned Indent =\n" 8453 " format(TheLine.First,\n" 8454 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8455 " IndentForLevel[TheLine.Level] :\n" 8456 " TheLine * 2,\n" 8457 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8458 Style); 8459 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8460 " aaaaaaaaaaaaaaa :\n" 8461 " bbbbbbbbbbbbbbb ? //\n" 8462 " ccccccccccccccc :\n" 8463 " ddddddddddddddd;", 8464 Style); 8465 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8466 " aaaaaaaaaaaaaaa :\n" 8467 " (bbbbbbbbbbbbbbb ? //\n" 8468 " ccccccccccccccc :\n" 8469 " ddddddddddddddd);", 8470 Style); 8471 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8472 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8473 " ccccccccccccccccccccccccccc;", 8474 Style); 8475 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8476 " aaaaa :\n" 8477 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8478 Style); 8479 8480 // Chained conditionals 8481 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8482 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8483 " 3333333333333333;", 8484 Style); 8485 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8486 " bbbbbbbbbb ? 2222222222222222 :\n" 8487 " 3333333333333333;", 8488 Style); 8489 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8490 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8491 " 3333333333333333;", 8492 Style); 8493 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8494 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8495 " 333333;", 8496 Style); 8497 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8498 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8499 " cccccccccccccccc ? 3333333333333333 :\n" 8500 " 4444444444444444;", 8501 Style); 8502 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8503 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8504 " 3333333333333333;", 8505 Style); 8506 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8507 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8508 " (aaa ? bbb : ccc);", 8509 Style); 8510 verifyFormat( 8511 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8512 " cccccccccccccccccc) :\n" 8513 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8514 " 3333333333333333;", 8515 Style); 8516 verifyFormat( 8517 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8518 " cccccccccccccccccc) :\n" 8519 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8520 " 3333333333333333;", 8521 Style); 8522 verifyFormat( 8523 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8524 " dddddddddddddddddd) :\n" 8525 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8526 " 3333333333333333;", 8527 Style); 8528 verifyFormat( 8529 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8530 " dddddddddddddddddd) :\n" 8531 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8532 " 3333333333333333;", 8533 Style); 8534 verifyFormat( 8535 "return aaaaaaaaa ? 1111111111111111 :\n" 8536 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8537 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8538 " dddddddddddddddddd)\n", 8539 Style); 8540 verifyFormat( 8541 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8542 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8543 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8544 " cccccccccccccccccc);", 8545 Style); 8546 verifyFormat( 8547 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8548 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8549 " eeeeeeeeeeeeeeeeee) :\n" 8550 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8551 " 3333333333333333;", 8552 Style); 8553 verifyFormat( 8554 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8555 " ccccccccccccc ? dddddddddddddddddd :\n" 8556 " eeeeeeeeeeeeeeeeee) :\n" 8557 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8558 " 3333333333333333;", 8559 Style); 8560 verifyFormat( 8561 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8562 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8563 " eeeeeeeeeeeeeeeeee) :\n" 8564 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8565 " 3333333333333333;", 8566 Style); 8567 verifyFormat( 8568 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8569 " cccccccccccccccccc :\n" 8570 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8571 " 3333333333333333;", 8572 Style); 8573 verifyFormat( 8574 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8575 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8576 " eeeeeeeeeeeeeeeeee :\n" 8577 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8578 " 3333333333333333;", 8579 Style); 8580 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8581 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8582 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8583 " eeeeeeeeeeeeeeeeee) :\n" 8584 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8585 " 3333333333333333;", 8586 Style); 8587 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8588 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8589 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8590 " eeeeeeeeeeeeeeeeee :\n" 8591 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8592 " 3333333333333333;", 8593 Style); 8594 } 8595 8596 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8597 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8598 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8599 verifyFormat("bool a = true, b = false;"); 8600 8601 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8602 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8603 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8604 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8605 verifyFormat( 8606 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8607 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8608 " d = e && f;"); 8609 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8610 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8611 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8612 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8613 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8614 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8615 8616 FormatStyle Style = getGoogleStyle(); 8617 Style.PointerAlignment = FormatStyle::PAS_Left; 8618 Style.DerivePointerAlignment = false; 8619 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8620 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8621 " *b = bbbbbbbbbbbbbbbbbbb;", 8622 Style); 8623 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8624 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8625 Style); 8626 verifyFormat("vector<int*> a, b;", Style); 8627 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8628 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8629 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8630 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8631 Style); 8632 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8633 Style); 8634 verifyFormat( 8635 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8636 Style); 8637 8638 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8639 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8640 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8641 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8642 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8643 Style); 8644 } 8645 8646 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8647 verifyFormat("arr[foo ? bar : baz];"); 8648 verifyFormat("f()[foo ? bar : baz];"); 8649 verifyFormat("(a + b)[foo ? bar : baz];"); 8650 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8651 } 8652 8653 TEST_F(FormatTest, AlignsStringLiterals) { 8654 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8655 " \"short literal\");"); 8656 verifyFormat( 8657 "looooooooooooooooooooooooongFunction(\n" 8658 " \"short literal\"\n" 8659 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8660 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8661 " \" string literals\",\n" 8662 " and, other, parameters);"); 8663 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8664 " \"5678\";", 8665 format("fun + \"1243\" /* comment */\n" 8666 " \"5678\";", 8667 getLLVMStyleWithColumns(28))); 8668 EXPECT_EQ( 8669 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8670 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8671 " \"aaaaaaaaaaaaaaaa\";", 8672 format("aaaaaa =" 8673 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8674 "aaaaaaaaaaaaaaaaaaaaa\" " 8675 "\"aaaaaaaaaaaaaaaa\";")); 8676 verifyFormat("a = a + \"a\"\n" 8677 " \"a\"\n" 8678 " \"a\";"); 8679 verifyFormat("f(\"a\", \"b\"\n" 8680 " \"c\");"); 8681 8682 verifyFormat( 8683 "#define LL_FORMAT \"ll\"\n" 8684 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8685 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8686 8687 verifyFormat("#define A(X) \\\n" 8688 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8689 " \"ccccc\"", 8690 getLLVMStyleWithColumns(23)); 8691 verifyFormat("#define A \"def\"\n" 8692 "f(\"abc\" A \"ghi\"\n" 8693 " \"jkl\");"); 8694 8695 verifyFormat("f(L\"a\"\n" 8696 " L\"b\");"); 8697 verifyFormat("#define A(X) \\\n" 8698 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8699 " L\"ccccc\"", 8700 getLLVMStyleWithColumns(25)); 8701 8702 verifyFormat("f(@\"a\"\n" 8703 " @\"b\");"); 8704 verifyFormat("NSString s = @\"a\"\n" 8705 " @\"b\"\n" 8706 " @\"c\";"); 8707 verifyFormat("NSString s = @\"a\"\n" 8708 " \"b\"\n" 8709 " \"c\";"); 8710 } 8711 8712 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8713 FormatStyle Style = getLLVMStyle(); 8714 // No declarations or definitions should be moved to own line. 8715 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8716 verifyFormat("class A {\n" 8717 " int f() { return 1; }\n" 8718 " int g();\n" 8719 "};\n" 8720 "int f() { return 1; }\n" 8721 "int g();\n", 8722 Style); 8723 8724 // All declarations and definitions should have the return type moved to its 8725 // own line. 8726 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8727 Style.TypenameMacros = {"LIST"}; 8728 verifyFormat("SomeType\n" 8729 "funcdecl(LIST(uint64_t));", 8730 Style); 8731 verifyFormat("class E {\n" 8732 " int\n" 8733 " f() {\n" 8734 " return 1;\n" 8735 " }\n" 8736 " int\n" 8737 " g();\n" 8738 "};\n" 8739 "int\n" 8740 "f() {\n" 8741 " return 1;\n" 8742 "}\n" 8743 "int\n" 8744 "g();\n", 8745 Style); 8746 8747 // Top-level definitions, and no kinds of declarations should have the 8748 // return type moved to its own line. 8749 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8750 verifyFormat("class B {\n" 8751 " int f() { return 1; }\n" 8752 " int g();\n" 8753 "};\n" 8754 "int\n" 8755 "f() {\n" 8756 " return 1;\n" 8757 "}\n" 8758 "int g();\n", 8759 Style); 8760 8761 // Top-level definitions and declarations should have the return type moved 8762 // to its own line. 8763 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8764 verifyFormat("class C {\n" 8765 " int f() { return 1; }\n" 8766 " int g();\n" 8767 "};\n" 8768 "int\n" 8769 "f() {\n" 8770 " return 1;\n" 8771 "}\n" 8772 "int\n" 8773 "g();\n", 8774 Style); 8775 8776 // All definitions should have the return type moved to its own line, but no 8777 // kinds of declarations. 8778 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8779 verifyFormat("class D {\n" 8780 " int\n" 8781 " f() {\n" 8782 " return 1;\n" 8783 " }\n" 8784 " int g();\n" 8785 "};\n" 8786 "int\n" 8787 "f() {\n" 8788 " return 1;\n" 8789 "}\n" 8790 "int g();\n", 8791 Style); 8792 verifyFormat("const char *\n" 8793 "f(void) {\n" // Break here. 8794 " return \"\";\n" 8795 "}\n" 8796 "const char *bar(void);\n", // No break here. 8797 Style); 8798 verifyFormat("template <class T>\n" 8799 "T *\n" 8800 "f(T &c) {\n" // Break here. 8801 " return NULL;\n" 8802 "}\n" 8803 "template <class T> T *f(T &c);\n", // No break here. 8804 Style); 8805 verifyFormat("class C {\n" 8806 " int\n" 8807 " operator+() {\n" 8808 " return 1;\n" 8809 " }\n" 8810 " int\n" 8811 " operator()() {\n" 8812 " return 1;\n" 8813 " }\n" 8814 "};\n", 8815 Style); 8816 verifyFormat("void\n" 8817 "A::operator()() {}\n" 8818 "void\n" 8819 "A::operator>>() {}\n" 8820 "void\n" 8821 "A::operator+() {}\n" 8822 "void\n" 8823 "A::operator*() {}\n" 8824 "void\n" 8825 "A::operator->() {}\n" 8826 "void\n" 8827 "A::operator void *() {}\n" 8828 "void\n" 8829 "A::operator void &() {}\n" 8830 "void\n" 8831 "A::operator void &&() {}\n" 8832 "void\n" 8833 "A::operator char *() {}\n" 8834 "void\n" 8835 "A::operator[]() {}\n" 8836 "void\n" 8837 "A::operator!() {}\n" 8838 "void\n" 8839 "A::operator**() {}\n" 8840 "void\n" 8841 "A::operator<Foo> *() {}\n" 8842 "void\n" 8843 "A::operator<Foo> **() {}\n" 8844 "void\n" 8845 "A::operator<Foo> &() {}\n" 8846 "void\n" 8847 "A::operator void **() {}\n", 8848 Style); 8849 verifyFormat("constexpr auto\n" 8850 "operator()() const -> reference {}\n" 8851 "constexpr auto\n" 8852 "operator>>() const -> reference {}\n" 8853 "constexpr auto\n" 8854 "operator+() const -> reference {}\n" 8855 "constexpr auto\n" 8856 "operator*() const -> reference {}\n" 8857 "constexpr auto\n" 8858 "operator->() const -> reference {}\n" 8859 "constexpr auto\n" 8860 "operator++() const -> reference {}\n" 8861 "constexpr auto\n" 8862 "operator void *() const -> reference {}\n" 8863 "constexpr auto\n" 8864 "operator void **() const -> reference {}\n" 8865 "constexpr auto\n" 8866 "operator void *() const -> reference {}\n" 8867 "constexpr auto\n" 8868 "operator void &() const -> reference {}\n" 8869 "constexpr auto\n" 8870 "operator void &&() const -> reference {}\n" 8871 "constexpr auto\n" 8872 "operator char *() const -> reference {}\n" 8873 "constexpr auto\n" 8874 "operator!() const -> reference {}\n" 8875 "constexpr auto\n" 8876 "operator[]() const -> reference {}\n", 8877 Style); 8878 verifyFormat("void *operator new(std::size_t s);", // No break here. 8879 Style); 8880 verifyFormat("void *\n" 8881 "operator new(std::size_t s) {}", 8882 Style); 8883 verifyFormat("void *\n" 8884 "operator delete[](void *ptr) {}", 8885 Style); 8886 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8887 verifyFormat("const char *\n" 8888 "f(void)\n" // Break here. 8889 "{\n" 8890 " return \"\";\n" 8891 "}\n" 8892 "const char *bar(void);\n", // No break here. 8893 Style); 8894 verifyFormat("template <class T>\n" 8895 "T *\n" // Problem here: no line break 8896 "f(T &c)\n" // Break here. 8897 "{\n" 8898 " return NULL;\n" 8899 "}\n" 8900 "template <class T> T *f(T &c);\n", // No break here. 8901 Style); 8902 verifyFormat("int\n" 8903 "foo(A<bool> a)\n" 8904 "{\n" 8905 " return a;\n" 8906 "}\n", 8907 Style); 8908 verifyFormat("int\n" 8909 "foo(A<8> a)\n" 8910 "{\n" 8911 " return a;\n" 8912 "}\n", 8913 Style); 8914 verifyFormat("int\n" 8915 "foo(A<B<bool>, 8> a)\n" 8916 "{\n" 8917 " return a;\n" 8918 "}\n", 8919 Style); 8920 verifyFormat("int\n" 8921 "foo(A<B<8>, bool> a)\n" 8922 "{\n" 8923 " return a;\n" 8924 "}\n", 8925 Style); 8926 verifyFormat("int\n" 8927 "foo(A<B<bool>, bool> a)\n" 8928 "{\n" 8929 " return a;\n" 8930 "}\n", 8931 Style); 8932 verifyFormat("int\n" 8933 "foo(A<B<8>, 8> a)\n" 8934 "{\n" 8935 " return a;\n" 8936 "}\n", 8937 Style); 8938 8939 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8940 Style.BraceWrapping.AfterFunction = true; 8941 verifyFormat("int f(i);\n" // No break here. 8942 "int\n" // Break here. 8943 "f(i)\n" 8944 "{\n" 8945 " return i + 1;\n" 8946 "}\n" 8947 "int\n" // Break here. 8948 "f(i)\n" 8949 "{\n" 8950 " return i + 1;\n" 8951 "};", 8952 Style); 8953 verifyFormat("int f(a, b, c);\n" // No break here. 8954 "int\n" // Break here. 8955 "f(a, b, c)\n" // Break here. 8956 "short a, b;\n" 8957 "float c;\n" 8958 "{\n" 8959 " return a + b < c;\n" 8960 "}\n" 8961 "int\n" // Break here. 8962 "f(a, b, c)\n" // Break here. 8963 "short a, b;\n" 8964 "float c;\n" 8965 "{\n" 8966 " return a + b < c;\n" 8967 "};", 8968 Style); 8969 verifyFormat("byte *\n" // Break here. 8970 "f(a)\n" // Break here. 8971 "byte a[];\n" 8972 "{\n" 8973 " return a;\n" 8974 "}", 8975 Style); 8976 verifyFormat("bool f(int a, int) override;\n" 8977 "Bar g(int a, Bar) final;\n" 8978 "Bar h(a, Bar) final;", 8979 Style); 8980 verifyFormat("int\n" 8981 "f(a)", 8982 Style); 8983 verifyFormat("bool\n" 8984 "f(size_t = 0, bool b = false)\n" 8985 "{\n" 8986 " return !b;\n" 8987 "}", 8988 Style); 8989 8990 // The return breaking style doesn't affect: 8991 // * function and object definitions with attribute-like macros 8992 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8993 " ABSL_GUARDED_BY(mutex) = {};", 8994 getGoogleStyleWithColumns(40)); 8995 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8996 " ABSL_GUARDED_BY(mutex); // comment", 8997 getGoogleStyleWithColumns(40)); 8998 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8999 " ABSL_GUARDED_BY(mutex1)\n" 9000 " ABSL_GUARDED_BY(mutex2);", 9001 getGoogleStyleWithColumns(40)); 9002 verifyFormat("Tttttt f(int a, int b)\n" 9003 " ABSL_GUARDED_BY(mutex1)\n" 9004 " ABSL_GUARDED_BY(mutex2);", 9005 getGoogleStyleWithColumns(40)); 9006 // * typedefs 9007 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9008 9009 Style = getGNUStyle(); 9010 9011 // Test for comments at the end of function declarations. 9012 verifyFormat("void\n" 9013 "foo (int a, /*abc*/ int b) // def\n" 9014 "{\n" 9015 "}\n", 9016 Style); 9017 9018 verifyFormat("void\n" 9019 "foo (int a, /* abc */ int b) /* def */\n" 9020 "{\n" 9021 "}\n", 9022 Style); 9023 9024 // Definitions that should not break after return type 9025 verifyFormat("void foo (int a, int b); // def\n", Style); 9026 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9027 verifyFormat("void foo (int a, int b);\n", Style); 9028 } 9029 9030 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9031 FormatStyle NoBreak = getLLVMStyle(); 9032 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9033 FormatStyle Break = getLLVMStyle(); 9034 Break.AlwaysBreakBeforeMultilineStrings = true; 9035 verifyFormat("aaaa = \"bbbb\"\n" 9036 " \"cccc\";", 9037 NoBreak); 9038 verifyFormat("aaaa =\n" 9039 " \"bbbb\"\n" 9040 " \"cccc\";", 9041 Break); 9042 verifyFormat("aaaa(\"bbbb\"\n" 9043 " \"cccc\");", 9044 NoBreak); 9045 verifyFormat("aaaa(\n" 9046 " \"bbbb\"\n" 9047 " \"cccc\");", 9048 Break); 9049 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9050 " \"cccc\");", 9051 NoBreak); 9052 verifyFormat("aaaa(qqq,\n" 9053 " \"bbbb\"\n" 9054 " \"cccc\");", 9055 Break); 9056 verifyFormat("aaaa(qqq,\n" 9057 " L\"bbbb\"\n" 9058 " L\"cccc\");", 9059 Break); 9060 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9061 " \"bbbb\"));", 9062 Break); 9063 verifyFormat("string s = someFunction(\n" 9064 " \"abc\"\n" 9065 " \"abc\");", 9066 Break); 9067 9068 // As we break before unary operators, breaking right after them is bad. 9069 verifyFormat("string foo = abc ? \"x\"\n" 9070 " \"blah blah blah blah blah blah\"\n" 9071 " : \"y\";", 9072 Break); 9073 9074 // Don't break if there is no column gain. 9075 verifyFormat("f(\"aaaa\"\n" 9076 " \"bbbb\");", 9077 Break); 9078 9079 // Treat literals with escaped newlines like multi-line string literals. 9080 EXPECT_EQ("x = \"a\\\n" 9081 "b\\\n" 9082 "c\";", 9083 format("x = \"a\\\n" 9084 "b\\\n" 9085 "c\";", 9086 NoBreak)); 9087 EXPECT_EQ("xxxx =\n" 9088 " \"a\\\n" 9089 "b\\\n" 9090 "c\";", 9091 format("xxxx = \"a\\\n" 9092 "b\\\n" 9093 "c\";", 9094 Break)); 9095 9096 EXPECT_EQ("NSString *const kString =\n" 9097 " @\"aaaa\"\n" 9098 " @\"bbbb\";", 9099 format("NSString *const kString = @\"aaaa\"\n" 9100 "@\"bbbb\";", 9101 Break)); 9102 9103 Break.ColumnLimit = 0; 9104 verifyFormat("const char *hello = \"hello llvm\";", Break); 9105 } 9106 9107 TEST_F(FormatTest, AlignsPipes) { 9108 verifyFormat( 9109 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9110 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9111 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9112 verifyFormat( 9113 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9114 " << aaaaaaaaaaaaaaaaaaaa;"); 9115 verifyFormat( 9116 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9117 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9118 verifyFormat( 9119 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9120 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9121 verifyFormat( 9122 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9123 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9124 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9125 verifyFormat( 9126 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9127 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9128 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9129 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9130 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9131 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9132 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9133 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9134 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9135 verifyFormat( 9136 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9137 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9138 verifyFormat( 9139 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9140 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9141 9142 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9143 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9144 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9145 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9146 " aaaaaaaaaaaaaaaaaaaaa)\n" 9147 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9148 verifyFormat("LOG_IF(aaa == //\n" 9149 " bbb)\n" 9150 " << a << b;"); 9151 9152 // But sometimes, breaking before the first "<<" is desirable. 9153 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9154 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9155 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9156 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9157 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9158 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9159 " << BEF << IsTemplate << Description << E->getType();"); 9160 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9161 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9162 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9163 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9164 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9165 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9166 " << aaa;"); 9167 9168 verifyFormat( 9169 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9170 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9171 9172 // Incomplete string literal. 9173 EXPECT_EQ("llvm::errs() << \"\n" 9174 " << a;", 9175 format("llvm::errs() << \"\n<<a;")); 9176 9177 verifyFormat("void f() {\n" 9178 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9179 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9180 "}"); 9181 9182 // Handle 'endl'. 9183 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9184 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9185 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9186 9187 // Handle '\n'. 9188 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9189 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9190 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9191 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9192 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9193 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9194 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9195 } 9196 9197 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9198 verifyFormat("return out << \"somepacket = {\\n\"\n" 9199 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9200 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9201 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9202 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9203 " << \"}\";"); 9204 9205 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9206 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9207 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9208 verifyFormat( 9209 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9210 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9211 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9212 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9213 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9214 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9215 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9216 verifyFormat( 9217 "void f() {\n" 9218 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9219 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9220 "}"); 9221 9222 // Breaking before the first "<<" is generally not desirable. 9223 verifyFormat( 9224 "llvm::errs()\n" 9225 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9226 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9227 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9228 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9229 getLLVMStyleWithColumns(70)); 9230 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9231 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9232 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9233 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9234 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9235 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9236 getLLVMStyleWithColumns(70)); 9237 9238 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9239 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9240 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9241 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9242 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9243 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9244 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9245 " (aaaa + aaaa);", 9246 getLLVMStyleWithColumns(40)); 9247 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9248 " (aaaaaaa + aaaaa));", 9249 getLLVMStyleWithColumns(40)); 9250 verifyFormat( 9251 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9252 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9253 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9254 } 9255 9256 TEST_F(FormatTest, UnderstandsEquals) { 9257 verifyFormat( 9258 "aaaaaaaaaaaaaaaaa =\n" 9259 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9260 verifyFormat( 9261 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9262 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9263 verifyFormat( 9264 "if (a) {\n" 9265 " f();\n" 9266 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9267 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9268 "}"); 9269 9270 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9271 " 100000000 + 10000000) {\n}"); 9272 } 9273 9274 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9275 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9276 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9277 9278 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9279 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9280 9281 verifyFormat( 9282 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9283 " Parameter2);"); 9284 9285 verifyFormat( 9286 "ShortObject->shortFunction(\n" 9287 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9288 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9289 9290 verifyFormat("loooooooooooooongFunction(\n" 9291 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9292 9293 verifyFormat( 9294 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9295 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9296 9297 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9298 " .WillRepeatedly(Return(SomeValue));"); 9299 verifyFormat("void f() {\n" 9300 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9301 " .Times(2)\n" 9302 " .WillRepeatedly(Return(SomeValue));\n" 9303 "}"); 9304 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9305 " ccccccccccccccccccccccc);"); 9306 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9308 " .aaaaa(aaaaa),\n" 9309 " aaaaaaaaaaaaaaaaaaaaa);"); 9310 verifyFormat("void f() {\n" 9311 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9312 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9313 "}"); 9314 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9316 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9317 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9318 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9319 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9320 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9321 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9322 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9323 "}"); 9324 9325 // Here, it is not necessary to wrap at "." or "->". 9326 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9327 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9328 verifyFormat( 9329 "aaaaaaaaaaa->aaaaaaaaa(\n" 9330 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9331 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9332 9333 verifyFormat( 9334 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9335 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9336 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9337 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9338 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9339 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9340 9341 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9342 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9343 " .a();"); 9344 9345 FormatStyle NoBinPacking = getLLVMStyle(); 9346 NoBinPacking.BinPackParameters = false; 9347 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9348 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9349 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9350 " aaaaaaaaaaaaaaaaaaa,\n" 9351 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9352 NoBinPacking); 9353 9354 // If there is a subsequent call, change to hanging indentation. 9355 verifyFormat( 9356 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9357 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9358 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9359 verifyFormat( 9360 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9361 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9362 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9363 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9364 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9365 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9367 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9368 } 9369 9370 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9371 verifyFormat("template <typename T>\n" 9372 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9373 verifyFormat("template <typename T>\n" 9374 "// T should be one of {A, B}.\n" 9375 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9376 verifyFormat( 9377 "template <typename T>\n" 9378 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9379 verifyFormat("template <typename T>\n" 9380 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9381 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9382 verifyFormat( 9383 "template <typename T>\n" 9384 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9385 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9386 verifyFormat( 9387 "template <typename T>\n" 9388 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9389 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9390 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9391 verifyFormat("template <typename T>\n" 9392 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9393 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9394 verifyFormat( 9395 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9396 " typename T4 = char>\n" 9397 "void f();"); 9398 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9399 " template <typename> class cccccccccccccccccccccc,\n" 9400 " typename ddddddddddddd>\n" 9401 "class C {};"); 9402 verifyFormat( 9403 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9404 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9405 9406 verifyFormat("void f() {\n" 9407 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9408 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9409 "}"); 9410 9411 verifyFormat("template <typename T> class C {};"); 9412 verifyFormat("template <typename T> void f();"); 9413 verifyFormat("template <typename T> void f() {}"); 9414 verifyFormat( 9415 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9416 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9418 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9419 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9420 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9421 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9422 getLLVMStyleWithColumns(72)); 9423 EXPECT_EQ("static_cast<A< //\n" 9424 " B> *>(\n" 9425 "\n" 9426 ");", 9427 format("static_cast<A<//\n" 9428 " B>*>(\n" 9429 "\n" 9430 " );")); 9431 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9432 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9433 9434 FormatStyle AlwaysBreak = getLLVMStyle(); 9435 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9436 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9437 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9438 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9439 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9440 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9441 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9442 verifyFormat("template <template <typename> class Fooooooo,\n" 9443 " template <typename> class Baaaaaaar>\n" 9444 "struct C {};", 9445 AlwaysBreak); 9446 verifyFormat("template <typename T> // T can be A, B or C.\n" 9447 "struct C {};", 9448 AlwaysBreak); 9449 verifyFormat("template <enum E> class A {\n" 9450 "public:\n" 9451 " E *f();\n" 9452 "};"); 9453 9454 FormatStyle NeverBreak = getLLVMStyle(); 9455 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9456 verifyFormat("template <typename T> class C {};", NeverBreak); 9457 verifyFormat("template <typename T> void f();", NeverBreak); 9458 verifyFormat("template <typename T> void f() {}", NeverBreak); 9459 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9460 "bbbbbbbbbbbbbbbbbbbb) {}", 9461 NeverBreak); 9462 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9463 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9464 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9465 NeverBreak); 9466 verifyFormat("template <template <typename> class Fooooooo,\n" 9467 " template <typename> class Baaaaaaar>\n" 9468 "struct C {};", 9469 NeverBreak); 9470 verifyFormat("template <typename T> // T can be A, B or C.\n" 9471 "struct C {};", 9472 NeverBreak); 9473 verifyFormat("template <enum E> class A {\n" 9474 "public:\n" 9475 " E *f();\n" 9476 "};", 9477 NeverBreak); 9478 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9479 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9480 "bbbbbbbbbbbbbbbbbbbb) {}", 9481 NeverBreak); 9482 } 9483 9484 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9485 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9486 Style.ColumnLimit = 60; 9487 EXPECT_EQ("// Baseline - no comments.\n" 9488 "template <\n" 9489 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9490 "void f() {}", 9491 format("// Baseline - no comments.\n" 9492 "template <\n" 9493 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9494 "void f() {}", 9495 Style)); 9496 9497 EXPECT_EQ("template <\n" 9498 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9499 "void f() {}", 9500 format("template <\n" 9501 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9502 "void f() {}", 9503 Style)); 9504 9505 EXPECT_EQ( 9506 "template <\n" 9507 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9508 "void f() {}", 9509 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9510 "void f() {}", 9511 Style)); 9512 9513 EXPECT_EQ( 9514 "template <\n" 9515 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9516 " // multiline\n" 9517 "void f() {}", 9518 format("template <\n" 9519 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9520 " // multiline\n" 9521 "void f() {}", 9522 Style)); 9523 9524 EXPECT_EQ( 9525 "template <typename aaaaaaaaaa<\n" 9526 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9527 "void f() {}", 9528 format( 9529 "template <\n" 9530 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9531 "void f() {}", 9532 Style)); 9533 } 9534 9535 TEST_F(FormatTest, WrapsTemplateParameters) { 9536 FormatStyle Style = getLLVMStyle(); 9537 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9538 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9539 verifyFormat( 9540 "template <typename... a> struct q {};\n" 9541 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9542 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9543 " y;", 9544 Style); 9545 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9546 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9547 verifyFormat( 9548 "template <typename... a> struct r {};\n" 9549 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9550 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9551 " y;", 9552 Style); 9553 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9554 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9555 verifyFormat("template <typename... a> struct s {};\n" 9556 "extern s<\n" 9557 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9558 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9559 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9560 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9561 " y;", 9562 Style); 9563 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9564 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9565 verifyFormat("template <typename... a> struct t {};\n" 9566 "extern t<\n" 9567 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9568 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9569 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9570 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9571 " y;", 9572 Style); 9573 } 9574 9575 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9576 verifyFormat( 9577 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9578 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9579 verifyFormat( 9580 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9581 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9582 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9583 9584 // FIXME: Should we have the extra indent after the second break? 9585 verifyFormat( 9586 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9587 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9588 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9589 9590 verifyFormat( 9591 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9592 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9593 9594 // Breaking at nested name specifiers is generally not desirable. 9595 verifyFormat( 9596 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9597 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9598 9599 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9600 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9601 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9602 " aaaaaaaaaaaaaaaaaaaaa);", 9603 getLLVMStyleWithColumns(74)); 9604 9605 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9606 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9607 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9608 } 9609 9610 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9611 verifyFormat("A<int> a;"); 9612 verifyFormat("A<A<A<int>>> a;"); 9613 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9614 verifyFormat("bool x = a < 1 || 2 > a;"); 9615 verifyFormat("bool x = 5 < f<int>();"); 9616 verifyFormat("bool x = f<int>() > 5;"); 9617 verifyFormat("bool x = 5 < a<int>::x;"); 9618 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9619 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9620 9621 verifyGoogleFormat("A<A<int>> a;"); 9622 verifyGoogleFormat("A<A<A<int>>> a;"); 9623 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9624 verifyGoogleFormat("A<A<int> > a;"); 9625 verifyGoogleFormat("A<A<A<int> > > a;"); 9626 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9627 verifyGoogleFormat("A<::A<int>> a;"); 9628 verifyGoogleFormat("A<::A> a;"); 9629 verifyGoogleFormat("A< ::A> a;"); 9630 verifyGoogleFormat("A< ::A<int> > a;"); 9631 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9632 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9633 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9634 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9635 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9636 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9637 9638 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9639 9640 // template closer followed by a token that starts with > or = 9641 verifyFormat("bool b = a<1> > 1;"); 9642 verifyFormat("bool b = a<1> >= 1;"); 9643 verifyFormat("int i = a<1> >> 1;"); 9644 FormatStyle Style = getLLVMStyle(); 9645 Style.SpaceBeforeAssignmentOperators = false; 9646 verifyFormat("bool b= a<1> == 1;", Style); 9647 verifyFormat("a<int> = 1;", Style); 9648 verifyFormat("a<int> >>= 1;", Style); 9649 9650 verifyFormat("test < a | b >> c;"); 9651 verifyFormat("test<test<a | b>> c;"); 9652 verifyFormat("test >> a >> b;"); 9653 verifyFormat("test << a >> b;"); 9654 9655 verifyFormat("f<int>();"); 9656 verifyFormat("template <typename T> void f() {}"); 9657 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9658 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9659 "sizeof(char)>::type>;"); 9660 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9661 verifyFormat("f(a.operator()<A>());"); 9662 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9663 " .template operator()<A>());", 9664 getLLVMStyleWithColumns(35)); 9665 verifyFormat("bool_constant<a && noexcept(f())>"); 9666 verifyFormat("bool_constant<a || noexcept(f())>"); 9667 9668 // Not template parameters. 9669 verifyFormat("return a < b && c > d;"); 9670 verifyFormat("void f() {\n" 9671 " while (a < b && c > d) {\n" 9672 " }\n" 9673 "}"); 9674 verifyFormat("template <typename... Types>\n" 9675 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9676 9677 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9678 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9679 getLLVMStyleWithColumns(60)); 9680 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9681 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9682 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9683 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9684 } 9685 9686 TEST_F(FormatTest, UnderstandsShiftOperators) { 9687 verifyFormat("if (i < x >> 1)"); 9688 verifyFormat("while (i < x >> 1)"); 9689 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9690 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9691 verifyFormat( 9692 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9693 verifyFormat("Foo.call<Bar<Function>>()"); 9694 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9695 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9696 "++i, v = v >> 1)"); 9697 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9698 } 9699 9700 TEST_F(FormatTest, BitshiftOperatorWidth) { 9701 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9702 " bar */", 9703 format("int a=1<<2; /* foo\n" 9704 " bar */")); 9705 9706 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9707 " bar */", 9708 format("int b =256>>1 ; /* foo\n" 9709 " bar */")); 9710 } 9711 9712 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9713 verifyFormat("COMPARE(a, ==, b);"); 9714 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9715 } 9716 9717 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9718 verifyFormat("int A::*x;"); 9719 verifyFormat("int (S::*func)(void *);"); 9720 verifyFormat("void f() { int (S::*func)(void *); }"); 9721 verifyFormat("typedef bool *(Class::*Member)() const;"); 9722 verifyFormat("void f() {\n" 9723 " (a->*f)();\n" 9724 " a->*x;\n" 9725 " (a.*f)();\n" 9726 " ((*a).*f)();\n" 9727 " a.*x;\n" 9728 "}"); 9729 verifyFormat("void f() {\n" 9730 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9731 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9732 "}"); 9733 verifyFormat( 9734 "(aaaaaaaaaa->*bbbbbbb)(\n" 9735 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9736 FormatStyle Style = getLLVMStyle(); 9737 Style.PointerAlignment = FormatStyle::PAS_Left; 9738 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9739 } 9740 9741 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9742 verifyFormat("int a = -2;"); 9743 verifyFormat("f(-1, -2, -3);"); 9744 verifyFormat("a[-1] = 5;"); 9745 verifyFormat("int a = 5 + -2;"); 9746 verifyFormat("if (i == -1) {\n}"); 9747 verifyFormat("if (i != -1) {\n}"); 9748 verifyFormat("if (i > -1) {\n}"); 9749 verifyFormat("if (i < -1) {\n}"); 9750 verifyFormat("++(a->f());"); 9751 verifyFormat("--(a->f());"); 9752 verifyFormat("(a->f())++;"); 9753 verifyFormat("a[42]++;"); 9754 verifyFormat("if (!(a->f())) {\n}"); 9755 verifyFormat("if (!+i) {\n}"); 9756 verifyFormat("~&a;"); 9757 9758 verifyFormat("a-- > b;"); 9759 verifyFormat("b ? -a : c;"); 9760 verifyFormat("n * sizeof char16;"); 9761 verifyFormat("n * alignof char16;", getGoogleStyle()); 9762 verifyFormat("sizeof(char);"); 9763 verifyFormat("alignof(char);", getGoogleStyle()); 9764 9765 verifyFormat("return -1;"); 9766 verifyFormat("throw -1;"); 9767 verifyFormat("switch (a) {\n" 9768 "case -1:\n" 9769 " break;\n" 9770 "}"); 9771 verifyFormat("#define X -1"); 9772 verifyFormat("#define X -kConstant"); 9773 9774 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9775 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9776 9777 verifyFormat("int a = /* confusing comment */ -1;"); 9778 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9779 verifyFormat("int a = i /* confusing comment */++;"); 9780 9781 verifyFormat("co_yield -1;"); 9782 verifyFormat("co_return -1;"); 9783 9784 // Check that * is not treated as a binary operator when we set 9785 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9786 FormatStyle PASLeftStyle = getLLVMStyle(); 9787 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9788 verifyFormat("co_return *a;", PASLeftStyle); 9789 verifyFormat("co_await *a;", PASLeftStyle); 9790 verifyFormat("co_yield *a", PASLeftStyle); 9791 verifyFormat("return *a;", PASLeftStyle); 9792 } 9793 9794 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9795 verifyFormat("if (!aaaaaaaaaa( // break\n" 9796 " aaaaa)) {\n" 9797 "}"); 9798 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9799 " aaaaa));"); 9800 verifyFormat("*aaa = aaaaaaa( // break\n" 9801 " bbbbbb);"); 9802 } 9803 9804 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9805 verifyFormat("bool operator<();"); 9806 verifyFormat("bool operator>();"); 9807 verifyFormat("bool operator=();"); 9808 verifyFormat("bool operator==();"); 9809 verifyFormat("bool operator!=();"); 9810 verifyFormat("int operator+();"); 9811 verifyFormat("int operator++();"); 9812 verifyFormat("int operator++(int) volatile noexcept;"); 9813 verifyFormat("bool operator,();"); 9814 verifyFormat("bool operator();"); 9815 verifyFormat("bool operator()();"); 9816 verifyFormat("bool operator[]();"); 9817 verifyFormat("operator bool();"); 9818 verifyFormat("operator int();"); 9819 verifyFormat("operator void *();"); 9820 verifyFormat("operator SomeType<int>();"); 9821 verifyFormat("operator SomeType<int, int>();"); 9822 verifyFormat("operator SomeType<SomeType<int>>();"); 9823 verifyFormat("operator< <>();"); 9824 verifyFormat("operator<< <>();"); 9825 verifyFormat("< <>"); 9826 9827 verifyFormat("void *operator new(std::size_t size);"); 9828 verifyFormat("void *operator new[](std::size_t size);"); 9829 verifyFormat("void operator delete(void *ptr);"); 9830 verifyFormat("void operator delete[](void *ptr);"); 9831 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9832 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9833 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9834 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9835 9836 verifyFormat( 9837 "ostream &operator<<(ostream &OutputStream,\n" 9838 " SomeReallyLongType WithSomeReallyLongValue);"); 9839 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9840 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9841 " return left.group < right.group;\n" 9842 "}"); 9843 verifyFormat("SomeType &operator=(const SomeType &S);"); 9844 verifyFormat("f.template operator()<int>();"); 9845 9846 verifyGoogleFormat("operator void*();"); 9847 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9848 verifyGoogleFormat("operator ::A();"); 9849 9850 verifyFormat("using A::operator+;"); 9851 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9852 "int i;"); 9853 9854 // Calling an operator as a member function. 9855 verifyFormat("void f() { a.operator*(); }"); 9856 verifyFormat("void f() { a.operator*(b & b); }"); 9857 verifyFormat("void f() { a->operator&(a * b); }"); 9858 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9859 // TODO: Calling an operator as a non-member function is hard to distinguish. 9860 // https://llvm.org/PR50629 9861 // verifyFormat("void f() { operator*(a & a); }"); 9862 // verifyFormat("void f() { operator&(a, b * b); }"); 9863 9864 verifyFormat("::operator delete(foo);"); 9865 verifyFormat("::operator new(n * sizeof(foo));"); 9866 verifyFormat("foo() { ::operator delete(foo); }"); 9867 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9868 } 9869 9870 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9871 verifyFormat("void A::b() && {}"); 9872 verifyFormat("void A::b() &&noexcept {}"); 9873 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9874 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9875 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9876 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9877 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9878 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9879 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9880 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9881 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9882 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9883 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9884 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9885 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9886 verifyFormat("void Fn(T const &) const &;"); 9887 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9888 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9889 verifyFormat("template <typename T>\n" 9890 "void F(T) && = delete;", 9891 getGoogleStyle()); 9892 verifyFormat("template <typename T> void operator=(T) &;"); 9893 verifyFormat("template <typename T> void operator=(T) const &;"); 9894 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9895 verifyFormat("template <typename T> void operator=(T) & = default;"); 9896 verifyFormat("template <typename T> void operator=(T) &&;"); 9897 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9898 verifyFormat("template <typename T> void operator=(T) & {}"); 9899 verifyFormat("template <typename T> void operator=(T) && {}"); 9900 9901 FormatStyle AlignLeft = getLLVMStyle(); 9902 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9903 verifyFormat("void A::b() && {}", AlignLeft); 9904 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9905 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9906 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9907 AlignLeft); 9908 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9909 AlignLeft); 9910 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9911 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9912 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9913 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9914 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9915 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9916 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9917 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9918 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9919 AlignLeft); 9920 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 9921 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 9922 verifyFormat("template <typename T> void operator=(T) & noexcept;", AlignLeft); 9923 verifyFormat("template <typename T> void operator=(T) & = default;", AlignLeft); 9924 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9925 verifyFormat("template <typename T> void operator=(T) && = delete;", AlignLeft); 9926 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9927 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9928 9929 FormatStyle AlignMiddle = getLLVMStyle(); 9930 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9931 verifyFormat("void A::b() && {}", AlignMiddle); 9932 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9933 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9934 AlignMiddle); 9935 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9936 AlignMiddle); 9937 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9938 AlignMiddle); 9939 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9940 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9941 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9942 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9943 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9944 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9945 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9946 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9947 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9948 AlignMiddle); 9949 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 9950 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 9951 verifyFormat("template <typename T> void operator=(T) & noexcept;", AlignMiddle); 9952 verifyFormat("template <typename T> void operator=(T) & = default;", AlignMiddle); 9953 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 9954 verifyFormat("template <typename T> void operator=(T) && = delete;", AlignMiddle); 9955 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 9956 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 9957 9958 FormatStyle Spaces = getLLVMStyle(); 9959 Spaces.SpacesInCStyleCastParentheses = true; 9960 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9961 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9962 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9963 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9964 9965 Spaces.SpacesInCStyleCastParentheses = false; 9966 Spaces.SpacesInParentheses = true; 9967 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9968 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9969 Spaces); 9970 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9971 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9972 9973 FormatStyle BreakTemplate = getLLVMStyle(); 9974 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9975 9976 verifyFormat("struct f {\n" 9977 " template <class T>\n" 9978 " int &foo(const std::string &str) &noexcept {}\n" 9979 "};", 9980 BreakTemplate); 9981 9982 verifyFormat("struct f {\n" 9983 " template <class T>\n" 9984 " int &foo(const std::string &str) &&noexcept {}\n" 9985 "};", 9986 BreakTemplate); 9987 9988 verifyFormat("struct f {\n" 9989 " template <class T>\n" 9990 " int &foo(const std::string &str) const &noexcept {}\n" 9991 "};", 9992 BreakTemplate); 9993 9994 verifyFormat("struct f {\n" 9995 " template <class T>\n" 9996 " int &foo(const std::string &str) const &noexcept {}\n" 9997 "};", 9998 BreakTemplate); 9999 10000 verifyFormat("struct f {\n" 10001 " template <class T>\n" 10002 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10003 "};", 10004 BreakTemplate); 10005 10006 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10007 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10008 FormatStyle::BTDS_Yes; 10009 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10010 10011 verifyFormat("struct f {\n" 10012 " template <class T>\n" 10013 " int& foo(const std::string& str) & noexcept {}\n" 10014 "};", 10015 AlignLeftBreakTemplate); 10016 10017 verifyFormat("struct f {\n" 10018 " template <class T>\n" 10019 " int& foo(const std::string& str) && noexcept {}\n" 10020 "};", 10021 AlignLeftBreakTemplate); 10022 10023 verifyFormat("struct f {\n" 10024 " template <class T>\n" 10025 " int& foo(const std::string& str) const& noexcept {}\n" 10026 "};", 10027 AlignLeftBreakTemplate); 10028 10029 verifyFormat("struct f {\n" 10030 " template <class T>\n" 10031 " int& foo(const std::string& str) const&& noexcept {}\n" 10032 "};", 10033 AlignLeftBreakTemplate); 10034 10035 verifyFormat("struct f {\n" 10036 " template <class T>\n" 10037 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10038 "};", 10039 AlignLeftBreakTemplate); 10040 10041 // The `&` in `Type&` should not be confused with a trailing `&` of 10042 // DEPRECATED(reason) member function. 10043 verifyFormat("struct f {\n" 10044 " template <class T>\n" 10045 " DEPRECATED(reason)\n" 10046 " Type &foo(arguments) {}\n" 10047 "};", 10048 BreakTemplate); 10049 10050 verifyFormat("struct f {\n" 10051 " template <class T>\n" 10052 " DEPRECATED(reason)\n" 10053 " Type& foo(arguments) {}\n" 10054 "};", 10055 AlignLeftBreakTemplate); 10056 10057 verifyFormat("void (*foopt)(int) = &func;"); 10058 10059 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10060 DerivePointerAlignment.DerivePointerAlignment = true; 10061 // There's always a space between the function and its trailing qualifiers. 10062 // This isn't evidence for PAS_Right (or for PAS_Left). 10063 std::string Prefix = "void a() &;\n" 10064 "void b() &;\n"; 10065 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10066 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10067 // Same if the function is an overloaded operator, and with &&. 10068 Prefix = "void operator()() &&;\n" 10069 "void operator()() &&;\n"; 10070 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10071 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10072 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10073 Prefix = "void a() const &;\n" 10074 "void b() const &;\n"; 10075 EXPECT_EQ(Prefix + "int *x;", 10076 format(Prefix + "int* x;", DerivePointerAlignment)); 10077 } 10078 10079 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10080 verifyFormat("void f() {\n" 10081 " A *a = new A;\n" 10082 " A *a = new (placement) A;\n" 10083 " delete a;\n" 10084 " delete (A *)a;\n" 10085 "}"); 10086 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10087 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10088 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10089 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10090 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10091 verifyFormat("delete[] h->p;"); 10092 verifyFormat("delete[] (void *)p;"); 10093 10094 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10095 verifyFormat("void operator new(void *foo) ATTRIB;"); 10096 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10097 verifyFormat("void operator delete(void *ptr) noexcept;"); 10098 10099 EXPECT_EQ("void new(link p);\n" 10100 "void delete(link p);\n", 10101 format("void new (link p);\n" 10102 "void delete (link p);\n")); 10103 } 10104 10105 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10106 verifyFormat("int *f(int *a) {}"); 10107 verifyFormat("int main(int argc, char **argv) {}"); 10108 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10109 verifyIndependentOfContext("f(a, *a);"); 10110 verifyFormat("void g() { f(*a); }"); 10111 verifyIndependentOfContext("int a = b * 10;"); 10112 verifyIndependentOfContext("int a = 10 * b;"); 10113 verifyIndependentOfContext("int a = b * c;"); 10114 verifyIndependentOfContext("int a += b * c;"); 10115 verifyIndependentOfContext("int a -= b * c;"); 10116 verifyIndependentOfContext("int a *= b * c;"); 10117 verifyIndependentOfContext("int a /= b * c;"); 10118 verifyIndependentOfContext("int a = *b;"); 10119 verifyIndependentOfContext("int a = *b * c;"); 10120 verifyIndependentOfContext("int a = b * *c;"); 10121 verifyIndependentOfContext("int a = b * (10);"); 10122 verifyIndependentOfContext("S << b * (10);"); 10123 verifyIndependentOfContext("return 10 * b;"); 10124 verifyIndependentOfContext("return *b * *c;"); 10125 verifyIndependentOfContext("return a & ~b;"); 10126 verifyIndependentOfContext("f(b ? *c : *d);"); 10127 verifyIndependentOfContext("int a = b ? *c : *d;"); 10128 verifyIndependentOfContext("*b = a;"); 10129 verifyIndependentOfContext("a * ~b;"); 10130 verifyIndependentOfContext("a * !b;"); 10131 verifyIndependentOfContext("a * +b;"); 10132 verifyIndependentOfContext("a * -b;"); 10133 verifyIndependentOfContext("a * ++b;"); 10134 verifyIndependentOfContext("a * --b;"); 10135 verifyIndependentOfContext("a[4] * b;"); 10136 verifyIndependentOfContext("a[a * a] = 1;"); 10137 verifyIndependentOfContext("f() * b;"); 10138 verifyIndependentOfContext("a * [self dostuff];"); 10139 verifyIndependentOfContext("int x = a * (a + b);"); 10140 verifyIndependentOfContext("(a *)(a + b);"); 10141 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10142 verifyIndependentOfContext("int *pa = (int *)&a;"); 10143 verifyIndependentOfContext("return sizeof(int **);"); 10144 verifyIndependentOfContext("return sizeof(int ******);"); 10145 verifyIndependentOfContext("return (int **&)a;"); 10146 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10147 verifyFormat("void f(Type (*parameter)[10]) {}"); 10148 verifyFormat("void f(Type (¶meter)[10]) {}"); 10149 verifyGoogleFormat("return sizeof(int**);"); 10150 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10151 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10152 verifyFormat("auto a = [](int **&, int ***) {};"); 10153 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10154 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10155 verifyFormat("[](const decltype(*a) &value) {}"); 10156 verifyFormat("[](const typeof(*a) &value) {}"); 10157 verifyFormat("[](const _Atomic(a *) &value) {}"); 10158 verifyFormat("[](const __underlying_type(a) &value) {}"); 10159 verifyFormat("decltype(a * b) F();"); 10160 verifyFormat("typeof(a * b) F();"); 10161 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10162 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10163 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10164 verifyIndependentOfContext("int i{a * b};"); 10165 verifyIndependentOfContext("aaa && aaa->f();"); 10166 verifyIndependentOfContext("int x = ~*p;"); 10167 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10168 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10169 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10170 verifyFormat("void f() { f(a, c * d); }"); 10171 verifyFormat("void f() { f(new a(), c * d); }"); 10172 verifyFormat("void f(const MyOverride &override);"); 10173 verifyFormat("void f(const MyFinal &final);"); 10174 verifyIndependentOfContext("bool a = f() && override.f();"); 10175 verifyIndependentOfContext("bool a = f() && final.f();"); 10176 10177 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10178 10179 verifyIndependentOfContext("A<int *> a;"); 10180 verifyIndependentOfContext("A<int **> a;"); 10181 verifyIndependentOfContext("A<int *, int *> a;"); 10182 verifyIndependentOfContext("A<int *[]> a;"); 10183 verifyIndependentOfContext( 10184 "const char *const p = reinterpret_cast<const char *const>(q);"); 10185 verifyIndependentOfContext("A<int **, int **> a;"); 10186 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10187 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10188 verifyFormat("for (; a && b;) {\n}"); 10189 verifyFormat("bool foo = true && [] { return false; }();"); 10190 10191 verifyFormat( 10192 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10193 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10194 10195 verifyGoogleFormat("int const* a = &b;"); 10196 verifyGoogleFormat("**outparam = 1;"); 10197 verifyGoogleFormat("*outparam = a * b;"); 10198 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10199 verifyGoogleFormat("A<int*> a;"); 10200 verifyGoogleFormat("A<int**> a;"); 10201 verifyGoogleFormat("A<int*, int*> a;"); 10202 verifyGoogleFormat("A<int**, int**> a;"); 10203 verifyGoogleFormat("f(b ? *c : *d);"); 10204 verifyGoogleFormat("int a = b ? *c : *d;"); 10205 verifyGoogleFormat("Type* t = **x;"); 10206 verifyGoogleFormat("Type* t = *++*x;"); 10207 verifyGoogleFormat("*++*x;"); 10208 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10209 verifyGoogleFormat("Type* t = x++ * y;"); 10210 verifyGoogleFormat( 10211 "const char* const p = reinterpret_cast<const char* const>(q);"); 10212 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10213 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10214 verifyGoogleFormat("template <typename T>\n" 10215 "void f(int i = 0, SomeType** temps = NULL);"); 10216 10217 FormatStyle Left = getLLVMStyle(); 10218 Left.PointerAlignment = FormatStyle::PAS_Left; 10219 verifyFormat("x = *a(x) = *a(y);", Left); 10220 verifyFormat("for (;; *a = b) {\n}", Left); 10221 verifyFormat("return *this += 1;", Left); 10222 verifyFormat("throw *x;", Left); 10223 verifyFormat("delete *x;", Left); 10224 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10225 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10226 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10227 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10228 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10229 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10230 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10231 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10232 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10233 10234 verifyIndependentOfContext("a = *(x + y);"); 10235 verifyIndependentOfContext("a = &(x + y);"); 10236 verifyIndependentOfContext("*(x + y).call();"); 10237 verifyIndependentOfContext("&(x + y)->call();"); 10238 verifyFormat("void f() { &(*I).first; }"); 10239 10240 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10241 verifyFormat("f(* /* confusing comment */ foo);"); 10242 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10243 verifyFormat("void foo(int * // this is the first paramters\n" 10244 " ,\n" 10245 " int second);"); 10246 verifyFormat("double term = a * // first\n" 10247 " b;"); 10248 verifyFormat( 10249 "int *MyValues = {\n" 10250 " *A, // Operator detection might be confused by the '{'\n" 10251 " *BB // Operator detection might be confused by previous comment\n" 10252 "};"); 10253 10254 verifyIndependentOfContext("if (int *a = &b)"); 10255 verifyIndependentOfContext("if (int &a = *b)"); 10256 verifyIndependentOfContext("if (a & b[i])"); 10257 verifyIndependentOfContext("if constexpr (a & b[i])"); 10258 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10259 verifyIndependentOfContext("if (a * (b * c))"); 10260 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10261 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10262 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10263 verifyIndependentOfContext("if (*b[i])"); 10264 verifyIndependentOfContext("if (int *a = (&b))"); 10265 verifyIndependentOfContext("while (int *a = &b)"); 10266 verifyIndependentOfContext("while (a * (b * c))"); 10267 verifyIndependentOfContext("size = sizeof *a;"); 10268 verifyIndependentOfContext("if (a && (b = c))"); 10269 verifyFormat("void f() {\n" 10270 " for (const int &v : Values) {\n" 10271 " }\n" 10272 "}"); 10273 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10274 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10275 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10276 10277 verifyFormat("#define A (!a * b)"); 10278 verifyFormat("#define MACRO \\\n" 10279 " int *i = a * b; \\\n" 10280 " void f(a *b);", 10281 getLLVMStyleWithColumns(19)); 10282 10283 verifyIndependentOfContext("A = new SomeType *[Length];"); 10284 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10285 verifyIndependentOfContext("T **t = new T *;"); 10286 verifyIndependentOfContext("T **t = new T *();"); 10287 verifyGoogleFormat("A = new SomeType*[Length]();"); 10288 verifyGoogleFormat("A = new SomeType*[Length];"); 10289 verifyGoogleFormat("T** t = new T*;"); 10290 verifyGoogleFormat("T** t = new T*();"); 10291 10292 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10293 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10294 verifyFormat("template <bool a, bool b> " 10295 "typename t::if<x && y>::type f() {}"); 10296 verifyFormat("template <int *y> f() {}"); 10297 verifyFormat("vector<int *> v;"); 10298 verifyFormat("vector<int *const> v;"); 10299 verifyFormat("vector<int *const **const *> v;"); 10300 verifyFormat("vector<int *volatile> v;"); 10301 verifyFormat("vector<a *_Nonnull> v;"); 10302 verifyFormat("vector<a *_Nullable> v;"); 10303 verifyFormat("vector<a *_Null_unspecified> v;"); 10304 verifyFormat("vector<a *__ptr32> v;"); 10305 verifyFormat("vector<a *__ptr64> v;"); 10306 verifyFormat("vector<a *__capability> v;"); 10307 FormatStyle TypeMacros = getLLVMStyle(); 10308 TypeMacros.TypenameMacros = {"LIST"}; 10309 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10310 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10311 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10312 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10313 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10314 10315 FormatStyle CustomQualifier = getLLVMStyle(); 10316 // Add identifiers that should not be parsed as a qualifier by default. 10317 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10318 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10319 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10320 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10321 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10322 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10323 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10324 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10325 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10326 verifyFormat("vector<a * _NotAQualifier> v;"); 10327 verifyFormat("vector<a * __not_a_qualifier> v;"); 10328 verifyFormat("vector<a * b> v;"); 10329 verifyFormat("foo<b && false>();"); 10330 verifyFormat("foo<b & 1>();"); 10331 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10332 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10333 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10334 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10335 verifyFormat( 10336 "template <class T, class = typename std::enable_if<\n" 10337 " std::is_integral<T>::value &&\n" 10338 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10339 "void F();", 10340 getLLVMStyleWithColumns(70)); 10341 verifyFormat("template <class T,\n" 10342 " class = typename std::enable_if<\n" 10343 " std::is_integral<T>::value &&\n" 10344 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10345 " class U>\n" 10346 "void F();", 10347 getLLVMStyleWithColumns(70)); 10348 verifyFormat( 10349 "template <class T,\n" 10350 " class = typename ::std::enable_if<\n" 10351 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10352 "void F();", 10353 getGoogleStyleWithColumns(68)); 10354 10355 verifyIndependentOfContext("MACRO(int *i);"); 10356 verifyIndependentOfContext("MACRO(auto *a);"); 10357 verifyIndependentOfContext("MACRO(const A *a);"); 10358 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10359 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10360 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10361 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10362 verifyIndependentOfContext("MACRO(A *const a);"); 10363 verifyIndependentOfContext("MACRO(A *restrict a);"); 10364 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10365 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10366 verifyIndependentOfContext("MACRO(A *volatile a);"); 10367 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10368 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10369 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10370 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10371 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10372 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10373 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10374 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10375 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10376 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10377 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10378 verifyIndependentOfContext("MACRO(A *__capability);"); 10379 verifyIndependentOfContext("MACRO(A &__capability);"); 10380 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10381 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10382 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10383 // a type declaration: 10384 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10385 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10386 // Also check that TypenameMacros prevents parsing it as multiplication: 10387 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10388 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10389 10390 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10391 verifyFormat("void f() { f(float{1}, a * a); }"); 10392 verifyFormat("void f() { f(float(1), a * a); }"); 10393 10394 verifyFormat("f((void (*)(int))g);"); 10395 verifyFormat("f((void (&)(int))g);"); 10396 verifyFormat("f((void (^)(int))g);"); 10397 10398 // FIXME: Is there a way to make this work? 10399 // verifyIndependentOfContext("MACRO(A *a);"); 10400 verifyFormat("MACRO(A &B);"); 10401 verifyFormat("MACRO(A *B);"); 10402 verifyFormat("void f() { MACRO(A * B); }"); 10403 verifyFormat("void f() { MACRO(A & B); }"); 10404 10405 // This lambda was mis-formatted after D88956 (treating it as a binop): 10406 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10407 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10408 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10409 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10410 10411 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10412 verifyFormat("return options != nullptr && operator==(*options);"); 10413 10414 EXPECT_EQ("#define OP(x) \\\n" 10415 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10416 " return s << a.DebugString(); \\\n" 10417 " }", 10418 format("#define OP(x) \\\n" 10419 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10420 " return s << a.DebugString(); \\\n" 10421 " }", 10422 getLLVMStyleWithColumns(50))); 10423 10424 // FIXME: We cannot handle this case yet; we might be able to figure out that 10425 // foo<x> d > v; doesn't make sense. 10426 verifyFormat("foo<a<b && c> d> v;"); 10427 10428 FormatStyle PointerMiddle = getLLVMStyle(); 10429 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10430 verifyFormat("delete *x;", PointerMiddle); 10431 verifyFormat("int * x;", PointerMiddle); 10432 verifyFormat("int *[] x;", PointerMiddle); 10433 verifyFormat("template <int * y> f() {}", PointerMiddle); 10434 verifyFormat("int * f(int * a) {}", PointerMiddle); 10435 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10436 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10437 verifyFormat("A<int *> a;", PointerMiddle); 10438 verifyFormat("A<int **> a;", PointerMiddle); 10439 verifyFormat("A<int *, int *> a;", PointerMiddle); 10440 verifyFormat("A<int *[]> a;", PointerMiddle); 10441 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10442 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10443 verifyFormat("T ** t = new T *;", PointerMiddle); 10444 10445 // Member function reference qualifiers aren't binary operators. 10446 verifyFormat("string // break\n" 10447 "operator()() & {}"); 10448 verifyFormat("string // break\n" 10449 "operator()() && {}"); 10450 verifyGoogleFormat("template <typename T>\n" 10451 "auto x() & -> int {}"); 10452 10453 // Should be binary operators when used as an argument expression (overloaded 10454 // operator invoked as a member function). 10455 verifyFormat("void f() { a.operator()(a * a); }"); 10456 verifyFormat("void f() { a->operator()(a & a); }"); 10457 verifyFormat("void f() { a.operator()(*a & *a); }"); 10458 verifyFormat("void f() { a->operator()(*a * *a); }"); 10459 10460 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10461 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10462 } 10463 10464 TEST_F(FormatTest, UnderstandsAttributes) { 10465 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10466 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10467 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10468 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10469 FormatStyle AfterType = getLLVMStyle(); 10470 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10471 verifyFormat("__attribute__((nodebug)) void\n" 10472 "foo() {}\n", 10473 AfterType); 10474 verifyFormat("__unused void\n" 10475 "foo() {}", 10476 AfterType); 10477 10478 FormatStyle CustomAttrs = getLLVMStyle(); 10479 CustomAttrs.AttributeMacros.push_back("__unused"); 10480 CustomAttrs.AttributeMacros.push_back("__attr1"); 10481 CustomAttrs.AttributeMacros.push_back("__attr2"); 10482 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10483 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10484 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10485 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10486 // Check that it is parsed as a multiplication without AttributeMacros and 10487 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10488 verifyFormat("vector<SomeType * __attr1> v;"); 10489 verifyFormat("vector<SomeType __attr1 *> v;"); 10490 verifyFormat("vector<SomeType __attr1 *const> v;"); 10491 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10492 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10493 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10494 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10495 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10496 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10497 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10498 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10499 10500 // Check that these are not parsed as function declarations: 10501 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10502 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10503 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10504 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10505 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10506 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10507 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10508 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10509 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10510 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10511 } 10512 10513 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10514 // Check that qualifiers on pointers don't break parsing of casts. 10515 verifyFormat("x = (foo *const)*v;"); 10516 verifyFormat("x = (foo *volatile)*v;"); 10517 verifyFormat("x = (foo *restrict)*v;"); 10518 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10519 verifyFormat("x = (foo *_Nonnull)*v;"); 10520 verifyFormat("x = (foo *_Nullable)*v;"); 10521 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10522 verifyFormat("x = (foo *_Nonnull)*v;"); 10523 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10524 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10525 verifyFormat("x = (foo *__ptr32)*v;"); 10526 verifyFormat("x = (foo *__ptr64)*v;"); 10527 verifyFormat("x = (foo *__capability)*v;"); 10528 10529 // Check that we handle multiple trailing qualifiers and skip them all to 10530 // determine that the expression is a cast to a pointer type. 10531 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10532 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10533 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10534 StringRef AllQualifiers = 10535 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10536 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10537 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10538 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10539 10540 // Also check that address-of is not parsed as a binary bitwise-and: 10541 verifyFormat("x = (foo *const)&v;"); 10542 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10543 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10544 10545 // Check custom qualifiers: 10546 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10547 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10548 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10549 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10550 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10551 CustomQualifier); 10552 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10553 CustomQualifier); 10554 10555 // Check that unknown identifiers result in binary operator parsing: 10556 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10557 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10558 } 10559 10560 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10561 verifyFormat("SomeType s [[unused]] (InitValue);"); 10562 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10563 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10564 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10565 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10566 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10567 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10568 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10569 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10570 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10571 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10572 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10573 10574 // Make sure we do not mistake attributes for array subscripts. 10575 verifyFormat("int a() {}\n" 10576 "[[unused]] int b() {}\n"); 10577 verifyFormat("NSArray *arr;\n" 10578 "arr[[Foo() bar]];"); 10579 10580 // On the other hand, we still need to correctly find array subscripts. 10581 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10582 10583 // Make sure that we do not mistake Objective-C method inside array literals 10584 // as attributes, even if those method names are also keywords. 10585 verifyFormat("@[ [foo bar] ];"); 10586 verifyFormat("@[ [NSArray class] ];"); 10587 verifyFormat("@[ [foo enum] ];"); 10588 10589 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10590 10591 // Make sure we do not parse attributes as lambda introducers. 10592 FormatStyle MultiLineFunctions = getLLVMStyle(); 10593 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10594 verifyFormat("[[unused]] int b() {\n" 10595 " return 42;\n" 10596 "}\n", 10597 MultiLineFunctions); 10598 } 10599 10600 TEST_F(FormatTest, AttributeClass) { 10601 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10602 verifyFormat("class S {\n" 10603 " S(S&&) = default;\n" 10604 "};", 10605 Style); 10606 verifyFormat("class [[nodiscard]] S {\n" 10607 " S(S&&) = default;\n" 10608 "};", 10609 Style); 10610 verifyFormat("class __attribute((maybeunused)) S {\n" 10611 " S(S&&) = default;\n" 10612 "};", 10613 Style); 10614 verifyFormat("struct S {\n" 10615 " S(S&&) = default;\n" 10616 "};", 10617 Style); 10618 verifyFormat("struct [[nodiscard]] S {\n" 10619 " S(S&&) = default;\n" 10620 "};", 10621 Style); 10622 } 10623 10624 TEST_F(FormatTest, AttributesAfterMacro) { 10625 FormatStyle Style = getLLVMStyle(); 10626 verifyFormat("MACRO;\n" 10627 "__attribute__((maybe_unused)) int foo() {\n" 10628 " //...\n" 10629 "}"); 10630 10631 verifyFormat("MACRO;\n" 10632 "[[nodiscard]] int foo() {\n" 10633 " //...\n" 10634 "}"); 10635 10636 EXPECT_EQ("MACRO\n\n" 10637 "__attribute__((maybe_unused)) int foo() {\n" 10638 " //...\n" 10639 "}", 10640 format("MACRO\n\n" 10641 "__attribute__((maybe_unused)) int foo() {\n" 10642 " //...\n" 10643 "}")); 10644 10645 EXPECT_EQ("MACRO\n\n" 10646 "[[nodiscard]] int foo() {\n" 10647 " //...\n" 10648 "}", 10649 format("MACRO\n\n" 10650 "[[nodiscard]] int foo() {\n" 10651 " //...\n" 10652 "}")); 10653 } 10654 10655 TEST_F(FormatTest, AttributePenaltyBreaking) { 10656 FormatStyle Style = getLLVMStyle(); 10657 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10658 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10659 Style); 10660 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10661 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10662 Style); 10663 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10664 "shared_ptr<ALongTypeName> &C d) {\n}", 10665 Style); 10666 } 10667 10668 TEST_F(FormatTest, UnderstandsEllipsis) { 10669 FormatStyle Style = getLLVMStyle(); 10670 verifyFormat("int printf(const char *fmt, ...);"); 10671 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10672 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10673 10674 verifyFormat("template <int *...PP> a;", Style); 10675 10676 Style.PointerAlignment = FormatStyle::PAS_Left; 10677 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10678 10679 verifyFormat("template <int*... PP> a;", Style); 10680 10681 Style.PointerAlignment = FormatStyle::PAS_Middle; 10682 verifyFormat("template <int *... PP> a;", Style); 10683 } 10684 10685 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10686 EXPECT_EQ("int *a;\n" 10687 "int *a;\n" 10688 "int *a;", 10689 format("int *a;\n" 10690 "int* a;\n" 10691 "int *a;", 10692 getGoogleStyle())); 10693 EXPECT_EQ("int* a;\n" 10694 "int* a;\n" 10695 "int* a;", 10696 format("int* a;\n" 10697 "int* a;\n" 10698 "int *a;", 10699 getGoogleStyle())); 10700 EXPECT_EQ("int *a;\n" 10701 "int *a;\n" 10702 "int *a;", 10703 format("int *a;\n" 10704 "int * a;\n" 10705 "int * a;", 10706 getGoogleStyle())); 10707 EXPECT_EQ("auto x = [] {\n" 10708 " int *a;\n" 10709 " int *a;\n" 10710 " int *a;\n" 10711 "};", 10712 format("auto x=[]{int *a;\n" 10713 "int * a;\n" 10714 "int * a;};", 10715 getGoogleStyle())); 10716 } 10717 10718 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10719 verifyFormat("int f(int &&a) {}"); 10720 verifyFormat("int f(int a, char &&b) {}"); 10721 verifyFormat("void f() { int &&a = b; }"); 10722 verifyGoogleFormat("int f(int a, char&& b) {}"); 10723 verifyGoogleFormat("void f() { int&& a = b; }"); 10724 10725 verifyIndependentOfContext("A<int &&> a;"); 10726 verifyIndependentOfContext("A<int &&, int &&> a;"); 10727 verifyGoogleFormat("A<int&&> a;"); 10728 verifyGoogleFormat("A<int&&, int&&> a;"); 10729 10730 // Not rvalue references: 10731 verifyFormat("template <bool B, bool C> class A {\n" 10732 " static_assert(B && C, \"Something is wrong\");\n" 10733 "};"); 10734 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10735 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10736 verifyFormat("#define A(a, b) (a && b)"); 10737 } 10738 10739 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10740 verifyFormat("void f() {\n" 10741 " x[aaaaaaaaa -\n" 10742 " b] = 23;\n" 10743 "}", 10744 getLLVMStyleWithColumns(15)); 10745 } 10746 10747 TEST_F(FormatTest, FormatsCasts) { 10748 verifyFormat("Type *A = static_cast<Type *>(P);"); 10749 verifyFormat("static_cast<Type *>(P);"); 10750 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10751 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10752 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10753 // Check that static_cast<...>(...) does not require the next token to be on 10754 // the same line. 10755 verifyFormat("some_loooong_output << something_something__ << " 10756 "static_cast<const void *>(R)\n" 10757 " << something;"); 10758 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10759 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10760 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10761 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10762 verifyFormat("Type *A = (Type *)P;"); 10763 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10764 verifyFormat("int a = (int)(2.0f);"); 10765 verifyFormat("int a = (int)2.0f;"); 10766 verifyFormat("x[(int32)y];"); 10767 verifyFormat("x = (int32)y;"); 10768 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10769 verifyFormat("int a = (int)*b;"); 10770 verifyFormat("int a = (int)2.0f;"); 10771 verifyFormat("int a = (int)~0;"); 10772 verifyFormat("int a = (int)++a;"); 10773 verifyFormat("int a = (int)sizeof(int);"); 10774 verifyFormat("int a = (int)+2;"); 10775 verifyFormat("my_int a = (my_int)2.0f;"); 10776 verifyFormat("my_int a = (my_int)sizeof(int);"); 10777 verifyFormat("return (my_int)aaa;"); 10778 verifyFormat("#define x ((int)-1)"); 10779 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10780 verifyFormat("#define p(q) ((int *)&q)"); 10781 verifyFormat("fn(a)(b) + 1;"); 10782 10783 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10784 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10785 verifyFormat("my_int a = (my_int)~0;"); 10786 verifyFormat("my_int a = (my_int)++a;"); 10787 verifyFormat("my_int a = (my_int)-2;"); 10788 verifyFormat("my_int a = (my_int)1;"); 10789 verifyFormat("my_int a = (my_int *)1;"); 10790 verifyFormat("my_int a = (const my_int)-1;"); 10791 verifyFormat("my_int a = (const my_int *)-1;"); 10792 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10793 verifyFormat("my_int a = (ns::my_int)-2;"); 10794 verifyFormat("case (my_int)ONE:"); 10795 verifyFormat("auto x = (X)this;"); 10796 // Casts in Obj-C style calls used to not be recognized as such. 10797 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10798 10799 // FIXME: single value wrapped with paren will be treated as cast. 10800 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10801 10802 verifyFormat("{ (void)F; }"); 10803 10804 // Don't break after a cast's 10805 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10806 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10807 " bbbbbbbbbbbbbbbbbbbbbb);"); 10808 10809 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10810 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10811 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10812 verifyFormat("bool *y = (bool *)(void *)(x);"); 10813 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10814 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10815 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10816 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10817 10818 // These are not casts. 10819 verifyFormat("void f(int *) {}"); 10820 verifyFormat("f(foo)->b;"); 10821 verifyFormat("f(foo).b;"); 10822 verifyFormat("f(foo)(b);"); 10823 verifyFormat("f(foo)[b];"); 10824 verifyFormat("[](foo) { return 4; }(bar);"); 10825 verifyFormat("(*funptr)(foo)[4];"); 10826 verifyFormat("funptrs[4](foo)[4];"); 10827 verifyFormat("void f(int *);"); 10828 verifyFormat("void f(int *) = 0;"); 10829 verifyFormat("void f(SmallVector<int>) {}"); 10830 verifyFormat("void f(SmallVector<int>);"); 10831 verifyFormat("void f(SmallVector<int>) = 0;"); 10832 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10833 verifyFormat("int a = sizeof(int) * b;"); 10834 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10835 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10836 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10837 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10838 10839 // These are not casts, but at some point were confused with casts. 10840 verifyFormat("virtual void foo(int *) override;"); 10841 verifyFormat("virtual void foo(char &) const;"); 10842 verifyFormat("virtual void foo(int *a, char *) const;"); 10843 verifyFormat("int a = sizeof(int *) + b;"); 10844 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10845 verifyFormat("bool b = f(g<int>) && c;"); 10846 verifyFormat("typedef void (*f)(int i) func;"); 10847 verifyFormat("void operator++(int) noexcept;"); 10848 verifyFormat("void operator++(int &) noexcept;"); 10849 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10850 "&) noexcept;"); 10851 verifyFormat( 10852 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10853 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10854 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10855 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10856 verifyFormat("void operator delete(foo &) noexcept;"); 10857 verifyFormat("void operator delete(foo) noexcept;"); 10858 verifyFormat("void operator delete(int) noexcept;"); 10859 verifyFormat("void operator delete(int &) noexcept;"); 10860 verifyFormat("void operator delete(int &) volatile noexcept;"); 10861 verifyFormat("void operator delete(int &) const"); 10862 verifyFormat("void operator delete(int &) = default"); 10863 verifyFormat("void operator delete(int &) = delete"); 10864 verifyFormat("void operator delete(int &) [[noreturn]]"); 10865 verifyFormat("void operator delete(int &) throw();"); 10866 verifyFormat("void operator delete(int &) throw(int);"); 10867 verifyFormat("auto operator delete(int &) -> int;"); 10868 verifyFormat("auto operator delete(int &) override"); 10869 verifyFormat("auto operator delete(int &) final"); 10870 10871 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10872 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10873 // FIXME: The indentation here is not ideal. 10874 verifyFormat( 10875 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10876 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10877 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10878 } 10879 10880 TEST_F(FormatTest, FormatsFunctionTypes) { 10881 verifyFormat("A<bool()> a;"); 10882 verifyFormat("A<SomeType()> a;"); 10883 verifyFormat("A<void (*)(int, std::string)> a;"); 10884 verifyFormat("A<void *(int)>;"); 10885 verifyFormat("void *(*a)(int *, SomeType *);"); 10886 verifyFormat("int (*func)(void *);"); 10887 verifyFormat("void f() { int (*func)(void *); }"); 10888 verifyFormat("template <class CallbackClass>\n" 10889 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10890 10891 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10892 verifyGoogleFormat("void* (*a)(int);"); 10893 verifyGoogleFormat( 10894 "template <class CallbackClass>\n" 10895 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10896 10897 // Other constructs can look somewhat like function types: 10898 verifyFormat("A<sizeof(*x)> a;"); 10899 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10900 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10901 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10902 verifyFormat("int x = f(&h)();"); 10903 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10904 verifyFormat("std::function<\n" 10905 " LooooooooooongTemplatedType<\n" 10906 " SomeType>*(\n" 10907 " LooooooooooooooooongType type)>\n" 10908 " function;", 10909 getGoogleStyleWithColumns(40)); 10910 } 10911 10912 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10913 verifyFormat("A (*foo_)[6];"); 10914 verifyFormat("vector<int> (*foo_)[6];"); 10915 } 10916 10917 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10918 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10919 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10920 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10921 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10922 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10923 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10924 10925 // Different ways of ()-initializiation. 10926 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10927 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10928 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10929 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10930 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10931 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10932 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10933 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10934 10935 // Lambdas should not confuse the variable declaration heuristic. 10936 verifyFormat("LooooooooooooooooongType\n" 10937 " variable(nullptr, [](A *a) {});", 10938 getLLVMStyleWithColumns(40)); 10939 } 10940 10941 TEST_F(FormatTest, BreaksLongDeclarations) { 10942 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10943 " AnotherNameForTheLongType;"); 10944 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10945 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10946 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10947 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10948 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10949 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10950 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10951 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10952 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10953 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10954 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10955 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10956 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10957 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10958 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10959 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10960 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10961 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10962 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10963 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10964 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10965 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10966 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10967 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10968 FormatStyle Indented = getLLVMStyle(); 10969 Indented.IndentWrappedFunctionNames = true; 10970 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10971 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10972 Indented); 10973 verifyFormat( 10974 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10975 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10976 Indented); 10977 verifyFormat( 10978 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10979 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10980 Indented); 10981 verifyFormat( 10982 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10983 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10984 Indented); 10985 10986 // FIXME: Without the comment, this breaks after "(". 10987 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10988 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10989 getGoogleStyle()); 10990 10991 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10992 " int LoooooooooooooooooooongParam2) {}"); 10993 verifyFormat( 10994 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10995 " SourceLocation L, IdentifierIn *II,\n" 10996 " Type *T) {}"); 10997 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10998 "ReallyReaaallyLongFunctionName(\n" 10999 " const std::string &SomeParameter,\n" 11000 " const SomeType<string, SomeOtherTemplateParameter>\n" 11001 " &ReallyReallyLongParameterName,\n" 11002 " const SomeType<string, SomeOtherTemplateParameter>\n" 11003 " &AnotherLongParameterName) {}"); 11004 verifyFormat("template <typename A>\n" 11005 "SomeLoooooooooooooooooooooongType<\n" 11006 " typename some_namespace::SomeOtherType<A>::Type>\n" 11007 "Function() {}"); 11008 11009 verifyGoogleFormat( 11010 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11011 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11012 verifyGoogleFormat( 11013 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11014 " SourceLocation L) {}"); 11015 verifyGoogleFormat( 11016 "some_namespace::LongReturnType\n" 11017 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11018 " int first_long_parameter, int second_parameter) {}"); 11019 11020 verifyGoogleFormat("template <typename T>\n" 11021 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11022 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11023 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11024 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11025 11026 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11027 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11028 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11029 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11030 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11031 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11032 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11033 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11034 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11035 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11036 11037 verifyFormat("template <typename T> // Templates on own line.\n" 11038 "static int // Some comment.\n" 11039 "MyFunction(int a);", 11040 getLLVMStyle()); 11041 } 11042 11043 TEST_F(FormatTest, FormatsAccessModifiers) { 11044 FormatStyle Style = getLLVMStyle(); 11045 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11046 FormatStyle::ELBAMS_LogicalBlock); 11047 verifyFormat("struct foo {\n" 11048 "private:\n" 11049 " void f() {}\n" 11050 "\n" 11051 "private:\n" 11052 " int i;\n" 11053 "\n" 11054 "protected:\n" 11055 " int j;\n" 11056 "};\n", 11057 Style); 11058 verifyFormat("struct foo {\n" 11059 "private:\n" 11060 " void f() {}\n" 11061 "\n" 11062 "private:\n" 11063 " int i;\n" 11064 "\n" 11065 "protected:\n" 11066 " int j;\n" 11067 "};\n", 11068 "struct foo {\n" 11069 "private:\n" 11070 " void f() {}\n" 11071 "private:\n" 11072 " int i;\n" 11073 "protected:\n" 11074 " int j;\n" 11075 "};\n", 11076 Style); 11077 verifyFormat("struct foo { /* comment */\n" 11078 "private:\n" 11079 " int i;\n" 11080 " // comment\n" 11081 "private:\n" 11082 " int j;\n" 11083 "};\n", 11084 Style); 11085 verifyFormat("struct foo {\n" 11086 "#ifdef FOO\n" 11087 "#endif\n" 11088 "private:\n" 11089 " int i;\n" 11090 "#ifdef FOO\n" 11091 "private:\n" 11092 "#endif\n" 11093 " int j;\n" 11094 "};\n", 11095 Style); 11096 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11097 verifyFormat("struct foo {\n" 11098 "private:\n" 11099 " void f() {}\n" 11100 "private:\n" 11101 " int i;\n" 11102 "protected:\n" 11103 " int j;\n" 11104 "};\n", 11105 Style); 11106 verifyFormat("struct foo {\n" 11107 "private:\n" 11108 " void f() {}\n" 11109 "private:\n" 11110 " int i;\n" 11111 "protected:\n" 11112 " int j;\n" 11113 "};\n", 11114 "struct foo {\n" 11115 "\n" 11116 "private:\n" 11117 " void f() {}\n" 11118 "\n" 11119 "private:\n" 11120 " int i;\n" 11121 "\n" 11122 "protected:\n" 11123 " int j;\n" 11124 "};\n", 11125 Style); 11126 verifyFormat("struct foo { /* comment */\n" 11127 "private:\n" 11128 " int i;\n" 11129 " // comment\n" 11130 "private:\n" 11131 " int j;\n" 11132 "};\n", 11133 "struct foo { /* comment */\n" 11134 "\n" 11135 "private:\n" 11136 " int i;\n" 11137 " // comment\n" 11138 "\n" 11139 "private:\n" 11140 " int j;\n" 11141 "};\n", 11142 Style); 11143 verifyFormat("struct foo {\n" 11144 "#ifdef FOO\n" 11145 "#endif\n" 11146 "private:\n" 11147 " int i;\n" 11148 "#ifdef FOO\n" 11149 "private:\n" 11150 "#endif\n" 11151 " int j;\n" 11152 "};\n", 11153 "struct foo {\n" 11154 "#ifdef FOO\n" 11155 "#endif\n" 11156 "\n" 11157 "private:\n" 11158 " int i;\n" 11159 "#ifdef FOO\n" 11160 "\n" 11161 "private:\n" 11162 "#endif\n" 11163 " int j;\n" 11164 "};\n", 11165 Style); 11166 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11167 verifyFormat("struct foo {\n" 11168 "private:\n" 11169 " void f() {}\n" 11170 "\n" 11171 "private:\n" 11172 " int i;\n" 11173 "\n" 11174 "protected:\n" 11175 " int j;\n" 11176 "};\n", 11177 Style); 11178 verifyFormat("struct foo {\n" 11179 "private:\n" 11180 " void f() {}\n" 11181 "\n" 11182 "private:\n" 11183 " int i;\n" 11184 "\n" 11185 "protected:\n" 11186 " int j;\n" 11187 "};\n", 11188 "struct foo {\n" 11189 "private:\n" 11190 " void f() {}\n" 11191 "private:\n" 11192 " int i;\n" 11193 "protected:\n" 11194 " int j;\n" 11195 "};\n", 11196 Style); 11197 verifyFormat("struct foo { /* comment */\n" 11198 "private:\n" 11199 " int i;\n" 11200 " // comment\n" 11201 "\n" 11202 "private:\n" 11203 " int j;\n" 11204 "};\n", 11205 "struct foo { /* comment */\n" 11206 "private:\n" 11207 " int i;\n" 11208 " // comment\n" 11209 "\n" 11210 "private:\n" 11211 " int j;\n" 11212 "};\n", 11213 Style); 11214 verifyFormat("struct foo {\n" 11215 "#ifdef FOO\n" 11216 "#endif\n" 11217 "\n" 11218 "private:\n" 11219 " int i;\n" 11220 "#ifdef FOO\n" 11221 "\n" 11222 "private:\n" 11223 "#endif\n" 11224 " int j;\n" 11225 "};\n", 11226 "struct foo {\n" 11227 "#ifdef FOO\n" 11228 "#endif\n" 11229 "private:\n" 11230 " int i;\n" 11231 "#ifdef FOO\n" 11232 "private:\n" 11233 "#endif\n" 11234 " int j;\n" 11235 "};\n", 11236 Style); 11237 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11238 EXPECT_EQ("struct foo {\n" 11239 "\n" 11240 "private:\n" 11241 " void f() {}\n" 11242 "\n" 11243 "private:\n" 11244 " int i;\n" 11245 "\n" 11246 "protected:\n" 11247 " int j;\n" 11248 "};\n", 11249 format("struct foo {\n" 11250 "\n" 11251 "private:\n" 11252 " void f() {}\n" 11253 "\n" 11254 "private:\n" 11255 " int i;\n" 11256 "\n" 11257 "protected:\n" 11258 " int j;\n" 11259 "};\n", 11260 Style)); 11261 verifyFormat("struct foo {\n" 11262 "private:\n" 11263 " void f() {}\n" 11264 "private:\n" 11265 " int i;\n" 11266 "protected:\n" 11267 " int j;\n" 11268 "};\n", 11269 Style); 11270 EXPECT_EQ("struct foo { /* comment */\n" 11271 "\n" 11272 "private:\n" 11273 " int i;\n" 11274 " // comment\n" 11275 "\n" 11276 "private:\n" 11277 " int j;\n" 11278 "};\n", 11279 format("struct foo { /* comment */\n" 11280 "\n" 11281 "private:\n" 11282 " int i;\n" 11283 " // comment\n" 11284 "\n" 11285 "private:\n" 11286 " int j;\n" 11287 "};\n", 11288 Style)); 11289 verifyFormat("struct foo { /* comment */\n" 11290 "private:\n" 11291 " int i;\n" 11292 " // comment\n" 11293 "private:\n" 11294 " int j;\n" 11295 "};\n", 11296 Style); 11297 EXPECT_EQ("struct foo {\n" 11298 "#ifdef FOO\n" 11299 "#endif\n" 11300 "\n" 11301 "private:\n" 11302 " int i;\n" 11303 "#ifdef FOO\n" 11304 "\n" 11305 "private:\n" 11306 "#endif\n" 11307 " int j;\n" 11308 "};\n", 11309 format("struct foo {\n" 11310 "#ifdef FOO\n" 11311 "#endif\n" 11312 "\n" 11313 "private:\n" 11314 " int i;\n" 11315 "#ifdef FOO\n" 11316 "\n" 11317 "private:\n" 11318 "#endif\n" 11319 " int j;\n" 11320 "};\n", 11321 Style)); 11322 verifyFormat("struct foo {\n" 11323 "#ifdef FOO\n" 11324 "#endif\n" 11325 "private:\n" 11326 " int i;\n" 11327 "#ifdef FOO\n" 11328 "private:\n" 11329 "#endif\n" 11330 " int j;\n" 11331 "};\n", 11332 Style); 11333 11334 FormatStyle NoEmptyLines = getLLVMStyle(); 11335 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11336 verifyFormat("struct foo {\n" 11337 "private:\n" 11338 " void f() {}\n" 11339 "\n" 11340 "private:\n" 11341 " int i;\n" 11342 "\n" 11343 "public:\n" 11344 "protected:\n" 11345 " int j;\n" 11346 "};\n", 11347 NoEmptyLines); 11348 11349 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11350 verifyFormat("struct foo {\n" 11351 "private:\n" 11352 " void f() {}\n" 11353 "private:\n" 11354 " int i;\n" 11355 "public:\n" 11356 "protected:\n" 11357 " int j;\n" 11358 "};\n", 11359 NoEmptyLines); 11360 11361 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11362 verifyFormat("struct foo {\n" 11363 "private:\n" 11364 " void f() {}\n" 11365 "\n" 11366 "private:\n" 11367 " int i;\n" 11368 "\n" 11369 "public:\n" 11370 "\n" 11371 "protected:\n" 11372 " int j;\n" 11373 "};\n", 11374 NoEmptyLines); 11375 } 11376 11377 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11378 11379 FormatStyle Style = getLLVMStyle(); 11380 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11381 verifyFormat("struct foo {\n" 11382 "private:\n" 11383 " void f() {}\n" 11384 "\n" 11385 "private:\n" 11386 " int i;\n" 11387 "\n" 11388 "protected:\n" 11389 " int j;\n" 11390 "};\n", 11391 Style); 11392 11393 // Check if lines are removed. 11394 verifyFormat("struct foo {\n" 11395 "private:\n" 11396 " void f() {}\n" 11397 "\n" 11398 "private:\n" 11399 " int i;\n" 11400 "\n" 11401 "protected:\n" 11402 " int j;\n" 11403 "};\n", 11404 "struct foo {\n" 11405 "private:\n" 11406 "\n" 11407 " void f() {}\n" 11408 "\n" 11409 "private:\n" 11410 "\n" 11411 " int i;\n" 11412 "\n" 11413 "protected:\n" 11414 "\n" 11415 " int j;\n" 11416 "};\n", 11417 Style); 11418 11419 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11420 verifyFormat("struct foo {\n" 11421 "private:\n" 11422 "\n" 11423 " void f() {}\n" 11424 "\n" 11425 "private:\n" 11426 "\n" 11427 " int i;\n" 11428 "\n" 11429 "protected:\n" 11430 "\n" 11431 " int j;\n" 11432 "};\n", 11433 Style); 11434 11435 // Check if lines are added. 11436 verifyFormat("struct foo {\n" 11437 "private:\n" 11438 "\n" 11439 " void f() {}\n" 11440 "\n" 11441 "private:\n" 11442 "\n" 11443 " int i;\n" 11444 "\n" 11445 "protected:\n" 11446 "\n" 11447 " int j;\n" 11448 "};\n", 11449 "struct foo {\n" 11450 "private:\n" 11451 " void f() {}\n" 11452 "\n" 11453 "private:\n" 11454 " int i;\n" 11455 "\n" 11456 "protected:\n" 11457 " int j;\n" 11458 "};\n", 11459 Style); 11460 11461 // Leave tests rely on the code layout, test::messUp can not be used. 11462 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11463 Style.MaxEmptyLinesToKeep = 0u; 11464 verifyFormat("struct foo {\n" 11465 "private:\n" 11466 " void f() {}\n" 11467 "\n" 11468 "private:\n" 11469 " int i;\n" 11470 "\n" 11471 "protected:\n" 11472 " int j;\n" 11473 "};\n", 11474 Style); 11475 11476 // Check if MaxEmptyLinesToKeep is respected. 11477 EXPECT_EQ("struct foo {\n" 11478 "private:\n" 11479 " void f() {}\n" 11480 "\n" 11481 "private:\n" 11482 " int i;\n" 11483 "\n" 11484 "protected:\n" 11485 " int j;\n" 11486 "};\n", 11487 format("struct foo {\n" 11488 "private:\n" 11489 "\n\n\n" 11490 " void f() {}\n" 11491 "\n" 11492 "private:\n" 11493 "\n\n\n" 11494 " int i;\n" 11495 "\n" 11496 "protected:\n" 11497 "\n\n\n" 11498 " int j;\n" 11499 "};\n", 11500 Style)); 11501 11502 Style.MaxEmptyLinesToKeep = 1u; 11503 EXPECT_EQ("struct foo {\n" 11504 "private:\n" 11505 "\n" 11506 " void f() {}\n" 11507 "\n" 11508 "private:\n" 11509 "\n" 11510 " int i;\n" 11511 "\n" 11512 "protected:\n" 11513 "\n" 11514 " int j;\n" 11515 "};\n", 11516 format("struct foo {\n" 11517 "private:\n" 11518 "\n" 11519 " void f() {}\n" 11520 "\n" 11521 "private:\n" 11522 "\n" 11523 " int i;\n" 11524 "\n" 11525 "protected:\n" 11526 "\n" 11527 " int j;\n" 11528 "};\n", 11529 Style)); 11530 // Check if no lines are kept. 11531 EXPECT_EQ("struct foo {\n" 11532 "private:\n" 11533 " void f() {}\n" 11534 "\n" 11535 "private:\n" 11536 " int i;\n" 11537 "\n" 11538 "protected:\n" 11539 " int j;\n" 11540 "};\n", 11541 format("struct foo {\n" 11542 "private:\n" 11543 " void f() {}\n" 11544 "\n" 11545 "private:\n" 11546 " int i;\n" 11547 "\n" 11548 "protected:\n" 11549 " int j;\n" 11550 "};\n", 11551 Style)); 11552 // Check if MaxEmptyLinesToKeep is respected. 11553 EXPECT_EQ("struct foo {\n" 11554 "private:\n" 11555 "\n" 11556 " void f() {}\n" 11557 "\n" 11558 "private:\n" 11559 "\n" 11560 " int i;\n" 11561 "\n" 11562 "protected:\n" 11563 "\n" 11564 " int j;\n" 11565 "};\n", 11566 format("struct foo {\n" 11567 "private:\n" 11568 "\n\n\n" 11569 " void f() {}\n" 11570 "\n" 11571 "private:\n" 11572 "\n\n\n" 11573 " int i;\n" 11574 "\n" 11575 "protected:\n" 11576 "\n\n\n" 11577 " int j;\n" 11578 "};\n", 11579 Style)); 11580 11581 Style.MaxEmptyLinesToKeep = 10u; 11582 EXPECT_EQ("struct foo {\n" 11583 "private:\n" 11584 "\n\n\n" 11585 " void f() {}\n" 11586 "\n" 11587 "private:\n" 11588 "\n\n\n" 11589 " int i;\n" 11590 "\n" 11591 "protected:\n" 11592 "\n\n\n" 11593 " int j;\n" 11594 "};\n", 11595 format("struct foo {\n" 11596 "private:\n" 11597 "\n\n\n" 11598 " void f() {}\n" 11599 "\n" 11600 "private:\n" 11601 "\n\n\n" 11602 " int i;\n" 11603 "\n" 11604 "protected:\n" 11605 "\n\n\n" 11606 " int j;\n" 11607 "};\n", 11608 Style)); 11609 11610 // Test with comments. 11611 Style = getLLVMStyle(); 11612 verifyFormat("struct foo {\n" 11613 "private:\n" 11614 " // comment\n" 11615 " void f() {}\n" 11616 "\n" 11617 "private: /* comment */\n" 11618 " int i;\n" 11619 "};\n", 11620 Style); 11621 verifyFormat("struct foo {\n" 11622 "private:\n" 11623 " // comment\n" 11624 " void f() {}\n" 11625 "\n" 11626 "private: /* comment */\n" 11627 " int i;\n" 11628 "};\n", 11629 "struct foo {\n" 11630 "private:\n" 11631 "\n" 11632 " // comment\n" 11633 " void f() {}\n" 11634 "\n" 11635 "private: /* comment */\n" 11636 "\n" 11637 " int i;\n" 11638 "};\n", 11639 Style); 11640 11641 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11642 verifyFormat("struct foo {\n" 11643 "private:\n" 11644 "\n" 11645 " // comment\n" 11646 " void f() {}\n" 11647 "\n" 11648 "private: /* comment */\n" 11649 "\n" 11650 " int i;\n" 11651 "};\n", 11652 "struct foo {\n" 11653 "private:\n" 11654 " // comment\n" 11655 " void f() {}\n" 11656 "\n" 11657 "private: /* comment */\n" 11658 " int i;\n" 11659 "};\n", 11660 Style); 11661 verifyFormat("struct foo {\n" 11662 "private:\n" 11663 "\n" 11664 " // comment\n" 11665 " void f() {}\n" 11666 "\n" 11667 "private: /* comment */\n" 11668 "\n" 11669 " int i;\n" 11670 "};\n", 11671 Style); 11672 11673 // Test with preprocessor defines. 11674 Style = getLLVMStyle(); 11675 verifyFormat("struct foo {\n" 11676 "private:\n" 11677 "#ifdef FOO\n" 11678 "#endif\n" 11679 " void f() {}\n" 11680 "};\n", 11681 Style); 11682 verifyFormat("struct foo {\n" 11683 "private:\n" 11684 "#ifdef FOO\n" 11685 "#endif\n" 11686 " void f() {}\n" 11687 "};\n", 11688 "struct foo {\n" 11689 "private:\n" 11690 "\n" 11691 "#ifdef FOO\n" 11692 "#endif\n" 11693 " void f() {}\n" 11694 "};\n", 11695 Style); 11696 11697 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11698 verifyFormat("struct foo {\n" 11699 "private:\n" 11700 "\n" 11701 "#ifdef FOO\n" 11702 "#endif\n" 11703 " void f() {}\n" 11704 "};\n", 11705 "struct foo {\n" 11706 "private:\n" 11707 "#ifdef FOO\n" 11708 "#endif\n" 11709 " void f() {}\n" 11710 "};\n", 11711 Style); 11712 verifyFormat("struct foo {\n" 11713 "private:\n" 11714 "\n" 11715 "#ifdef FOO\n" 11716 "#endif\n" 11717 " void f() {}\n" 11718 "};\n", 11719 Style); 11720 } 11721 11722 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11723 // Combined tests of EmptyLineAfterAccessModifier and 11724 // EmptyLineBeforeAccessModifier. 11725 FormatStyle Style = getLLVMStyle(); 11726 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11727 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11728 verifyFormat("struct foo {\n" 11729 "private:\n" 11730 "\n" 11731 "protected:\n" 11732 "};\n", 11733 Style); 11734 11735 Style.MaxEmptyLinesToKeep = 10u; 11736 // Both remove all new lines. 11737 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11738 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11739 verifyFormat("struct foo {\n" 11740 "private:\n" 11741 "protected:\n" 11742 "};\n", 11743 "struct foo {\n" 11744 "private:\n" 11745 "\n\n\n" 11746 "protected:\n" 11747 "};\n", 11748 Style); 11749 11750 // Leave tests rely on the code layout, test::messUp can not be used. 11751 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11752 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11753 Style.MaxEmptyLinesToKeep = 10u; 11754 EXPECT_EQ("struct foo {\n" 11755 "private:\n" 11756 "\n\n\n" 11757 "protected:\n" 11758 "};\n", 11759 format("struct foo {\n" 11760 "private:\n" 11761 "\n\n\n" 11762 "protected:\n" 11763 "};\n", 11764 Style)); 11765 Style.MaxEmptyLinesToKeep = 3u; 11766 EXPECT_EQ("struct foo {\n" 11767 "private:\n" 11768 "\n\n\n" 11769 "protected:\n" 11770 "};\n", 11771 format("struct foo {\n" 11772 "private:\n" 11773 "\n\n\n" 11774 "protected:\n" 11775 "};\n", 11776 Style)); 11777 Style.MaxEmptyLinesToKeep = 1u; 11778 EXPECT_EQ("struct foo {\n" 11779 "private:\n" 11780 "\n\n\n" 11781 "protected:\n" 11782 "};\n", 11783 format("struct foo {\n" 11784 "private:\n" 11785 "\n\n\n" 11786 "protected:\n" 11787 "};\n", 11788 Style)); // Based on new lines in original document and not 11789 // on the setting. 11790 11791 Style.MaxEmptyLinesToKeep = 10u; 11792 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11793 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11794 // Newlines are kept if they are greater than zero, 11795 // test::messUp removes all new lines which changes the logic 11796 EXPECT_EQ("struct foo {\n" 11797 "private:\n" 11798 "\n\n\n" 11799 "protected:\n" 11800 "};\n", 11801 format("struct foo {\n" 11802 "private:\n" 11803 "\n\n\n" 11804 "protected:\n" 11805 "};\n", 11806 Style)); 11807 11808 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11809 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11810 // test::messUp removes all new lines which changes the logic 11811 EXPECT_EQ("struct foo {\n" 11812 "private:\n" 11813 "\n\n\n" 11814 "protected:\n" 11815 "};\n", 11816 format("struct foo {\n" 11817 "private:\n" 11818 "\n\n\n" 11819 "protected:\n" 11820 "};\n", 11821 Style)); 11822 11823 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11824 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11825 EXPECT_EQ("struct foo {\n" 11826 "private:\n" 11827 "\n\n\n" 11828 "protected:\n" 11829 "};\n", 11830 format("struct foo {\n" 11831 "private:\n" 11832 "\n\n\n" 11833 "protected:\n" 11834 "};\n", 11835 Style)); // test::messUp removes all new lines which changes 11836 // the logic. 11837 11838 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11839 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11840 verifyFormat("struct foo {\n" 11841 "private:\n" 11842 "protected:\n" 11843 "};\n", 11844 "struct foo {\n" 11845 "private:\n" 11846 "\n\n\n" 11847 "protected:\n" 11848 "};\n", 11849 Style); 11850 11851 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11852 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11853 EXPECT_EQ("struct foo {\n" 11854 "private:\n" 11855 "\n\n\n" 11856 "protected:\n" 11857 "};\n", 11858 format("struct foo {\n" 11859 "private:\n" 11860 "\n\n\n" 11861 "protected:\n" 11862 "};\n", 11863 Style)); // test::messUp removes all new lines which changes 11864 // the logic. 11865 11866 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11867 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11868 verifyFormat("struct foo {\n" 11869 "private:\n" 11870 "protected:\n" 11871 "};\n", 11872 "struct foo {\n" 11873 "private:\n" 11874 "\n\n\n" 11875 "protected:\n" 11876 "};\n", 11877 Style); 11878 11879 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11880 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11881 verifyFormat("struct foo {\n" 11882 "private:\n" 11883 "protected:\n" 11884 "};\n", 11885 "struct foo {\n" 11886 "private:\n" 11887 "\n\n\n" 11888 "protected:\n" 11889 "};\n", 11890 Style); 11891 11892 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11893 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11894 verifyFormat("struct foo {\n" 11895 "private:\n" 11896 "protected:\n" 11897 "};\n", 11898 "struct foo {\n" 11899 "private:\n" 11900 "\n\n\n" 11901 "protected:\n" 11902 "};\n", 11903 Style); 11904 11905 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11906 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11907 verifyFormat("struct foo {\n" 11908 "private:\n" 11909 "protected:\n" 11910 "};\n", 11911 "struct foo {\n" 11912 "private:\n" 11913 "\n\n\n" 11914 "protected:\n" 11915 "};\n", 11916 Style); 11917 } 11918 11919 TEST_F(FormatTest, FormatsArrays) { 11920 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11921 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11922 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11923 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11924 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11925 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11926 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11927 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11928 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11929 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11930 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11931 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11932 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11933 verifyFormat( 11934 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11935 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11936 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11937 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11938 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11939 11940 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11941 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11942 verifyFormat( 11943 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11944 " .aaaaaaa[0]\n" 11945 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11946 verifyFormat("a[::b::c];"); 11947 11948 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11949 11950 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11951 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11952 } 11953 11954 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11955 verifyFormat("(a)->b();"); 11956 verifyFormat("--a;"); 11957 } 11958 11959 TEST_F(FormatTest, HandlesIncludeDirectives) { 11960 verifyFormat("#include <string>\n" 11961 "#include <a/b/c.h>\n" 11962 "#include \"a/b/string\"\n" 11963 "#include \"string.h\"\n" 11964 "#include \"string.h\"\n" 11965 "#include <a-a>\n" 11966 "#include < path with space >\n" 11967 "#include_next <test.h>" 11968 "#include \"abc.h\" // this is included for ABC\n" 11969 "#include \"some long include\" // with a comment\n" 11970 "#include \"some very long include path\"\n" 11971 "#include <some/very/long/include/path>\n", 11972 getLLVMStyleWithColumns(35)); 11973 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11974 EXPECT_EQ("#include <a>", format("#include<a>")); 11975 11976 verifyFormat("#import <string>"); 11977 verifyFormat("#import <a/b/c.h>"); 11978 verifyFormat("#import \"a/b/string\""); 11979 verifyFormat("#import \"string.h\""); 11980 verifyFormat("#import \"string.h\""); 11981 verifyFormat("#if __has_include(<strstream>)\n" 11982 "#include <strstream>\n" 11983 "#endif"); 11984 11985 verifyFormat("#define MY_IMPORT <a/b>"); 11986 11987 verifyFormat("#if __has_include(<a/b>)"); 11988 verifyFormat("#if __has_include_next(<a/b>)"); 11989 verifyFormat("#define F __has_include(<a/b>)"); 11990 verifyFormat("#define F __has_include_next(<a/b>)"); 11991 11992 // Protocol buffer definition or missing "#". 11993 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11994 getLLVMStyleWithColumns(30)); 11995 11996 FormatStyle Style = getLLVMStyle(); 11997 Style.AlwaysBreakBeforeMultilineStrings = true; 11998 Style.ColumnLimit = 0; 11999 verifyFormat("#import \"abc.h\"", Style); 12000 12001 // But 'import' might also be a regular C++ namespace. 12002 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12003 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12004 } 12005 12006 //===----------------------------------------------------------------------===// 12007 // Error recovery tests. 12008 //===----------------------------------------------------------------------===// 12009 12010 TEST_F(FormatTest, IncompleteParameterLists) { 12011 FormatStyle NoBinPacking = getLLVMStyle(); 12012 NoBinPacking.BinPackParameters = false; 12013 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12014 " double *min_x,\n" 12015 " double *max_x,\n" 12016 " double *min_y,\n" 12017 " double *max_y,\n" 12018 " double *min_z,\n" 12019 " double *max_z, ) {}", 12020 NoBinPacking); 12021 } 12022 12023 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12024 verifyFormat("void f() { return; }\n42"); 12025 verifyFormat("void f() {\n" 12026 " if (0)\n" 12027 " return;\n" 12028 "}\n" 12029 "42"); 12030 verifyFormat("void f() { return }\n42"); 12031 verifyFormat("void f() {\n" 12032 " if (0)\n" 12033 " return\n" 12034 "}\n" 12035 "42"); 12036 } 12037 12038 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12039 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12040 EXPECT_EQ("void f() {\n" 12041 " if (a)\n" 12042 " return\n" 12043 "}", 12044 format("void f ( ) { if ( a ) return }")); 12045 EXPECT_EQ("namespace N {\n" 12046 "void f()\n" 12047 "}", 12048 format("namespace N { void f() }")); 12049 EXPECT_EQ("namespace N {\n" 12050 "void f() {}\n" 12051 "void g()\n" 12052 "} // namespace N", 12053 format("namespace N { void f( ) { } void g( ) }")); 12054 } 12055 12056 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12057 verifyFormat("int aaaaaaaa =\n" 12058 " // Overlylongcomment\n" 12059 " b;", 12060 getLLVMStyleWithColumns(20)); 12061 verifyFormat("function(\n" 12062 " ShortArgument,\n" 12063 " LoooooooooooongArgument);\n", 12064 getLLVMStyleWithColumns(20)); 12065 } 12066 12067 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12068 verifyFormat("public:"); 12069 verifyFormat("class A {\n" 12070 "public\n" 12071 " void f() {}\n" 12072 "};"); 12073 verifyFormat("public\n" 12074 "int qwerty;"); 12075 verifyFormat("public\n" 12076 "B {}"); 12077 verifyFormat("public\n" 12078 "{}"); 12079 verifyFormat("public\n" 12080 "B { int x; }"); 12081 } 12082 12083 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12084 verifyFormat("{"); 12085 verifyFormat("#})"); 12086 verifyNoCrash("(/**/[:!] ?[)."); 12087 } 12088 12089 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12090 // Found by oss-fuzz: 12091 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12092 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12093 Style.ColumnLimit = 60; 12094 verifyNoCrash( 12095 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12096 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12097 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12098 Style); 12099 } 12100 12101 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12102 verifyFormat("do {\n}"); 12103 verifyFormat("do {\n}\n" 12104 "f();"); 12105 verifyFormat("do {\n}\n" 12106 "wheeee(fun);"); 12107 verifyFormat("do {\n" 12108 " f();\n" 12109 "}"); 12110 } 12111 12112 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12113 verifyFormat("if {\n foo;\n foo();\n}"); 12114 verifyFormat("switch {\n foo;\n foo();\n}"); 12115 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12116 verifyFormat("while {\n foo;\n foo();\n}"); 12117 verifyFormat("do {\n foo;\n foo();\n} while;"); 12118 } 12119 12120 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12121 verifyIncompleteFormat("namespace {\n" 12122 "class Foo { Foo (\n" 12123 "};\n" 12124 "} // namespace"); 12125 } 12126 12127 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12128 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12129 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12130 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12131 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12132 12133 EXPECT_EQ("{\n" 12134 " {\n" 12135 " breakme(\n" 12136 " qwe);\n" 12137 " }\n", 12138 format("{\n" 12139 " {\n" 12140 " breakme(qwe);\n" 12141 "}\n", 12142 getLLVMStyleWithColumns(10))); 12143 } 12144 12145 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12146 verifyFormat("int x = {\n" 12147 " avariable,\n" 12148 " b(alongervariable)};", 12149 getLLVMStyleWithColumns(25)); 12150 } 12151 12152 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12153 verifyFormat("return (a)(b){1, 2, 3};"); 12154 } 12155 12156 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12157 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12158 verifyFormat("vector<int> x{\n" 12159 " 1,\n" 12160 " 2,\n" 12161 " 3,\n" 12162 " 4,\n" 12163 "};"); 12164 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12165 verifyFormat("f({1, 2});"); 12166 verifyFormat("auto v = Foo{-1};"); 12167 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12168 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12169 verifyFormat("new vector<int>{1, 2, 3};"); 12170 verifyFormat("new int[3]{1, 2, 3};"); 12171 verifyFormat("new int{1};"); 12172 verifyFormat("return {arg1, arg2};"); 12173 verifyFormat("return {arg1, SomeType{parameter}};"); 12174 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12175 verifyFormat("new T{arg1, arg2};"); 12176 verifyFormat("f(MyMap[{composite, key}]);"); 12177 verifyFormat("class Class {\n" 12178 " T member = {arg1, arg2};\n" 12179 "};"); 12180 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12181 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12182 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12183 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12184 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12185 12186 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12187 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12188 verifyFormat("auto i = decltype(x){};"); 12189 verifyFormat("auto i = typeof(x){};"); 12190 verifyFormat("auto i = _Atomic(x){};"); 12191 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12192 verifyFormat("Node n{1, Node{1000}, //\n" 12193 " 2};"); 12194 verifyFormat("Aaaa aaaaaaa{\n" 12195 " {\n" 12196 " aaaa,\n" 12197 " },\n" 12198 "};"); 12199 verifyFormat("class C : public D {\n" 12200 " SomeClass SC{2};\n" 12201 "};"); 12202 verifyFormat("class C : public A {\n" 12203 " class D : public B {\n" 12204 " void f() { int i{2}; }\n" 12205 " };\n" 12206 "};"); 12207 verifyFormat("#define A {a, a},"); 12208 // Don't confuse braced list initializers with compound statements. 12209 verifyFormat( 12210 "class A {\n" 12211 " A() : a{} {}\n" 12212 " A(int b) : b(b) {}\n" 12213 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12214 " int a, b;\n" 12215 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12216 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12217 "{}\n" 12218 "};"); 12219 12220 // Avoid breaking between equal sign and opening brace 12221 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12222 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12223 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12224 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12225 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12226 " {\"ccccccccccccccccccccc\", 2}};", 12227 AvoidBreakingFirstArgument); 12228 12229 // Binpacking only if there is no trailing comma 12230 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12231 " cccccccccc, dddddddddd};", 12232 getLLVMStyleWithColumns(50)); 12233 verifyFormat("const Aaaaaa aaaaa = {\n" 12234 " aaaaaaaaaaa,\n" 12235 " bbbbbbbbbbb,\n" 12236 " ccccccccccc,\n" 12237 " ddddddddddd,\n" 12238 "};", 12239 getLLVMStyleWithColumns(50)); 12240 12241 // Cases where distinguising braced lists and blocks is hard. 12242 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12243 verifyFormat("void f() {\n" 12244 " return; // comment\n" 12245 "}\n" 12246 "SomeType t;"); 12247 verifyFormat("void f() {\n" 12248 " if (a) {\n" 12249 " f();\n" 12250 " }\n" 12251 "}\n" 12252 "SomeType t;"); 12253 12254 // In combination with BinPackArguments = false. 12255 FormatStyle NoBinPacking = getLLVMStyle(); 12256 NoBinPacking.BinPackArguments = false; 12257 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12258 " bbbbb,\n" 12259 " ccccc,\n" 12260 " ddddd,\n" 12261 " eeeee,\n" 12262 " ffffff,\n" 12263 " ggggg,\n" 12264 " hhhhhh,\n" 12265 " iiiiii,\n" 12266 " jjjjjj,\n" 12267 " kkkkkk};", 12268 NoBinPacking); 12269 verifyFormat("const Aaaaaa aaaaa = {\n" 12270 " aaaaa,\n" 12271 " bbbbb,\n" 12272 " ccccc,\n" 12273 " ddddd,\n" 12274 " eeeee,\n" 12275 " ffffff,\n" 12276 " ggggg,\n" 12277 " hhhhhh,\n" 12278 " iiiiii,\n" 12279 " jjjjjj,\n" 12280 " kkkkkk,\n" 12281 "};", 12282 NoBinPacking); 12283 verifyFormat( 12284 "const Aaaaaa aaaaa = {\n" 12285 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12286 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12287 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12288 "};", 12289 NoBinPacking); 12290 12291 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12292 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12293 " CDDDP83848_BMCR_REGISTER,\n" 12294 " CDDDP83848_BMSR_REGISTER,\n" 12295 " CDDDP83848_RBR_REGISTER};", 12296 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12297 " CDDDP83848_BMSR_REGISTER,\n" 12298 " CDDDP83848_RBR_REGISTER};", 12299 NoBinPacking)); 12300 12301 // FIXME: The alignment of these trailing comments might be bad. Then again, 12302 // this might be utterly useless in real code. 12303 verifyFormat("Constructor::Constructor()\n" 12304 " : some_value{ //\n" 12305 " aaaaaaa, //\n" 12306 " bbbbbbb} {}"); 12307 12308 // In braced lists, the first comment is always assumed to belong to the 12309 // first element. Thus, it can be moved to the next or previous line as 12310 // appropriate. 12311 EXPECT_EQ("function({// First element:\n" 12312 " 1,\n" 12313 " // Second element:\n" 12314 " 2});", 12315 format("function({\n" 12316 " // First element:\n" 12317 " 1,\n" 12318 " // Second element:\n" 12319 " 2});")); 12320 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12321 " // First element:\n" 12322 " 1,\n" 12323 " // Second element:\n" 12324 " 2};", 12325 format("std::vector<int> MyNumbers{// First element:\n" 12326 " 1,\n" 12327 " // Second element:\n" 12328 " 2};", 12329 getLLVMStyleWithColumns(30))); 12330 // A trailing comma should still lead to an enforced line break and no 12331 // binpacking. 12332 EXPECT_EQ("vector<int> SomeVector = {\n" 12333 " // aaa\n" 12334 " 1,\n" 12335 " 2,\n" 12336 "};", 12337 format("vector<int> SomeVector = { // aaa\n" 12338 " 1, 2, };")); 12339 12340 // C++11 brace initializer list l-braces should not be treated any differently 12341 // when breaking before lambda bodies is enabled 12342 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12343 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12344 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12345 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12346 verifyFormat( 12347 "std::runtime_error{\n" 12348 " \"Long string which will force a break onto the next line...\"};", 12349 BreakBeforeLambdaBody); 12350 12351 FormatStyle ExtraSpaces = getLLVMStyle(); 12352 ExtraSpaces.Cpp11BracedListStyle = false; 12353 ExtraSpaces.ColumnLimit = 75; 12354 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12355 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12356 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12357 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12358 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12359 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12360 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12361 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12362 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12363 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12364 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12365 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12366 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12367 verifyFormat("class Class {\n" 12368 " T member = { arg1, arg2 };\n" 12369 "};", 12370 ExtraSpaces); 12371 verifyFormat( 12372 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12373 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12374 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12375 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12376 ExtraSpaces); 12377 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12378 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12379 ExtraSpaces); 12380 verifyFormat( 12381 "someFunction(OtherParam,\n" 12382 " BracedList{ // comment 1 (Forcing interesting break)\n" 12383 " param1, param2,\n" 12384 " // comment 2\n" 12385 " param3, param4 });", 12386 ExtraSpaces); 12387 verifyFormat( 12388 "std::this_thread::sleep_for(\n" 12389 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12390 ExtraSpaces); 12391 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12392 " aaaaaaa,\n" 12393 " aaaaaaaaaa,\n" 12394 " aaaaa,\n" 12395 " aaaaaaaaaaaaaaa,\n" 12396 " aaa,\n" 12397 " aaaaaaaaaa,\n" 12398 " a,\n" 12399 " aaaaaaaaaaaaaaaaaaaaa,\n" 12400 " aaaaaaaaaaaa,\n" 12401 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12402 " aaaaaaa,\n" 12403 " a};"); 12404 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12405 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12406 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12407 12408 // Avoid breaking between initializer/equal sign and opening brace 12409 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12410 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12411 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12412 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12413 " { \"ccccccccccccccccccccc\", 2 }\n" 12414 "};", 12415 ExtraSpaces); 12416 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12417 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12418 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12419 " { \"ccccccccccccccccccccc\", 2 }\n" 12420 "};", 12421 ExtraSpaces); 12422 12423 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12424 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12425 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12426 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12427 12428 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12429 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12430 SpaceBetweenBraces.SpacesInParentheses = true; 12431 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12432 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12433 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12434 verifyFormat("vector< int > x{ // comment 1\n" 12435 " 1, 2, 3, 4 };", 12436 SpaceBetweenBraces); 12437 SpaceBetweenBraces.ColumnLimit = 20; 12438 EXPECT_EQ("vector< int > x{\n" 12439 " 1, 2, 3, 4 };", 12440 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12441 SpaceBetweenBraces.ColumnLimit = 24; 12442 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12443 " 3, 4 };", 12444 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12445 EXPECT_EQ("vector< int > x{\n" 12446 " 1,\n" 12447 " 2,\n" 12448 " 3,\n" 12449 " 4,\n" 12450 "};", 12451 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12452 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12453 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12454 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12455 } 12456 12457 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12458 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12459 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12460 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12461 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12462 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12463 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12464 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12465 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12466 " 1, 22, 333, 4444, 55555, //\n" 12467 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12468 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12469 verifyFormat( 12470 "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, // comment\n" 12473 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12474 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12475 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12476 " 7777777};"); 12477 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12478 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12479 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12480 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12481 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12482 " // Separating comment.\n" 12483 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12484 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12485 " // Leading comment\n" 12486 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12487 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12488 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12489 " 1, 1, 1, 1};", 12490 getLLVMStyleWithColumns(39)); 12491 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12492 " 1, 1, 1, 1};", 12493 getLLVMStyleWithColumns(38)); 12494 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12495 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12496 getLLVMStyleWithColumns(43)); 12497 verifyFormat( 12498 "static unsigned SomeValues[10][3] = {\n" 12499 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12500 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12501 verifyFormat("static auto fields = new vector<string>{\n" 12502 " \"aaaaaaaaaaaaa\",\n" 12503 " \"aaaaaaaaaaaaa\",\n" 12504 " \"aaaaaaaaaaaa\",\n" 12505 " \"aaaaaaaaaaaaaa\",\n" 12506 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12507 " \"aaaaaaaaaaaa\",\n" 12508 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12509 "};"); 12510 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12511 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12512 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12513 " 3, cccccccccccccccccccccc};", 12514 getLLVMStyleWithColumns(60)); 12515 12516 // Trailing commas. 12517 verifyFormat("vector<int> x = {\n" 12518 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12519 "};", 12520 getLLVMStyleWithColumns(39)); 12521 verifyFormat("vector<int> x = {\n" 12522 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12523 "};", 12524 getLLVMStyleWithColumns(39)); 12525 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12526 " 1, 1, 1, 1,\n" 12527 " /**/ /**/};", 12528 getLLVMStyleWithColumns(39)); 12529 12530 // Trailing comment in the first line. 12531 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12532 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12533 " 111111111, 222222222, 3333333333, 444444444, //\n" 12534 " 11111111, 22222222, 333333333, 44444444};"); 12535 // Trailing comment in the last line. 12536 verifyFormat("int aaaaa[] = {\n" 12537 " 1, 2, 3, // comment\n" 12538 " 4, 5, 6 // comment\n" 12539 "};"); 12540 12541 // With nested lists, we should either format one item per line or all nested 12542 // lists one on line. 12543 // FIXME: For some nested lists, we can do better. 12544 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12545 " {aaaaaaaaaaaaaaaaaaa},\n" 12546 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12547 " {aaaaaaaaaaaaaaaaa}};", 12548 getLLVMStyleWithColumns(60)); 12549 verifyFormat( 12550 "SomeStruct my_struct_array = {\n" 12551 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12552 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12553 " {aaa, aaa},\n" 12554 " {aaa, aaa},\n" 12555 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12556 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12557 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12558 12559 // No column layout should be used here. 12560 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12561 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12562 12563 verifyNoCrash("a<,"); 12564 12565 // No braced initializer here. 12566 verifyFormat("void f() {\n" 12567 " struct Dummy {};\n" 12568 " f(v);\n" 12569 "}"); 12570 12571 // Long lists should be formatted in columns even if they are nested. 12572 verifyFormat( 12573 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12574 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12575 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12576 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12577 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12578 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12579 12580 // Allow "single-column" layout even if that violates the column limit. There 12581 // isn't going to be a better way. 12582 verifyFormat("std::vector<int> a = {\n" 12583 " aaaaaaaa,\n" 12584 " aaaaaaaa,\n" 12585 " aaaaaaaa,\n" 12586 " aaaaaaaa,\n" 12587 " aaaaaaaaaa,\n" 12588 " aaaaaaaa,\n" 12589 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12590 getLLVMStyleWithColumns(30)); 12591 verifyFormat("vector<int> aaaa = {\n" 12592 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12593 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12594 " aaaaaa.aaaaaaa,\n" 12595 " aaaaaa.aaaaaaa,\n" 12596 " aaaaaa.aaaaaaa,\n" 12597 " aaaaaa.aaaaaaa,\n" 12598 "};"); 12599 12600 // Don't create hanging lists. 12601 verifyFormat("someFunction(Param, {List1, List2,\n" 12602 " List3});", 12603 getLLVMStyleWithColumns(35)); 12604 verifyFormat("someFunction(Param, Param,\n" 12605 " {List1, List2,\n" 12606 " List3});", 12607 getLLVMStyleWithColumns(35)); 12608 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12609 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12610 } 12611 12612 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12613 FormatStyle DoNotMerge = getLLVMStyle(); 12614 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12615 12616 verifyFormat("void f() { return 42; }"); 12617 verifyFormat("void f() {\n" 12618 " return 42;\n" 12619 "}", 12620 DoNotMerge); 12621 verifyFormat("void f() {\n" 12622 " // Comment\n" 12623 "}"); 12624 verifyFormat("{\n" 12625 "#error {\n" 12626 " int a;\n" 12627 "}"); 12628 verifyFormat("{\n" 12629 " int a;\n" 12630 "#error {\n" 12631 "}"); 12632 verifyFormat("void f() {} // comment"); 12633 verifyFormat("void f() { int a; } // comment"); 12634 verifyFormat("void f() {\n" 12635 "} // comment", 12636 DoNotMerge); 12637 verifyFormat("void f() {\n" 12638 " int a;\n" 12639 "} // comment", 12640 DoNotMerge); 12641 verifyFormat("void f() {\n" 12642 "} // comment", 12643 getLLVMStyleWithColumns(15)); 12644 12645 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12646 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12647 12648 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12649 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12650 verifyFormat("class C {\n" 12651 " C()\n" 12652 " : iiiiiiii(nullptr),\n" 12653 " kkkkkkk(nullptr),\n" 12654 " mmmmmmm(nullptr),\n" 12655 " nnnnnnn(nullptr) {}\n" 12656 "};", 12657 getGoogleStyle()); 12658 12659 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12660 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12661 EXPECT_EQ("class C {\n" 12662 " A() : b(0) {}\n" 12663 "};", 12664 format("class C{A():b(0){}};", NoColumnLimit)); 12665 EXPECT_EQ("A()\n" 12666 " : b(0) {\n" 12667 "}", 12668 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12669 12670 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12671 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12672 FormatStyle::SFS_None; 12673 EXPECT_EQ("A()\n" 12674 " : b(0) {\n" 12675 "}", 12676 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12677 EXPECT_EQ("A()\n" 12678 " : b(0) {\n" 12679 "}", 12680 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12681 12682 verifyFormat("#define A \\\n" 12683 " void f() { \\\n" 12684 " int i; \\\n" 12685 " }", 12686 getLLVMStyleWithColumns(20)); 12687 verifyFormat("#define A \\\n" 12688 " void f() { int i; }", 12689 getLLVMStyleWithColumns(21)); 12690 verifyFormat("#define A \\\n" 12691 " void f() { \\\n" 12692 " int i; \\\n" 12693 " } \\\n" 12694 " int j;", 12695 getLLVMStyleWithColumns(22)); 12696 verifyFormat("#define A \\\n" 12697 " void f() { int i; } \\\n" 12698 " int j;", 12699 getLLVMStyleWithColumns(23)); 12700 } 12701 12702 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12703 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12704 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12705 verifyFormat("class C {\n" 12706 " int f() {}\n" 12707 "};", 12708 MergeEmptyOnly); 12709 verifyFormat("class C {\n" 12710 " int f() {\n" 12711 " return 42;\n" 12712 " }\n" 12713 "};", 12714 MergeEmptyOnly); 12715 verifyFormat("int f() {}", MergeEmptyOnly); 12716 verifyFormat("int f() {\n" 12717 " return 42;\n" 12718 "}", 12719 MergeEmptyOnly); 12720 12721 // Also verify behavior when BraceWrapping.AfterFunction = true 12722 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12723 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12724 verifyFormat("int f() {}", MergeEmptyOnly); 12725 verifyFormat("class C {\n" 12726 " int f() {}\n" 12727 "};", 12728 MergeEmptyOnly); 12729 } 12730 12731 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12732 FormatStyle MergeInlineOnly = getLLVMStyle(); 12733 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12734 verifyFormat("class C {\n" 12735 " int f() { return 42; }\n" 12736 "};", 12737 MergeInlineOnly); 12738 verifyFormat("int f() {\n" 12739 " return 42;\n" 12740 "}", 12741 MergeInlineOnly); 12742 12743 // SFS_Inline implies SFS_Empty 12744 verifyFormat("class C {\n" 12745 " int f() {}\n" 12746 "};", 12747 MergeInlineOnly); 12748 verifyFormat("int f() {}", MergeInlineOnly); 12749 // https://llvm.org/PR54147 12750 verifyFormat("auto lambda = []() {\n" 12751 " // comment\n" 12752 " f();\n" 12753 " g();\n" 12754 "};", 12755 MergeInlineOnly); 12756 12757 // Also verify behavior when BraceWrapping.AfterFunction = true 12758 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12759 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12760 verifyFormat("class C {\n" 12761 " int f() { return 42; }\n" 12762 "};", 12763 MergeInlineOnly); 12764 verifyFormat("int f()\n" 12765 "{\n" 12766 " return 42;\n" 12767 "}", 12768 MergeInlineOnly); 12769 12770 // SFS_Inline implies SFS_Empty 12771 verifyFormat("int f() {}", MergeInlineOnly); 12772 verifyFormat("class C {\n" 12773 " int f() {}\n" 12774 "};", 12775 MergeInlineOnly); 12776 12777 MergeInlineOnly.BraceWrapping.AfterClass = true; 12778 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12779 verifyFormat("class C\n" 12780 "{\n" 12781 " int f() { return 42; }\n" 12782 "};", 12783 MergeInlineOnly); 12784 verifyFormat("struct C\n" 12785 "{\n" 12786 " int f() { return 42; }\n" 12787 "};", 12788 MergeInlineOnly); 12789 verifyFormat("int f()\n" 12790 "{\n" 12791 " return 42;\n" 12792 "}", 12793 MergeInlineOnly); 12794 verifyFormat("int f() {}", MergeInlineOnly); 12795 verifyFormat("class C\n" 12796 "{\n" 12797 " int f() { return 42; }\n" 12798 "};", 12799 MergeInlineOnly); 12800 verifyFormat("struct C\n" 12801 "{\n" 12802 " int f() { return 42; }\n" 12803 "};", 12804 MergeInlineOnly); 12805 verifyFormat("struct C\n" 12806 "// comment\n" 12807 "/* comment */\n" 12808 "// comment\n" 12809 "{\n" 12810 " int f() { return 42; }\n" 12811 "};", 12812 MergeInlineOnly); 12813 verifyFormat("/* comment */ struct C\n" 12814 "{\n" 12815 " int f() { return 42; }\n" 12816 "};", 12817 MergeInlineOnly); 12818 } 12819 12820 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12821 FormatStyle MergeInlineOnly = getLLVMStyle(); 12822 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12823 FormatStyle::SFS_InlineOnly; 12824 verifyFormat("class C {\n" 12825 " int f() { return 42; }\n" 12826 "};", 12827 MergeInlineOnly); 12828 verifyFormat("int f() {\n" 12829 " return 42;\n" 12830 "}", 12831 MergeInlineOnly); 12832 12833 // SFS_InlineOnly does not imply SFS_Empty 12834 verifyFormat("class C {\n" 12835 " int f() {}\n" 12836 "};", 12837 MergeInlineOnly); 12838 verifyFormat("int f() {\n" 12839 "}", 12840 MergeInlineOnly); 12841 12842 // Also verify behavior when BraceWrapping.AfterFunction = true 12843 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12844 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12845 verifyFormat("class C {\n" 12846 " int f() { return 42; }\n" 12847 "};", 12848 MergeInlineOnly); 12849 verifyFormat("int f()\n" 12850 "{\n" 12851 " return 42;\n" 12852 "}", 12853 MergeInlineOnly); 12854 12855 // SFS_InlineOnly does not imply SFS_Empty 12856 verifyFormat("int f()\n" 12857 "{\n" 12858 "}", 12859 MergeInlineOnly); 12860 verifyFormat("class C {\n" 12861 " int f() {}\n" 12862 "};", 12863 MergeInlineOnly); 12864 } 12865 12866 TEST_F(FormatTest, SplitEmptyFunction) { 12867 FormatStyle Style = getLLVMStyleWithColumns(40); 12868 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12869 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12870 Style.BraceWrapping.AfterFunction = true; 12871 Style.BraceWrapping.SplitEmptyFunction = false; 12872 12873 verifyFormat("int f()\n" 12874 "{}", 12875 Style); 12876 verifyFormat("int f()\n" 12877 "{\n" 12878 " return 42;\n" 12879 "}", 12880 Style); 12881 verifyFormat("int f()\n" 12882 "{\n" 12883 " // some comment\n" 12884 "}", 12885 Style); 12886 12887 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12888 verifyFormat("int f() {}", Style); 12889 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12890 "{}", 12891 Style); 12892 verifyFormat("int f()\n" 12893 "{\n" 12894 " return 0;\n" 12895 "}", 12896 Style); 12897 12898 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12899 verifyFormat("class Foo {\n" 12900 " int f() {}\n" 12901 "};\n", 12902 Style); 12903 verifyFormat("class Foo {\n" 12904 " int f() { return 0; }\n" 12905 "};\n", 12906 Style); 12907 verifyFormat("class Foo {\n" 12908 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12909 " {}\n" 12910 "};\n", 12911 Style); 12912 verifyFormat("class Foo {\n" 12913 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12914 " {\n" 12915 " return 0;\n" 12916 " }\n" 12917 "};\n", 12918 Style); 12919 12920 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12921 verifyFormat("int f() {}", Style); 12922 verifyFormat("int f() { return 0; }", Style); 12923 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12924 "{}", 12925 Style); 12926 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12927 "{\n" 12928 " return 0;\n" 12929 "}", 12930 Style); 12931 } 12932 12933 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12934 FormatStyle Style = getLLVMStyleWithColumns(40); 12935 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12936 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12937 Style.BraceWrapping.AfterFunction = true; 12938 Style.BraceWrapping.SplitEmptyFunction = true; 12939 Style.BraceWrapping.SplitEmptyRecord = false; 12940 12941 verifyFormat("class C {};", Style); 12942 verifyFormat("struct C {};", Style); 12943 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12944 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12945 "{\n" 12946 "}", 12947 Style); 12948 verifyFormat("class C {\n" 12949 " C()\n" 12950 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12951 " bbbbbbbbbbbbbbbbbbb()\n" 12952 " {\n" 12953 " }\n" 12954 " void\n" 12955 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12956 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12957 " {\n" 12958 " }\n" 12959 "};", 12960 Style); 12961 } 12962 12963 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12964 FormatStyle Style = getLLVMStyle(); 12965 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12966 verifyFormat("#ifdef A\n" 12967 "int f() {}\n" 12968 "#else\n" 12969 "int g() {}\n" 12970 "#endif", 12971 Style); 12972 } 12973 12974 TEST_F(FormatTest, SplitEmptyClass) { 12975 FormatStyle Style = getLLVMStyle(); 12976 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12977 Style.BraceWrapping.AfterClass = true; 12978 Style.BraceWrapping.SplitEmptyRecord = false; 12979 12980 verifyFormat("class Foo\n" 12981 "{};", 12982 Style); 12983 verifyFormat("/* something */ class Foo\n" 12984 "{};", 12985 Style); 12986 verifyFormat("template <typename X> class Foo\n" 12987 "{};", 12988 Style); 12989 verifyFormat("class Foo\n" 12990 "{\n" 12991 " Foo();\n" 12992 "};", 12993 Style); 12994 verifyFormat("typedef class Foo\n" 12995 "{\n" 12996 "} Foo_t;", 12997 Style); 12998 12999 Style.BraceWrapping.SplitEmptyRecord = true; 13000 Style.BraceWrapping.AfterStruct = true; 13001 verifyFormat("class rep\n" 13002 "{\n" 13003 "};", 13004 Style); 13005 verifyFormat("struct rep\n" 13006 "{\n" 13007 "};", 13008 Style); 13009 verifyFormat("template <typename T> class rep\n" 13010 "{\n" 13011 "};", 13012 Style); 13013 verifyFormat("template <typename T> struct rep\n" 13014 "{\n" 13015 "};", 13016 Style); 13017 verifyFormat("class rep\n" 13018 "{\n" 13019 " int x;\n" 13020 "};", 13021 Style); 13022 verifyFormat("struct rep\n" 13023 "{\n" 13024 " int x;\n" 13025 "};", 13026 Style); 13027 verifyFormat("template <typename T> class rep\n" 13028 "{\n" 13029 " int x;\n" 13030 "};", 13031 Style); 13032 verifyFormat("template <typename T> struct rep\n" 13033 "{\n" 13034 " int x;\n" 13035 "};", 13036 Style); 13037 verifyFormat("template <typename T> class rep // Foo\n" 13038 "{\n" 13039 " int x;\n" 13040 "};", 13041 Style); 13042 verifyFormat("template <typename T> struct rep // Bar\n" 13043 "{\n" 13044 " int x;\n" 13045 "};", 13046 Style); 13047 13048 verifyFormat("template <typename T> class rep<T>\n" 13049 "{\n" 13050 " int x;\n" 13051 "};", 13052 Style); 13053 13054 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13055 "{\n" 13056 " int x;\n" 13057 "};", 13058 Style); 13059 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13060 "{\n" 13061 "};", 13062 Style); 13063 13064 verifyFormat("#include \"stdint.h\"\n" 13065 "namespace rep {}", 13066 Style); 13067 verifyFormat("#include <stdint.h>\n" 13068 "namespace rep {}", 13069 Style); 13070 verifyFormat("#include <stdint.h>\n" 13071 "namespace rep {}", 13072 "#include <stdint.h>\n" 13073 "namespace rep {\n" 13074 "\n" 13075 "\n" 13076 "}", 13077 Style); 13078 } 13079 13080 TEST_F(FormatTest, SplitEmptyStruct) { 13081 FormatStyle Style = getLLVMStyle(); 13082 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13083 Style.BraceWrapping.AfterStruct = true; 13084 Style.BraceWrapping.SplitEmptyRecord = false; 13085 13086 verifyFormat("struct Foo\n" 13087 "{};", 13088 Style); 13089 verifyFormat("/* something */ struct Foo\n" 13090 "{};", 13091 Style); 13092 verifyFormat("template <typename X> struct Foo\n" 13093 "{};", 13094 Style); 13095 verifyFormat("struct Foo\n" 13096 "{\n" 13097 " Foo();\n" 13098 "};", 13099 Style); 13100 verifyFormat("typedef struct Foo\n" 13101 "{\n" 13102 "} Foo_t;", 13103 Style); 13104 // typedef struct Bar {} Bar_t; 13105 } 13106 13107 TEST_F(FormatTest, SplitEmptyUnion) { 13108 FormatStyle Style = getLLVMStyle(); 13109 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13110 Style.BraceWrapping.AfterUnion = true; 13111 Style.BraceWrapping.SplitEmptyRecord = false; 13112 13113 verifyFormat("union Foo\n" 13114 "{};", 13115 Style); 13116 verifyFormat("/* something */ union Foo\n" 13117 "{};", 13118 Style); 13119 verifyFormat("union Foo\n" 13120 "{\n" 13121 " A,\n" 13122 "};", 13123 Style); 13124 verifyFormat("typedef union Foo\n" 13125 "{\n" 13126 "} Foo_t;", 13127 Style); 13128 } 13129 13130 TEST_F(FormatTest, SplitEmptyNamespace) { 13131 FormatStyle Style = getLLVMStyle(); 13132 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13133 Style.BraceWrapping.AfterNamespace = true; 13134 Style.BraceWrapping.SplitEmptyNamespace = false; 13135 13136 verifyFormat("namespace Foo\n" 13137 "{};", 13138 Style); 13139 verifyFormat("/* something */ namespace Foo\n" 13140 "{};", 13141 Style); 13142 verifyFormat("inline namespace Foo\n" 13143 "{};", 13144 Style); 13145 verifyFormat("/* something */ inline namespace Foo\n" 13146 "{};", 13147 Style); 13148 verifyFormat("export namespace Foo\n" 13149 "{};", 13150 Style); 13151 verifyFormat("namespace Foo\n" 13152 "{\n" 13153 "void Bar();\n" 13154 "};", 13155 Style); 13156 } 13157 13158 TEST_F(FormatTest, NeverMergeShortRecords) { 13159 FormatStyle Style = getLLVMStyle(); 13160 13161 verifyFormat("class Foo {\n" 13162 " Foo();\n" 13163 "};", 13164 Style); 13165 verifyFormat("typedef class Foo {\n" 13166 " Foo();\n" 13167 "} Foo_t;", 13168 Style); 13169 verifyFormat("struct Foo {\n" 13170 " Foo();\n" 13171 "};", 13172 Style); 13173 verifyFormat("typedef struct Foo {\n" 13174 " Foo();\n" 13175 "} Foo_t;", 13176 Style); 13177 verifyFormat("union Foo {\n" 13178 " A,\n" 13179 "};", 13180 Style); 13181 verifyFormat("typedef union Foo {\n" 13182 " A,\n" 13183 "} Foo_t;", 13184 Style); 13185 verifyFormat("namespace Foo {\n" 13186 "void Bar();\n" 13187 "};", 13188 Style); 13189 13190 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13191 Style.BraceWrapping.AfterClass = true; 13192 Style.BraceWrapping.AfterStruct = true; 13193 Style.BraceWrapping.AfterUnion = true; 13194 Style.BraceWrapping.AfterNamespace = true; 13195 verifyFormat("class Foo\n" 13196 "{\n" 13197 " Foo();\n" 13198 "};", 13199 Style); 13200 verifyFormat("typedef class Foo\n" 13201 "{\n" 13202 " Foo();\n" 13203 "} Foo_t;", 13204 Style); 13205 verifyFormat("struct Foo\n" 13206 "{\n" 13207 " Foo();\n" 13208 "};", 13209 Style); 13210 verifyFormat("typedef struct Foo\n" 13211 "{\n" 13212 " Foo();\n" 13213 "} Foo_t;", 13214 Style); 13215 verifyFormat("union Foo\n" 13216 "{\n" 13217 " A,\n" 13218 "};", 13219 Style); 13220 verifyFormat("typedef union Foo\n" 13221 "{\n" 13222 " A,\n" 13223 "} Foo_t;", 13224 Style); 13225 verifyFormat("namespace Foo\n" 13226 "{\n" 13227 "void Bar();\n" 13228 "};", 13229 Style); 13230 } 13231 13232 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13233 // Elaborate type variable declarations. 13234 verifyFormat("struct foo a = {bar};\nint n;"); 13235 verifyFormat("class foo a = {bar};\nint n;"); 13236 verifyFormat("union foo a = {bar};\nint n;"); 13237 13238 // Elaborate types inside function definitions. 13239 verifyFormat("struct foo f() {}\nint n;"); 13240 verifyFormat("class foo f() {}\nint n;"); 13241 verifyFormat("union foo f() {}\nint n;"); 13242 13243 // Templates. 13244 verifyFormat("template <class X> void f() {}\nint n;"); 13245 verifyFormat("template <struct X> void f() {}\nint n;"); 13246 verifyFormat("template <union X> void f() {}\nint n;"); 13247 13248 // Actual definitions... 13249 verifyFormat("struct {\n} n;"); 13250 verifyFormat( 13251 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13252 verifyFormat("union Z {\n int n;\n} x;"); 13253 verifyFormat("class MACRO Z {\n} n;"); 13254 verifyFormat("class MACRO(X) Z {\n} n;"); 13255 verifyFormat("class __attribute__(X) Z {\n} n;"); 13256 verifyFormat("class __declspec(X) Z {\n} n;"); 13257 verifyFormat("class A##B##C {\n} n;"); 13258 verifyFormat("class alignas(16) Z {\n} n;"); 13259 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13260 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13261 13262 // Redefinition from nested context: 13263 verifyFormat("class A::B::C {\n} n;"); 13264 13265 // Template definitions. 13266 verifyFormat( 13267 "template <typename F>\n" 13268 "Matcher(const Matcher<F> &Other,\n" 13269 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13270 " !is_same<F, T>::value>::type * = 0)\n" 13271 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13272 13273 // FIXME: This is still incorrectly handled at the formatter side. 13274 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13275 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13276 13277 // FIXME: 13278 // This now gets parsed incorrectly as class definition. 13279 // verifyFormat("class A<int> f() {\n}\nint n;"); 13280 13281 // Elaborate types where incorrectly parsing the structural element would 13282 // break the indent. 13283 verifyFormat("if (true)\n" 13284 " class X x;\n" 13285 "else\n" 13286 " f();\n"); 13287 13288 // This is simply incomplete. Formatting is not important, but must not crash. 13289 verifyFormat("class A:"); 13290 } 13291 13292 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13293 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13294 format("#error Leave all white!!!!! space* alone!\n")); 13295 EXPECT_EQ( 13296 "#warning Leave all white!!!!! space* alone!\n", 13297 format("#warning Leave all white!!!!! space* alone!\n")); 13298 EXPECT_EQ("#error 1", format(" # error 1")); 13299 EXPECT_EQ("#warning 1", format(" # warning 1")); 13300 } 13301 13302 TEST_F(FormatTest, FormatHashIfExpressions) { 13303 verifyFormat("#if AAAA && BBBB"); 13304 verifyFormat("#if (AAAA && BBBB)"); 13305 verifyFormat("#elif (AAAA && BBBB)"); 13306 // FIXME: Come up with a better indentation for #elif. 13307 verifyFormat( 13308 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13309 " defined(BBBBBBBB)\n" 13310 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13311 " defined(BBBBBBBB)\n" 13312 "#endif", 13313 getLLVMStyleWithColumns(65)); 13314 } 13315 13316 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13317 FormatStyle AllowsMergedIf = getGoogleStyle(); 13318 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13319 FormatStyle::SIS_WithoutElse; 13320 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13321 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13322 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13323 EXPECT_EQ("if (true) return 42;", 13324 format("if (true)\nreturn 42;", AllowsMergedIf)); 13325 FormatStyle ShortMergedIf = AllowsMergedIf; 13326 ShortMergedIf.ColumnLimit = 25; 13327 verifyFormat("#define A \\\n" 13328 " if (true) return 42;", 13329 ShortMergedIf); 13330 verifyFormat("#define A \\\n" 13331 " f(); \\\n" 13332 " if (true)\n" 13333 "#define B", 13334 ShortMergedIf); 13335 verifyFormat("#define A \\\n" 13336 " f(); \\\n" 13337 " if (true)\n" 13338 "g();", 13339 ShortMergedIf); 13340 verifyFormat("{\n" 13341 "#ifdef A\n" 13342 " // Comment\n" 13343 " if (true) continue;\n" 13344 "#endif\n" 13345 " // Comment\n" 13346 " if (true) continue;\n" 13347 "}", 13348 ShortMergedIf); 13349 ShortMergedIf.ColumnLimit = 33; 13350 verifyFormat("#define A \\\n" 13351 " if constexpr (true) return 42;", 13352 ShortMergedIf); 13353 verifyFormat("#define A \\\n" 13354 " if CONSTEXPR (true) return 42;", 13355 ShortMergedIf); 13356 ShortMergedIf.ColumnLimit = 29; 13357 verifyFormat("#define A \\\n" 13358 " if (aaaaaaaaaa) return 1; \\\n" 13359 " return 2;", 13360 ShortMergedIf); 13361 ShortMergedIf.ColumnLimit = 28; 13362 verifyFormat("#define A \\\n" 13363 " if (aaaaaaaaaa) \\\n" 13364 " return 1; \\\n" 13365 " return 2;", 13366 ShortMergedIf); 13367 verifyFormat("#define A \\\n" 13368 " if constexpr (aaaaaaa) \\\n" 13369 " return 1; \\\n" 13370 " return 2;", 13371 ShortMergedIf); 13372 verifyFormat("#define A \\\n" 13373 " if CONSTEXPR (aaaaaaa) \\\n" 13374 " return 1; \\\n" 13375 " return 2;", 13376 ShortMergedIf); 13377 } 13378 13379 TEST_F(FormatTest, FormatStarDependingOnContext) { 13380 verifyFormat("void f(int *a);"); 13381 verifyFormat("void f() { f(fint * b); }"); 13382 verifyFormat("class A {\n void f(int *a);\n};"); 13383 verifyFormat("class A {\n int *a;\n};"); 13384 verifyFormat("namespace a {\n" 13385 "namespace b {\n" 13386 "class A {\n" 13387 " void f() {}\n" 13388 " int *a;\n" 13389 "};\n" 13390 "} // namespace b\n" 13391 "} // namespace a"); 13392 } 13393 13394 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13395 verifyFormat("while"); 13396 verifyFormat("operator"); 13397 } 13398 13399 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13400 // This code would be painfully slow to format if we didn't skip it. 13401 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 13402 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13403 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13404 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13405 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13406 "A(1, 1)\n" 13407 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13408 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13409 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13410 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13411 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13412 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13413 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13414 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13415 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13416 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13417 // Deeply nested part is untouched, rest is formatted. 13418 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13419 format(std::string("int i;\n") + Code + "int j;\n", 13420 getLLVMStyle(), SC_ExpectIncomplete)); 13421 } 13422 13423 //===----------------------------------------------------------------------===// 13424 // Objective-C tests. 13425 //===----------------------------------------------------------------------===// 13426 13427 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13428 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13429 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13430 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13431 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13432 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13433 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13434 format("-(NSInteger)Method3:(id)anObject;")); 13435 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13436 format("-(NSInteger)Method4:(id)anObject;")); 13437 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13438 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13439 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13440 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13441 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13442 "forAllCells:(BOOL)flag;", 13443 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13444 "forAllCells:(BOOL)flag;")); 13445 13446 // Very long objectiveC method declaration. 13447 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13448 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13449 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13450 " inRange:(NSRange)range\n" 13451 " outRange:(NSRange)out_range\n" 13452 " outRange1:(NSRange)out_range1\n" 13453 " outRange2:(NSRange)out_range2\n" 13454 " outRange3:(NSRange)out_range3\n" 13455 " outRange4:(NSRange)out_range4\n" 13456 " outRange5:(NSRange)out_range5\n" 13457 " outRange6:(NSRange)out_range6\n" 13458 " outRange7:(NSRange)out_range7\n" 13459 " outRange8:(NSRange)out_range8\n" 13460 " outRange9:(NSRange)out_range9;"); 13461 13462 // When the function name has to be wrapped. 13463 FormatStyle Style = getLLVMStyle(); 13464 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13465 // and always indents instead. 13466 Style.IndentWrappedFunctionNames = false; 13467 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13468 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13469 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13470 "}", 13471 Style); 13472 Style.IndentWrappedFunctionNames = true; 13473 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13474 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13475 " anotherName:(NSString)dddddddddddddd {\n" 13476 "}", 13477 Style); 13478 13479 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13480 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13481 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13482 // protocol lists (but not for template classes): 13483 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13484 13485 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13486 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13487 13488 // If there's no return type (very rare in practice!), LLVM and Google style 13489 // agree. 13490 verifyFormat("- foo;"); 13491 verifyFormat("- foo:(int)f;"); 13492 verifyGoogleFormat("- foo:(int)foo;"); 13493 } 13494 13495 TEST_F(FormatTest, BreaksStringLiterals) { 13496 EXPECT_EQ("\"some text \"\n" 13497 "\"other\";", 13498 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13499 EXPECT_EQ("\"some text \"\n" 13500 "\"other\";", 13501 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13502 EXPECT_EQ( 13503 "#define A \\\n" 13504 " \"some \" \\\n" 13505 " \"text \" \\\n" 13506 " \"other\";", 13507 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13508 EXPECT_EQ( 13509 "#define A \\\n" 13510 " \"so \" \\\n" 13511 " \"text \" \\\n" 13512 " \"other\";", 13513 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13514 13515 EXPECT_EQ("\"some text\"", 13516 format("\"some text\"", getLLVMStyleWithColumns(1))); 13517 EXPECT_EQ("\"some text\"", 13518 format("\"some text\"", getLLVMStyleWithColumns(11))); 13519 EXPECT_EQ("\"some \"\n" 13520 "\"text\"", 13521 format("\"some text\"", getLLVMStyleWithColumns(10))); 13522 EXPECT_EQ("\"some \"\n" 13523 "\"text\"", 13524 format("\"some text\"", getLLVMStyleWithColumns(7))); 13525 EXPECT_EQ("\"some\"\n" 13526 "\" tex\"\n" 13527 "\"t\"", 13528 format("\"some text\"", getLLVMStyleWithColumns(6))); 13529 EXPECT_EQ("\"some\"\n" 13530 "\" tex\"\n" 13531 "\" and\"", 13532 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13533 EXPECT_EQ("\"some\"\n" 13534 "\"/tex\"\n" 13535 "\"/and\"", 13536 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13537 13538 EXPECT_EQ("variable =\n" 13539 " \"long string \"\n" 13540 " \"literal\";", 13541 format("variable = \"long string literal\";", 13542 getLLVMStyleWithColumns(20))); 13543 13544 EXPECT_EQ("variable = f(\n" 13545 " \"long string \"\n" 13546 " \"literal\",\n" 13547 " short,\n" 13548 " loooooooooooooooooooong);", 13549 format("variable = f(\"long string literal\", short, " 13550 "loooooooooooooooooooong);", 13551 getLLVMStyleWithColumns(20))); 13552 13553 EXPECT_EQ( 13554 "f(g(\"long string \"\n" 13555 " \"literal\"),\n" 13556 " b);", 13557 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13558 EXPECT_EQ("f(g(\"long string \"\n" 13559 " \"literal\",\n" 13560 " a),\n" 13561 " b);", 13562 format("f(g(\"long string literal\", a), b);", 13563 getLLVMStyleWithColumns(20))); 13564 EXPECT_EQ( 13565 "f(\"one two\".split(\n" 13566 " variable));", 13567 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13568 EXPECT_EQ("f(\"one two three four five six \"\n" 13569 " \"seven\".split(\n" 13570 " really_looooong_variable));", 13571 format("f(\"one two three four five six seven\"." 13572 "split(really_looooong_variable));", 13573 getLLVMStyleWithColumns(33))); 13574 13575 EXPECT_EQ("f(\"some \"\n" 13576 " \"text\",\n" 13577 " other);", 13578 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13579 13580 // Only break as a last resort. 13581 verifyFormat( 13582 "aaaaaaaaaaaaaaaaaaaa(\n" 13583 " aaaaaaaaaaaaaaaaaaaa,\n" 13584 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13585 13586 EXPECT_EQ("\"splitmea\"\n" 13587 "\"trandomp\"\n" 13588 "\"oint\"", 13589 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13590 13591 EXPECT_EQ("\"split/\"\n" 13592 "\"pathat/\"\n" 13593 "\"slashes\"", 13594 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13595 13596 EXPECT_EQ("\"split/\"\n" 13597 "\"pathat/\"\n" 13598 "\"slashes\"", 13599 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13600 EXPECT_EQ("\"split at \"\n" 13601 "\"spaces/at/\"\n" 13602 "\"slashes.at.any$\"\n" 13603 "\"non-alphanumeric%\"\n" 13604 "\"1111111111characte\"\n" 13605 "\"rs\"", 13606 format("\"split at " 13607 "spaces/at/" 13608 "slashes.at." 13609 "any$non-" 13610 "alphanumeric%" 13611 "1111111111characte" 13612 "rs\"", 13613 getLLVMStyleWithColumns(20))); 13614 13615 // Verify that splitting the strings understands 13616 // Style::AlwaysBreakBeforeMultilineStrings. 13617 EXPECT_EQ("aaaaaaaaaaaa(\n" 13618 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13619 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13620 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13621 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13622 "aaaaaaaaaaaaaaaaaaaaaa\");", 13623 getGoogleStyle())); 13624 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13625 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13626 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13627 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13628 "aaaaaaaaaaaaaaaaaaaaaa\";", 13629 getGoogleStyle())); 13630 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13631 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13632 format("llvm::outs() << " 13633 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13634 "aaaaaaaaaaaaaaaaaaa\";")); 13635 EXPECT_EQ("ffff(\n" 13636 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13637 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13638 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13639 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13640 getGoogleStyle())); 13641 13642 FormatStyle Style = getLLVMStyleWithColumns(12); 13643 Style.BreakStringLiterals = false; 13644 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13645 13646 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13647 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13648 EXPECT_EQ("#define A \\\n" 13649 " \"some \" \\\n" 13650 " \"text \" \\\n" 13651 " \"other\";", 13652 format("#define A \"some text other\";", AlignLeft)); 13653 } 13654 13655 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13656 EXPECT_EQ("C a = \"some more \"\n" 13657 " \"text\";", 13658 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13659 } 13660 13661 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13662 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13663 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13664 EXPECT_EQ("int i = a(b());", 13665 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13666 } 13667 13668 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13669 EXPECT_EQ( 13670 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13671 "(\n" 13672 " \"x\t\");", 13673 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13674 "aaaaaaa(" 13675 "\"x\t\");")); 13676 } 13677 13678 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13679 EXPECT_EQ( 13680 "u8\"utf8 string \"\n" 13681 "u8\"literal\";", 13682 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13683 EXPECT_EQ( 13684 "u\"utf16 string \"\n" 13685 "u\"literal\";", 13686 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13687 EXPECT_EQ( 13688 "U\"utf32 string \"\n" 13689 "U\"literal\";", 13690 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13691 EXPECT_EQ("L\"wide string \"\n" 13692 "L\"literal\";", 13693 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13694 EXPECT_EQ("@\"NSString \"\n" 13695 "@\"literal\";", 13696 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13697 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13698 13699 // This input makes clang-format try to split the incomplete unicode escape 13700 // sequence, which used to lead to a crasher. 13701 verifyNoCrash( 13702 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13703 getLLVMStyleWithColumns(60)); 13704 } 13705 13706 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13707 FormatStyle Style = getGoogleStyleWithColumns(15); 13708 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13709 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13710 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13711 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13712 EXPECT_EQ("u8R\"x(raw literal)x\";", 13713 format("u8R\"x(raw literal)x\";", Style)); 13714 } 13715 13716 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13717 FormatStyle Style = getLLVMStyleWithColumns(20); 13718 EXPECT_EQ( 13719 "_T(\"aaaaaaaaaaaaaa\")\n" 13720 "_T(\"aaaaaaaaaaaaaa\")\n" 13721 "_T(\"aaaaaaaaaaaa\")", 13722 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13723 EXPECT_EQ("f(x,\n" 13724 " _T(\"aaaaaaaaaaaa\")\n" 13725 " _T(\"aaa\"),\n" 13726 " z);", 13727 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13728 13729 // FIXME: Handle embedded spaces in one iteration. 13730 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13731 // "_T(\"aaaaaaaaaaaaa\")\n" 13732 // "_T(\"aaaaaaaaaaaaa\")\n" 13733 // "_T(\"a\")", 13734 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13735 // getLLVMStyleWithColumns(20))); 13736 EXPECT_EQ( 13737 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13738 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13739 EXPECT_EQ("f(\n" 13740 "#if !TEST\n" 13741 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13742 "#endif\n" 13743 ");", 13744 format("f(\n" 13745 "#if !TEST\n" 13746 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13747 "#endif\n" 13748 ");")); 13749 EXPECT_EQ("f(\n" 13750 "\n" 13751 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13752 format("f(\n" 13753 "\n" 13754 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13755 // Regression test for accessing tokens past the end of a vector in the 13756 // TokenLexer. 13757 verifyNoCrash(R"(_T( 13758 " 13759 ) 13760 )"); 13761 } 13762 13763 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13764 // In a function call with two operands, the second can be broken with no line 13765 // break before it. 13766 EXPECT_EQ( 13767 "func(a, \"long long \"\n" 13768 " \"long long\");", 13769 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13770 // In a function call with three operands, the second must be broken with a 13771 // line break before it. 13772 EXPECT_EQ("func(a,\n" 13773 " \"long long long \"\n" 13774 " \"long\",\n" 13775 " c);", 13776 format("func(a, \"long long long long\", c);", 13777 getLLVMStyleWithColumns(24))); 13778 // In a function call with three operands, the third must be broken with a 13779 // line break before it. 13780 EXPECT_EQ("func(a, b,\n" 13781 " \"long long long \"\n" 13782 " \"long\");", 13783 format("func(a, b, \"long long long long\");", 13784 getLLVMStyleWithColumns(24))); 13785 // In a function call with three operands, both the second and the third must 13786 // be broken with a line break before them. 13787 EXPECT_EQ("func(a,\n" 13788 " \"long long long \"\n" 13789 " \"long\",\n" 13790 " \"long long long \"\n" 13791 " \"long\");", 13792 format("func(a, \"long long long long\", \"long long long long\");", 13793 getLLVMStyleWithColumns(24))); 13794 // In a chain of << with two operands, the second can be broken with no line 13795 // break before it. 13796 EXPECT_EQ("a << \"line line \"\n" 13797 " \"line\";", 13798 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13799 // In a chain of << with three operands, the second can be broken with no line 13800 // break before it. 13801 EXPECT_EQ( 13802 "abcde << \"line \"\n" 13803 " \"line line\"\n" 13804 " << c;", 13805 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13806 // In a chain of << with three operands, the third must be broken with a line 13807 // break before it. 13808 EXPECT_EQ( 13809 "a << b\n" 13810 " << \"line line \"\n" 13811 " \"line\";", 13812 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13813 // In a chain of << with three operands, the second can be broken with no line 13814 // break before it and the third must be broken with a line break before it. 13815 EXPECT_EQ("abcd << \"line line \"\n" 13816 " \"line\"\n" 13817 " << \"line line \"\n" 13818 " \"line\";", 13819 format("abcd << \"line line line\" << \"line line line\";", 13820 getLLVMStyleWithColumns(20))); 13821 // In a chain of binary operators with two operands, the second can be broken 13822 // with no line break before it. 13823 EXPECT_EQ( 13824 "abcd + \"line line \"\n" 13825 " \"line line\";", 13826 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13827 // In a chain of binary operators with three operands, the second must be 13828 // broken with a line break before it. 13829 EXPECT_EQ("abcd +\n" 13830 " \"line line \"\n" 13831 " \"line line\" +\n" 13832 " e;", 13833 format("abcd + \"line line line line\" + e;", 13834 getLLVMStyleWithColumns(20))); 13835 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13836 // the first must be broken with a line break before it. 13837 FormatStyle Style = getLLVMStyleWithColumns(25); 13838 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13839 EXPECT_EQ("someFunction(\n" 13840 " \"long long long \"\n" 13841 " \"long\",\n" 13842 " a);", 13843 format("someFunction(\"long long long long\", a);", Style)); 13844 } 13845 13846 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13847 EXPECT_EQ( 13848 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13849 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13850 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13851 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13852 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13853 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13854 } 13855 13856 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13857 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13858 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13859 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13860 "multiline raw string literal xxxxxxxxxxxxxx\n" 13861 ")x\",\n" 13862 " a),\n" 13863 " b);", 13864 format("fffffffffff(g(R\"x(\n" 13865 "multiline raw string literal xxxxxxxxxxxxxx\n" 13866 ")x\", a), b);", 13867 getGoogleStyleWithColumns(20))); 13868 EXPECT_EQ("fffffffffff(\n" 13869 " g(R\"x(qqq\n" 13870 "multiline raw string literal xxxxxxxxxxxxxx\n" 13871 ")x\",\n" 13872 " a),\n" 13873 " b);", 13874 format("fffffffffff(g(R\"x(qqq\n" 13875 "multiline raw string literal xxxxxxxxxxxxxx\n" 13876 ")x\", a), b);", 13877 getGoogleStyleWithColumns(20))); 13878 13879 EXPECT_EQ("fffffffffff(R\"x(\n" 13880 "multiline raw string literal xxxxxxxxxxxxxx\n" 13881 ")x\");", 13882 format("fffffffffff(R\"x(\n" 13883 "multiline raw string literal xxxxxxxxxxxxxx\n" 13884 ")x\");", 13885 getGoogleStyleWithColumns(20))); 13886 EXPECT_EQ("fffffffffff(R\"x(\n" 13887 "multiline raw string literal xxxxxxxxxxxxxx\n" 13888 ")x\" + bbbbbb);", 13889 format("fffffffffff(R\"x(\n" 13890 "multiline raw string literal xxxxxxxxxxxxxx\n" 13891 ")x\" + bbbbbb);", 13892 getGoogleStyleWithColumns(20))); 13893 EXPECT_EQ("fffffffffff(\n" 13894 " R\"x(\n" 13895 "multiline raw string literal xxxxxxxxxxxxxx\n" 13896 ")x\" +\n" 13897 " bbbbbb);", 13898 format("fffffffffff(\n" 13899 " R\"x(\n" 13900 "multiline raw string literal xxxxxxxxxxxxxx\n" 13901 ")x\" + bbbbbb);", 13902 getGoogleStyleWithColumns(20))); 13903 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13904 format("fffffffffff(\n" 13905 " R\"(single line raw string)\" + bbbbbb);")); 13906 } 13907 13908 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13909 verifyFormat("string a = \"unterminated;"); 13910 EXPECT_EQ("function(\"unterminated,\n" 13911 " OtherParameter);", 13912 format("function( \"unterminated,\n" 13913 " OtherParameter);")); 13914 } 13915 13916 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13917 FormatStyle Style = getLLVMStyle(); 13918 Style.Standard = FormatStyle::LS_Cpp03; 13919 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13920 format("#define x(_a) printf(\"foo\"_a);", Style)); 13921 } 13922 13923 TEST_F(FormatTest, CppLexVersion) { 13924 FormatStyle Style = getLLVMStyle(); 13925 // Formatting of x * y differs if x is a type. 13926 verifyFormat("void foo() { MACRO(a * b); }", Style); 13927 verifyFormat("void foo() { MACRO(int *b); }", Style); 13928 13929 // LLVM style uses latest lexer. 13930 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13931 Style.Standard = FormatStyle::LS_Cpp17; 13932 // But in c++17, char8_t isn't a keyword. 13933 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13934 } 13935 13936 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13937 13938 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13939 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13940 " \"ddeeefff\");", 13941 format("someFunction(\"aaabbbcccdddeeefff\");", 13942 getLLVMStyleWithColumns(25))); 13943 EXPECT_EQ("someFunction1234567890(\n" 13944 " \"aaabbbcccdddeeefff\");", 13945 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13946 getLLVMStyleWithColumns(26))); 13947 EXPECT_EQ("someFunction1234567890(\n" 13948 " \"aaabbbcccdddeeeff\"\n" 13949 " \"f\");", 13950 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13951 getLLVMStyleWithColumns(25))); 13952 EXPECT_EQ("someFunction1234567890(\n" 13953 " \"aaabbbcccdddeeeff\"\n" 13954 " \"f\");", 13955 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13956 getLLVMStyleWithColumns(24))); 13957 EXPECT_EQ("someFunction(\n" 13958 " \"aaabbbcc ddde \"\n" 13959 " \"efff\");", 13960 format("someFunction(\"aaabbbcc ddde efff\");", 13961 getLLVMStyleWithColumns(25))); 13962 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13963 " \"ddeeefff\");", 13964 format("someFunction(\"aaabbbccc ddeeefff\");", 13965 getLLVMStyleWithColumns(25))); 13966 EXPECT_EQ("someFunction1234567890(\n" 13967 " \"aaabb \"\n" 13968 " \"cccdddeeefff\");", 13969 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13970 getLLVMStyleWithColumns(25))); 13971 EXPECT_EQ("#define A \\\n" 13972 " string s = \\\n" 13973 " \"123456789\" \\\n" 13974 " \"0\"; \\\n" 13975 " int i;", 13976 format("#define A string s = \"1234567890\"; int i;", 13977 getLLVMStyleWithColumns(20))); 13978 EXPECT_EQ("someFunction(\n" 13979 " \"aaabbbcc \"\n" 13980 " \"dddeeefff\");", 13981 format("someFunction(\"aaabbbcc dddeeefff\");", 13982 getLLVMStyleWithColumns(25))); 13983 } 13984 13985 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13986 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13987 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13988 EXPECT_EQ("\"test\"\n" 13989 "\"\\n\"", 13990 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13991 EXPECT_EQ("\"tes\\\\\"\n" 13992 "\"n\"", 13993 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13994 EXPECT_EQ("\"\\\\\\\\\"\n" 13995 "\"\\n\"", 13996 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13997 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13998 EXPECT_EQ("\"\\uff01\"\n" 13999 "\"test\"", 14000 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14001 EXPECT_EQ("\"\\Uff01ff02\"", 14002 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14003 EXPECT_EQ("\"\\x000000000001\"\n" 14004 "\"next\"", 14005 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14006 EXPECT_EQ("\"\\x000000000001next\"", 14007 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14008 EXPECT_EQ("\"\\x000000000001\"", 14009 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14010 EXPECT_EQ("\"test\"\n" 14011 "\"\\000000\"\n" 14012 "\"000001\"", 14013 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14014 EXPECT_EQ("\"test\\000\"\n" 14015 "\"00000000\"\n" 14016 "\"1\"", 14017 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14018 } 14019 14020 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14021 verifyFormat("void f() {\n" 14022 " return g() {}\n" 14023 " void h() {}"); 14024 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14025 "g();\n" 14026 "}"); 14027 } 14028 14029 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14030 verifyFormat( 14031 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14032 } 14033 14034 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14035 verifyFormat("class X {\n" 14036 " void f() {\n" 14037 " }\n" 14038 "};", 14039 getLLVMStyleWithColumns(12)); 14040 } 14041 14042 TEST_F(FormatTest, ConfigurableIndentWidth) { 14043 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14044 EightIndent.IndentWidth = 8; 14045 EightIndent.ContinuationIndentWidth = 8; 14046 verifyFormat("void f() {\n" 14047 " someFunction();\n" 14048 " if (true) {\n" 14049 " f();\n" 14050 " }\n" 14051 "}", 14052 EightIndent); 14053 verifyFormat("class X {\n" 14054 " void f() {\n" 14055 " }\n" 14056 "};", 14057 EightIndent); 14058 verifyFormat("int x[] = {\n" 14059 " call(),\n" 14060 " call()};", 14061 EightIndent); 14062 } 14063 14064 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14065 verifyFormat("double\n" 14066 "f();", 14067 getLLVMStyleWithColumns(8)); 14068 } 14069 14070 TEST_F(FormatTest, ConfigurableUseOfTab) { 14071 FormatStyle Tab = getLLVMStyleWithColumns(42); 14072 Tab.IndentWidth = 8; 14073 Tab.UseTab = FormatStyle::UT_Always; 14074 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14075 14076 EXPECT_EQ("if (aaaaaaaa && // q\n" 14077 " bb)\t\t// w\n" 14078 "\t;", 14079 format("if (aaaaaaaa &&// q\n" 14080 "bb)// w\n" 14081 ";", 14082 Tab)); 14083 EXPECT_EQ("if (aaa && bbb) // w\n" 14084 "\t;", 14085 format("if(aaa&&bbb)// w\n" 14086 ";", 14087 Tab)); 14088 14089 verifyFormat("class X {\n" 14090 "\tvoid f() {\n" 14091 "\t\tsomeFunction(parameter1,\n" 14092 "\t\t\t parameter2);\n" 14093 "\t}\n" 14094 "};", 14095 Tab); 14096 verifyFormat("#define A \\\n" 14097 "\tvoid f() { \\\n" 14098 "\t\tsomeFunction( \\\n" 14099 "\t\t parameter1, \\\n" 14100 "\t\t parameter2); \\\n" 14101 "\t}", 14102 Tab); 14103 verifyFormat("int a;\t // x\n" 14104 "int bbbbbbbb; // x\n", 14105 Tab); 14106 14107 Tab.TabWidth = 4; 14108 Tab.IndentWidth = 8; 14109 verifyFormat("class TabWidth4Indent8 {\n" 14110 "\t\tvoid f() {\n" 14111 "\t\t\t\tsomeFunction(parameter1,\n" 14112 "\t\t\t\t\t\t\t parameter2);\n" 14113 "\t\t}\n" 14114 "};", 14115 Tab); 14116 14117 Tab.TabWidth = 4; 14118 Tab.IndentWidth = 4; 14119 verifyFormat("class TabWidth4Indent4 {\n" 14120 "\tvoid f() {\n" 14121 "\t\tsomeFunction(parameter1,\n" 14122 "\t\t\t\t\t parameter2);\n" 14123 "\t}\n" 14124 "};", 14125 Tab); 14126 14127 Tab.TabWidth = 8; 14128 Tab.IndentWidth = 4; 14129 verifyFormat("class TabWidth8Indent4 {\n" 14130 " void f() {\n" 14131 "\tsomeFunction(parameter1,\n" 14132 "\t\t parameter2);\n" 14133 " }\n" 14134 "};", 14135 Tab); 14136 14137 Tab.TabWidth = 8; 14138 Tab.IndentWidth = 8; 14139 EXPECT_EQ("/*\n" 14140 "\t a\t\tcomment\n" 14141 "\t in multiple lines\n" 14142 " */", 14143 format(" /*\t \t \n" 14144 " \t \t a\t\tcomment\t \t\n" 14145 " \t \t in multiple lines\t\n" 14146 " \t */", 14147 Tab)); 14148 14149 Tab.UseTab = FormatStyle::UT_ForIndentation; 14150 verifyFormat("{\n" 14151 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14152 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14153 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14154 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14155 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14156 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14157 "};", 14158 Tab); 14159 verifyFormat("enum AA {\n" 14160 "\ta1, // Force multiple lines\n" 14161 "\ta2,\n" 14162 "\ta3\n" 14163 "};", 14164 Tab); 14165 EXPECT_EQ("if (aaaaaaaa && // q\n" 14166 " bb) // w\n" 14167 "\t;", 14168 format("if (aaaaaaaa &&// q\n" 14169 "bb)// w\n" 14170 ";", 14171 Tab)); 14172 verifyFormat("class X {\n" 14173 "\tvoid f() {\n" 14174 "\t\tsomeFunction(parameter1,\n" 14175 "\t\t parameter2);\n" 14176 "\t}\n" 14177 "};", 14178 Tab); 14179 verifyFormat("{\n" 14180 "\tQ(\n" 14181 "\t {\n" 14182 "\t\t int a;\n" 14183 "\t\t someFunction(aaaaaaaa,\n" 14184 "\t\t bbbbbbb);\n" 14185 "\t },\n" 14186 "\t p);\n" 14187 "}", 14188 Tab); 14189 EXPECT_EQ("{\n" 14190 "\t/* aaaa\n" 14191 "\t bbbb */\n" 14192 "}", 14193 format("{\n" 14194 "/* aaaa\n" 14195 " bbbb */\n" 14196 "}", 14197 Tab)); 14198 EXPECT_EQ("{\n" 14199 "\t/*\n" 14200 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14201 "\t bbbbbbbbbbbbb\n" 14202 "\t*/\n" 14203 "}", 14204 format("{\n" 14205 "/*\n" 14206 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14207 "*/\n" 14208 "}", 14209 Tab)); 14210 EXPECT_EQ("{\n" 14211 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14212 "\t// bbbbbbbbbbbbb\n" 14213 "}", 14214 format("{\n" 14215 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14216 "}", 14217 Tab)); 14218 EXPECT_EQ("{\n" 14219 "\t/*\n" 14220 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14221 "\t bbbbbbbbbbbbb\n" 14222 "\t*/\n" 14223 "}", 14224 format("{\n" 14225 "\t/*\n" 14226 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14227 "\t*/\n" 14228 "}", 14229 Tab)); 14230 EXPECT_EQ("{\n" 14231 "\t/*\n" 14232 "\n" 14233 "\t*/\n" 14234 "}", 14235 format("{\n" 14236 "\t/*\n" 14237 "\n" 14238 "\t*/\n" 14239 "}", 14240 Tab)); 14241 EXPECT_EQ("{\n" 14242 "\t/*\n" 14243 " asdf\n" 14244 "\t*/\n" 14245 "}", 14246 format("{\n" 14247 "\t/*\n" 14248 " asdf\n" 14249 "\t*/\n" 14250 "}", 14251 Tab)); 14252 14253 verifyFormat("void f() {\n" 14254 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14255 "\t : bbbbbbbbbbbbbbbbbb\n" 14256 "}", 14257 Tab); 14258 FormatStyle TabNoBreak = Tab; 14259 TabNoBreak.BreakBeforeTernaryOperators = false; 14260 verifyFormat("void f() {\n" 14261 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14262 "\t bbbbbbbbbbbbbbbbbb\n" 14263 "}", 14264 TabNoBreak); 14265 verifyFormat("void f() {\n" 14266 "\treturn true ?\n" 14267 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14268 "\t bbbbbbbbbbbbbbbbbbbb\n" 14269 "}", 14270 TabNoBreak); 14271 14272 Tab.UseTab = FormatStyle::UT_Never; 14273 EXPECT_EQ("/*\n" 14274 " a\t\tcomment\n" 14275 " in multiple lines\n" 14276 " */", 14277 format(" /*\t \t \n" 14278 " \t \t a\t\tcomment\t \t\n" 14279 " \t \t in multiple lines\t\n" 14280 " \t */", 14281 Tab)); 14282 EXPECT_EQ("/* some\n" 14283 " comment */", 14284 format(" \t \t /* some\n" 14285 " \t \t comment */", 14286 Tab)); 14287 EXPECT_EQ("int a; /* some\n" 14288 " comment */", 14289 format(" \t \t int a; /* some\n" 14290 " \t \t comment */", 14291 Tab)); 14292 14293 EXPECT_EQ("int a; /* some\n" 14294 "comment */", 14295 format(" \t \t int\ta; /* some\n" 14296 " \t \t comment */", 14297 Tab)); 14298 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14299 " comment */", 14300 format(" \t \t f(\"\t\t\"); /* some\n" 14301 " \t \t comment */", 14302 Tab)); 14303 EXPECT_EQ("{\n" 14304 " /*\n" 14305 " * Comment\n" 14306 " */\n" 14307 " int i;\n" 14308 "}", 14309 format("{\n" 14310 "\t/*\n" 14311 "\t * Comment\n" 14312 "\t */\n" 14313 "\t int i;\n" 14314 "}", 14315 Tab)); 14316 14317 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14318 Tab.TabWidth = 8; 14319 Tab.IndentWidth = 8; 14320 EXPECT_EQ("if (aaaaaaaa && // q\n" 14321 " bb) // w\n" 14322 "\t;", 14323 format("if (aaaaaaaa &&// q\n" 14324 "bb)// w\n" 14325 ";", 14326 Tab)); 14327 EXPECT_EQ("if (aaa && bbb) // w\n" 14328 "\t;", 14329 format("if(aaa&&bbb)// w\n" 14330 ";", 14331 Tab)); 14332 verifyFormat("class X {\n" 14333 "\tvoid f() {\n" 14334 "\t\tsomeFunction(parameter1,\n" 14335 "\t\t\t parameter2);\n" 14336 "\t}\n" 14337 "};", 14338 Tab); 14339 verifyFormat("#define A \\\n" 14340 "\tvoid f() { \\\n" 14341 "\t\tsomeFunction( \\\n" 14342 "\t\t parameter1, \\\n" 14343 "\t\t parameter2); \\\n" 14344 "\t}", 14345 Tab); 14346 Tab.TabWidth = 4; 14347 Tab.IndentWidth = 8; 14348 verifyFormat("class TabWidth4Indent8 {\n" 14349 "\t\tvoid f() {\n" 14350 "\t\t\t\tsomeFunction(parameter1,\n" 14351 "\t\t\t\t\t\t\t parameter2);\n" 14352 "\t\t}\n" 14353 "};", 14354 Tab); 14355 Tab.TabWidth = 4; 14356 Tab.IndentWidth = 4; 14357 verifyFormat("class TabWidth4Indent4 {\n" 14358 "\tvoid f() {\n" 14359 "\t\tsomeFunction(parameter1,\n" 14360 "\t\t\t\t\t parameter2);\n" 14361 "\t}\n" 14362 "};", 14363 Tab); 14364 Tab.TabWidth = 8; 14365 Tab.IndentWidth = 4; 14366 verifyFormat("class TabWidth8Indent4 {\n" 14367 " void f() {\n" 14368 "\tsomeFunction(parameter1,\n" 14369 "\t\t parameter2);\n" 14370 " }\n" 14371 "};", 14372 Tab); 14373 Tab.TabWidth = 8; 14374 Tab.IndentWidth = 8; 14375 EXPECT_EQ("/*\n" 14376 "\t a\t\tcomment\n" 14377 "\t in multiple lines\n" 14378 " */", 14379 format(" /*\t \t \n" 14380 " \t \t a\t\tcomment\t \t\n" 14381 " \t \t in multiple lines\t\n" 14382 " \t */", 14383 Tab)); 14384 verifyFormat("{\n" 14385 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14386 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14387 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14388 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14389 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14390 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14391 "};", 14392 Tab); 14393 verifyFormat("enum AA {\n" 14394 "\ta1, // Force multiple lines\n" 14395 "\ta2,\n" 14396 "\ta3\n" 14397 "};", 14398 Tab); 14399 EXPECT_EQ("if (aaaaaaaa && // q\n" 14400 " bb) // w\n" 14401 "\t;", 14402 format("if (aaaaaaaa &&// q\n" 14403 "bb)// w\n" 14404 ";", 14405 Tab)); 14406 verifyFormat("class X {\n" 14407 "\tvoid f() {\n" 14408 "\t\tsomeFunction(parameter1,\n" 14409 "\t\t\t parameter2);\n" 14410 "\t}\n" 14411 "};", 14412 Tab); 14413 verifyFormat("{\n" 14414 "\tQ(\n" 14415 "\t {\n" 14416 "\t\t int a;\n" 14417 "\t\t someFunction(aaaaaaaa,\n" 14418 "\t\t\t\t bbbbbbb);\n" 14419 "\t },\n" 14420 "\t p);\n" 14421 "}", 14422 Tab); 14423 EXPECT_EQ("{\n" 14424 "\t/* aaaa\n" 14425 "\t bbbb */\n" 14426 "}", 14427 format("{\n" 14428 "/* aaaa\n" 14429 " bbbb */\n" 14430 "}", 14431 Tab)); 14432 EXPECT_EQ("{\n" 14433 "\t/*\n" 14434 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14435 "\t bbbbbbbbbbbbb\n" 14436 "\t*/\n" 14437 "}", 14438 format("{\n" 14439 "/*\n" 14440 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14441 "*/\n" 14442 "}", 14443 Tab)); 14444 EXPECT_EQ("{\n" 14445 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14446 "\t// bbbbbbbbbbbbb\n" 14447 "}", 14448 format("{\n" 14449 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14450 "}", 14451 Tab)); 14452 EXPECT_EQ("{\n" 14453 "\t/*\n" 14454 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14455 "\t bbbbbbbbbbbbb\n" 14456 "\t*/\n" 14457 "}", 14458 format("{\n" 14459 "\t/*\n" 14460 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14461 "\t*/\n" 14462 "}", 14463 Tab)); 14464 EXPECT_EQ("{\n" 14465 "\t/*\n" 14466 "\n" 14467 "\t*/\n" 14468 "}", 14469 format("{\n" 14470 "\t/*\n" 14471 "\n" 14472 "\t*/\n" 14473 "}", 14474 Tab)); 14475 EXPECT_EQ("{\n" 14476 "\t/*\n" 14477 " asdf\n" 14478 "\t*/\n" 14479 "}", 14480 format("{\n" 14481 "\t/*\n" 14482 " asdf\n" 14483 "\t*/\n" 14484 "}", 14485 Tab)); 14486 EXPECT_EQ("/* some\n" 14487 " comment */", 14488 format(" \t \t /* some\n" 14489 " \t \t comment */", 14490 Tab)); 14491 EXPECT_EQ("int a; /* some\n" 14492 " comment */", 14493 format(" \t \t int a; /* some\n" 14494 " \t \t comment */", 14495 Tab)); 14496 EXPECT_EQ("int a; /* some\n" 14497 "comment */", 14498 format(" \t \t int\ta; /* some\n" 14499 " \t \t comment */", 14500 Tab)); 14501 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14502 " comment */", 14503 format(" \t \t f(\"\t\t\"); /* some\n" 14504 " \t \t comment */", 14505 Tab)); 14506 EXPECT_EQ("{\n" 14507 "\t/*\n" 14508 "\t * Comment\n" 14509 "\t */\n" 14510 "\tint i;\n" 14511 "}", 14512 format("{\n" 14513 "\t/*\n" 14514 "\t * Comment\n" 14515 "\t */\n" 14516 "\t int i;\n" 14517 "}", 14518 Tab)); 14519 Tab.TabWidth = 2; 14520 Tab.IndentWidth = 2; 14521 EXPECT_EQ("{\n" 14522 "\t/* aaaa\n" 14523 "\t\t bbbb */\n" 14524 "}", 14525 format("{\n" 14526 "/* aaaa\n" 14527 "\t bbbb */\n" 14528 "}", 14529 Tab)); 14530 EXPECT_EQ("{\n" 14531 "\t/*\n" 14532 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14533 "\t\tbbbbbbbbbbbbb\n" 14534 "\t*/\n" 14535 "}", 14536 format("{\n" 14537 "/*\n" 14538 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14539 "*/\n" 14540 "}", 14541 Tab)); 14542 Tab.AlignConsecutiveAssignments.Enabled = true; 14543 Tab.AlignConsecutiveDeclarations.Enabled = true; 14544 Tab.TabWidth = 4; 14545 Tab.IndentWidth = 4; 14546 verifyFormat("class Assign {\n" 14547 "\tvoid f() {\n" 14548 "\t\tint x = 123;\n" 14549 "\t\tint random = 4;\n" 14550 "\t\tstd::string alphabet =\n" 14551 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14552 "\t}\n" 14553 "};", 14554 Tab); 14555 14556 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14557 Tab.TabWidth = 8; 14558 Tab.IndentWidth = 8; 14559 EXPECT_EQ("if (aaaaaaaa && // q\n" 14560 " bb) // w\n" 14561 "\t;", 14562 format("if (aaaaaaaa &&// q\n" 14563 "bb)// w\n" 14564 ";", 14565 Tab)); 14566 EXPECT_EQ("if (aaa && bbb) // w\n" 14567 "\t;", 14568 format("if(aaa&&bbb)// w\n" 14569 ";", 14570 Tab)); 14571 verifyFormat("class X {\n" 14572 "\tvoid f() {\n" 14573 "\t\tsomeFunction(parameter1,\n" 14574 "\t\t parameter2);\n" 14575 "\t}\n" 14576 "};", 14577 Tab); 14578 verifyFormat("#define A \\\n" 14579 "\tvoid f() { \\\n" 14580 "\t\tsomeFunction( \\\n" 14581 "\t\t parameter1, \\\n" 14582 "\t\t parameter2); \\\n" 14583 "\t}", 14584 Tab); 14585 Tab.TabWidth = 4; 14586 Tab.IndentWidth = 8; 14587 verifyFormat("class TabWidth4Indent8 {\n" 14588 "\t\tvoid f() {\n" 14589 "\t\t\t\tsomeFunction(parameter1,\n" 14590 "\t\t\t\t parameter2);\n" 14591 "\t\t}\n" 14592 "};", 14593 Tab); 14594 Tab.TabWidth = 4; 14595 Tab.IndentWidth = 4; 14596 verifyFormat("class TabWidth4Indent4 {\n" 14597 "\tvoid f() {\n" 14598 "\t\tsomeFunction(parameter1,\n" 14599 "\t\t parameter2);\n" 14600 "\t}\n" 14601 "};", 14602 Tab); 14603 Tab.TabWidth = 8; 14604 Tab.IndentWidth = 4; 14605 verifyFormat("class TabWidth8Indent4 {\n" 14606 " void f() {\n" 14607 "\tsomeFunction(parameter1,\n" 14608 "\t parameter2);\n" 14609 " }\n" 14610 "};", 14611 Tab); 14612 Tab.TabWidth = 8; 14613 Tab.IndentWidth = 8; 14614 EXPECT_EQ("/*\n" 14615 " a\t\tcomment\n" 14616 " in multiple lines\n" 14617 " */", 14618 format(" /*\t \t \n" 14619 " \t \t a\t\tcomment\t \t\n" 14620 " \t \t in multiple lines\t\n" 14621 " \t */", 14622 Tab)); 14623 verifyFormat("{\n" 14624 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14625 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14626 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14627 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14628 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14629 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14630 "};", 14631 Tab); 14632 verifyFormat("enum AA {\n" 14633 "\ta1, // Force multiple lines\n" 14634 "\ta2,\n" 14635 "\ta3\n" 14636 "};", 14637 Tab); 14638 EXPECT_EQ("if (aaaaaaaa && // q\n" 14639 " bb) // w\n" 14640 "\t;", 14641 format("if (aaaaaaaa &&// q\n" 14642 "bb)// w\n" 14643 ";", 14644 Tab)); 14645 verifyFormat("class X {\n" 14646 "\tvoid f() {\n" 14647 "\t\tsomeFunction(parameter1,\n" 14648 "\t\t parameter2);\n" 14649 "\t}\n" 14650 "};", 14651 Tab); 14652 verifyFormat("{\n" 14653 "\tQ(\n" 14654 "\t {\n" 14655 "\t\t int a;\n" 14656 "\t\t someFunction(aaaaaaaa,\n" 14657 "\t\t bbbbbbb);\n" 14658 "\t },\n" 14659 "\t p);\n" 14660 "}", 14661 Tab); 14662 EXPECT_EQ("{\n" 14663 "\t/* aaaa\n" 14664 "\t bbbb */\n" 14665 "}", 14666 format("{\n" 14667 "/* aaaa\n" 14668 " bbbb */\n" 14669 "}", 14670 Tab)); 14671 EXPECT_EQ("{\n" 14672 "\t/*\n" 14673 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14674 "\t bbbbbbbbbbbbb\n" 14675 "\t*/\n" 14676 "}", 14677 format("{\n" 14678 "/*\n" 14679 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14680 "*/\n" 14681 "}", 14682 Tab)); 14683 EXPECT_EQ("{\n" 14684 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14685 "\t// bbbbbbbbbbbbb\n" 14686 "}", 14687 format("{\n" 14688 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14689 "}", 14690 Tab)); 14691 EXPECT_EQ("{\n" 14692 "\t/*\n" 14693 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14694 "\t bbbbbbbbbbbbb\n" 14695 "\t*/\n" 14696 "}", 14697 format("{\n" 14698 "\t/*\n" 14699 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14700 "\t*/\n" 14701 "}", 14702 Tab)); 14703 EXPECT_EQ("{\n" 14704 "\t/*\n" 14705 "\n" 14706 "\t*/\n" 14707 "}", 14708 format("{\n" 14709 "\t/*\n" 14710 "\n" 14711 "\t*/\n" 14712 "}", 14713 Tab)); 14714 EXPECT_EQ("{\n" 14715 "\t/*\n" 14716 " asdf\n" 14717 "\t*/\n" 14718 "}", 14719 format("{\n" 14720 "\t/*\n" 14721 " asdf\n" 14722 "\t*/\n" 14723 "}", 14724 Tab)); 14725 EXPECT_EQ("/* some\n" 14726 " comment */", 14727 format(" \t \t /* some\n" 14728 " \t \t comment */", 14729 Tab)); 14730 EXPECT_EQ("int a; /* some\n" 14731 " comment */", 14732 format(" \t \t int a; /* some\n" 14733 " \t \t comment */", 14734 Tab)); 14735 EXPECT_EQ("int a; /* some\n" 14736 "comment */", 14737 format(" \t \t int\ta; /* some\n" 14738 " \t \t comment */", 14739 Tab)); 14740 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14741 " comment */", 14742 format(" \t \t f(\"\t\t\"); /* some\n" 14743 " \t \t comment */", 14744 Tab)); 14745 EXPECT_EQ("{\n" 14746 "\t/*\n" 14747 "\t * Comment\n" 14748 "\t */\n" 14749 "\tint i;\n" 14750 "}", 14751 format("{\n" 14752 "\t/*\n" 14753 "\t * Comment\n" 14754 "\t */\n" 14755 "\t int i;\n" 14756 "}", 14757 Tab)); 14758 Tab.TabWidth = 2; 14759 Tab.IndentWidth = 2; 14760 EXPECT_EQ("{\n" 14761 "\t/* aaaa\n" 14762 "\t bbbb */\n" 14763 "}", 14764 format("{\n" 14765 "/* aaaa\n" 14766 " bbbb */\n" 14767 "}", 14768 Tab)); 14769 EXPECT_EQ("{\n" 14770 "\t/*\n" 14771 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14772 "\t bbbbbbbbbbbbb\n" 14773 "\t*/\n" 14774 "}", 14775 format("{\n" 14776 "/*\n" 14777 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14778 "*/\n" 14779 "}", 14780 Tab)); 14781 Tab.AlignConsecutiveAssignments.Enabled = true; 14782 Tab.AlignConsecutiveDeclarations.Enabled = true; 14783 Tab.TabWidth = 4; 14784 Tab.IndentWidth = 4; 14785 verifyFormat("class Assign {\n" 14786 "\tvoid f() {\n" 14787 "\t\tint x = 123;\n" 14788 "\t\tint random = 4;\n" 14789 "\t\tstd::string alphabet =\n" 14790 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14791 "\t}\n" 14792 "};", 14793 Tab); 14794 Tab.AlignOperands = FormatStyle::OAS_Align; 14795 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14796 " cccccccccccccccccccc;", 14797 Tab); 14798 // no alignment 14799 verifyFormat("int aaaaaaaaaa =\n" 14800 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14801 Tab); 14802 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14803 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14804 " : 333333333333333;", 14805 Tab); 14806 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14807 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14808 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14809 " + cccccccccccccccccccc;", 14810 Tab); 14811 } 14812 14813 TEST_F(FormatTest, ZeroTabWidth) { 14814 FormatStyle Tab = getLLVMStyleWithColumns(42); 14815 Tab.IndentWidth = 8; 14816 Tab.UseTab = FormatStyle::UT_Never; 14817 Tab.TabWidth = 0; 14818 EXPECT_EQ("void a(){\n" 14819 " // line starts with '\t'\n" 14820 "};", 14821 format("void a(){\n" 14822 "\t// line starts with '\t'\n" 14823 "};", 14824 Tab)); 14825 14826 EXPECT_EQ("void a(){\n" 14827 " // line starts with '\t'\n" 14828 "};", 14829 format("void a(){\n" 14830 "\t\t// line starts with '\t'\n" 14831 "};", 14832 Tab)); 14833 14834 Tab.UseTab = FormatStyle::UT_ForIndentation; 14835 EXPECT_EQ("void a(){\n" 14836 " // line starts with '\t'\n" 14837 "};", 14838 format("void a(){\n" 14839 "\t// line starts with '\t'\n" 14840 "};", 14841 Tab)); 14842 14843 EXPECT_EQ("void a(){\n" 14844 " // line starts with '\t'\n" 14845 "};", 14846 format("void a(){\n" 14847 "\t\t// line starts with '\t'\n" 14848 "};", 14849 Tab)); 14850 14851 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14852 EXPECT_EQ("void a(){\n" 14853 " // line starts with '\t'\n" 14854 "};", 14855 format("void a(){\n" 14856 "\t// line starts with '\t'\n" 14857 "};", 14858 Tab)); 14859 14860 EXPECT_EQ("void a(){\n" 14861 " // line starts with '\t'\n" 14862 "};", 14863 format("void a(){\n" 14864 "\t\t// line starts with '\t'\n" 14865 "};", 14866 Tab)); 14867 14868 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14869 EXPECT_EQ("void a(){\n" 14870 " // line starts with '\t'\n" 14871 "};", 14872 format("void a(){\n" 14873 "\t// line starts with '\t'\n" 14874 "};", 14875 Tab)); 14876 14877 EXPECT_EQ("void a(){\n" 14878 " // line starts with '\t'\n" 14879 "};", 14880 format("void a(){\n" 14881 "\t\t// line starts with '\t'\n" 14882 "};", 14883 Tab)); 14884 14885 Tab.UseTab = FormatStyle::UT_Always; 14886 EXPECT_EQ("void a(){\n" 14887 "// line starts with '\t'\n" 14888 "};", 14889 format("void a(){\n" 14890 "\t// line starts with '\t'\n" 14891 "};", 14892 Tab)); 14893 14894 EXPECT_EQ("void a(){\n" 14895 "// line starts with '\t'\n" 14896 "};", 14897 format("void a(){\n" 14898 "\t\t// line starts with '\t'\n" 14899 "};", 14900 Tab)); 14901 } 14902 14903 TEST_F(FormatTest, CalculatesOriginalColumn) { 14904 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14905 "q\"; /* some\n" 14906 " comment */", 14907 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14908 "q\"; /* some\n" 14909 " comment */", 14910 getLLVMStyle())); 14911 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14912 "/* some\n" 14913 " comment */", 14914 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14915 " /* some\n" 14916 " comment */", 14917 getLLVMStyle())); 14918 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14919 "qqq\n" 14920 "/* some\n" 14921 " comment */", 14922 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14923 "qqq\n" 14924 " /* some\n" 14925 " comment */", 14926 getLLVMStyle())); 14927 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14928 "wwww; /* some\n" 14929 " comment */", 14930 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14931 "wwww; /* some\n" 14932 " comment */", 14933 getLLVMStyle())); 14934 } 14935 14936 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14937 FormatStyle NoSpace = getLLVMStyle(); 14938 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14939 14940 verifyFormat("while(true)\n" 14941 " continue;", 14942 NoSpace); 14943 verifyFormat("for(;;)\n" 14944 " continue;", 14945 NoSpace); 14946 verifyFormat("if(true)\n" 14947 " f();\n" 14948 "else if(true)\n" 14949 " f();", 14950 NoSpace); 14951 verifyFormat("do {\n" 14952 " do_something();\n" 14953 "} while(something());", 14954 NoSpace); 14955 verifyFormat("switch(x) {\n" 14956 "default:\n" 14957 " break;\n" 14958 "}", 14959 NoSpace); 14960 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14961 verifyFormat("size_t x = sizeof(x);", NoSpace); 14962 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14963 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14964 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14965 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14966 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14967 verifyFormat("alignas(128) char a[128];", NoSpace); 14968 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14969 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14970 verifyFormat("int f() throw(Deprecated);", NoSpace); 14971 verifyFormat("typedef void (*cb)(int);", NoSpace); 14972 verifyFormat("T A::operator()();", NoSpace); 14973 verifyFormat("X A::operator++(T);", NoSpace); 14974 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14975 14976 FormatStyle Space = getLLVMStyle(); 14977 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14978 14979 verifyFormat("int f ();", Space); 14980 verifyFormat("void f (int a, T b) {\n" 14981 " while (true)\n" 14982 " continue;\n" 14983 "}", 14984 Space); 14985 verifyFormat("if (true)\n" 14986 " f ();\n" 14987 "else if (true)\n" 14988 " f ();", 14989 Space); 14990 verifyFormat("do {\n" 14991 " do_something ();\n" 14992 "} while (something ());", 14993 Space); 14994 verifyFormat("switch (x) {\n" 14995 "default:\n" 14996 " break;\n" 14997 "}", 14998 Space); 14999 verifyFormat("A::A () : a (1) {}", Space); 15000 verifyFormat("void f () __attribute__ ((asdf));", Space); 15001 verifyFormat("*(&a + 1);\n" 15002 "&((&a)[1]);\n" 15003 "a[(b + c) * d];\n" 15004 "(((a + 1) * 2) + 3) * 4;", 15005 Space); 15006 verifyFormat("#define A(x) x", Space); 15007 verifyFormat("#define A (x) x", Space); 15008 verifyFormat("#if defined(x)\n" 15009 "#endif", 15010 Space); 15011 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15012 verifyFormat("size_t x = sizeof (x);", Space); 15013 verifyFormat("auto f (int x) -> decltype (x);", Space); 15014 verifyFormat("auto f (int x) -> typeof (x);", Space); 15015 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15016 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15017 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15018 verifyFormat("alignas (128) char a[128];", Space); 15019 verifyFormat("size_t x = alignof (MyType);", Space); 15020 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15021 verifyFormat("int f () throw (Deprecated);", Space); 15022 verifyFormat("typedef void (*cb) (int);", Space); 15023 // FIXME these tests regressed behaviour. 15024 // verifyFormat("T A::operator() ();", Space); 15025 // verifyFormat("X A::operator++ (T);", Space); 15026 verifyFormat("auto lambda = [] () { return 0; };", Space); 15027 verifyFormat("int x = int (y);", Space); 15028 15029 FormatStyle SomeSpace = getLLVMStyle(); 15030 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15031 15032 verifyFormat("[]() -> float {}", SomeSpace); 15033 verifyFormat("[] (auto foo) {}", SomeSpace); 15034 verifyFormat("[foo]() -> int {}", SomeSpace); 15035 verifyFormat("int f();", SomeSpace); 15036 verifyFormat("void f (int a, T b) {\n" 15037 " while (true)\n" 15038 " continue;\n" 15039 "}", 15040 SomeSpace); 15041 verifyFormat("if (true)\n" 15042 " f();\n" 15043 "else if (true)\n" 15044 " f();", 15045 SomeSpace); 15046 verifyFormat("do {\n" 15047 " do_something();\n" 15048 "} while (something());", 15049 SomeSpace); 15050 verifyFormat("switch (x) {\n" 15051 "default:\n" 15052 " break;\n" 15053 "}", 15054 SomeSpace); 15055 verifyFormat("A::A() : a (1) {}", SomeSpace); 15056 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15057 verifyFormat("*(&a + 1);\n" 15058 "&((&a)[1]);\n" 15059 "a[(b + c) * d];\n" 15060 "(((a + 1) * 2) + 3) * 4;", 15061 SomeSpace); 15062 verifyFormat("#define A(x) x", SomeSpace); 15063 verifyFormat("#define A (x) x", SomeSpace); 15064 verifyFormat("#if defined(x)\n" 15065 "#endif", 15066 SomeSpace); 15067 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15068 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15069 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15070 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15071 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15072 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15073 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15074 verifyFormat("alignas (128) char a[128];", SomeSpace); 15075 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15076 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15077 SomeSpace); 15078 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15079 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15080 verifyFormat("T A::operator()();", SomeSpace); 15081 // FIXME these tests regressed behaviour. 15082 // verifyFormat("X A::operator++ (T);", SomeSpace); 15083 verifyFormat("int x = int (y);", SomeSpace); 15084 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15085 15086 FormatStyle SpaceControlStatements = getLLVMStyle(); 15087 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15088 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15089 15090 verifyFormat("while (true)\n" 15091 " continue;", 15092 SpaceControlStatements); 15093 verifyFormat("if (true)\n" 15094 " f();\n" 15095 "else if (true)\n" 15096 " f();", 15097 SpaceControlStatements); 15098 verifyFormat("for (;;) {\n" 15099 " do_something();\n" 15100 "}", 15101 SpaceControlStatements); 15102 verifyFormat("do {\n" 15103 " do_something();\n" 15104 "} while (something());", 15105 SpaceControlStatements); 15106 verifyFormat("switch (x) {\n" 15107 "default:\n" 15108 " break;\n" 15109 "}", 15110 SpaceControlStatements); 15111 15112 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15113 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15114 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15115 15116 verifyFormat("int f ();", SpaceFuncDecl); 15117 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15118 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15119 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15120 verifyFormat("#define A(x) x", SpaceFuncDecl); 15121 verifyFormat("#define A (x) x", SpaceFuncDecl); 15122 verifyFormat("#if defined(x)\n" 15123 "#endif", 15124 SpaceFuncDecl); 15125 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15126 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15127 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15128 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15129 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15130 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15131 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15132 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15133 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15134 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15135 SpaceFuncDecl); 15136 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15137 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15138 // FIXME these tests regressed behaviour. 15139 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15140 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15141 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15142 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15143 verifyFormat("int x = int(y);", SpaceFuncDecl); 15144 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15145 SpaceFuncDecl); 15146 15147 FormatStyle SpaceFuncDef = getLLVMStyle(); 15148 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15149 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15150 15151 verifyFormat("int f();", SpaceFuncDef); 15152 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15153 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15154 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15155 verifyFormat("#define A(x) x", SpaceFuncDef); 15156 verifyFormat("#define A (x) x", SpaceFuncDef); 15157 verifyFormat("#if defined(x)\n" 15158 "#endif", 15159 SpaceFuncDef); 15160 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15161 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15162 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15163 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15164 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15165 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15166 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15167 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15168 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15169 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15170 SpaceFuncDef); 15171 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15172 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15173 verifyFormat("T A::operator()();", SpaceFuncDef); 15174 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15175 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15176 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15177 verifyFormat("int x = int(y);", SpaceFuncDef); 15178 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15179 SpaceFuncDef); 15180 15181 FormatStyle SpaceIfMacros = getLLVMStyle(); 15182 SpaceIfMacros.IfMacros.clear(); 15183 SpaceIfMacros.IfMacros.push_back("MYIF"); 15184 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15185 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15186 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15187 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15188 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15189 15190 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15191 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15192 FormatStyle::SBS_Never); 15193 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15194 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15195 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15196 verifyFormat("for (;;) {\n" 15197 "}", 15198 SpaceForeachMacros); 15199 verifyFormat("foreach (Item *item, itemlist) {\n" 15200 "}", 15201 SpaceForeachMacros); 15202 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15203 "}", 15204 SpaceForeachMacros); 15205 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15206 "}", 15207 SpaceForeachMacros); 15208 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15209 15210 FormatStyle SomeSpace2 = getLLVMStyle(); 15211 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15212 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15213 verifyFormat("[]() -> float {}", SomeSpace2); 15214 verifyFormat("[] (auto foo) {}", SomeSpace2); 15215 verifyFormat("[foo]() -> int {}", SomeSpace2); 15216 verifyFormat("int f();", SomeSpace2); 15217 verifyFormat("void f (int a, T b) {\n" 15218 " while (true)\n" 15219 " continue;\n" 15220 "}", 15221 SomeSpace2); 15222 verifyFormat("if (true)\n" 15223 " f();\n" 15224 "else if (true)\n" 15225 " f();", 15226 SomeSpace2); 15227 verifyFormat("do {\n" 15228 " do_something();\n" 15229 "} while (something());", 15230 SomeSpace2); 15231 verifyFormat("switch (x) {\n" 15232 "default:\n" 15233 " break;\n" 15234 "}", 15235 SomeSpace2); 15236 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15237 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15238 verifyFormat("*(&a + 1);\n" 15239 "&((&a)[1]);\n" 15240 "a[(b + c) * d];\n" 15241 "(((a + 1) * 2) + 3) * 4;", 15242 SomeSpace2); 15243 verifyFormat("#define A(x) x", SomeSpace2); 15244 verifyFormat("#define A (x) x", SomeSpace2); 15245 verifyFormat("#if defined(x)\n" 15246 "#endif", 15247 SomeSpace2); 15248 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15249 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15250 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15251 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15252 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15253 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15254 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15255 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15256 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15257 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15258 SomeSpace2); 15259 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15260 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15261 verifyFormat("T A::operator()();", SomeSpace2); 15262 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15263 verifyFormat("int x = int (y);", SomeSpace2); 15264 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15265 15266 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15267 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15268 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15269 .AfterOverloadedOperator = true; 15270 15271 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15272 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15273 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15274 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15275 15276 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15277 .AfterOverloadedOperator = false; 15278 15279 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15280 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15281 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15282 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15283 15284 auto SpaceAfterRequires = getLLVMStyle(); 15285 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15286 EXPECT_FALSE( 15287 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15288 EXPECT_FALSE( 15289 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15290 verifyFormat("void f(auto x)\n" 15291 " requires requires(int i) { x + i; }\n" 15292 "{}", 15293 SpaceAfterRequires); 15294 verifyFormat("void f(auto x)\n" 15295 " requires(requires(int i) { x + i; })\n" 15296 "{}", 15297 SpaceAfterRequires); 15298 verifyFormat("if (requires(int i) { x + i; })\n" 15299 " return;", 15300 SpaceAfterRequires); 15301 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15302 verifyFormat("template <typename T>\n" 15303 " requires(Foo<T>)\n" 15304 "class Bar;", 15305 SpaceAfterRequires); 15306 15307 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15308 verifyFormat("void f(auto x)\n" 15309 " requires requires(int i) { x + i; }\n" 15310 "{}", 15311 SpaceAfterRequires); 15312 verifyFormat("void f(auto x)\n" 15313 " requires (requires(int i) { x + i; })\n" 15314 "{}", 15315 SpaceAfterRequires); 15316 verifyFormat("if (requires(int i) { x + i; })\n" 15317 " return;", 15318 SpaceAfterRequires); 15319 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15320 verifyFormat("template <typename T>\n" 15321 " requires (Foo<T>)\n" 15322 "class Bar;", 15323 SpaceAfterRequires); 15324 15325 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15326 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15327 verifyFormat("void f(auto x)\n" 15328 " requires requires (int i) { x + i; }\n" 15329 "{}", 15330 SpaceAfterRequires); 15331 verifyFormat("void f(auto x)\n" 15332 " requires(requires (int i) { x + i; })\n" 15333 "{}", 15334 SpaceAfterRequires); 15335 verifyFormat("if (requires (int i) { x + i; })\n" 15336 " return;", 15337 SpaceAfterRequires); 15338 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15339 verifyFormat("template <typename T>\n" 15340 " requires(Foo<T>)\n" 15341 "class Bar;", 15342 SpaceAfterRequires); 15343 15344 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15345 verifyFormat("void f(auto x)\n" 15346 " requires requires (int i) { x + i; }\n" 15347 "{}", 15348 SpaceAfterRequires); 15349 verifyFormat("void f(auto x)\n" 15350 " requires (requires (int i) { x + i; })\n" 15351 "{}", 15352 SpaceAfterRequires); 15353 verifyFormat("if (requires (int i) { x + i; })\n" 15354 " return;", 15355 SpaceAfterRequires); 15356 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15357 verifyFormat("template <typename T>\n" 15358 " requires (Foo<T>)\n" 15359 "class Bar;", 15360 SpaceAfterRequires); 15361 } 15362 15363 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15364 FormatStyle Spaces = getLLVMStyle(); 15365 Spaces.SpaceAfterLogicalNot = true; 15366 15367 verifyFormat("bool x = ! y", Spaces); 15368 verifyFormat("if (! isFailure())", Spaces); 15369 verifyFormat("if (! (a && b))", Spaces); 15370 verifyFormat("\"Error!\"", Spaces); 15371 verifyFormat("! ! x", Spaces); 15372 } 15373 15374 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15375 FormatStyle Spaces = getLLVMStyle(); 15376 15377 Spaces.SpacesInParentheses = true; 15378 verifyFormat("do_something( ::globalVar );", Spaces); 15379 verifyFormat("call( x, y, z );", Spaces); 15380 verifyFormat("call();", Spaces); 15381 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15382 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15383 Spaces); 15384 verifyFormat("while ( (bool)1 )\n" 15385 " continue;", 15386 Spaces); 15387 verifyFormat("for ( ;; )\n" 15388 " continue;", 15389 Spaces); 15390 verifyFormat("if ( true )\n" 15391 " f();\n" 15392 "else if ( true )\n" 15393 " f();", 15394 Spaces); 15395 verifyFormat("do {\n" 15396 " do_something( (int)i );\n" 15397 "} while ( something() );", 15398 Spaces); 15399 verifyFormat("switch ( x ) {\n" 15400 "default:\n" 15401 " break;\n" 15402 "}", 15403 Spaces); 15404 15405 Spaces.SpacesInParentheses = false; 15406 Spaces.SpacesInCStyleCastParentheses = true; 15407 verifyFormat("Type *A = ( Type * )P;", Spaces); 15408 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15409 verifyFormat("x = ( int32 )y;", Spaces); 15410 verifyFormat("int a = ( int )(2.0f);", Spaces); 15411 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15412 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15413 verifyFormat("#define x (( int )-1)", Spaces); 15414 15415 // Run the first set of tests again with: 15416 Spaces.SpacesInParentheses = false; 15417 Spaces.SpaceInEmptyParentheses = true; 15418 Spaces.SpacesInCStyleCastParentheses = true; 15419 verifyFormat("call(x, y, z);", Spaces); 15420 verifyFormat("call( );", Spaces); 15421 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15422 verifyFormat("while (( bool )1)\n" 15423 " continue;", 15424 Spaces); 15425 verifyFormat("for (;;)\n" 15426 " continue;", 15427 Spaces); 15428 verifyFormat("if (true)\n" 15429 " f( );\n" 15430 "else if (true)\n" 15431 " f( );", 15432 Spaces); 15433 verifyFormat("do {\n" 15434 " do_something(( int )i);\n" 15435 "} while (something( ));", 15436 Spaces); 15437 verifyFormat("switch (x) {\n" 15438 "default:\n" 15439 " break;\n" 15440 "}", 15441 Spaces); 15442 15443 // Run the first set of tests again with: 15444 Spaces.SpaceAfterCStyleCast = true; 15445 verifyFormat("call(x, y, z);", Spaces); 15446 verifyFormat("call( );", Spaces); 15447 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15448 verifyFormat("while (( bool ) 1)\n" 15449 " continue;", 15450 Spaces); 15451 verifyFormat("for (;;)\n" 15452 " continue;", 15453 Spaces); 15454 verifyFormat("if (true)\n" 15455 " f( );\n" 15456 "else if (true)\n" 15457 " f( );", 15458 Spaces); 15459 verifyFormat("do {\n" 15460 " do_something(( int ) i);\n" 15461 "} while (something( ));", 15462 Spaces); 15463 verifyFormat("switch (x) {\n" 15464 "default:\n" 15465 " break;\n" 15466 "}", 15467 Spaces); 15468 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15469 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15470 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15471 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15472 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15473 15474 // Run subset of tests again with: 15475 Spaces.SpacesInCStyleCastParentheses = false; 15476 Spaces.SpaceAfterCStyleCast = true; 15477 verifyFormat("while ((bool) 1)\n" 15478 " continue;", 15479 Spaces); 15480 verifyFormat("do {\n" 15481 " do_something((int) i);\n" 15482 "} while (something( ));", 15483 Spaces); 15484 15485 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15486 verifyFormat("size_t idx = (size_t) a;", Spaces); 15487 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15488 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15489 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15490 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15491 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15492 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15493 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15494 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15495 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15496 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15497 Spaces.ColumnLimit = 80; 15498 Spaces.IndentWidth = 4; 15499 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15500 verifyFormat("void foo( ) {\n" 15501 " size_t foo = (*(function))(\n" 15502 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15503 "BarrrrrrrrrrrrLong,\n" 15504 " FoooooooooLooooong);\n" 15505 "}", 15506 Spaces); 15507 Spaces.SpaceAfterCStyleCast = false; 15508 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15509 verifyFormat("size_t idx = (size_t)a;", Spaces); 15510 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15511 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15512 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15513 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15514 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15515 15516 verifyFormat("void foo( ) {\n" 15517 " size_t foo = (*(function))(\n" 15518 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15519 "BarrrrrrrrrrrrLong,\n" 15520 " FoooooooooLooooong);\n" 15521 "}", 15522 Spaces); 15523 } 15524 15525 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15526 verifyFormat("int a[5];"); 15527 verifyFormat("a[3] += 42;"); 15528 15529 FormatStyle Spaces = getLLVMStyle(); 15530 Spaces.SpacesInSquareBrackets = true; 15531 // Not lambdas. 15532 verifyFormat("int a[ 5 ];", Spaces); 15533 verifyFormat("a[ 3 ] += 42;", Spaces); 15534 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15535 verifyFormat("double &operator[](int i) { return 0; }\n" 15536 "int i;", 15537 Spaces); 15538 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15539 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15540 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15541 // Lambdas. 15542 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15543 verifyFormat("return [ i, args... ] {};", Spaces); 15544 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15545 verifyFormat("int foo = [ = ]() {};", Spaces); 15546 verifyFormat("int foo = [ & ]() {};", Spaces); 15547 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15548 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15549 } 15550 15551 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15552 FormatStyle NoSpaceStyle = getLLVMStyle(); 15553 verifyFormat("int a[5];", NoSpaceStyle); 15554 verifyFormat("a[3] += 42;", NoSpaceStyle); 15555 15556 verifyFormat("int a[1];", NoSpaceStyle); 15557 verifyFormat("int 1 [a];", NoSpaceStyle); 15558 verifyFormat("int a[1][2];", NoSpaceStyle); 15559 verifyFormat("a[7] = 5;", NoSpaceStyle); 15560 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15561 verifyFormat("f([] {})", NoSpaceStyle); 15562 15563 FormatStyle Space = getLLVMStyle(); 15564 Space.SpaceBeforeSquareBrackets = true; 15565 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15566 verifyFormat("return [i, args...] {};", Space); 15567 15568 verifyFormat("int a [5];", Space); 15569 verifyFormat("a [3] += 42;", Space); 15570 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15571 verifyFormat("double &operator[](int i) { return 0; }\n" 15572 "int i;", 15573 Space); 15574 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15575 verifyFormat("int i = a [a][a]->f();", Space); 15576 verifyFormat("int i = (*b) [a]->f();", Space); 15577 15578 verifyFormat("int a [1];", Space); 15579 verifyFormat("int 1 [a];", Space); 15580 verifyFormat("int a [1][2];", Space); 15581 verifyFormat("a [7] = 5;", Space); 15582 verifyFormat("int a = (f()) [23];", Space); 15583 verifyFormat("f([] {})", Space); 15584 } 15585 15586 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15587 verifyFormat("int a = 5;"); 15588 verifyFormat("a += 42;"); 15589 verifyFormat("a or_eq 8;"); 15590 15591 FormatStyle Spaces = getLLVMStyle(); 15592 Spaces.SpaceBeforeAssignmentOperators = false; 15593 verifyFormat("int a= 5;", Spaces); 15594 verifyFormat("a+= 42;", Spaces); 15595 verifyFormat("a or_eq 8;", Spaces); 15596 } 15597 15598 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15599 verifyFormat("class Foo : public Bar {};"); 15600 verifyFormat("Foo::Foo() : foo(1) {}"); 15601 verifyFormat("for (auto a : b) {\n}"); 15602 verifyFormat("int x = a ? b : c;"); 15603 verifyFormat("{\n" 15604 "label0:\n" 15605 " int x = 0;\n" 15606 "}"); 15607 verifyFormat("switch (x) {\n" 15608 "case 1:\n" 15609 "default:\n" 15610 "}"); 15611 verifyFormat("switch (allBraces) {\n" 15612 "case 1: {\n" 15613 " break;\n" 15614 "}\n" 15615 "case 2: {\n" 15616 " [[fallthrough]];\n" 15617 "}\n" 15618 "default: {\n" 15619 " break;\n" 15620 "}\n" 15621 "}"); 15622 15623 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15624 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15625 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15626 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15627 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15628 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15629 verifyFormat("{\n" 15630 "label1:\n" 15631 " int x = 0;\n" 15632 "}", 15633 CtorInitializerStyle); 15634 verifyFormat("switch (x) {\n" 15635 "case 1:\n" 15636 "default:\n" 15637 "}", 15638 CtorInitializerStyle); 15639 verifyFormat("switch (allBraces) {\n" 15640 "case 1: {\n" 15641 " break;\n" 15642 "}\n" 15643 "case 2: {\n" 15644 " [[fallthrough]];\n" 15645 "}\n" 15646 "default: {\n" 15647 " break;\n" 15648 "}\n" 15649 "}", 15650 CtorInitializerStyle); 15651 CtorInitializerStyle.BreakConstructorInitializers = 15652 FormatStyle::BCIS_AfterColon; 15653 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15654 " aaaaaaaaaaaaaaaa(1),\n" 15655 " bbbbbbbbbbbbbbbb(2) {}", 15656 CtorInitializerStyle); 15657 CtorInitializerStyle.BreakConstructorInitializers = 15658 FormatStyle::BCIS_BeforeComma; 15659 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15660 " : aaaaaaaaaaaaaaaa(1)\n" 15661 " , bbbbbbbbbbbbbbbb(2) {}", 15662 CtorInitializerStyle); 15663 CtorInitializerStyle.BreakConstructorInitializers = 15664 FormatStyle::BCIS_BeforeColon; 15665 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15666 " : aaaaaaaaaaaaaaaa(1),\n" 15667 " bbbbbbbbbbbbbbbb(2) {}", 15668 CtorInitializerStyle); 15669 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15670 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15671 ": aaaaaaaaaaaaaaaa(1),\n" 15672 " bbbbbbbbbbbbbbbb(2) {}", 15673 CtorInitializerStyle); 15674 15675 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15676 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15677 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15678 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15679 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15680 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15681 verifyFormat("{\n" 15682 "label2:\n" 15683 " int x = 0;\n" 15684 "}", 15685 InheritanceStyle); 15686 verifyFormat("switch (x) {\n" 15687 "case 1:\n" 15688 "default:\n" 15689 "}", 15690 InheritanceStyle); 15691 verifyFormat("switch (allBraces) {\n" 15692 "case 1: {\n" 15693 " break;\n" 15694 "}\n" 15695 "case 2: {\n" 15696 " [[fallthrough]];\n" 15697 "}\n" 15698 "default: {\n" 15699 " break;\n" 15700 "}\n" 15701 "}", 15702 InheritanceStyle); 15703 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15704 verifyFormat("class Foooooooooooooooooooooo\n" 15705 " : public aaaaaaaaaaaaaaaaaa,\n" 15706 " public bbbbbbbbbbbbbbbbbb {\n" 15707 "}", 15708 InheritanceStyle); 15709 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15710 verifyFormat("class Foooooooooooooooooooooo:\n" 15711 " public aaaaaaaaaaaaaaaaaa,\n" 15712 " public bbbbbbbbbbbbbbbbbb {\n" 15713 "}", 15714 InheritanceStyle); 15715 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15716 verifyFormat("class Foooooooooooooooooooooo\n" 15717 " : public aaaaaaaaaaaaaaaaaa\n" 15718 " , public bbbbbbbbbbbbbbbbbb {\n" 15719 "}", 15720 InheritanceStyle); 15721 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15722 verifyFormat("class Foooooooooooooooooooooo\n" 15723 " : public aaaaaaaaaaaaaaaaaa,\n" 15724 " public bbbbbbbbbbbbbbbbbb {\n" 15725 "}", 15726 InheritanceStyle); 15727 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15728 verifyFormat("class Foooooooooooooooooooooo\n" 15729 ": public aaaaaaaaaaaaaaaaaa,\n" 15730 " public bbbbbbbbbbbbbbbbbb {}", 15731 InheritanceStyle); 15732 15733 FormatStyle ForLoopStyle = getLLVMStyle(); 15734 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15735 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15736 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15737 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15738 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15739 verifyFormat("{\n" 15740 "label2:\n" 15741 " int x = 0;\n" 15742 "}", 15743 ForLoopStyle); 15744 verifyFormat("switch (x) {\n" 15745 "case 1:\n" 15746 "default:\n" 15747 "}", 15748 ForLoopStyle); 15749 verifyFormat("switch (allBraces) {\n" 15750 "case 1: {\n" 15751 " break;\n" 15752 "}\n" 15753 "case 2: {\n" 15754 " [[fallthrough]];\n" 15755 "}\n" 15756 "default: {\n" 15757 " break;\n" 15758 "}\n" 15759 "}", 15760 ForLoopStyle); 15761 15762 FormatStyle CaseStyle = getLLVMStyle(); 15763 CaseStyle.SpaceBeforeCaseColon = true; 15764 verifyFormat("class Foo : public Bar {};", CaseStyle); 15765 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15766 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15767 verifyFormat("int x = a ? b : c;", CaseStyle); 15768 verifyFormat("switch (x) {\n" 15769 "case 1 :\n" 15770 "default :\n" 15771 "}", 15772 CaseStyle); 15773 verifyFormat("switch (allBraces) {\n" 15774 "case 1 : {\n" 15775 " break;\n" 15776 "}\n" 15777 "case 2 : {\n" 15778 " [[fallthrough]];\n" 15779 "}\n" 15780 "default : {\n" 15781 " break;\n" 15782 "}\n" 15783 "}", 15784 CaseStyle); 15785 15786 FormatStyle NoSpaceStyle = getLLVMStyle(); 15787 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15788 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15789 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15790 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15791 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15792 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15793 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15794 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15795 verifyFormat("{\n" 15796 "label3:\n" 15797 " int x = 0;\n" 15798 "}", 15799 NoSpaceStyle); 15800 verifyFormat("switch (x) {\n" 15801 "case 1:\n" 15802 "default:\n" 15803 "}", 15804 NoSpaceStyle); 15805 verifyFormat("switch (allBraces) {\n" 15806 "case 1: {\n" 15807 " break;\n" 15808 "}\n" 15809 "case 2: {\n" 15810 " [[fallthrough]];\n" 15811 "}\n" 15812 "default: {\n" 15813 " break;\n" 15814 "}\n" 15815 "}", 15816 NoSpaceStyle); 15817 15818 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15819 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15820 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15821 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15822 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15823 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15824 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15825 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15826 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15827 verifyFormat("{\n" 15828 "label3:\n" 15829 " int x = 0;\n" 15830 "}", 15831 InvertedSpaceStyle); 15832 verifyFormat("switch (x) {\n" 15833 "case 1 :\n" 15834 "case 2 : {\n" 15835 " break;\n" 15836 "}\n" 15837 "default :\n" 15838 " break;\n" 15839 "}", 15840 InvertedSpaceStyle); 15841 verifyFormat("switch (allBraces) {\n" 15842 "case 1 : {\n" 15843 " break;\n" 15844 "}\n" 15845 "case 2 : {\n" 15846 " [[fallthrough]];\n" 15847 "}\n" 15848 "default : {\n" 15849 " break;\n" 15850 "}\n" 15851 "}", 15852 InvertedSpaceStyle); 15853 } 15854 15855 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15856 FormatStyle Style = getLLVMStyle(); 15857 15858 Style.PointerAlignment = FormatStyle::PAS_Left; 15859 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15860 verifyFormat("void* const* x = NULL;", Style); 15861 15862 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15863 do { \ 15864 Style.PointerAlignment = FormatStyle::Pointers; \ 15865 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15866 verifyFormat(Code, Style); \ 15867 } while (false) 15868 15869 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15870 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15871 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15872 15873 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15874 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15875 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15876 15877 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15878 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15879 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15880 15881 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15882 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15883 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15884 15885 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15886 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15887 SAPQ_Default); 15888 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15889 SAPQ_Default); 15890 15891 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15892 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15893 SAPQ_Before); 15894 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15895 SAPQ_Before); 15896 15897 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15898 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15899 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15900 SAPQ_After); 15901 15902 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15903 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15904 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15905 15906 #undef verifyQualifierSpaces 15907 15908 FormatStyle Spaces = getLLVMStyle(); 15909 Spaces.AttributeMacros.push_back("qualified"); 15910 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15911 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15912 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15913 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15914 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15915 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15916 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15917 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15918 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15919 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15920 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15921 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15922 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15923 15924 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15925 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15926 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15927 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15928 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15929 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15930 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15931 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15932 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15933 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15934 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15935 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15936 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15937 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15938 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15939 15940 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15941 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15942 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15943 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15944 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15945 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15946 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15947 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15948 } 15949 15950 TEST_F(FormatTest, AlignConsecutiveMacros) { 15951 FormatStyle Style = getLLVMStyle(); 15952 Style.AlignConsecutiveAssignments.Enabled = true; 15953 Style.AlignConsecutiveDeclarations.Enabled = true; 15954 15955 verifyFormat("#define a 3\n" 15956 "#define bbbb 4\n" 15957 "#define ccc (5)", 15958 Style); 15959 15960 verifyFormat("#define f(x) (x * x)\n" 15961 "#define fff(x, y, z) (x * y + z)\n" 15962 "#define ffff(x, y) (x - y)", 15963 Style); 15964 15965 verifyFormat("#define foo(x, y) (x + y)\n" 15966 "#define bar (5, 6)(2 + 2)", 15967 Style); 15968 15969 verifyFormat("#define a 3\n" 15970 "#define bbbb 4\n" 15971 "#define ccc (5)\n" 15972 "#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 Style.AlignConsecutiveMacros.Enabled = true; 15978 verifyFormat("#define a 3\n" 15979 "#define bbbb 4\n" 15980 "#define ccc (5)", 15981 Style); 15982 15983 verifyFormat("#define f(x) (x * x)\n" 15984 "#define fff(x, y, z) (x * y + z)\n" 15985 "#define ffff(x, y) (x - y)", 15986 Style); 15987 15988 verifyFormat("#define foo(x, y) (x + y)\n" 15989 "#define bar (5, 6)(2 + 2)", 15990 Style); 15991 15992 verifyFormat("#define a 3\n" 15993 "#define bbbb 4\n" 15994 "#define ccc (5)\n" 15995 "#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 a 5\n" 16001 "#define foo(x, y) (x + y)\n" 16002 "#define CCC (6)\n" 16003 "auto lambda = []() {\n" 16004 " auto ii = 0;\n" 16005 " float j = 0;\n" 16006 " return 0;\n" 16007 "};\n" 16008 "int i = 0;\n" 16009 "float i2 = 0;\n" 16010 "auto v = type{\n" 16011 " i = 1, //\n" 16012 " (i = 2), //\n" 16013 " i = 3 //\n" 16014 "};", 16015 Style); 16016 16017 Style.AlignConsecutiveMacros.Enabled = false; 16018 Style.ColumnLimit = 20; 16019 16020 verifyFormat("#define a \\\n" 16021 " \"aabbbbbbbbbbbb\"\n" 16022 "#define D \\\n" 16023 " \"aabbbbbbbbbbbb\" \\\n" 16024 " \"ccddeeeeeeeee\"\n" 16025 "#define B \\\n" 16026 " \"QQQQQQQQQQQQQ\" \\\n" 16027 " \"FFFFFFFFFFFFF\" \\\n" 16028 " \"LLLLLLLL\"\n", 16029 Style); 16030 16031 Style.AlignConsecutiveMacros.Enabled = true; 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 // Test across comments 16044 Style.MaxEmptyLinesToKeep = 10; 16045 Style.ReflowComments = false; 16046 Style.AlignConsecutiveMacros.AcrossComments = true; 16047 EXPECT_EQ("#define a 3\n" 16048 "// line comment\n" 16049 "#define bbbb 4\n" 16050 "#define ccc (5)", 16051 format("#define a 3\n" 16052 "// line comment\n" 16053 "#define bbbb 4\n" 16054 "#define ccc (5)", 16055 Style)); 16056 16057 EXPECT_EQ("#define a 3\n" 16058 "/* block comment */\n" 16059 "#define bbbb 4\n" 16060 "#define ccc (5)", 16061 format("#define a 3\n" 16062 "/* block comment */\n" 16063 "#define bbbb 4\n" 16064 "#define ccc (5)", 16065 Style)); 16066 16067 EXPECT_EQ("#define a 3\n" 16068 "/* multi-line *\n" 16069 " * block comment */\n" 16070 "#define bbbb 4\n" 16071 "#define ccc (5)", 16072 format("#define a 3\n" 16073 "/* multi-line *\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 line comment\n" 16081 "//\n" 16082 "#define bbbb 4\n" 16083 "#define ccc (5)", 16084 format("#define a 3\n" 16085 "// multi-line line comment\n" 16086 "//\n" 16087 "#define bbbb 4\n" 16088 "#define ccc (5)", 16089 Style)); 16090 16091 EXPECT_EQ("#define a 3\n" 16092 "// empty lines still break.\n" 16093 "\n" 16094 "#define bbbb 4\n" 16095 "#define ccc (5)", 16096 format("#define a 3\n" 16097 "// empty lines still break.\n" 16098 "\n" 16099 "#define bbbb 4\n" 16100 "#define ccc (5)", 16101 Style)); 16102 16103 // Test across empty lines 16104 Style.AlignConsecutiveMacros.AcrossComments = false; 16105 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16106 EXPECT_EQ("#define a 3\n" 16107 "\n" 16108 "#define bbbb 4\n" 16109 "#define ccc (5)", 16110 format("#define a 3\n" 16111 "\n" 16112 "#define bbbb 4\n" 16113 "#define ccc (5)", 16114 Style)); 16115 16116 EXPECT_EQ("#define a 3\n" 16117 "\n" 16118 "\n" 16119 "\n" 16120 "#define bbbb 4\n" 16121 "#define ccc (5)", 16122 format("#define a 3\n" 16123 "\n" 16124 "\n" 16125 "\n" 16126 "#define bbbb 4\n" 16127 "#define ccc (5)", 16128 Style)); 16129 16130 EXPECT_EQ("#define a 3\n" 16131 "// comments should break alignment\n" 16132 "//\n" 16133 "#define bbbb 4\n" 16134 "#define ccc (5)", 16135 format("#define a 3\n" 16136 "// comments should break alignment\n" 16137 "//\n" 16138 "#define bbbb 4\n" 16139 "#define ccc (5)", 16140 Style)); 16141 16142 // Test across empty lines and comments 16143 Style.AlignConsecutiveMacros.AcrossComments = true; 16144 verifyFormat("#define a 3\n" 16145 "\n" 16146 "// line comment\n" 16147 "#define bbbb 4\n" 16148 "#define ccc (5)", 16149 Style); 16150 16151 EXPECT_EQ("#define a 3\n" 16152 "\n" 16153 "\n" 16154 "/* multi-line *\n" 16155 " * block comment */\n" 16156 "\n" 16157 "\n" 16158 "#define bbbb 4\n" 16159 "#define ccc (5)", 16160 format("#define a 3\n" 16161 "\n" 16162 "\n" 16163 "/* multi-line *\n" 16164 " * block comment */\n" 16165 "\n" 16166 "\n" 16167 "#define bbbb 4\n" 16168 "#define ccc (5)", 16169 Style)); 16170 16171 EXPECT_EQ("#define a 3\n" 16172 "\n" 16173 "\n" 16174 "/* multi-line *\n" 16175 " * block comment */\n" 16176 "\n" 16177 "\n" 16178 "#define bbbb 4\n" 16179 "#define ccc (5)", 16180 format("#define a 3\n" 16181 "\n" 16182 "\n" 16183 "/* multi-line *\n" 16184 " * block comment */\n" 16185 "\n" 16186 "\n" 16187 "#define bbbb 4\n" 16188 "#define ccc (5)", 16189 Style)); 16190 } 16191 16192 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16193 FormatStyle Alignment = getLLVMStyle(); 16194 Alignment.AlignConsecutiveMacros.Enabled = true; 16195 Alignment.AlignConsecutiveAssignments.Enabled = true; 16196 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16197 16198 Alignment.MaxEmptyLinesToKeep = 10; 16199 /* Test alignment across empty lines */ 16200 EXPECT_EQ("int a = 5;\n" 16201 "\n" 16202 "int oneTwoThree = 123;", 16203 format("int a = 5;\n" 16204 "\n" 16205 "int oneTwoThree= 123;", 16206 Alignment)); 16207 EXPECT_EQ("int a = 5;\n" 16208 "int one = 1;\n" 16209 "\n" 16210 "int oneTwoThree = 123;", 16211 format("int a = 5;\n" 16212 "int one = 1;\n" 16213 "\n" 16214 "int oneTwoThree = 123;", 16215 Alignment)); 16216 EXPECT_EQ("int a = 5;\n" 16217 "int one = 1;\n" 16218 "\n" 16219 "int oneTwoThree = 123;\n" 16220 "int oneTwo = 12;", 16221 format("int a = 5;\n" 16222 "int one = 1;\n" 16223 "\n" 16224 "int oneTwoThree = 123;\n" 16225 "int oneTwo = 12;", 16226 Alignment)); 16227 16228 /* Test across comments */ 16229 EXPECT_EQ("int a = 5;\n" 16230 "/* block comment */\n" 16231 "int oneTwoThree = 123;", 16232 format("int a = 5;\n" 16233 "/* block comment */\n" 16234 "int oneTwoThree=123;", 16235 Alignment)); 16236 16237 EXPECT_EQ("int a = 5;\n" 16238 "// line comment\n" 16239 "int oneTwoThree = 123;", 16240 format("int a = 5;\n" 16241 "// line comment\n" 16242 "int oneTwoThree=123;", 16243 Alignment)); 16244 16245 /* Test across comments and newlines */ 16246 EXPECT_EQ("int a = 5;\n" 16247 "\n" 16248 "/* block comment */\n" 16249 "int oneTwoThree = 123;", 16250 format("int a = 5;\n" 16251 "\n" 16252 "/* block comment */\n" 16253 "int oneTwoThree=123;", 16254 Alignment)); 16255 16256 EXPECT_EQ("int a = 5;\n" 16257 "\n" 16258 "// line comment\n" 16259 "int oneTwoThree = 123;", 16260 format("int a = 5;\n" 16261 "\n" 16262 "// line comment\n" 16263 "int oneTwoThree=123;", 16264 Alignment)); 16265 } 16266 16267 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16268 FormatStyle Alignment = getLLVMStyle(); 16269 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16270 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16271 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16272 16273 Alignment.MaxEmptyLinesToKeep = 10; 16274 /* Test alignment across empty lines */ 16275 EXPECT_EQ("int a = 5;\n" 16276 "\n" 16277 "float const oneTwoThree = 123;", 16278 format("int a = 5;\n" 16279 "\n" 16280 "float const oneTwoThree = 123;", 16281 Alignment)); 16282 EXPECT_EQ("int a = 5;\n" 16283 "float const one = 1;\n" 16284 "\n" 16285 "int oneTwoThree = 123;", 16286 format("int a = 5;\n" 16287 "float const one = 1;\n" 16288 "\n" 16289 "int oneTwoThree = 123;", 16290 Alignment)); 16291 16292 /* Test across comments */ 16293 EXPECT_EQ("float const a = 5;\n" 16294 "/* block comment */\n" 16295 "int oneTwoThree = 123;", 16296 format("float const a = 5;\n" 16297 "/* block comment */\n" 16298 "int oneTwoThree=123;", 16299 Alignment)); 16300 16301 EXPECT_EQ("float const a = 5;\n" 16302 "// line comment\n" 16303 "int oneTwoThree = 123;", 16304 format("float const a = 5;\n" 16305 "// line comment\n" 16306 "int oneTwoThree=123;", 16307 Alignment)); 16308 16309 /* Test across comments and newlines */ 16310 EXPECT_EQ("float const a = 5;\n" 16311 "\n" 16312 "/* block comment */\n" 16313 "int oneTwoThree = 123;", 16314 format("float const a = 5;\n" 16315 "\n" 16316 "/* block comment */\n" 16317 "int oneTwoThree=123;", 16318 Alignment)); 16319 16320 EXPECT_EQ("float const a = 5;\n" 16321 "\n" 16322 "// line comment\n" 16323 "int oneTwoThree = 123;", 16324 format("float const a = 5;\n" 16325 "\n" 16326 "// line comment\n" 16327 "int oneTwoThree=123;", 16328 Alignment)); 16329 } 16330 16331 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16332 FormatStyle Alignment = getLLVMStyle(); 16333 Alignment.AlignConsecutiveBitFields.Enabled = true; 16334 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16335 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16336 16337 Alignment.MaxEmptyLinesToKeep = 10; 16338 /* Test alignment across empty lines */ 16339 EXPECT_EQ("int a : 5;\n" 16340 "\n" 16341 "int longbitfield : 6;", 16342 format("int a : 5;\n" 16343 "\n" 16344 "int longbitfield : 6;", 16345 Alignment)); 16346 EXPECT_EQ("int a : 5;\n" 16347 "int one : 1;\n" 16348 "\n" 16349 "int longbitfield : 6;", 16350 format("int a : 5;\n" 16351 "int one : 1;\n" 16352 "\n" 16353 "int longbitfield : 6;", 16354 Alignment)); 16355 16356 /* Test across comments */ 16357 EXPECT_EQ("int a : 5;\n" 16358 "/* block comment */\n" 16359 "int longbitfield : 6;", 16360 format("int a : 5;\n" 16361 "/* block comment */\n" 16362 "int longbitfield : 6;", 16363 Alignment)); 16364 EXPECT_EQ("int a : 5;\n" 16365 "int one : 1;\n" 16366 "// line comment\n" 16367 "int longbitfield : 6;", 16368 format("int a : 5;\n" 16369 "int one : 1;\n" 16370 "// line comment\n" 16371 "int longbitfield : 6;", 16372 Alignment)); 16373 16374 /* Test across comments and newlines */ 16375 EXPECT_EQ("int a : 5;\n" 16376 "/* block comment */\n" 16377 "\n" 16378 "int longbitfield : 6;", 16379 format("int a : 5;\n" 16380 "/* block comment */\n" 16381 "\n" 16382 "int longbitfield : 6;", 16383 Alignment)); 16384 EXPECT_EQ("int a : 5;\n" 16385 "int one : 1;\n" 16386 "\n" 16387 "// line comment\n" 16388 "\n" 16389 "int longbitfield : 6;", 16390 format("int a : 5;\n" 16391 "int one : 1;\n" 16392 "\n" 16393 "// line comment \n" 16394 "\n" 16395 "int longbitfield : 6;", 16396 Alignment)); 16397 } 16398 16399 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16400 FormatStyle Alignment = getLLVMStyle(); 16401 Alignment.AlignConsecutiveMacros.Enabled = true; 16402 Alignment.AlignConsecutiveAssignments.Enabled = true; 16403 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16404 16405 Alignment.MaxEmptyLinesToKeep = 10; 16406 /* Test alignment across empty lines */ 16407 EXPECT_EQ("int a = 5;\n" 16408 "\n" 16409 "int oneTwoThree = 123;", 16410 format("int a = 5;\n" 16411 "\n" 16412 "int oneTwoThree= 123;", 16413 Alignment)); 16414 EXPECT_EQ("int a = 5;\n" 16415 "int one = 1;\n" 16416 "\n" 16417 "int oneTwoThree = 123;", 16418 format("int a = 5;\n" 16419 "int one = 1;\n" 16420 "\n" 16421 "int oneTwoThree = 123;", 16422 Alignment)); 16423 16424 /* Test across comments */ 16425 EXPECT_EQ("int a = 5;\n" 16426 "/* block comment */\n" 16427 "int oneTwoThree = 123;", 16428 format("int a = 5;\n" 16429 "/* block comment */\n" 16430 "int oneTwoThree=123;", 16431 Alignment)); 16432 16433 EXPECT_EQ("int a = 5;\n" 16434 "// line comment\n" 16435 "int oneTwoThree = 123;", 16436 format("int a = 5;\n" 16437 "// line comment\n" 16438 "int oneTwoThree=123;", 16439 Alignment)); 16440 16441 EXPECT_EQ("int a = 5;\n" 16442 "/*\n" 16443 " * multi-line block comment\n" 16444 " */\n" 16445 "int oneTwoThree = 123;", 16446 format("int a = 5;\n" 16447 "/*\n" 16448 " * multi-line block comment\n" 16449 " */\n" 16450 "int oneTwoThree=123;", 16451 Alignment)); 16452 16453 EXPECT_EQ("int a = 5;\n" 16454 "//\n" 16455 "// multi-line line comment\n" 16456 "//\n" 16457 "int oneTwoThree = 123;", 16458 format("int a = 5;\n" 16459 "//\n" 16460 "// multi-line line comment\n" 16461 "//\n" 16462 "int oneTwoThree=123;", 16463 Alignment)); 16464 16465 /* Test across comments and newlines */ 16466 EXPECT_EQ("int a = 5;\n" 16467 "\n" 16468 "/* block comment */\n" 16469 "int oneTwoThree = 123;", 16470 format("int a = 5;\n" 16471 "\n" 16472 "/* block comment */\n" 16473 "int oneTwoThree=123;", 16474 Alignment)); 16475 16476 EXPECT_EQ("int a = 5;\n" 16477 "\n" 16478 "// line comment\n" 16479 "int oneTwoThree = 123;", 16480 format("int a = 5;\n" 16481 "\n" 16482 "// line comment\n" 16483 "int oneTwoThree=123;", 16484 Alignment)); 16485 } 16486 16487 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16488 FormatStyle Alignment = getLLVMStyle(); 16489 Alignment.AlignConsecutiveMacros.Enabled = true; 16490 Alignment.AlignConsecutiveAssignments.Enabled = true; 16491 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16492 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16493 verifyFormat("int a = 5;\n" 16494 "int oneTwoThree = 123;", 16495 Alignment); 16496 verifyFormat("int a = method();\n" 16497 "int oneTwoThree = 133;", 16498 Alignment); 16499 verifyFormat("a &= 5;\n" 16500 "bcd *= 5;\n" 16501 "ghtyf += 5;\n" 16502 "dvfvdb -= 5;\n" 16503 "a /= 5;\n" 16504 "vdsvsv %= 5;\n" 16505 "sfdbddfbdfbb ^= 5;\n" 16506 "dvsdsv |= 5;\n" 16507 "int dsvvdvsdvvv = 123;", 16508 Alignment); 16509 verifyFormat("int i = 1, j = 10;\n" 16510 "something = 2000;", 16511 Alignment); 16512 verifyFormat("something = 2000;\n" 16513 "int i = 1, j = 10;\n", 16514 Alignment); 16515 verifyFormat("something = 2000;\n" 16516 "another = 911;\n" 16517 "int i = 1, j = 10;\n" 16518 "oneMore = 1;\n" 16519 "i = 2;", 16520 Alignment); 16521 verifyFormat("int a = 5;\n" 16522 "int one = 1;\n" 16523 "method();\n" 16524 "int oneTwoThree = 123;\n" 16525 "int oneTwo = 12;", 16526 Alignment); 16527 verifyFormat("int oneTwoThree = 123;\n" 16528 "int oneTwo = 12;\n" 16529 "method();\n", 16530 Alignment); 16531 verifyFormat("int oneTwoThree = 123; // comment\n" 16532 "int oneTwo = 12; // comment", 16533 Alignment); 16534 16535 // Bug 25167 16536 /* Uncomment when fixed 16537 verifyFormat("#if A\n" 16538 "#else\n" 16539 "int aaaaaaaa = 12;\n" 16540 "#endif\n" 16541 "#if B\n" 16542 "#else\n" 16543 "int a = 12;\n" 16544 "#endif\n", 16545 Alignment); 16546 verifyFormat("enum foo {\n" 16547 "#if A\n" 16548 "#else\n" 16549 " aaaaaaaa = 12;\n" 16550 "#endif\n" 16551 "#if B\n" 16552 "#else\n" 16553 " a = 12;\n" 16554 "#endif\n" 16555 "};\n", 16556 Alignment); 16557 */ 16558 16559 Alignment.MaxEmptyLinesToKeep = 10; 16560 /* Test alignment across empty lines */ 16561 EXPECT_EQ("int a = 5;\n" 16562 "\n" 16563 "int oneTwoThree = 123;", 16564 format("int a = 5;\n" 16565 "\n" 16566 "int oneTwoThree= 123;", 16567 Alignment)); 16568 EXPECT_EQ("int a = 5;\n" 16569 "int one = 1;\n" 16570 "\n" 16571 "int oneTwoThree = 123;", 16572 format("int a = 5;\n" 16573 "int one = 1;\n" 16574 "\n" 16575 "int oneTwoThree = 123;", 16576 Alignment)); 16577 EXPECT_EQ("int a = 5;\n" 16578 "int one = 1;\n" 16579 "\n" 16580 "int oneTwoThree = 123;\n" 16581 "int oneTwo = 12;", 16582 format("int a = 5;\n" 16583 "int one = 1;\n" 16584 "\n" 16585 "int oneTwoThree = 123;\n" 16586 "int oneTwo = 12;", 16587 Alignment)); 16588 16589 /* Test across comments */ 16590 EXPECT_EQ("int a = 5;\n" 16591 "/* block comment */\n" 16592 "int oneTwoThree = 123;", 16593 format("int a = 5;\n" 16594 "/* block comment */\n" 16595 "int oneTwoThree=123;", 16596 Alignment)); 16597 16598 EXPECT_EQ("int a = 5;\n" 16599 "// line comment\n" 16600 "int oneTwoThree = 123;", 16601 format("int a = 5;\n" 16602 "// line comment\n" 16603 "int oneTwoThree=123;", 16604 Alignment)); 16605 16606 /* Test across comments and newlines */ 16607 EXPECT_EQ("int a = 5;\n" 16608 "\n" 16609 "/* block comment */\n" 16610 "int oneTwoThree = 123;", 16611 format("int a = 5;\n" 16612 "\n" 16613 "/* block comment */\n" 16614 "int oneTwoThree=123;", 16615 Alignment)); 16616 16617 EXPECT_EQ("int a = 5;\n" 16618 "\n" 16619 "// line comment\n" 16620 "int oneTwoThree = 123;", 16621 format("int a = 5;\n" 16622 "\n" 16623 "// line comment\n" 16624 "int oneTwoThree=123;", 16625 Alignment)); 16626 16627 EXPECT_EQ("int a = 5;\n" 16628 "//\n" 16629 "// multi-line line comment\n" 16630 "//\n" 16631 "int oneTwoThree = 123;", 16632 format("int a = 5;\n" 16633 "//\n" 16634 "// multi-line line comment\n" 16635 "//\n" 16636 "int oneTwoThree=123;", 16637 Alignment)); 16638 16639 EXPECT_EQ("int a = 5;\n" 16640 "/*\n" 16641 " * multi-line block comment\n" 16642 " */\n" 16643 "int oneTwoThree = 123;", 16644 format("int a = 5;\n" 16645 "/*\n" 16646 " * multi-line block comment\n" 16647 " */\n" 16648 "int oneTwoThree=123;", 16649 Alignment)); 16650 16651 EXPECT_EQ("int a = 5;\n" 16652 "\n" 16653 "/* block comment */\n" 16654 "\n" 16655 "\n" 16656 "\n" 16657 "int oneTwoThree = 123;", 16658 format("int a = 5;\n" 16659 "\n" 16660 "/* block comment */\n" 16661 "\n" 16662 "\n" 16663 "\n" 16664 "int oneTwoThree=123;", 16665 Alignment)); 16666 16667 EXPECT_EQ("int a = 5;\n" 16668 "\n" 16669 "// line comment\n" 16670 "\n" 16671 "\n" 16672 "\n" 16673 "int oneTwoThree = 123;", 16674 format("int a = 5;\n" 16675 "\n" 16676 "// line comment\n" 16677 "\n" 16678 "\n" 16679 "\n" 16680 "int oneTwoThree=123;", 16681 Alignment)); 16682 16683 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16684 verifyFormat("#define A \\\n" 16685 " int aaaa = 12; \\\n" 16686 " int b = 23; \\\n" 16687 " int ccc = 234; \\\n" 16688 " int dddddddddd = 2345;", 16689 Alignment); 16690 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16691 verifyFormat("#define A \\\n" 16692 " int aaaa = 12; \\\n" 16693 " int b = 23; \\\n" 16694 " int ccc = 234; \\\n" 16695 " int dddddddddd = 2345;", 16696 Alignment); 16697 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16698 verifyFormat("#define A " 16699 " \\\n" 16700 " int aaaa = 12; " 16701 " \\\n" 16702 " int b = 23; " 16703 " \\\n" 16704 " int ccc = 234; " 16705 " \\\n" 16706 " int dddddddddd = 2345;", 16707 Alignment); 16708 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16709 "k = 4, int l = 5,\n" 16710 " int m = 6) {\n" 16711 " int j = 10;\n" 16712 " otherThing = 1;\n" 16713 "}", 16714 Alignment); 16715 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16716 " int i = 1;\n" 16717 " int j = 2;\n" 16718 " int big = 10000;\n" 16719 "}", 16720 Alignment); 16721 verifyFormat("class C {\n" 16722 "public:\n" 16723 " int i = 1;\n" 16724 " virtual void f() = 0;\n" 16725 "};", 16726 Alignment); 16727 verifyFormat("int i = 1;\n" 16728 "if (SomeType t = getSomething()) {\n" 16729 "}\n" 16730 "int j = 2;\n" 16731 "int big = 10000;", 16732 Alignment); 16733 verifyFormat("int j = 7;\n" 16734 "for (int k = 0; k < N; ++k) {\n" 16735 "}\n" 16736 "int j = 2;\n" 16737 "int big = 10000;\n" 16738 "}", 16739 Alignment); 16740 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16741 verifyFormat("int i = 1;\n" 16742 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16743 " = someLooooooooooooooooongFunction();\n" 16744 "int j = 2;", 16745 Alignment); 16746 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16747 verifyFormat("int i = 1;\n" 16748 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16749 " someLooooooooooooooooongFunction();\n" 16750 "int j = 2;", 16751 Alignment); 16752 16753 verifyFormat("auto lambda = []() {\n" 16754 " auto i = 0;\n" 16755 " return 0;\n" 16756 "};\n" 16757 "int i = 0;\n" 16758 "auto v = type{\n" 16759 " i = 1, //\n" 16760 " (i = 2), //\n" 16761 " i = 3 //\n" 16762 "};", 16763 Alignment); 16764 16765 verifyFormat( 16766 "int i = 1;\n" 16767 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16768 " loooooooooooooooooooooongParameterB);\n" 16769 "int j = 2;", 16770 Alignment); 16771 16772 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16773 " typename B = very_long_type_name_1,\n" 16774 " typename T_2 = very_long_type_name_2>\n" 16775 "auto foo() {}\n", 16776 Alignment); 16777 verifyFormat("int a, b = 1;\n" 16778 "int c = 2;\n" 16779 "int dd = 3;\n", 16780 Alignment); 16781 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16782 "float b[1][] = {{3.f}};\n", 16783 Alignment); 16784 verifyFormat("for (int i = 0; i < 1; i++)\n" 16785 " int x = 1;\n", 16786 Alignment); 16787 verifyFormat("for (i = 0; i < 1; i++)\n" 16788 " x = 1;\n" 16789 "y = 1;\n", 16790 Alignment); 16791 16792 Alignment.ReflowComments = true; 16793 Alignment.ColumnLimit = 50; 16794 EXPECT_EQ("int x = 0;\n" 16795 "int yy = 1; /// specificlennospace\n" 16796 "int zzz = 2;\n", 16797 format("int x = 0;\n" 16798 "int yy = 1; ///specificlennospace\n" 16799 "int zzz = 2;\n", 16800 Alignment)); 16801 } 16802 16803 TEST_F(FormatTest, AlignCompoundAssignments) { 16804 FormatStyle Alignment = getLLVMStyle(); 16805 Alignment.AlignConsecutiveAssignments.Enabled = true; 16806 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 16807 Alignment.AlignConsecutiveAssignments.PadOperators = false; 16808 verifyFormat("sfdbddfbdfbb = 5;\n" 16809 "dvsdsv = 5;\n" 16810 "int dsvvdvsdvvv = 123;", 16811 Alignment); 16812 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16813 "dvsdsv |= 5;\n" 16814 "int dsvvdvsdvvv = 123;", 16815 Alignment); 16816 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16817 "dvsdsv <<= 5;\n" 16818 "int dsvvdvsdvvv = 123;", 16819 Alignment); 16820 // Test that `<=` is not treated as a compound assignment. 16821 verifyFormat("aa &= 5;\n" 16822 "b <= 10;\n" 16823 "c = 15;", 16824 Alignment); 16825 Alignment.AlignConsecutiveAssignments.PadOperators = true; 16826 verifyFormat("sfdbddfbdfbb = 5;\n" 16827 "dvsdsv = 5;\n" 16828 "int dsvvdvsdvvv = 123;", 16829 Alignment); 16830 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16831 "dvsdsv |= 5;\n" 16832 "int dsvvdvsdvvv = 123;", 16833 Alignment); 16834 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16835 "dvsdsv <<= 5;\n" 16836 "int dsvvdvsdvvv = 123;", 16837 Alignment); 16838 EXPECT_EQ("a += 5;\n" 16839 "one = 1;\n" 16840 "\n" 16841 "oneTwoThree = 123;\n", 16842 format("a += 5;\n" 16843 "one = 1;\n" 16844 "\n" 16845 "oneTwoThree = 123;\n", 16846 Alignment)); 16847 EXPECT_EQ("a += 5;\n" 16848 "one = 1;\n" 16849 "//\n" 16850 "oneTwoThree = 123;\n", 16851 format("a += 5;\n" 16852 "one = 1;\n" 16853 "//\n" 16854 "oneTwoThree = 123;\n", 16855 Alignment)); 16856 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16857 EXPECT_EQ("a += 5;\n" 16858 "one = 1;\n" 16859 "\n" 16860 "oneTwoThree = 123;\n", 16861 format("a += 5;\n" 16862 "one = 1;\n" 16863 "\n" 16864 "oneTwoThree = 123;\n", 16865 Alignment)); 16866 EXPECT_EQ("a += 5;\n" 16867 "one = 1;\n" 16868 "//\n" 16869 "oneTwoThree = 123;\n", 16870 format("a += 5;\n" 16871 "one = 1;\n" 16872 "//\n" 16873 "oneTwoThree = 123;\n", 16874 Alignment)); 16875 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 16876 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16877 EXPECT_EQ("a += 5;\n" 16878 "one = 1;\n" 16879 "\n" 16880 "oneTwoThree = 123;\n", 16881 format("a += 5;\n" 16882 "one = 1;\n" 16883 "\n" 16884 "oneTwoThree = 123;\n", 16885 Alignment)); 16886 EXPECT_EQ("a += 5;\n" 16887 "one = 1;\n" 16888 "//\n" 16889 "oneTwoThree = 123;\n", 16890 format("a += 5;\n" 16891 "one = 1;\n" 16892 "//\n" 16893 "oneTwoThree = 123;\n", 16894 Alignment)); 16895 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16896 EXPECT_EQ("a += 5;\n" 16897 "one >>= 1;\n" 16898 "\n" 16899 "oneTwoThree = 123;\n", 16900 format("a += 5;\n" 16901 "one >>= 1;\n" 16902 "\n" 16903 "oneTwoThree = 123;\n", 16904 Alignment)); 16905 EXPECT_EQ("a += 5;\n" 16906 "one = 1;\n" 16907 "//\n" 16908 "oneTwoThree <<= 123;\n", 16909 format("a += 5;\n" 16910 "one = 1;\n" 16911 "//\n" 16912 "oneTwoThree <<= 123;\n", 16913 Alignment)); 16914 } 16915 16916 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16917 FormatStyle Alignment = getLLVMStyle(); 16918 Alignment.AlignConsecutiveMacros.Enabled = true; 16919 verifyFormat("int a = 5;\n" 16920 "int oneTwoThree = 123;", 16921 Alignment); 16922 verifyFormat("int a = 5;\n" 16923 "int oneTwoThree = 123;", 16924 Alignment); 16925 16926 Alignment.AlignConsecutiveAssignments.Enabled = true; 16927 verifyFormat("int a = 5;\n" 16928 "int oneTwoThree = 123;", 16929 Alignment); 16930 verifyFormat("int a = method();\n" 16931 "int oneTwoThree = 133;", 16932 Alignment); 16933 verifyFormat("aa <= 5;\n" 16934 "a &= 5;\n" 16935 "bcd *= 5;\n" 16936 "ghtyf += 5;\n" 16937 "dvfvdb -= 5;\n" 16938 "a /= 5;\n" 16939 "vdsvsv %= 5;\n" 16940 "sfdbddfbdfbb ^= 5;\n" 16941 "dvsdsv |= 5;\n" 16942 "int dsvvdvsdvvv = 123;", 16943 Alignment); 16944 verifyFormat("int i = 1, j = 10;\n" 16945 "something = 2000;", 16946 Alignment); 16947 verifyFormat("something = 2000;\n" 16948 "int i = 1, j = 10;\n", 16949 Alignment); 16950 verifyFormat("something = 2000;\n" 16951 "another = 911;\n" 16952 "int i = 1, j = 10;\n" 16953 "oneMore = 1;\n" 16954 "i = 2;", 16955 Alignment); 16956 verifyFormat("int a = 5;\n" 16957 "int one = 1;\n" 16958 "method();\n" 16959 "int oneTwoThree = 123;\n" 16960 "int oneTwo = 12;", 16961 Alignment); 16962 verifyFormat("int oneTwoThree = 123;\n" 16963 "int oneTwo = 12;\n" 16964 "method();\n", 16965 Alignment); 16966 verifyFormat("int oneTwoThree = 123; // comment\n" 16967 "int oneTwo = 12; // comment", 16968 Alignment); 16969 verifyFormat("int f() = default;\n" 16970 "int &operator() = default;\n" 16971 "int &operator=() {", 16972 Alignment); 16973 verifyFormat("int f() = delete;\n" 16974 "int &operator() = delete;\n" 16975 "int &operator=() {", 16976 Alignment); 16977 verifyFormat("int f() = default; // comment\n" 16978 "int &operator() = default; // comment\n" 16979 "int &operator=() {", 16980 Alignment); 16981 verifyFormat("int f() = default;\n" 16982 "int &operator() = default;\n" 16983 "int &operator==() {", 16984 Alignment); 16985 verifyFormat("int f() = default;\n" 16986 "int &operator() = default;\n" 16987 "int &operator<=() {", 16988 Alignment); 16989 verifyFormat("int f() = default;\n" 16990 "int &operator() = default;\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() = delete;\n" 16998 "int &operator() = delete;\n" 16999 "int &operator=();", 17000 Alignment); 17001 verifyFormat("/* long long padding */ int f() = default;\n" 17002 "int &operator() = default;\n" 17003 "int &operator/**/ =();", 17004 Alignment); 17005 // https://llvm.org/PR33697 17006 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17007 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17008 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17009 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17010 " void f() = delete;\n" 17011 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17012 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17013 "};\n", 17014 AlignmentWithPenalty); 17015 17016 // Bug 25167 17017 /* Uncomment when fixed 17018 verifyFormat("#if A\n" 17019 "#else\n" 17020 "int aaaaaaaa = 12;\n" 17021 "#endif\n" 17022 "#if B\n" 17023 "#else\n" 17024 "int a = 12;\n" 17025 "#endif\n", 17026 Alignment); 17027 verifyFormat("enum foo {\n" 17028 "#if A\n" 17029 "#else\n" 17030 " aaaaaaaa = 12;\n" 17031 "#endif\n" 17032 "#if B\n" 17033 "#else\n" 17034 " a = 12;\n" 17035 "#endif\n" 17036 "};\n", 17037 Alignment); 17038 */ 17039 17040 EXPECT_EQ("int a = 5;\n" 17041 "\n" 17042 "int oneTwoThree = 123;", 17043 format("int a = 5;\n" 17044 "\n" 17045 "int oneTwoThree= 123;", 17046 Alignment)); 17047 EXPECT_EQ("int a = 5;\n" 17048 "int one = 1;\n" 17049 "\n" 17050 "int oneTwoThree = 123;", 17051 format("int a = 5;\n" 17052 "int one = 1;\n" 17053 "\n" 17054 "int oneTwoThree = 123;", 17055 Alignment)); 17056 EXPECT_EQ("int a = 5;\n" 17057 "int one = 1;\n" 17058 "\n" 17059 "int oneTwoThree = 123;\n" 17060 "int oneTwo = 12;", 17061 format("int a = 5;\n" 17062 "int one = 1;\n" 17063 "\n" 17064 "int oneTwoThree = 123;\n" 17065 "int oneTwo = 12;", 17066 Alignment)); 17067 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17068 verifyFormat("#define A \\\n" 17069 " int aaaa = 12; \\\n" 17070 " int b = 23; \\\n" 17071 " int ccc = 234; \\\n" 17072 " int dddddddddd = 2345;", 17073 Alignment); 17074 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17075 verifyFormat("#define A \\\n" 17076 " int aaaa = 12; \\\n" 17077 " int b = 23; \\\n" 17078 " int ccc = 234; \\\n" 17079 " int dddddddddd = 2345;", 17080 Alignment); 17081 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17082 verifyFormat("#define A " 17083 " \\\n" 17084 " int aaaa = 12; " 17085 " \\\n" 17086 " int b = 23; " 17087 " \\\n" 17088 " int ccc = 234; " 17089 " \\\n" 17090 " int dddddddddd = 2345;", 17091 Alignment); 17092 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17093 "k = 4, int l = 5,\n" 17094 " int m = 6) {\n" 17095 " int j = 10;\n" 17096 " otherThing = 1;\n" 17097 "}", 17098 Alignment); 17099 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17100 " int i = 1;\n" 17101 " int j = 2;\n" 17102 " int big = 10000;\n" 17103 "}", 17104 Alignment); 17105 verifyFormat("class C {\n" 17106 "public:\n" 17107 " int i = 1;\n" 17108 " virtual void f() = 0;\n" 17109 "};", 17110 Alignment); 17111 verifyFormat("int i = 1;\n" 17112 "if (SomeType t = getSomething()) {\n" 17113 "}\n" 17114 "int j = 2;\n" 17115 "int big = 10000;", 17116 Alignment); 17117 verifyFormat("int j = 7;\n" 17118 "for (int k = 0; k < N; ++k) {\n" 17119 "}\n" 17120 "int j = 2;\n" 17121 "int big = 10000;\n" 17122 "}", 17123 Alignment); 17124 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17125 verifyFormat("int i = 1;\n" 17126 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17127 " = someLooooooooooooooooongFunction();\n" 17128 "int j = 2;", 17129 Alignment); 17130 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17131 verifyFormat("int i = 1;\n" 17132 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17133 " someLooooooooooooooooongFunction();\n" 17134 "int j = 2;", 17135 Alignment); 17136 17137 verifyFormat("auto lambda = []() {\n" 17138 " auto i = 0;\n" 17139 " return 0;\n" 17140 "};\n" 17141 "int i = 0;\n" 17142 "auto v = type{\n" 17143 " i = 1, //\n" 17144 " (i = 2), //\n" 17145 " i = 3 //\n" 17146 "};", 17147 Alignment); 17148 17149 verifyFormat( 17150 "int i = 1;\n" 17151 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17152 " loooooooooooooooooooooongParameterB);\n" 17153 "int j = 2;", 17154 Alignment); 17155 17156 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17157 " typename B = very_long_type_name_1,\n" 17158 " typename T_2 = very_long_type_name_2>\n" 17159 "auto foo() {}\n", 17160 Alignment); 17161 verifyFormat("int a, b = 1;\n" 17162 "int c = 2;\n" 17163 "int dd = 3;\n", 17164 Alignment); 17165 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17166 "float b[1][] = {{3.f}};\n", 17167 Alignment); 17168 verifyFormat("for (int i = 0; i < 1; i++)\n" 17169 " int x = 1;\n", 17170 Alignment); 17171 verifyFormat("for (i = 0; i < 1; i++)\n" 17172 " x = 1;\n" 17173 "y = 1;\n", 17174 Alignment); 17175 17176 EXPECT_EQ(Alignment.ReflowComments, true); 17177 Alignment.ColumnLimit = 50; 17178 EXPECT_EQ("int x = 0;\n" 17179 "int yy = 1; /// specificlennospace\n" 17180 "int zzz = 2;\n", 17181 format("int x = 0;\n" 17182 "int yy = 1; ///specificlennospace\n" 17183 "int zzz = 2;\n", 17184 Alignment)); 17185 17186 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17187 "auto b = [] {\n" 17188 " f();\n" 17189 " return;\n" 17190 "};", 17191 Alignment); 17192 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17193 "auto b = g([] {\n" 17194 " f();\n" 17195 " return;\n" 17196 "});", 17197 Alignment); 17198 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17199 "auto b = g(param, [] {\n" 17200 " f();\n" 17201 " return;\n" 17202 "});", 17203 Alignment); 17204 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17205 "auto b = [] {\n" 17206 " if (condition) {\n" 17207 " return;\n" 17208 " }\n" 17209 "};", 17210 Alignment); 17211 17212 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17213 " ccc ? aaaaa : bbbbb,\n" 17214 " dddddddddddddddddddddddddd);", 17215 Alignment); 17216 // FIXME: https://llvm.org/PR53497 17217 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17218 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17219 // " ccc ? aaaaa : bbbbb,\n" 17220 // " dddddddddddddddddddddddddd);", 17221 // Alignment); 17222 } 17223 17224 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17225 FormatStyle Alignment = getLLVMStyle(); 17226 Alignment.AlignConsecutiveBitFields.Enabled = true; 17227 verifyFormat("int const a : 5;\n" 17228 "int oneTwoThree : 23;", 17229 Alignment); 17230 17231 // Initializers are allowed starting with c++2a 17232 verifyFormat("int const a : 5 = 1;\n" 17233 "int oneTwoThree : 23 = 0;", 17234 Alignment); 17235 17236 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17237 verifyFormat("int const a : 5;\n" 17238 "int oneTwoThree : 23;", 17239 Alignment); 17240 17241 verifyFormat("int const a : 5; // comment\n" 17242 "int oneTwoThree : 23; // comment", 17243 Alignment); 17244 17245 verifyFormat("int const a : 5 = 1;\n" 17246 "int oneTwoThree : 23 = 0;", 17247 Alignment); 17248 17249 Alignment.AlignConsecutiveAssignments.Enabled = true; 17250 verifyFormat("int const a : 5 = 1;\n" 17251 "int oneTwoThree : 23 = 0;", 17252 Alignment); 17253 verifyFormat("int const a : 5 = {1};\n" 17254 "int oneTwoThree : 23 = 0;", 17255 Alignment); 17256 17257 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17258 verifyFormat("int const a :5;\n" 17259 "int oneTwoThree:23;", 17260 Alignment); 17261 17262 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17263 verifyFormat("int const a :5;\n" 17264 "int oneTwoThree :23;", 17265 Alignment); 17266 17267 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17268 verifyFormat("int const a : 5;\n" 17269 "int oneTwoThree: 23;", 17270 Alignment); 17271 17272 // Known limitations: ':' is only recognized as a bitfield colon when 17273 // followed by a number. 17274 /* 17275 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17276 "int a : 5;", 17277 Alignment); 17278 */ 17279 } 17280 17281 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17282 FormatStyle Alignment = getLLVMStyle(); 17283 Alignment.AlignConsecutiveMacros.Enabled = true; 17284 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17285 verifyFormat("float const a = 5;\n" 17286 "int oneTwoThree = 123;", 17287 Alignment); 17288 verifyFormat("int a = 5;\n" 17289 "float const oneTwoThree = 123;", 17290 Alignment); 17291 17292 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17293 verifyFormat("float const a = 5;\n" 17294 "int oneTwoThree = 123;", 17295 Alignment); 17296 verifyFormat("int a = method();\n" 17297 "float const oneTwoThree = 133;", 17298 Alignment); 17299 verifyFormat("int i = 1, j = 10;\n" 17300 "something = 2000;", 17301 Alignment); 17302 verifyFormat("something = 2000;\n" 17303 "int i = 1, j = 10;\n", 17304 Alignment); 17305 verifyFormat("float something = 2000;\n" 17306 "double another = 911;\n" 17307 "int i = 1, j = 10;\n" 17308 "const int *oneMore = 1;\n" 17309 "unsigned i = 2;", 17310 Alignment); 17311 verifyFormat("float a = 5;\n" 17312 "int one = 1;\n" 17313 "method();\n" 17314 "const double oneTwoThree = 123;\n" 17315 "const unsigned int oneTwo = 12;", 17316 Alignment); 17317 verifyFormat("int oneTwoThree{0}; // comment\n" 17318 "unsigned oneTwo; // comment", 17319 Alignment); 17320 verifyFormat("unsigned int *a;\n" 17321 "int *b;\n" 17322 "unsigned int Const *c;\n" 17323 "unsigned int const *d;\n" 17324 "unsigned int Const &e;\n" 17325 "unsigned int const &f;", 17326 Alignment); 17327 verifyFormat("Const unsigned int *c;\n" 17328 "const unsigned int *d;\n" 17329 "Const unsigned int &e;\n" 17330 "const unsigned int &f;\n" 17331 "const unsigned g;\n" 17332 "Const unsigned h;", 17333 Alignment); 17334 EXPECT_EQ("float const a = 5;\n" 17335 "\n" 17336 "int oneTwoThree = 123;", 17337 format("float const a = 5;\n" 17338 "\n" 17339 "int oneTwoThree= 123;", 17340 Alignment)); 17341 EXPECT_EQ("float a = 5;\n" 17342 "int one = 1;\n" 17343 "\n" 17344 "unsigned oneTwoThree = 123;", 17345 format("float a = 5;\n" 17346 "int one = 1;\n" 17347 "\n" 17348 "unsigned oneTwoThree = 123;", 17349 Alignment)); 17350 EXPECT_EQ("float a = 5;\n" 17351 "int one = 1;\n" 17352 "\n" 17353 "unsigned oneTwoThree = 123;\n" 17354 "int oneTwo = 12;", 17355 format("float a = 5;\n" 17356 "int one = 1;\n" 17357 "\n" 17358 "unsigned oneTwoThree = 123;\n" 17359 "int oneTwo = 12;", 17360 Alignment)); 17361 // Function prototype alignment 17362 verifyFormat("int a();\n" 17363 "double b();", 17364 Alignment); 17365 verifyFormat("int a(int x);\n" 17366 "double b();", 17367 Alignment); 17368 unsigned OldColumnLimit = Alignment.ColumnLimit; 17369 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17370 // otherwise the function parameters will be re-flowed onto a single line. 17371 Alignment.ColumnLimit = 0; 17372 EXPECT_EQ("int a(int x,\n" 17373 " float y);\n" 17374 "double b(int x,\n" 17375 " double y);", 17376 format("int a(int x,\n" 17377 " float y);\n" 17378 "double b(int x,\n" 17379 " double y);", 17380 Alignment)); 17381 // This ensures that function parameters of function declarations are 17382 // correctly indented when their owning functions are indented. 17383 // The failure case here is for 'double y' to not be indented enough. 17384 EXPECT_EQ("double a(int x);\n" 17385 "int b(int y,\n" 17386 " double z);", 17387 format("double a(int x);\n" 17388 "int b(int y,\n" 17389 " double z);", 17390 Alignment)); 17391 // Set ColumnLimit low so that we induce wrapping immediately after 17392 // the function name and opening paren. 17393 Alignment.ColumnLimit = 13; 17394 verifyFormat("int function(\n" 17395 " int x,\n" 17396 " bool y);", 17397 Alignment); 17398 Alignment.ColumnLimit = OldColumnLimit; 17399 // Ensure function pointers don't screw up recursive alignment 17400 verifyFormat("int a(int x, void (*fp)(int y));\n" 17401 "double b();", 17402 Alignment); 17403 Alignment.AlignConsecutiveAssignments.Enabled = true; 17404 // Ensure recursive alignment is broken by function braces, so that the 17405 // "a = 1" does not align with subsequent assignments inside the function 17406 // body. 17407 verifyFormat("int func(int a = 1) {\n" 17408 " int b = 2;\n" 17409 " int cc = 3;\n" 17410 "}", 17411 Alignment); 17412 verifyFormat("float something = 2000;\n" 17413 "double another = 911;\n" 17414 "int i = 1, j = 10;\n" 17415 "const int *oneMore = 1;\n" 17416 "unsigned i = 2;", 17417 Alignment); 17418 verifyFormat("int oneTwoThree = {0}; // comment\n" 17419 "unsigned oneTwo = 0; // comment", 17420 Alignment); 17421 // Make sure that scope is correctly tracked, in the absence of braces 17422 verifyFormat("for (int i = 0; i < n; i++)\n" 17423 " j = i;\n" 17424 "double x = 1;\n", 17425 Alignment); 17426 verifyFormat("if (int i = 0)\n" 17427 " j = i;\n" 17428 "double x = 1;\n", 17429 Alignment); 17430 // Ensure operator[] and operator() are comprehended 17431 verifyFormat("struct test {\n" 17432 " long long int foo();\n" 17433 " int operator[](int a);\n" 17434 " double bar();\n" 17435 "};\n", 17436 Alignment); 17437 verifyFormat("struct test {\n" 17438 " long long int foo();\n" 17439 " int operator()(int a);\n" 17440 " double bar();\n" 17441 "};\n", 17442 Alignment); 17443 // http://llvm.org/PR52914 17444 verifyFormat("char *a[] = {\"a\", // comment\n" 17445 " \"bb\"};\n" 17446 "int bbbbbbb = 0;", 17447 Alignment); 17448 17449 // PAS_Right 17450 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17451 " int const i = 1;\n" 17452 " int *j = 2;\n" 17453 " int big = 10000;\n" 17454 "\n" 17455 " unsigned oneTwoThree = 123;\n" 17456 " int oneTwo = 12;\n" 17457 " method();\n" 17458 " float k = 2;\n" 17459 " int ll = 10000;\n" 17460 "}", 17461 format("void SomeFunction(int parameter= 0) {\n" 17462 " int const i= 1;\n" 17463 " int *j=2;\n" 17464 " int big = 10000;\n" 17465 "\n" 17466 "unsigned oneTwoThree =123;\n" 17467 "int oneTwo = 12;\n" 17468 " method();\n" 17469 "float k= 2;\n" 17470 "int ll=10000;\n" 17471 "}", 17472 Alignment)); 17473 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17474 " int const i = 1;\n" 17475 " int **j = 2, ***k;\n" 17476 " int &k = i;\n" 17477 " int &&l = i + j;\n" 17478 " int big = 10000;\n" 17479 "\n" 17480 " unsigned oneTwoThree = 123;\n" 17481 " int oneTwo = 12;\n" 17482 " method();\n" 17483 " float k = 2;\n" 17484 " int ll = 10000;\n" 17485 "}", 17486 format("void SomeFunction(int parameter= 0) {\n" 17487 " int const i= 1;\n" 17488 " int **j=2,***k;\n" 17489 "int &k=i;\n" 17490 "int &&l=i+j;\n" 17491 " int big = 10000;\n" 17492 "\n" 17493 "unsigned oneTwoThree =123;\n" 17494 "int oneTwo = 12;\n" 17495 " method();\n" 17496 "float k= 2;\n" 17497 "int ll=10000;\n" 17498 "}", 17499 Alignment)); 17500 // variables are aligned at their name, pointers are at the right most 17501 // position 17502 verifyFormat("int *a;\n" 17503 "int **b;\n" 17504 "int ***c;\n" 17505 "int foobar;\n", 17506 Alignment); 17507 17508 // PAS_Left 17509 FormatStyle AlignmentLeft = Alignment; 17510 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17511 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17512 " int const i = 1;\n" 17513 " int* j = 2;\n" 17514 " int big = 10000;\n" 17515 "\n" 17516 " unsigned oneTwoThree = 123;\n" 17517 " int oneTwo = 12;\n" 17518 " method();\n" 17519 " float k = 2;\n" 17520 " int ll = 10000;\n" 17521 "}", 17522 format("void SomeFunction(int parameter= 0) {\n" 17523 " int const i= 1;\n" 17524 " int *j=2;\n" 17525 " int big = 10000;\n" 17526 "\n" 17527 "unsigned oneTwoThree =123;\n" 17528 "int oneTwo = 12;\n" 17529 " method();\n" 17530 "float k= 2;\n" 17531 "int ll=10000;\n" 17532 "}", 17533 AlignmentLeft)); 17534 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17535 " int const i = 1;\n" 17536 " int** j = 2;\n" 17537 " int& k = i;\n" 17538 " int&& l = i + j;\n" 17539 " int big = 10000;\n" 17540 "\n" 17541 " unsigned oneTwoThree = 123;\n" 17542 " int oneTwo = 12;\n" 17543 " method();\n" 17544 " float k = 2;\n" 17545 " int ll = 10000;\n" 17546 "}", 17547 format("void SomeFunction(int parameter= 0) {\n" 17548 " int const i= 1;\n" 17549 " int **j=2;\n" 17550 "int &k=i;\n" 17551 "int &&l=i+j;\n" 17552 " int big = 10000;\n" 17553 "\n" 17554 "unsigned oneTwoThree =123;\n" 17555 "int oneTwo = 12;\n" 17556 " method();\n" 17557 "float k= 2;\n" 17558 "int ll=10000;\n" 17559 "}", 17560 AlignmentLeft)); 17561 // variables are aligned at their name, pointers are at the left most position 17562 verifyFormat("int* a;\n" 17563 "int** b;\n" 17564 "int*** c;\n" 17565 "int foobar;\n", 17566 AlignmentLeft); 17567 17568 // PAS_Middle 17569 FormatStyle AlignmentMiddle = Alignment; 17570 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17571 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17572 " int const i = 1;\n" 17573 " int * j = 2;\n" 17574 " int big = 10000;\n" 17575 "\n" 17576 " unsigned oneTwoThree = 123;\n" 17577 " int oneTwo = 12;\n" 17578 " method();\n" 17579 " float k = 2;\n" 17580 " int ll = 10000;\n" 17581 "}", 17582 format("void SomeFunction(int parameter= 0) {\n" 17583 " int const i= 1;\n" 17584 " int *j=2;\n" 17585 " int big = 10000;\n" 17586 "\n" 17587 "unsigned oneTwoThree =123;\n" 17588 "int oneTwo = 12;\n" 17589 " method();\n" 17590 "float k= 2;\n" 17591 "int ll=10000;\n" 17592 "}", 17593 AlignmentMiddle)); 17594 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17595 " int const i = 1;\n" 17596 " int ** j = 2, ***k;\n" 17597 " int & k = i;\n" 17598 " int && l = i + j;\n" 17599 " int big = 10000;\n" 17600 "\n" 17601 " unsigned oneTwoThree = 123;\n" 17602 " int oneTwo = 12;\n" 17603 " method();\n" 17604 " float k = 2;\n" 17605 " int ll = 10000;\n" 17606 "}", 17607 format("void SomeFunction(int parameter= 0) {\n" 17608 " int const i= 1;\n" 17609 " int **j=2,***k;\n" 17610 "int &k=i;\n" 17611 "int &&l=i+j;\n" 17612 " int big = 10000;\n" 17613 "\n" 17614 "unsigned oneTwoThree =123;\n" 17615 "int oneTwo = 12;\n" 17616 " method();\n" 17617 "float k= 2;\n" 17618 "int ll=10000;\n" 17619 "}", 17620 AlignmentMiddle)); 17621 // variables are aligned at their name, pointers are in the middle 17622 verifyFormat("int * a;\n" 17623 "int * b;\n" 17624 "int *** c;\n" 17625 "int foobar;\n", 17626 AlignmentMiddle); 17627 17628 Alignment.AlignConsecutiveAssignments.Enabled = false; 17629 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17630 verifyFormat("#define A \\\n" 17631 " int aaaa = 12; \\\n" 17632 " float b = 23; \\\n" 17633 " const int ccc = 234; \\\n" 17634 " unsigned dddddddddd = 2345;", 17635 Alignment); 17636 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17637 verifyFormat("#define A \\\n" 17638 " int aaaa = 12; \\\n" 17639 " float b = 23; \\\n" 17640 " const int ccc = 234; \\\n" 17641 " unsigned dddddddddd = 2345;", 17642 Alignment); 17643 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17644 Alignment.ColumnLimit = 30; 17645 verifyFormat("#define A \\\n" 17646 " int aaaa = 12; \\\n" 17647 " float b = 23; \\\n" 17648 " const int ccc = 234; \\\n" 17649 " int dddddddddd = 2345;", 17650 Alignment); 17651 Alignment.ColumnLimit = 80; 17652 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17653 "k = 4, int l = 5,\n" 17654 " int m = 6) {\n" 17655 " const int j = 10;\n" 17656 " otherThing = 1;\n" 17657 "}", 17658 Alignment); 17659 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17660 " int const i = 1;\n" 17661 " int *j = 2;\n" 17662 " int big = 10000;\n" 17663 "}", 17664 Alignment); 17665 verifyFormat("class C {\n" 17666 "public:\n" 17667 " int i = 1;\n" 17668 " virtual void f() = 0;\n" 17669 "};", 17670 Alignment); 17671 verifyFormat("float i = 1;\n" 17672 "if (SomeType t = getSomething()) {\n" 17673 "}\n" 17674 "const unsigned j = 2;\n" 17675 "int big = 10000;", 17676 Alignment); 17677 verifyFormat("float j = 7;\n" 17678 "for (int k = 0; k < N; ++k) {\n" 17679 "}\n" 17680 "unsigned j = 2;\n" 17681 "int big = 10000;\n" 17682 "}", 17683 Alignment); 17684 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17685 verifyFormat("float i = 1;\n" 17686 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17687 " = someLooooooooooooooooongFunction();\n" 17688 "int j = 2;", 17689 Alignment); 17690 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17691 verifyFormat("int i = 1;\n" 17692 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17693 " someLooooooooooooooooongFunction();\n" 17694 "int j = 2;", 17695 Alignment); 17696 17697 Alignment.AlignConsecutiveAssignments.Enabled = true; 17698 verifyFormat("auto lambda = []() {\n" 17699 " auto ii = 0;\n" 17700 " float j = 0;\n" 17701 " return 0;\n" 17702 "};\n" 17703 "int i = 0;\n" 17704 "float i2 = 0;\n" 17705 "auto v = type{\n" 17706 " i = 1, //\n" 17707 " (i = 2), //\n" 17708 " i = 3 //\n" 17709 "};", 17710 Alignment); 17711 Alignment.AlignConsecutiveAssignments.Enabled = false; 17712 17713 verifyFormat( 17714 "int i = 1;\n" 17715 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17716 " loooooooooooooooooooooongParameterB);\n" 17717 "int j = 2;", 17718 Alignment); 17719 17720 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17721 // We expect declarations and assignments to align, as long as it doesn't 17722 // exceed the column limit, starting a new alignment sequence whenever it 17723 // happens. 17724 Alignment.AlignConsecutiveAssignments.Enabled = true; 17725 Alignment.ColumnLimit = 30; 17726 verifyFormat("float ii = 1;\n" 17727 "unsigned j = 2;\n" 17728 "int someVerylongVariable = 1;\n" 17729 "AnotherLongType ll = 123456;\n" 17730 "VeryVeryLongType k = 2;\n" 17731 "int myvar = 1;", 17732 Alignment); 17733 Alignment.ColumnLimit = 80; 17734 Alignment.AlignConsecutiveAssignments.Enabled = false; 17735 17736 verifyFormat( 17737 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17738 " typename LongType, typename B>\n" 17739 "auto foo() {}\n", 17740 Alignment); 17741 verifyFormat("float a, b = 1;\n" 17742 "int c = 2;\n" 17743 "int dd = 3;\n", 17744 Alignment); 17745 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17746 "float b[1][] = {{3.f}};\n", 17747 Alignment); 17748 Alignment.AlignConsecutiveAssignments.Enabled = true; 17749 verifyFormat("float a, b = 1;\n" 17750 "int c = 2;\n" 17751 "int dd = 3;\n", 17752 Alignment); 17753 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17754 "float b[1][] = {{3.f}};\n", 17755 Alignment); 17756 Alignment.AlignConsecutiveAssignments.Enabled = false; 17757 17758 Alignment.ColumnLimit = 30; 17759 Alignment.BinPackParameters = false; 17760 verifyFormat("void foo(float a,\n" 17761 " float b,\n" 17762 " int c,\n" 17763 " uint32_t *d) {\n" 17764 " int *e = 0;\n" 17765 " float f = 0;\n" 17766 " double g = 0;\n" 17767 "}\n" 17768 "void bar(ino_t a,\n" 17769 " int b,\n" 17770 " uint32_t *c,\n" 17771 " bool d) {}\n", 17772 Alignment); 17773 Alignment.BinPackParameters = true; 17774 Alignment.ColumnLimit = 80; 17775 17776 // Bug 33507 17777 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17778 verifyFormat( 17779 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17780 " static const Version verVs2017;\n" 17781 " return true;\n" 17782 "});\n", 17783 Alignment); 17784 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17785 17786 // See llvm.org/PR35641 17787 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17788 verifyFormat("int func() { //\n" 17789 " int b;\n" 17790 " unsigned c;\n" 17791 "}", 17792 Alignment); 17793 17794 // See PR37175 17795 FormatStyle Style = getMozillaStyle(); 17796 Style.AlignConsecutiveDeclarations.Enabled = true; 17797 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17798 "foo(int a);", 17799 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17800 17801 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17802 verifyFormat("unsigned int* a;\n" 17803 "int* b;\n" 17804 "unsigned int Const* c;\n" 17805 "unsigned int const* d;\n" 17806 "unsigned int Const& e;\n" 17807 "unsigned int const& f;", 17808 Alignment); 17809 verifyFormat("Const unsigned int* c;\n" 17810 "const unsigned int* d;\n" 17811 "Const unsigned int& e;\n" 17812 "const unsigned int& f;\n" 17813 "const unsigned g;\n" 17814 "Const unsigned h;", 17815 Alignment); 17816 17817 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17818 verifyFormat("unsigned int * a;\n" 17819 "int * b;\n" 17820 "unsigned int Const * c;\n" 17821 "unsigned int const * d;\n" 17822 "unsigned int Const & e;\n" 17823 "unsigned int const & f;", 17824 Alignment); 17825 verifyFormat("Const unsigned int * c;\n" 17826 "const unsigned int * d;\n" 17827 "Const unsigned int & e;\n" 17828 "const unsigned int & f;\n" 17829 "const unsigned g;\n" 17830 "Const unsigned h;", 17831 Alignment); 17832 17833 // See PR46529 17834 FormatStyle BracedAlign = getLLVMStyle(); 17835 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 17836 verifyFormat("const auto result{[]() {\n" 17837 " const auto something = 1;\n" 17838 " return 2;\n" 17839 "}};", 17840 BracedAlign); 17841 verifyFormat("int foo{[]() {\n" 17842 " int bar{0};\n" 17843 " return 0;\n" 17844 "}()};", 17845 BracedAlign); 17846 BracedAlign.Cpp11BracedListStyle = false; 17847 verifyFormat("const auto result{ []() {\n" 17848 " const auto something = 1;\n" 17849 " return 2;\n" 17850 "} };", 17851 BracedAlign); 17852 verifyFormat("int foo{ []() {\n" 17853 " int bar{ 0 };\n" 17854 " return 0;\n" 17855 "}() };", 17856 BracedAlign); 17857 } 17858 17859 TEST_F(FormatTest, AlignWithLineBreaks) { 17860 auto Style = getLLVMStyleWithColumns(120); 17861 17862 EXPECT_EQ(Style.AlignConsecutiveAssignments, 17863 FormatStyle::AlignConsecutiveStyle( 17864 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 17865 /*AcrossComments=*/false, /*AlignCompound=*/false, 17866 /*PadOperators=*/true})); 17867 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 17868 FormatStyle::AlignConsecutiveStyle({})); 17869 verifyFormat("void foo() {\n" 17870 " int myVar = 5;\n" 17871 " double x = 3.14;\n" 17872 " auto str = \"Hello \"\n" 17873 " \"World\";\n" 17874 " auto s = \"Hello \"\n" 17875 " \"Again\";\n" 17876 "}", 17877 Style); 17878 17879 // clang-format off 17880 verifyFormat("void foo() {\n" 17881 " const int capacityBefore = Entries.capacity();\n" 17882 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17883 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17884 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17885 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17886 "}", 17887 Style); 17888 // clang-format on 17889 17890 Style.AlignConsecutiveAssignments.Enabled = true; 17891 verifyFormat("void foo() {\n" 17892 " int myVar = 5;\n" 17893 " double x = 3.14;\n" 17894 " auto str = \"Hello \"\n" 17895 " \"World\";\n" 17896 " auto s = \"Hello \"\n" 17897 " \"Again\";\n" 17898 "}", 17899 Style); 17900 17901 // clang-format off 17902 verifyFormat("void foo() {\n" 17903 " const int capacityBefore = Entries.capacity();\n" 17904 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17905 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17906 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17907 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17908 "}", 17909 Style); 17910 // clang-format on 17911 17912 Style.AlignConsecutiveAssignments.Enabled = false; 17913 Style.AlignConsecutiveDeclarations.Enabled = true; 17914 verifyFormat("void foo() {\n" 17915 " int myVar = 5;\n" 17916 " double x = 3.14;\n" 17917 " auto str = \"Hello \"\n" 17918 " \"World\";\n" 17919 " auto s = \"Hello \"\n" 17920 " \"Again\";\n" 17921 "}", 17922 Style); 17923 17924 // clang-format off 17925 verifyFormat("void foo() {\n" 17926 " const int capacityBefore = Entries.capacity();\n" 17927 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17928 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17929 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17930 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17931 "}", 17932 Style); 17933 // clang-format on 17934 17935 Style.AlignConsecutiveAssignments.Enabled = true; 17936 Style.AlignConsecutiveDeclarations.Enabled = true; 17937 17938 verifyFormat("void foo() {\n" 17939 " int myVar = 5;\n" 17940 " double x = 3.14;\n" 17941 " auto str = \"Hello \"\n" 17942 " \"World\";\n" 17943 " auto s = \"Hello \"\n" 17944 " \"Again\";\n" 17945 "}", 17946 Style); 17947 17948 // clang-format off 17949 verifyFormat("void foo() {\n" 17950 " const int capacityBefore = Entries.capacity();\n" 17951 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17952 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17953 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17954 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17955 "}", 17956 Style); 17957 // clang-format on 17958 17959 Style = getLLVMStyleWithColumns(120); 17960 Style.AlignConsecutiveAssignments.Enabled = true; 17961 Style.ContinuationIndentWidth = 4; 17962 Style.IndentWidth = 4; 17963 17964 // clang-format off 17965 verifyFormat("void SomeFunc() {\n" 17966 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17967 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17968 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17969 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17970 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17971 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17972 "}", 17973 Style); 17974 // clang-format on 17975 17976 Style.BinPackArguments = false; 17977 17978 // clang-format off 17979 verifyFormat("void SomeFunc() {\n" 17980 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17981 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17982 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17983 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17984 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17985 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17986 "}", 17987 Style); 17988 // clang-format on 17989 } 17990 17991 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17992 auto Style = getLLVMStyleWithColumns(60); 17993 17994 verifyFormat("void foo1(void) {\n" 17995 " BYTE p[1] = 1;\n" 17996 " A B = {.one_foooooooooooooooo = 2,\n" 17997 " .two_fooooooooooooo = 3,\n" 17998 " .three_fooooooooooooo = 4};\n" 17999 " BYTE payload = 2;\n" 18000 "}", 18001 Style); 18002 18003 Style.AlignConsecutiveAssignments.Enabled = true; 18004 Style.AlignConsecutiveDeclarations.Enabled = false; 18005 verifyFormat("void foo2(void) {\n" 18006 " BYTE p[1] = 1;\n" 18007 " A B = {.one_foooooooooooooooo = 2,\n" 18008 " .two_fooooooooooooo = 3,\n" 18009 " .three_fooooooooooooo = 4};\n" 18010 " BYTE payload = 2;\n" 18011 "}", 18012 Style); 18013 18014 Style.AlignConsecutiveAssignments.Enabled = false; 18015 Style.AlignConsecutiveDeclarations.Enabled = true; 18016 verifyFormat("void foo3(void) {\n" 18017 " BYTE p[1] = 1;\n" 18018 " A B = {.one_foooooooooooooooo = 2,\n" 18019 " .two_fooooooooooooo = 3,\n" 18020 " .three_fooooooooooooo = 4};\n" 18021 " BYTE payload = 2;\n" 18022 "}", 18023 Style); 18024 18025 Style.AlignConsecutiveAssignments.Enabled = true; 18026 Style.AlignConsecutiveDeclarations.Enabled = true; 18027 verifyFormat("void foo4(void) {\n" 18028 " BYTE p[1] = 1;\n" 18029 " A B = {.one_foooooooooooooooo = 2,\n" 18030 " .two_fooooooooooooo = 3,\n" 18031 " .three_fooooooooooooo = 4};\n" 18032 " BYTE payload = 2;\n" 18033 "}", 18034 Style); 18035 } 18036 18037 TEST_F(FormatTest, LinuxBraceBreaking) { 18038 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18039 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18040 verifyFormat("namespace a\n" 18041 "{\n" 18042 "class A\n" 18043 "{\n" 18044 " void f()\n" 18045 " {\n" 18046 " if (true) {\n" 18047 " a();\n" 18048 " b();\n" 18049 " } else {\n" 18050 " a();\n" 18051 " }\n" 18052 " }\n" 18053 " void g() { return; }\n" 18054 "};\n" 18055 "struct B {\n" 18056 " int x;\n" 18057 "};\n" 18058 "} // namespace a\n", 18059 LinuxBraceStyle); 18060 verifyFormat("enum X {\n" 18061 " Y = 0,\n" 18062 "}\n", 18063 LinuxBraceStyle); 18064 verifyFormat("struct S {\n" 18065 " int Type;\n" 18066 " union {\n" 18067 " int x;\n" 18068 " double y;\n" 18069 " } Value;\n" 18070 " class C\n" 18071 " {\n" 18072 " MyFavoriteType Value;\n" 18073 " } Class;\n" 18074 "}\n", 18075 LinuxBraceStyle); 18076 } 18077 18078 TEST_F(FormatTest, MozillaBraceBreaking) { 18079 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18080 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18081 MozillaBraceStyle.FixNamespaceComments = false; 18082 verifyFormat("namespace a {\n" 18083 "class A\n" 18084 "{\n" 18085 " void f()\n" 18086 " {\n" 18087 " if (true) {\n" 18088 " a();\n" 18089 " b();\n" 18090 " }\n" 18091 " }\n" 18092 " void g() { return; }\n" 18093 "};\n" 18094 "enum E\n" 18095 "{\n" 18096 " A,\n" 18097 " // foo\n" 18098 " B,\n" 18099 " C\n" 18100 "};\n" 18101 "struct B\n" 18102 "{\n" 18103 " int x;\n" 18104 "};\n" 18105 "}\n", 18106 MozillaBraceStyle); 18107 verifyFormat("struct S\n" 18108 "{\n" 18109 " int Type;\n" 18110 " union\n" 18111 " {\n" 18112 " int x;\n" 18113 " double y;\n" 18114 " } Value;\n" 18115 " class C\n" 18116 " {\n" 18117 " MyFavoriteType Value;\n" 18118 " } Class;\n" 18119 "}\n", 18120 MozillaBraceStyle); 18121 } 18122 18123 TEST_F(FormatTest, StroustrupBraceBreaking) { 18124 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18125 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18126 verifyFormat("namespace a {\n" 18127 "class A {\n" 18128 " void f()\n" 18129 " {\n" 18130 " if (true) {\n" 18131 " a();\n" 18132 " b();\n" 18133 " }\n" 18134 " }\n" 18135 " void g() { return; }\n" 18136 "};\n" 18137 "struct B {\n" 18138 " int x;\n" 18139 "};\n" 18140 "} // namespace a\n", 18141 StroustrupBraceStyle); 18142 18143 verifyFormat("void foo()\n" 18144 "{\n" 18145 " if (a) {\n" 18146 " a();\n" 18147 " }\n" 18148 " else {\n" 18149 " b();\n" 18150 " }\n" 18151 "}\n", 18152 StroustrupBraceStyle); 18153 18154 verifyFormat("#ifdef _DEBUG\n" 18155 "int foo(int i = 0)\n" 18156 "#else\n" 18157 "int foo(int i = 5)\n" 18158 "#endif\n" 18159 "{\n" 18160 " return i;\n" 18161 "}", 18162 StroustrupBraceStyle); 18163 18164 verifyFormat("void foo() {}\n" 18165 "void bar()\n" 18166 "#ifdef _DEBUG\n" 18167 "{\n" 18168 " foo();\n" 18169 "}\n" 18170 "#else\n" 18171 "{\n" 18172 "}\n" 18173 "#endif", 18174 StroustrupBraceStyle); 18175 18176 verifyFormat("void foobar() { int i = 5; }\n" 18177 "#ifdef _DEBUG\n" 18178 "void bar() {}\n" 18179 "#else\n" 18180 "void bar() { foobar(); }\n" 18181 "#endif", 18182 StroustrupBraceStyle); 18183 } 18184 18185 TEST_F(FormatTest, AllmanBraceBreaking) { 18186 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18187 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18188 18189 EXPECT_EQ("namespace a\n" 18190 "{\n" 18191 "void f();\n" 18192 "void g();\n" 18193 "} // namespace a\n", 18194 format("namespace a\n" 18195 "{\n" 18196 "void f();\n" 18197 "void g();\n" 18198 "}\n", 18199 AllmanBraceStyle)); 18200 18201 verifyFormat("namespace a\n" 18202 "{\n" 18203 "class A\n" 18204 "{\n" 18205 " void f()\n" 18206 " {\n" 18207 " if (true)\n" 18208 " {\n" 18209 " a();\n" 18210 " b();\n" 18211 " }\n" 18212 " }\n" 18213 " void g() { return; }\n" 18214 "};\n" 18215 "struct B\n" 18216 "{\n" 18217 " int x;\n" 18218 "};\n" 18219 "union C\n" 18220 "{\n" 18221 "};\n" 18222 "} // namespace a", 18223 AllmanBraceStyle); 18224 18225 verifyFormat("void f()\n" 18226 "{\n" 18227 " if (true)\n" 18228 " {\n" 18229 " a();\n" 18230 " }\n" 18231 " else if (false)\n" 18232 " {\n" 18233 " b();\n" 18234 " }\n" 18235 " else\n" 18236 " {\n" 18237 " c();\n" 18238 " }\n" 18239 "}\n", 18240 AllmanBraceStyle); 18241 18242 verifyFormat("void f()\n" 18243 "{\n" 18244 " for (int i = 0; i < 10; ++i)\n" 18245 " {\n" 18246 " a();\n" 18247 " }\n" 18248 " while (false)\n" 18249 " {\n" 18250 " b();\n" 18251 " }\n" 18252 " do\n" 18253 " {\n" 18254 " c();\n" 18255 " } while (false)\n" 18256 "}\n", 18257 AllmanBraceStyle); 18258 18259 verifyFormat("void f(int a)\n" 18260 "{\n" 18261 " switch (a)\n" 18262 " {\n" 18263 " case 0:\n" 18264 " break;\n" 18265 " case 1:\n" 18266 " {\n" 18267 " break;\n" 18268 " }\n" 18269 " case 2:\n" 18270 " {\n" 18271 " }\n" 18272 " break;\n" 18273 " default:\n" 18274 " break;\n" 18275 " }\n" 18276 "}\n", 18277 AllmanBraceStyle); 18278 18279 verifyFormat("enum X\n" 18280 "{\n" 18281 " Y = 0,\n" 18282 "}\n", 18283 AllmanBraceStyle); 18284 verifyFormat("enum X\n" 18285 "{\n" 18286 " Y = 0\n" 18287 "}\n", 18288 AllmanBraceStyle); 18289 18290 verifyFormat("@interface BSApplicationController ()\n" 18291 "{\n" 18292 "@private\n" 18293 " id _extraIvar;\n" 18294 "}\n" 18295 "@end\n", 18296 AllmanBraceStyle); 18297 18298 verifyFormat("#ifdef _DEBUG\n" 18299 "int foo(int i = 0)\n" 18300 "#else\n" 18301 "int foo(int i = 5)\n" 18302 "#endif\n" 18303 "{\n" 18304 " return i;\n" 18305 "}", 18306 AllmanBraceStyle); 18307 18308 verifyFormat("void foo() {}\n" 18309 "void bar()\n" 18310 "#ifdef _DEBUG\n" 18311 "{\n" 18312 " foo();\n" 18313 "}\n" 18314 "#else\n" 18315 "{\n" 18316 "}\n" 18317 "#endif", 18318 AllmanBraceStyle); 18319 18320 verifyFormat("void foobar() { int i = 5; }\n" 18321 "#ifdef _DEBUG\n" 18322 "void bar() {}\n" 18323 "#else\n" 18324 "void bar() { foobar(); }\n" 18325 "#endif", 18326 AllmanBraceStyle); 18327 18328 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18329 FormatStyle::SLS_All); 18330 18331 verifyFormat("[](int i) { return i + 2; };\n" 18332 "[](int i, int j)\n" 18333 "{\n" 18334 " auto x = i + j;\n" 18335 " auto y = i * j;\n" 18336 " return x ^ y;\n" 18337 "};\n" 18338 "void foo()\n" 18339 "{\n" 18340 " auto shortLambda = [](int i) { return i + 2; };\n" 18341 " auto longLambda = [](int i, int j)\n" 18342 " {\n" 18343 " auto x = i + j;\n" 18344 " auto y = i * j;\n" 18345 " return x ^ y;\n" 18346 " };\n" 18347 "}", 18348 AllmanBraceStyle); 18349 18350 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18351 18352 verifyFormat("[](int i)\n" 18353 "{\n" 18354 " return i + 2;\n" 18355 "};\n" 18356 "[](int i, int j)\n" 18357 "{\n" 18358 " auto x = i + j;\n" 18359 " auto y = i * j;\n" 18360 " return x ^ y;\n" 18361 "};\n" 18362 "void foo()\n" 18363 "{\n" 18364 " auto shortLambda = [](int i)\n" 18365 " {\n" 18366 " return i + 2;\n" 18367 " };\n" 18368 " auto longLambda = [](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 "}", 18375 AllmanBraceStyle); 18376 18377 // Reset 18378 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18379 18380 // This shouldn't affect ObjC blocks.. 18381 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18382 " // ...\n" 18383 " int i;\n" 18384 "}];", 18385 AllmanBraceStyle); 18386 verifyFormat("void (^block)(void) = ^{\n" 18387 " // ...\n" 18388 " int i;\n" 18389 "};", 18390 AllmanBraceStyle); 18391 // .. or dict literals. 18392 verifyFormat("void f()\n" 18393 "{\n" 18394 " // ...\n" 18395 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18396 "}", 18397 AllmanBraceStyle); 18398 verifyFormat("void f()\n" 18399 "{\n" 18400 " // ...\n" 18401 " [object someMethod:@{a : @\"b\"}];\n" 18402 "}", 18403 AllmanBraceStyle); 18404 verifyFormat("int f()\n" 18405 "{ // comment\n" 18406 " return 42;\n" 18407 "}", 18408 AllmanBraceStyle); 18409 18410 AllmanBraceStyle.ColumnLimit = 19; 18411 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18412 AllmanBraceStyle.ColumnLimit = 18; 18413 verifyFormat("void f()\n" 18414 "{\n" 18415 " int i;\n" 18416 "}", 18417 AllmanBraceStyle); 18418 AllmanBraceStyle.ColumnLimit = 80; 18419 18420 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18421 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18422 FormatStyle::SIS_WithoutElse; 18423 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18424 verifyFormat("void f(bool b)\n" 18425 "{\n" 18426 " if (b)\n" 18427 " {\n" 18428 " return;\n" 18429 " }\n" 18430 "}\n", 18431 BreakBeforeBraceShortIfs); 18432 verifyFormat("void f(bool b)\n" 18433 "{\n" 18434 " if constexpr (b)\n" 18435 " {\n" 18436 " return;\n" 18437 " }\n" 18438 "}\n", 18439 BreakBeforeBraceShortIfs); 18440 verifyFormat("void f(bool b)\n" 18441 "{\n" 18442 " if CONSTEXPR (b)\n" 18443 " {\n" 18444 " return;\n" 18445 " }\n" 18446 "}\n", 18447 BreakBeforeBraceShortIfs); 18448 verifyFormat("void f(bool b)\n" 18449 "{\n" 18450 " if (b) return;\n" 18451 "}\n", 18452 BreakBeforeBraceShortIfs); 18453 verifyFormat("void f(bool b)\n" 18454 "{\n" 18455 " if constexpr (b) return;\n" 18456 "}\n", 18457 BreakBeforeBraceShortIfs); 18458 verifyFormat("void f(bool b)\n" 18459 "{\n" 18460 " if CONSTEXPR (b) return;\n" 18461 "}\n", 18462 BreakBeforeBraceShortIfs); 18463 verifyFormat("void f(bool b)\n" 18464 "{\n" 18465 " while (b)\n" 18466 " {\n" 18467 " return;\n" 18468 " }\n" 18469 "}\n", 18470 BreakBeforeBraceShortIfs); 18471 } 18472 18473 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18474 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18475 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18476 18477 // Make a few changes to the style for testing purposes 18478 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18479 FormatStyle::SFS_Empty; 18480 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18481 18482 // FIXME: this test case can't decide whether there should be a blank line 18483 // after the ~D() line or not. It adds one if one doesn't exist in the test 18484 // and it removes the line if one exists. 18485 /* 18486 verifyFormat("class A;\n" 18487 "namespace B\n" 18488 " {\n" 18489 "class C;\n" 18490 "// Comment\n" 18491 "class D\n" 18492 " {\n" 18493 "public:\n" 18494 " D();\n" 18495 " ~D() {}\n" 18496 "private:\n" 18497 " enum E\n" 18498 " {\n" 18499 " F\n" 18500 " }\n" 18501 " };\n" 18502 " } // namespace B\n", 18503 WhitesmithsBraceStyle); 18504 */ 18505 18506 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18507 verifyFormat("namespace a\n" 18508 " {\n" 18509 "class A\n" 18510 " {\n" 18511 " void f()\n" 18512 " {\n" 18513 " if (true)\n" 18514 " {\n" 18515 " a();\n" 18516 " b();\n" 18517 " }\n" 18518 " }\n" 18519 " void g()\n" 18520 " {\n" 18521 " return;\n" 18522 " }\n" 18523 " };\n" 18524 "struct B\n" 18525 " {\n" 18526 " int x;\n" 18527 " };\n" 18528 " } // namespace a", 18529 WhitesmithsBraceStyle); 18530 18531 verifyFormat("namespace a\n" 18532 " {\n" 18533 "namespace b\n" 18534 " {\n" 18535 "class A\n" 18536 " {\n" 18537 " void f()\n" 18538 " {\n" 18539 " if (true)\n" 18540 " {\n" 18541 " a();\n" 18542 " b();\n" 18543 " }\n" 18544 " }\n" 18545 " void g()\n" 18546 " {\n" 18547 " return;\n" 18548 " }\n" 18549 " };\n" 18550 "struct B\n" 18551 " {\n" 18552 " int x;\n" 18553 " };\n" 18554 " } // namespace b\n" 18555 " } // namespace a", 18556 WhitesmithsBraceStyle); 18557 18558 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18559 verifyFormat("namespace a\n" 18560 " {\n" 18561 "namespace b\n" 18562 " {\n" 18563 " class A\n" 18564 " {\n" 18565 " void f()\n" 18566 " {\n" 18567 " if (true)\n" 18568 " {\n" 18569 " a();\n" 18570 " b();\n" 18571 " }\n" 18572 " }\n" 18573 " void g()\n" 18574 " {\n" 18575 " return;\n" 18576 " }\n" 18577 " };\n" 18578 " struct B\n" 18579 " {\n" 18580 " int x;\n" 18581 " };\n" 18582 " } // namespace b\n" 18583 " } // namespace a", 18584 WhitesmithsBraceStyle); 18585 18586 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18587 verifyFormat("namespace a\n" 18588 " {\n" 18589 " namespace b\n" 18590 " {\n" 18591 " class A\n" 18592 " {\n" 18593 " void f()\n" 18594 " {\n" 18595 " if (true)\n" 18596 " {\n" 18597 " a();\n" 18598 " b();\n" 18599 " }\n" 18600 " }\n" 18601 " void g()\n" 18602 " {\n" 18603 " return;\n" 18604 " }\n" 18605 " };\n" 18606 " struct B\n" 18607 " {\n" 18608 " int x;\n" 18609 " };\n" 18610 " } // namespace b\n" 18611 " } // namespace a", 18612 WhitesmithsBraceStyle); 18613 18614 verifyFormat("void f()\n" 18615 " {\n" 18616 " if (true)\n" 18617 " {\n" 18618 " a();\n" 18619 " }\n" 18620 " else if (false)\n" 18621 " {\n" 18622 " b();\n" 18623 " }\n" 18624 " else\n" 18625 " {\n" 18626 " c();\n" 18627 " }\n" 18628 " }\n", 18629 WhitesmithsBraceStyle); 18630 18631 verifyFormat("void f()\n" 18632 " {\n" 18633 " for (int i = 0; i < 10; ++i)\n" 18634 " {\n" 18635 " a();\n" 18636 " }\n" 18637 " while (false)\n" 18638 " {\n" 18639 " b();\n" 18640 " }\n" 18641 " do\n" 18642 " {\n" 18643 " c();\n" 18644 " } while (false)\n" 18645 " }\n", 18646 WhitesmithsBraceStyle); 18647 18648 WhitesmithsBraceStyle.IndentCaseLabels = true; 18649 verifyFormat("void switchTest1(int a)\n" 18650 " {\n" 18651 " switch (a)\n" 18652 " {\n" 18653 " case 2:\n" 18654 " {\n" 18655 " }\n" 18656 " break;\n" 18657 " }\n" 18658 " }\n", 18659 WhitesmithsBraceStyle); 18660 18661 verifyFormat("void switchTest2(int a)\n" 18662 " {\n" 18663 " switch (a)\n" 18664 " {\n" 18665 " case 0:\n" 18666 " break;\n" 18667 " case 1:\n" 18668 " {\n" 18669 " break;\n" 18670 " }\n" 18671 " case 2:\n" 18672 " {\n" 18673 " }\n" 18674 " break;\n" 18675 " default:\n" 18676 " break;\n" 18677 " }\n" 18678 " }\n", 18679 WhitesmithsBraceStyle); 18680 18681 verifyFormat("void switchTest3(int a)\n" 18682 " {\n" 18683 " switch (a)\n" 18684 " {\n" 18685 " case 0:\n" 18686 " {\n" 18687 " foo(x);\n" 18688 " }\n" 18689 " break;\n" 18690 " default:\n" 18691 " {\n" 18692 " foo(1);\n" 18693 " }\n" 18694 " break;\n" 18695 " }\n" 18696 " }\n", 18697 WhitesmithsBraceStyle); 18698 18699 WhitesmithsBraceStyle.IndentCaseLabels = false; 18700 18701 verifyFormat("void switchTest4(int a)\n" 18702 " {\n" 18703 " switch (a)\n" 18704 " {\n" 18705 " case 2:\n" 18706 " {\n" 18707 " }\n" 18708 " break;\n" 18709 " }\n" 18710 " }\n", 18711 WhitesmithsBraceStyle); 18712 18713 verifyFormat("void switchTest5(int a)\n" 18714 " {\n" 18715 " switch (a)\n" 18716 " {\n" 18717 " case 0:\n" 18718 " break;\n" 18719 " case 1:\n" 18720 " {\n" 18721 " foo();\n" 18722 " break;\n" 18723 " }\n" 18724 " case 2:\n" 18725 " {\n" 18726 " }\n" 18727 " break;\n" 18728 " default:\n" 18729 " break;\n" 18730 " }\n" 18731 " }\n", 18732 WhitesmithsBraceStyle); 18733 18734 verifyFormat("void switchTest6(int a)\n" 18735 " {\n" 18736 " switch (a)\n" 18737 " {\n" 18738 " case 0:\n" 18739 " {\n" 18740 " foo(x);\n" 18741 " }\n" 18742 " break;\n" 18743 " default:\n" 18744 " {\n" 18745 " foo(1);\n" 18746 " }\n" 18747 " break;\n" 18748 " }\n" 18749 " }\n", 18750 WhitesmithsBraceStyle); 18751 18752 verifyFormat("enum X\n" 18753 " {\n" 18754 " Y = 0, // testing\n" 18755 " }\n", 18756 WhitesmithsBraceStyle); 18757 18758 verifyFormat("enum X\n" 18759 " {\n" 18760 " Y = 0\n" 18761 " }\n", 18762 WhitesmithsBraceStyle); 18763 verifyFormat("enum X\n" 18764 " {\n" 18765 " Y = 0,\n" 18766 " Z = 1\n" 18767 " };\n", 18768 WhitesmithsBraceStyle); 18769 18770 verifyFormat("@interface BSApplicationController ()\n" 18771 " {\n" 18772 "@private\n" 18773 " id _extraIvar;\n" 18774 " }\n" 18775 "@end\n", 18776 WhitesmithsBraceStyle); 18777 18778 verifyFormat("#ifdef _DEBUG\n" 18779 "int foo(int i = 0)\n" 18780 "#else\n" 18781 "int foo(int i = 5)\n" 18782 "#endif\n" 18783 " {\n" 18784 " return i;\n" 18785 " }", 18786 WhitesmithsBraceStyle); 18787 18788 verifyFormat("void foo() {}\n" 18789 "void bar()\n" 18790 "#ifdef _DEBUG\n" 18791 " {\n" 18792 " foo();\n" 18793 " }\n" 18794 "#else\n" 18795 " {\n" 18796 " }\n" 18797 "#endif", 18798 WhitesmithsBraceStyle); 18799 18800 verifyFormat("void foobar()\n" 18801 " {\n" 18802 " int i = 5;\n" 18803 " }\n" 18804 "#ifdef _DEBUG\n" 18805 "void bar()\n" 18806 " {\n" 18807 " }\n" 18808 "#else\n" 18809 "void bar()\n" 18810 " {\n" 18811 " foobar();\n" 18812 " }\n" 18813 "#endif", 18814 WhitesmithsBraceStyle); 18815 18816 // This shouldn't affect ObjC blocks.. 18817 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18818 " // ...\n" 18819 " int i;\n" 18820 "}];", 18821 WhitesmithsBraceStyle); 18822 verifyFormat("void (^block)(void) = ^{\n" 18823 " // ...\n" 18824 " int i;\n" 18825 "};", 18826 WhitesmithsBraceStyle); 18827 // .. or dict literals. 18828 verifyFormat("void f()\n" 18829 " {\n" 18830 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18831 " }", 18832 WhitesmithsBraceStyle); 18833 18834 verifyFormat("int f()\n" 18835 " { // comment\n" 18836 " return 42;\n" 18837 " }", 18838 WhitesmithsBraceStyle); 18839 18840 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18841 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18842 FormatStyle::SIS_OnlyFirstIf; 18843 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18844 verifyFormat("void f(bool b)\n" 18845 " {\n" 18846 " if (b)\n" 18847 " {\n" 18848 " return;\n" 18849 " }\n" 18850 " }\n", 18851 BreakBeforeBraceShortIfs); 18852 verifyFormat("void f(bool b)\n" 18853 " {\n" 18854 " if (b) return;\n" 18855 " }\n", 18856 BreakBeforeBraceShortIfs); 18857 verifyFormat("void f(bool b)\n" 18858 " {\n" 18859 " while (b)\n" 18860 " {\n" 18861 " return;\n" 18862 " }\n" 18863 " }\n", 18864 BreakBeforeBraceShortIfs); 18865 } 18866 18867 TEST_F(FormatTest, GNUBraceBreaking) { 18868 FormatStyle GNUBraceStyle = getLLVMStyle(); 18869 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18870 verifyFormat("namespace a\n" 18871 "{\n" 18872 "class A\n" 18873 "{\n" 18874 " void f()\n" 18875 " {\n" 18876 " int a;\n" 18877 " {\n" 18878 " int b;\n" 18879 " }\n" 18880 " if (true)\n" 18881 " {\n" 18882 " a();\n" 18883 " b();\n" 18884 " }\n" 18885 " }\n" 18886 " void g() { return; }\n" 18887 "}\n" 18888 "} // namespace a", 18889 GNUBraceStyle); 18890 18891 verifyFormat("void f()\n" 18892 "{\n" 18893 " if (true)\n" 18894 " {\n" 18895 " a();\n" 18896 " }\n" 18897 " else if (false)\n" 18898 " {\n" 18899 " b();\n" 18900 " }\n" 18901 " else\n" 18902 " {\n" 18903 " c();\n" 18904 " }\n" 18905 "}\n", 18906 GNUBraceStyle); 18907 18908 verifyFormat("void f()\n" 18909 "{\n" 18910 " for (int i = 0; i < 10; ++i)\n" 18911 " {\n" 18912 " a();\n" 18913 " }\n" 18914 " while (false)\n" 18915 " {\n" 18916 " b();\n" 18917 " }\n" 18918 " do\n" 18919 " {\n" 18920 " c();\n" 18921 " }\n" 18922 " while (false);\n" 18923 "}\n", 18924 GNUBraceStyle); 18925 18926 verifyFormat("void f(int a)\n" 18927 "{\n" 18928 " switch (a)\n" 18929 " {\n" 18930 " case 0:\n" 18931 " break;\n" 18932 " case 1:\n" 18933 " {\n" 18934 " break;\n" 18935 " }\n" 18936 " case 2:\n" 18937 " {\n" 18938 " }\n" 18939 " break;\n" 18940 " default:\n" 18941 " break;\n" 18942 " }\n" 18943 "}\n", 18944 GNUBraceStyle); 18945 18946 verifyFormat("enum X\n" 18947 "{\n" 18948 " Y = 0,\n" 18949 "}\n", 18950 GNUBraceStyle); 18951 18952 verifyFormat("@interface BSApplicationController ()\n" 18953 "{\n" 18954 "@private\n" 18955 " id _extraIvar;\n" 18956 "}\n" 18957 "@end\n", 18958 GNUBraceStyle); 18959 18960 verifyFormat("#ifdef _DEBUG\n" 18961 "int foo(int i = 0)\n" 18962 "#else\n" 18963 "int foo(int i = 5)\n" 18964 "#endif\n" 18965 "{\n" 18966 " return i;\n" 18967 "}", 18968 GNUBraceStyle); 18969 18970 verifyFormat("void foo() {}\n" 18971 "void bar()\n" 18972 "#ifdef _DEBUG\n" 18973 "{\n" 18974 " foo();\n" 18975 "}\n" 18976 "#else\n" 18977 "{\n" 18978 "}\n" 18979 "#endif", 18980 GNUBraceStyle); 18981 18982 verifyFormat("void foobar() { int i = 5; }\n" 18983 "#ifdef _DEBUG\n" 18984 "void bar() {}\n" 18985 "#else\n" 18986 "void bar() { foobar(); }\n" 18987 "#endif", 18988 GNUBraceStyle); 18989 } 18990 18991 TEST_F(FormatTest, WebKitBraceBreaking) { 18992 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18993 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18994 WebKitBraceStyle.FixNamespaceComments = false; 18995 verifyFormat("namespace a {\n" 18996 "class A {\n" 18997 " void f()\n" 18998 " {\n" 18999 " if (true) {\n" 19000 " a();\n" 19001 " b();\n" 19002 " }\n" 19003 " }\n" 19004 " void g() { return; }\n" 19005 "};\n" 19006 "enum E {\n" 19007 " A,\n" 19008 " // foo\n" 19009 " B,\n" 19010 " C\n" 19011 "};\n" 19012 "struct B {\n" 19013 " int x;\n" 19014 "};\n" 19015 "}\n", 19016 WebKitBraceStyle); 19017 verifyFormat("struct S {\n" 19018 " int Type;\n" 19019 " union {\n" 19020 " int x;\n" 19021 " double y;\n" 19022 " } Value;\n" 19023 " class C {\n" 19024 " MyFavoriteType Value;\n" 19025 " } Class;\n" 19026 "};\n", 19027 WebKitBraceStyle); 19028 } 19029 19030 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19031 verifyFormat("void f() {\n" 19032 " try {\n" 19033 " } catch (const Exception &e) {\n" 19034 " }\n" 19035 "}\n", 19036 getLLVMStyle()); 19037 } 19038 19039 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19040 auto Style = getLLVMStyle(); 19041 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19042 Style.AlignConsecutiveAssignments.Enabled = true; 19043 Style.AlignConsecutiveDeclarations.Enabled = true; 19044 verifyFormat("struct test demo[] = {\n" 19045 " {56, 23, \"hello\"},\n" 19046 " {-1, 93463, \"world\"},\n" 19047 " { 7, 5, \"!!\"}\n" 19048 "};\n", 19049 Style); 19050 19051 verifyFormat("struct test demo[] = {\n" 19052 " {56, 23, \"hello\"}, // first line\n" 19053 " {-1, 93463, \"world\"}, // second line\n" 19054 " { 7, 5, \"!!\"} // third line\n" 19055 "};\n", 19056 Style); 19057 19058 verifyFormat("struct test demo[4] = {\n" 19059 " { 56, 23, 21, \"oh\"}, // first line\n" 19060 " { -1, 93463, 22, \"my\"}, // second line\n" 19061 " { 7, 5, 1, \"goodness\"} // third line\n" 19062 " {234, 5, 1, \"gracious\"} // fourth line\n" 19063 "};\n", 19064 Style); 19065 19066 verifyFormat("struct test demo[3] = {\n" 19067 " {56, 23, \"hello\"},\n" 19068 " {-1, 93463, \"world\"},\n" 19069 " { 7, 5, \"!!\"}\n" 19070 "};\n", 19071 Style); 19072 19073 verifyFormat("struct test demo[3] = {\n" 19074 " {int{56}, 23, \"hello\"},\n" 19075 " {int{-1}, 93463, \"world\"},\n" 19076 " { int{7}, 5, \"!!\"}\n" 19077 "};\n", 19078 Style); 19079 19080 verifyFormat("struct test demo[] = {\n" 19081 " {56, 23, \"hello\"},\n" 19082 " {-1, 93463, \"world\"},\n" 19083 " { 7, 5, \"!!\"},\n" 19084 "};\n", 19085 Style); 19086 19087 verifyFormat("test demo[] = {\n" 19088 " {56, 23, \"hello\"},\n" 19089 " {-1, 93463, \"world\"},\n" 19090 " { 7, 5, \"!!\"},\n" 19091 "};\n", 19092 Style); 19093 19094 verifyFormat("demo = std::array<struct test, 3>{\n" 19095 " test{56, 23, \"hello\"},\n" 19096 " test{-1, 93463, \"world\"},\n" 19097 " test{ 7, 5, \"!!\"},\n" 19098 "};\n", 19099 Style); 19100 19101 verifyFormat("test demo[] = {\n" 19102 " {56, 23, \"hello\"},\n" 19103 "#if X\n" 19104 " {-1, 93463, \"world\"},\n" 19105 "#endif\n" 19106 " { 7, 5, \"!!\"}\n" 19107 "};\n", 19108 Style); 19109 19110 verifyFormat( 19111 "test demo[] = {\n" 19112 " { 7, 23,\n" 19113 " \"hello world i am a very long line that really, in any\"\n" 19114 " \"just world, ought to be split over multiple lines\"},\n" 19115 " {-1, 93463, \"world\"},\n" 19116 " {56, 5, \"!!\"}\n" 19117 "};\n", 19118 Style); 19119 19120 verifyFormat("return GradForUnaryCwise(g, {\n" 19121 " {{\"sign\"}, \"Sign\", " 19122 " {\"x\", \"dy\"}},\n" 19123 " { {\"dx\"}, \"Mul\", {\"dy\"" 19124 ", \"sign\"}},\n" 19125 "});\n", 19126 Style); 19127 19128 Style.ColumnLimit = 0; 19129 EXPECT_EQ( 19130 "test demo[] = {\n" 19131 " {56, 23, \"hello world i am a very long line that really, " 19132 "in any just world, ought to be split over multiple lines\"},\n" 19133 " {-1, 93463, " 19134 " \"world\"},\n" 19135 " { 7, 5, " 19136 " \"!!\"},\n" 19137 "};", 19138 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19139 "that really, in any just world, ought to be split over multiple " 19140 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19141 Style)); 19142 19143 Style.ColumnLimit = 80; 19144 verifyFormat("test demo[] = {\n" 19145 " {56, 23, /* a comment */ \"hello\"},\n" 19146 " {-1, 93463, \"world\"},\n" 19147 " { 7, 5, \"!!\"}\n" 19148 "};\n", 19149 Style); 19150 19151 verifyFormat("test demo[] = {\n" 19152 " {56, 23, \"hello\"},\n" 19153 " {-1, 93463, \"world\" /* comment here */},\n" 19154 " { 7, 5, \"!!\"}\n" 19155 "};\n", 19156 Style); 19157 19158 verifyFormat("test demo[] = {\n" 19159 " {56, /* a comment */ 23, \"hello\"},\n" 19160 " {-1, 93463, \"world\"},\n" 19161 " { 7, 5, \"!!\"}\n" 19162 "};\n", 19163 Style); 19164 19165 Style.ColumnLimit = 20; 19166 EXPECT_EQ( 19167 "demo = std::array<\n" 19168 " struct test, 3>{\n" 19169 " test{\n" 19170 " 56, 23,\n" 19171 " \"hello \"\n" 19172 " \"world i \"\n" 19173 " \"am a very \"\n" 19174 " \"long line \"\n" 19175 " \"that \"\n" 19176 " \"really, \"\n" 19177 " \"in any \"\n" 19178 " \"just \"\n" 19179 " \"world, \"\n" 19180 " \"ought to \"\n" 19181 " \"be split \"\n" 19182 " \"over \"\n" 19183 " \"multiple \"\n" 19184 " \"lines\"},\n" 19185 " test{-1, 93463,\n" 19186 " \"world\"},\n" 19187 " test{ 7, 5,\n" 19188 " \"!!\" },\n" 19189 "};", 19190 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19191 "i am a very long line that really, in any just world, ought " 19192 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19193 "test{7, 5, \"!!\"},};", 19194 Style)); 19195 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19196 Style = getLLVMStyleWithColumns(50); 19197 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19198 verifyFormat("static A x = {\n" 19199 " {{init1, init2, init3, init4},\n" 19200 " {init1, init2, init3, init4}}\n" 19201 "};", 19202 Style); 19203 // TODO: Fix the indentations below when this option is fully functional. 19204 verifyFormat("int a[][] = {\n" 19205 " {\n" 19206 " {0, 2}, //\n" 19207 " {1, 2} //\n" 19208 " }\n" 19209 "};", 19210 Style); 19211 Style.ColumnLimit = 100; 19212 EXPECT_EQ( 19213 "test demo[] = {\n" 19214 " {56, 23,\n" 19215 " \"hello world i am a very long line that really, in any just world" 19216 ", ought to be split over \"\n" 19217 " \"multiple lines\" },\n" 19218 " {-1, 93463, \"world\"},\n" 19219 " { 7, 5, \"!!\"},\n" 19220 "};", 19221 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19222 "that really, in any just world, ought to be split over multiple " 19223 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19224 Style)); 19225 19226 Style = getLLVMStyleWithColumns(50); 19227 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19228 verifyFormat("struct test demo[] = {\n" 19229 " {56, 23, \"hello\"},\n" 19230 " {-1, 93463, \"world\"},\n" 19231 " { 7, 5, \"!!\"}\n" 19232 "};\n" 19233 "static A x = {\n" 19234 " {{init1, init2, init3, init4},\n" 19235 " {init1, init2, init3, init4}}\n" 19236 "};", 19237 Style); 19238 Style.ColumnLimit = 100; 19239 Style.AlignConsecutiveAssignments.AcrossComments = true; 19240 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19241 verifyFormat("struct test demo[] = {\n" 19242 " {56, 23, \"hello\"},\n" 19243 " {-1, 93463, \"world\"},\n" 19244 " { 7, 5, \"!!\"}\n" 19245 "};\n" 19246 "struct test demo[4] = {\n" 19247 " { 56, 23, 21, \"oh\"}, // first line\n" 19248 " { -1, 93463, 22, \"my\"}, // second line\n" 19249 " { 7, 5, 1, \"goodness\"} // third line\n" 19250 " {234, 5, 1, \"gracious\"} // fourth line\n" 19251 "};\n", 19252 Style); 19253 EXPECT_EQ( 19254 "test demo[] = {\n" 19255 " {56,\n" 19256 " \"hello world i am a very long line that really, in any just world" 19257 ", ought to be split over \"\n" 19258 " \"multiple lines\", 23},\n" 19259 " {-1, \"world\", 93463},\n" 19260 " { 7, \"!!\", 5},\n" 19261 "};", 19262 format("test demo[] = {{56, \"hello world i am a very long line " 19263 "that really, in any just world, ought to be split over multiple " 19264 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19265 Style)); 19266 } 19267 19268 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19269 auto Style = getLLVMStyle(); 19270 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19271 /* FIXME: This case gets misformatted. 19272 verifyFormat("auto foo = Items{\n" 19273 " Section{0, bar(), },\n" 19274 " Section{1, boo() }\n" 19275 "};\n", 19276 Style); 19277 */ 19278 verifyFormat("auto foo = Items{\n" 19279 " Section{\n" 19280 " 0, bar(),\n" 19281 " }\n" 19282 "};\n", 19283 Style); 19284 verifyFormat("struct test demo[] = {\n" 19285 " {56, 23, \"hello\"},\n" 19286 " {-1, 93463, \"world\"},\n" 19287 " {7, 5, \"!!\" }\n" 19288 "};\n", 19289 Style); 19290 verifyFormat("struct test demo[] = {\n" 19291 " {56, 23, \"hello\"}, // first line\n" 19292 " {-1, 93463, \"world\"}, // second line\n" 19293 " {7, 5, \"!!\" } // third line\n" 19294 "};\n", 19295 Style); 19296 verifyFormat("struct test demo[4] = {\n" 19297 " {56, 23, 21, \"oh\" }, // first line\n" 19298 " {-1, 93463, 22, \"my\" }, // second line\n" 19299 " {7, 5, 1, \"goodness\"} // third line\n" 19300 " {234, 5, 1, \"gracious\"} // fourth line\n" 19301 "};\n", 19302 Style); 19303 verifyFormat("struct test demo[3] = {\n" 19304 " {56, 23, \"hello\"},\n" 19305 " {-1, 93463, \"world\"},\n" 19306 " {7, 5, \"!!\" }\n" 19307 "};\n", 19308 Style); 19309 19310 verifyFormat("struct test demo[3] = {\n" 19311 " {int{56}, 23, \"hello\"},\n" 19312 " {int{-1}, 93463, \"world\"},\n" 19313 " {int{7}, 5, \"!!\" }\n" 19314 "};\n", 19315 Style); 19316 verifyFormat("struct test demo[] = {\n" 19317 " {56, 23, \"hello\"},\n" 19318 " {-1, 93463, \"world\"},\n" 19319 " {7, 5, \"!!\" },\n" 19320 "};\n", 19321 Style); 19322 verifyFormat("test demo[] = {\n" 19323 " {56, 23, \"hello\"},\n" 19324 " {-1, 93463, \"world\"},\n" 19325 " {7, 5, \"!!\" },\n" 19326 "};\n", 19327 Style); 19328 verifyFormat("demo = std::array<struct test, 3>{\n" 19329 " test{56, 23, \"hello\"},\n" 19330 " test{-1, 93463, \"world\"},\n" 19331 " test{7, 5, \"!!\" },\n" 19332 "};\n", 19333 Style); 19334 verifyFormat("test demo[] = {\n" 19335 " {56, 23, \"hello\"},\n" 19336 "#if X\n" 19337 " {-1, 93463, \"world\"},\n" 19338 "#endif\n" 19339 " {7, 5, \"!!\" }\n" 19340 "};\n", 19341 Style); 19342 verifyFormat( 19343 "test demo[] = {\n" 19344 " {7, 23,\n" 19345 " \"hello world i am a very long line that really, in any\"\n" 19346 " \"just world, ought to be split over multiple lines\"},\n" 19347 " {-1, 93463, \"world\" },\n" 19348 " {56, 5, \"!!\" }\n" 19349 "};\n", 19350 Style); 19351 19352 verifyFormat("return GradForUnaryCwise(g, {\n" 19353 " {{\"sign\"}, \"Sign\", {\"x\", " 19354 "\"dy\"} },\n" 19355 " {{\"dx\"}, \"Mul\", " 19356 "{\"dy\", \"sign\"}},\n" 19357 "});\n", 19358 Style); 19359 19360 Style.ColumnLimit = 0; 19361 EXPECT_EQ( 19362 "test demo[] = {\n" 19363 " {56, 23, \"hello world i am a very long line that really, in any " 19364 "just world, ought to be split over multiple lines\"},\n" 19365 " {-1, 93463, \"world\" " 19366 " },\n" 19367 " {7, 5, \"!!\" " 19368 " },\n" 19369 "};", 19370 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19371 "that really, in any just world, ought to be split over multiple " 19372 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19373 Style)); 19374 19375 Style.ColumnLimit = 80; 19376 verifyFormat("test demo[] = {\n" 19377 " {56, 23, /* a comment */ \"hello\"},\n" 19378 " {-1, 93463, \"world\" },\n" 19379 " {7, 5, \"!!\" }\n" 19380 "};\n", 19381 Style); 19382 19383 verifyFormat("test demo[] = {\n" 19384 " {56, 23, \"hello\" },\n" 19385 " {-1, 93463, \"world\" /* comment here */},\n" 19386 " {7, 5, \"!!\" }\n" 19387 "};\n", 19388 Style); 19389 19390 verifyFormat("test demo[] = {\n" 19391 " {56, /* a comment */ 23, \"hello\"},\n" 19392 " {-1, 93463, \"world\"},\n" 19393 " {7, 5, \"!!\" }\n" 19394 "};\n", 19395 Style); 19396 19397 Style.ColumnLimit = 20; 19398 EXPECT_EQ( 19399 "demo = std::array<\n" 19400 " struct test, 3>{\n" 19401 " test{\n" 19402 " 56, 23,\n" 19403 " \"hello \"\n" 19404 " \"world i \"\n" 19405 " \"am a very \"\n" 19406 " \"long line \"\n" 19407 " \"that \"\n" 19408 " \"really, \"\n" 19409 " \"in any \"\n" 19410 " \"just \"\n" 19411 " \"world, \"\n" 19412 " \"ought to \"\n" 19413 " \"be split \"\n" 19414 " \"over \"\n" 19415 " \"multiple \"\n" 19416 " \"lines\"},\n" 19417 " test{-1, 93463,\n" 19418 " \"world\"},\n" 19419 " test{7, 5,\n" 19420 " \"!!\" },\n" 19421 "};", 19422 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19423 "i am a very long line that really, in any just world, ought " 19424 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19425 "test{7, 5, \"!!\"},};", 19426 Style)); 19427 19428 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19429 Style = getLLVMStyleWithColumns(50); 19430 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19431 verifyFormat("static A x = {\n" 19432 " {{init1, init2, init3, init4},\n" 19433 " {init1, init2, init3, init4}}\n" 19434 "};", 19435 Style); 19436 Style.ColumnLimit = 100; 19437 EXPECT_EQ( 19438 "test demo[] = {\n" 19439 " {56, 23,\n" 19440 " \"hello world i am a very long line that really, in any just world" 19441 ", ought to be split over \"\n" 19442 " \"multiple lines\" },\n" 19443 " {-1, 93463, \"world\"},\n" 19444 " {7, 5, \"!!\" },\n" 19445 "};", 19446 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19447 "that really, in any just world, ought to be split over multiple " 19448 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19449 Style)); 19450 } 19451 19452 TEST_F(FormatTest, UnderstandsPragmas) { 19453 verifyFormat("#pragma omp reduction(| : var)"); 19454 verifyFormat("#pragma omp reduction(+ : var)"); 19455 19456 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19457 "(including parentheses).", 19458 format("#pragma mark Any non-hyphenated or hyphenated string " 19459 "(including parentheses).")); 19460 } 19461 19462 TEST_F(FormatTest, UnderstandPragmaOption) { 19463 verifyFormat("#pragma option -C -A"); 19464 19465 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19466 } 19467 19468 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19469 FormatStyle Style = getLLVMStyleWithColumns(20); 19470 19471 // See PR41213 19472 EXPECT_EQ("/*\n" 19473 " *\t9012345\n" 19474 " * /8901\n" 19475 " */", 19476 format("/*\n" 19477 " *\t9012345 /8901\n" 19478 " */", 19479 Style)); 19480 EXPECT_EQ("/*\n" 19481 " *345678\n" 19482 " *\t/8901\n" 19483 " */", 19484 format("/*\n" 19485 " *345678\t/8901\n" 19486 " */", 19487 Style)); 19488 19489 verifyFormat("int a; // the\n" 19490 " // comment", 19491 Style); 19492 EXPECT_EQ("int a; /* first line\n" 19493 " * second\n" 19494 " * line third\n" 19495 " * line\n" 19496 " */", 19497 format("int a; /* first line\n" 19498 " * second\n" 19499 " * line third\n" 19500 " * line\n" 19501 " */", 19502 Style)); 19503 EXPECT_EQ("int a; // first line\n" 19504 " // second\n" 19505 " // line third\n" 19506 " // line", 19507 format("int a; // first line\n" 19508 " // second line\n" 19509 " // third line", 19510 Style)); 19511 19512 Style.PenaltyExcessCharacter = 90; 19513 verifyFormat("int a; // the comment", Style); 19514 EXPECT_EQ("int a; // the comment\n" 19515 " // aaa", 19516 format("int a; // the comment aaa", Style)); 19517 EXPECT_EQ("int a; /* first line\n" 19518 " * second line\n" 19519 " * third line\n" 19520 " */", 19521 format("int a; /* first line\n" 19522 " * second line\n" 19523 " * third line\n" 19524 " */", 19525 Style)); 19526 EXPECT_EQ("int a; // first line\n" 19527 " // second line\n" 19528 " // third line", 19529 format("int a; // first line\n" 19530 " // second line\n" 19531 " // third line", 19532 Style)); 19533 // FIXME: Investigate why this is not getting the same layout as the test 19534 // above. 19535 EXPECT_EQ("int a; /* first line\n" 19536 " * second line\n" 19537 " * third line\n" 19538 " */", 19539 format("int a; /* first line second line third line" 19540 "\n*/", 19541 Style)); 19542 19543 EXPECT_EQ("// foo bar baz bazfoo\n" 19544 "// foo bar foo bar\n", 19545 format("// foo bar baz bazfoo\n" 19546 "// foo bar foo bar\n", 19547 Style)); 19548 EXPECT_EQ("// foo bar baz bazfoo\n" 19549 "// foo bar foo bar\n", 19550 format("// foo bar baz bazfoo\n" 19551 "// foo bar foo bar\n", 19552 Style)); 19553 19554 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19555 // next one. 19556 EXPECT_EQ("// foo bar baz bazfoo\n" 19557 "// bar foo bar\n", 19558 format("// foo bar baz bazfoo bar\n" 19559 "// foo bar\n", 19560 Style)); 19561 19562 EXPECT_EQ("// foo bar baz bazfoo\n" 19563 "// foo bar baz bazfoo\n" 19564 "// bar foo bar\n", 19565 format("// foo bar baz bazfoo\n" 19566 "// foo bar baz bazfoo bar\n" 19567 "// foo bar\n", 19568 Style)); 19569 19570 EXPECT_EQ("// foo bar baz bazfoo\n" 19571 "// foo bar baz bazfoo\n" 19572 "// bar foo bar\n", 19573 format("// foo bar baz bazfoo\n" 19574 "// foo bar baz bazfoo bar\n" 19575 "// foo bar\n", 19576 Style)); 19577 19578 // Make sure we do not keep protruding characters if strict mode reflow is 19579 // cheaper than keeping protruding characters. 19580 Style.ColumnLimit = 21; 19581 EXPECT_EQ( 19582 "// foo foo foo foo\n" 19583 "// foo foo foo foo\n" 19584 "// foo foo foo foo\n", 19585 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19586 19587 EXPECT_EQ("int a = /* long block\n" 19588 " comment */\n" 19589 " 42;", 19590 format("int a = /* long block comment */ 42;", Style)); 19591 } 19592 19593 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19594 FormatStyle Style = getLLVMStyle(); 19595 Style.ColumnLimit = 8; 19596 Style.PenaltyExcessCharacter = 15; 19597 verifyFormat("int foo(\n" 19598 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19599 Style); 19600 Style.PenaltyBreakOpenParenthesis = 200; 19601 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19602 format("int foo(\n" 19603 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19604 Style)); 19605 } 19606 19607 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19608 FormatStyle Style = getLLVMStyle(); 19609 Style.ColumnLimit = 5; 19610 Style.PenaltyExcessCharacter = 150; 19611 verifyFormat("foo((\n" 19612 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19613 19614 Style); 19615 Style.PenaltyBreakOpenParenthesis = 100000; 19616 EXPECT_EQ("foo((int)\n" 19617 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19618 format("foo((\n" 19619 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19620 Style)); 19621 } 19622 19623 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19624 FormatStyle Style = getLLVMStyle(); 19625 Style.ColumnLimit = 4; 19626 Style.PenaltyExcessCharacter = 100; 19627 verifyFormat("for (\n" 19628 " int iiiiiiiiiiiiiiiii =\n" 19629 " 0;\n" 19630 " iiiiiiiiiiiiiiiii <\n" 19631 " 2;\n" 19632 " iiiiiiiiiiiiiiiii++) {\n" 19633 "}", 19634 19635 Style); 19636 Style.PenaltyBreakOpenParenthesis = 1250; 19637 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19638 " 0;\n" 19639 " iiiiiiiiiiiiiiiii <\n" 19640 " 2;\n" 19641 " iiiiiiiiiiiiiiiii++) {\n" 19642 "}", 19643 format("for (\n" 19644 " int iiiiiiiiiiiiiiiii =\n" 19645 " 0;\n" 19646 " iiiiiiiiiiiiiiiii <\n" 19647 " 2;\n" 19648 " iiiiiiiiiiiiiiiii++) {\n" 19649 "}", 19650 Style)); 19651 } 19652 19653 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19654 for (size_t i = 1; i < Styles.size(); ++i) \ 19655 EXPECT_EQ(Styles[0], Styles[i]) \ 19656 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19657 19658 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19659 SmallVector<FormatStyle, 3> Styles; 19660 Styles.resize(3); 19661 19662 Styles[0] = getLLVMStyle(); 19663 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19664 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19665 EXPECT_ALL_STYLES_EQUAL(Styles); 19666 19667 Styles[0] = getGoogleStyle(); 19668 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19669 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19670 EXPECT_ALL_STYLES_EQUAL(Styles); 19671 19672 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19673 EXPECT_TRUE( 19674 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19675 EXPECT_TRUE( 19676 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19677 EXPECT_ALL_STYLES_EQUAL(Styles); 19678 19679 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19680 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19681 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19682 EXPECT_ALL_STYLES_EQUAL(Styles); 19683 19684 Styles[0] = getMozillaStyle(); 19685 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19686 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19687 EXPECT_ALL_STYLES_EQUAL(Styles); 19688 19689 Styles[0] = getWebKitStyle(); 19690 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19691 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19692 EXPECT_ALL_STYLES_EQUAL(Styles); 19693 19694 Styles[0] = getGNUStyle(); 19695 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19696 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19697 EXPECT_ALL_STYLES_EQUAL(Styles); 19698 19699 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19700 } 19701 19702 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19703 SmallVector<FormatStyle, 8> Styles; 19704 Styles.resize(2); 19705 19706 Styles[0] = getGoogleStyle(); 19707 Styles[1] = getLLVMStyle(); 19708 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19709 EXPECT_ALL_STYLES_EQUAL(Styles); 19710 19711 Styles.resize(5); 19712 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19713 Styles[1] = getLLVMStyle(); 19714 Styles[1].Language = FormatStyle::LK_JavaScript; 19715 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19716 19717 Styles[2] = getLLVMStyle(); 19718 Styles[2].Language = FormatStyle::LK_JavaScript; 19719 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19720 "BasedOnStyle: Google", 19721 &Styles[2]) 19722 .value()); 19723 19724 Styles[3] = getLLVMStyle(); 19725 Styles[3].Language = FormatStyle::LK_JavaScript; 19726 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19727 "Language: JavaScript", 19728 &Styles[3]) 19729 .value()); 19730 19731 Styles[4] = getLLVMStyle(); 19732 Styles[4].Language = FormatStyle::LK_JavaScript; 19733 EXPECT_EQ(0, parseConfiguration("---\n" 19734 "BasedOnStyle: LLVM\n" 19735 "IndentWidth: 123\n" 19736 "---\n" 19737 "BasedOnStyle: Google\n" 19738 "Language: JavaScript", 19739 &Styles[4]) 19740 .value()); 19741 EXPECT_ALL_STYLES_EQUAL(Styles); 19742 } 19743 19744 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19745 Style.FIELD = false; \ 19746 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19747 EXPECT_TRUE(Style.FIELD); \ 19748 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19749 EXPECT_FALSE(Style.FIELD); 19750 19751 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19752 19753 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19754 Style.STRUCT.FIELD = false; \ 19755 EXPECT_EQ(0, \ 19756 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19757 .value()); \ 19758 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19759 EXPECT_EQ(0, \ 19760 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19761 .value()); \ 19762 EXPECT_FALSE(Style.STRUCT.FIELD); 19763 19764 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19765 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19766 19767 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19768 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19769 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19770 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19771 19772 TEST_F(FormatTest, ParsesConfigurationBools) { 19773 FormatStyle Style = {}; 19774 Style.Language = FormatStyle::LK_Cpp; 19775 CHECK_PARSE_BOOL(AlignTrailingComments); 19776 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19777 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19778 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19779 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19780 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19781 CHECK_PARSE_BOOL(BinPackArguments); 19782 CHECK_PARSE_BOOL(BinPackParameters); 19783 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19784 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19785 CHECK_PARSE_BOOL(BreakStringLiterals); 19786 CHECK_PARSE_BOOL(CompactNamespaces); 19787 CHECK_PARSE_BOOL(DeriveLineEnding); 19788 CHECK_PARSE_BOOL(DerivePointerAlignment); 19789 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19790 CHECK_PARSE_BOOL(DisableFormat); 19791 CHECK_PARSE_BOOL(IndentAccessModifiers); 19792 CHECK_PARSE_BOOL(IndentCaseLabels); 19793 CHECK_PARSE_BOOL(IndentCaseBlocks); 19794 CHECK_PARSE_BOOL(IndentGotoLabels); 19795 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19796 CHECK_PARSE_BOOL(IndentRequiresClause); 19797 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19798 CHECK_PARSE_BOOL(InsertBraces); 19799 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19800 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19801 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19802 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19803 CHECK_PARSE_BOOL(ReflowComments); 19804 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19805 CHECK_PARSE_BOOL(SortUsingDeclarations); 19806 CHECK_PARSE_BOOL(SpacesInParentheses); 19807 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19808 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19809 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19810 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19811 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19812 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19813 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19814 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19815 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19816 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19817 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19818 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19819 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19820 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19821 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19822 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19823 CHECK_PARSE_BOOL(UseCRLF); 19824 19825 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19826 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19827 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19828 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19829 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19830 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19831 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19832 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19833 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19834 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19835 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19836 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19837 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19838 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19839 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19840 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19841 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19842 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19843 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19844 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19845 AfterFunctionDeclarationName); 19846 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19847 AfterFunctionDefinitionName); 19848 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19849 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19850 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19851 } 19852 19853 #undef CHECK_PARSE_BOOL 19854 19855 TEST_F(FormatTest, ParsesConfiguration) { 19856 FormatStyle Style = {}; 19857 Style.Language = FormatStyle::LK_Cpp; 19858 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19859 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19860 ConstructorInitializerIndentWidth, 1234u); 19861 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19862 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19863 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19864 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19865 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19866 PenaltyBreakBeforeFirstCallParameter, 1234u); 19867 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19868 PenaltyBreakTemplateDeclaration, 1234u); 19869 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19870 1234u); 19871 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19872 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19873 PenaltyReturnTypeOnItsOwnLine, 1234u); 19874 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19875 SpacesBeforeTrailingComments, 1234u); 19876 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19877 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19878 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19879 19880 Style.QualifierAlignment = FormatStyle::QAS_Right; 19881 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19882 FormatStyle::QAS_Leave); 19883 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19884 FormatStyle::QAS_Right); 19885 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19886 FormatStyle::QAS_Left); 19887 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19888 FormatStyle::QAS_Custom); 19889 19890 Style.QualifierOrder.clear(); 19891 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19892 std::vector<std::string>({"const", "volatile", "type"})); 19893 Style.QualifierOrder.clear(); 19894 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19895 std::vector<std::string>({"const", "type"})); 19896 Style.QualifierOrder.clear(); 19897 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19898 std::vector<std::string>({"volatile", "type"})); 19899 19900 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 19901 do { \ 19902 Style.FIELD.Enabled = true; \ 19903 CHECK_PARSE(#FIELD ": None", FIELD, \ 19904 FormatStyle::AlignConsecutiveStyle( \ 19905 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19906 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19907 /*PadOperators=*/true})); \ 19908 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 19909 FormatStyle::AlignConsecutiveStyle( \ 19910 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19911 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19912 /*PadOperators=*/true})); \ 19913 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 19914 FormatStyle::AlignConsecutiveStyle( \ 19915 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19916 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19917 /*PadOperators=*/true})); \ 19918 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 19919 FormatStyle::AlignConsecutiveStyle( \ 19920 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19921 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 19922 /*PadOperators=*/true})); \ 19923 /* For backwards compability, false / true should still parse */ \ 19924 CHECK_PARSE(#FIELD ": false", FIELD, \ 19925 FormatStyle::AlignConsecutiveStyle( \ 19926 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19927 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19928 /*PadOperators=*/true})); \ 19929 CHECK_PARSE(#FIELD ": true", FIELD, \ 19930 FormatStyle::AlignConsecutiveStyle( \ 19931 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19932 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19933 /*PadOperators=*/true})); \ 19934 \ 19935 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 19936 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 19937 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 19938 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 19939 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 19940 } while (false) 19941 19942 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 19943 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 19944 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 19945 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 19946 19947 #undef CHECK_ALIGN_CONSECUTIVE 19948 19949 Style.PointerAlignment = FormatStyle::PAS_Middle; 19950 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19951 FormatStyle::PAS_Left); 19952 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19953 FormatStyle::PAS_Right); 19954 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19955 FormatStyle::PAS_Middle); 19956 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19957 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19958 FormatStyle::RAS_Pointer); 19959 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19960 FormatStyle::RAS_Left); 19961 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19962 FormatStyle::RAS_Right); 19963 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19964 FormatStyle::RAS_Middle); 19965 // For backward compatibility: 19966 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19967 FormatStyle::PAS_Left); 19968 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19969 FormatStyle::PAS_Right); 19970 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19971 FormatStyle::PAS_Middle); 19972 19973 Style.Standard = FormatStyle::LS_Auto; 19974 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19975 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19976 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19977 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19978 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19979 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19980 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19981 // Legacy aliases: 19982 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19983 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19984 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19985 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19986 19987 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19988 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19989 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19990 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19991 FormatStyle::BOS_None); 19992 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19993 FormatStyle::BOS_All); 19994 // For backward compatibility: 19995 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19996 FormatStyle::BOS_None); 19997 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19998 FormatStyle::BOS_All); 19999 20000 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20001 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20002 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20003 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20004 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20005 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20006 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20007 // For backward compatibility: 20008 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20009 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20010 20011 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20012 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20013 FormatStyle::BILS_AfterComma); 20014 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20015 FormatStyle::BILS_BeforeComma); 20016 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20017 FormatStyle::BILS_AfterColon); 20018 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20019 FormatStyle::BILS_BeforeColon); 20020 // For backward compatibility: 20021 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20022 FormatStyle::BILS_BeforeComma); 20023 20024 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20025 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20026 FormatStyle::PCIS_Never); 20027 CHECK_PARSE("PackConstructorInitializers: BinPack", 20028 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20029 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20030 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20031 CHECK_PARSE("PackConstructorInitializers: NextLine", 20032 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20033 // For backward compatibility: 20034 CHECK_PARSE("BasedOnStyle: Google\n" 20035 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20036 "AllowAllConstructorInitializersOnNextLine: false", 20037 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20038 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20039 CHECK_PARSE("BasedOnStyle: Google\n" 20040 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20041 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20042 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20043 "AllowAllConstructorInitializersOnNextLine: true", 20044 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20045 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20046 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20047 "AllowAllConstructorInitializersOnNextLine: false", 20048 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20049 20050 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20051 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20052 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20053 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20054 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20055 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20056 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20057 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20058 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20059 20060 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20061 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20062 FormatStyle::BAS_Align); 20063 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20064 FormatStyle::BAS_DontAlign); 20065 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20066 FormatStyle::BAS_AlwaysBreak); 20067 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20068 FormatStyle::BAS_BlockIndent); 20069 // For backward compatibility: 20070 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20071 FormatStyle::BAS_DontAlign); 20072 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20073 FormatStyle::BAS_Align); 20074 20075 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20076 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20077 FormatStyle::ENAS_DontAlign); 20078 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20079 FormatStyle::ENAS_Left); 20080 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20081 FormatStyle::ENAS_Right); 20082 // For backward compatibility: 20083 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20084 FormatStyle::ENAS_Left); 20085 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20086 FormatStyle::ENAS_Right); 20087 20088 Style.AlignOperands = FormatStyle::OAS_Align; 20089 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20090 FormatStyle::OAS_DontAlign); 20091 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20092 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20093 FormatStyle::OAS_AlignAfterOperator); 20094 // For backward compatibility: 20095 CHECK_PARSE("AlignOperands: false", AlignOperands, 20096 FormatStyle::OAS_DontAlign); 20097 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20098 20099 Style.UseTab = FormatStyle::UT_ForIndentation; 20100 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20101 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20102 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20103 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20104 FormatStyle::UT_ForContinuationAndIndentation); 20105 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20106 FormatStyle::UT_AlignWithSpaces); 20107 // For backward compatibility: 20108 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20109 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20110 20111 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20112 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20113 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20114 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20115 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20116 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20117 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20118 // For backward compatibility: 20119 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20120 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20121 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20122 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20123 20124 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20125 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20126 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20127 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20128 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20129 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20130 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20131 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20132 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20133 // For backward compatibility: 20134 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20135 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20136 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20137 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20138 20139 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20140 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20141 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20142 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20143 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20144 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20145 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20146 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20147 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20148 20149 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20150 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20151 FormatStyle::SBPO_Never); 20152 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20153 FormatStyle::SBPO_Always); 20154 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20155 FormatStyle::SBPO_ControlStatements); 20156 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20157 SpaceBeforeParens, 20158 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20159 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20160 FormatStyle::SBPO_NonEmptyParentheses); 20161 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20162 FormatStyle::SBPO_Custom); 20163 // For backward compatibility: 20164 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20165 FormatStyle::SBPO_Never); 20166 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20167 FormatStyle::SBPO_ControlStatements); 20168 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20169 SpaceBeforeParens, 20170 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20171 20172 Style.ColumnLimit = 123; 20173 FormatStyle BaseStyle = getLLVMStyle(); 20174 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20175 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20176 20177 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20178 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20179 FormatStyle::BS_Attach); 20180 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20181 FormatStyle::BS_Linux); 20182 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20183 FormatStyle::BS_Mozilla); 20184 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20185 FormatStyle::BS_Stroustrup); 20186 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20187 FormatStyle::BS_Allman); 20188 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20189 FormatStyle::BS_Whitesmiths); 20190 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20191 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20192 FormatStyle::BS_WebKit); 20193 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20194 FormatStyle::BS_Custom); 20195 20196 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20197 CHECK_PARSE("BraceWrapping:\n" 20198 " AfterControlStatement: MultiLine", 20199 BraceWrapping.AfterControlStatement, 20200 FormatStyle::BWACS_MultiLine); 20201 CHECK_PARSE("BraceWrapping:\n" 20202 " AfterControlStatement: Always", 20203 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20204 CHECK_PARSE("BraceWrapping:\n" 20205 " AfterControlStatement: Never", 20206 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20207 // For backward compatibility: 20208 CHECK_PARSE("BraceWrapping:\n" 20209 " AfterControlStatement: true", 20210 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20211 CHECK_PARSE("BraceWrapping:\n" 20212 " AfterControlStatement: false", 20213 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20214 20215 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20216 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20217 FormatStyle::RTBS_None); 20218 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20219 FormatStyle::RTBS_All); 20220 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20221 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20222 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20223 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20224 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20225 AlwaysBreakAfterReturnType, 20226 FormatStyle::RTBS_TopLevelDefinitions); 20227 20228 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20229 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20230 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20231 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20232 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20233 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20234 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20235 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20236 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20237 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20238 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20239 20240 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20241 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20242 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20243 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20244 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20245 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20246 AlwaysBreakAfterDefinitionReturnType, 20247 FormatStyle::DRTBS_TopLevel); 20248 20249 Style.NamespaceIndentation = FormatStyle::NI_All; 20250 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20251 FormatStyle::NI_None); 20252 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20253 FormatStyle::NI_Inner); 20254 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20255 FormatStyle::NI_All); 20256 20257 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20258 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20259 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20260 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20261 AllowShortIfStatementsOnASingleLine, 20262 FormatStyle::SIS_WithoutElse); 20263 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20264 AllowShortIfStatementsOnASingleLine, 20265 FormatStyle::SIS_OnlyFirstIf); 20266 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20267 AllowShortIfStatementsOnASingleLine, 20268 FormatStyle::SIS_AllIfsAndElse); 20269 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20270 AllowShortIfStatementsOnASingleLine, 20271 FormatStyle::SIS_OnlyFirstIf); 20272 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20273 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20274 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20275 AllowShortIfStatementsOnASingleLine, 20276 FormatStyle::SIS_WithoutElse); 20277 20278 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20279 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20280 FormatStyle::IEBS_AfterExternBlock); 20281 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20282 FormatStyle::IEBS_Indent); 20283 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20284 FormatStyle::IEBS_NoIndent); 20285 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20286 FormatStyle::IEBS_Indent); 20287 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20288 FormatStyle::IEBS_NoIndent); 20289 20290 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20291 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20292 FormatStyle::BFCS_Both); 20293 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20294 FormatStyle::BFCS_None); 20295 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20296 FormatStyle::BFCS_Before); 20297 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20298 FormatStyle::BFCS_After); 20299 20300 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20301 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20302 FormatStyle::SJSIO_After); 20303 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20304 FormatStyle::SJSIO_Before); 20305 20306 // FIXME: This is required because parsing a configuration simply overwrites 20307 // the first N elements of the list instead of resetting it. 20308 Style.ForEachMacros.clear(); 20309 std::vector<std::string> BoostForeach; 20310 BoostForeach.push_back("BOOST_FOREACH"); 20311 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20312 std::vector<std::string> BoostAndQForeach; 20313 BoostAndQForeach.push_back("BOOST_FOREACH"); 20314 BoostAndQForeach.push_back("Q_FOREACH"); 20315 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20316 BoostAndQForeach); 20317 20318 Style.IfMacros.clear(); 20319 std::vector<std::string> CustomIfs; 20320 CustomIfs.push_back("MYIF"); 20321 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20322 20323 Style.AttributeMacros.clear(); 20324 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20325 std::vector<std::string>{"__capability"}); 20326 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20327 std::vector<std::string>({"attr1", "attr2"})); 20328 20329 Style.StatementAttributeLikeMacros.clear(); 20330 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20331 StatementAttributeLikeMacros, 20332 std::vector<std::string>({"emit", "Q_EMIT"})); 20333 20334 Style.StatementMacros.clear(); 20335 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20336 std::vector<std::string>{"QUNUSED"}); 20337 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20338 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20339 20340 Style.NamespaceMacros.clear(); 20341 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20342 std::vector<std::string>{"TESTSUITE"}); 20343 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20344 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20345 20346 Style.WhitespaceSensitiveMacros.clear(); 20347 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20348 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20349 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20350 WhitespaceSensitiveMacros, 20351 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20352 Style.WhitespaceSensitiveMacros.clear(); 20353 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20354 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20355 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20356 WhitespaceSensitiveMacros, 20357 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20358 20359 Style.IncludeStyle.IncludeCategories.clear(); 20360 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20361 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20362 CHECK_PARSE("IncludeCategories:\n" 20363 " - Regex: abc/.*\n" 20364 " Priority: 2\n" 20365 " - Regex: .*\n" 20366 " Priority: 1\n" 20367 " CaseSensitive: true\n", 20368 IncludeStyle.IncludeCategories, ExpectedCategories); 20369 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20370 "abc$"); 20371 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20372 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20373 20374 Style.SortIncludes = FormatStyle::SI_Never; 20375 CHECK_PARSE("SortIncludes: true", SortIncludes, 20376 FormatStyle::SI_CaseSensitive); 20377 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20378 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20379 FormatStyle::SI_CaseInsensitive); 20380 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20381 FormatStyle::SI_CaseSensitive); 20382 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20383 20384 Style.RawStringFormats.clear(); 20385 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20386 { 20387 FormatStyle::LK_TextProto, 20388 {"pb", "proto"}, 20389 {"PARSE_TEXT_PROTO"}, 20390 /*CanonicalDelimiter=*/"", 20391 "llvm", 20392 }, 20393 { 20394 FormatStyle::LK_Cpp, 20395 {"cc", "cpp"}, 20396 {"C_CODEBLOCK", "CPPEVAL"}, 20397 /*CanonicalDelimiter=*/"cc", 20398 /*BasedOnStyle=*/"", 20399 }, 20400 }; 20401 20402 CHECK_PARSE("RawStringFormats:\n" 20403 " - Language: TextProto\n" 20404 " Delimiters:\n" 20405 " - 'pb'\n" 20406 " - 'proto'\n" 20407 " EnclosingFunctions:\n" 20408 " - 'PARSE_TEXT_PROTO'\n" 20409 " BasedOnStyle: llvm\n" 20410 " - Language: Cpp\n" 20411 " Delimiters:\n" 20412 " - 'cc'\n" 20413 " - 'cpp'\n" 20414 " EnclosingFunctions:\n" 20415 " - 'C_CODEBLOCK'\n" 20416 " - 'CPPEVAL'\n" 20417 " CanonicalDelimiter: 'cc'", 20418 RawStringFormats, ExpectedRawStringFormats); 20419 20420 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20421 " Minimum: 0\n" 20422 " Maximum: 0", 20423 SpacesInLineCommentPrefix.Minimum, 0u); 20424 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20425 Style.SpacesInLineCommentPrefix.Minimum = 1; 20426 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20427 " Minimum: 2", 20428 SpacesInLineCommentPrefix.Minimum, 0u); 20429 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20430 " Maximum: -1", 20431 SpacesInLineCommentPrefix.Maximum, -1u); 20432 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20433 " Minimum: 2", 20434 SpacesInLineCommentPrefix.Minimum, 2u); 20435 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20436 " Maximum: 1", 20437 SpacesInLineCommentPrefix.Maximum, 1u); 20438 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20439 20440 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20441 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20442 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20443 FormatStyle::SIAS_Always); 20444 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20445 // For backward compatibility: 20446 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20447 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20448 20449 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20450 FormatStyle::RCPS_WithPreceding); 20451 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20452 FormatStyle::RCPS_WithFollowing); 20453 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20454 FormatStyle::RCPS_SingleLine); 20455 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20456 FormatStyle::RCPS_OwnLine); 20457 20458 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20459 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20460 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20461 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20462 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20463 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20464 // For backward compatibility: 20465 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20466 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20467 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20468 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20469 } 20470 20471 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20472 FormatStyle Style = {}; 20473 Style.Language = FormatStyle::LK_Cpp; 20474 CHECK_PARSE("Language: Cpp\n" 20475 "IndentWidth: 12", 20476 IndentWidth, 12u); 20477 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20478 "IndentWidth: 34", 20479 &Style), 20480 ParseError::Unsuitable); 20481 FormatStyle BinPackedTCS = {}; 20482 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20483 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20484 "InsertTrailingCommas: Wrapped", 20485 &BinPackedTCS), 20486 ParseError::BinPackTrailingCommaConflict); 20487 EXPECT_EQ(12u, Style.IndentWidth); 20488 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20489 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20490 20491 Style.Language = FormatStyle::LK_JavaScript; 20492 CHECK_PARSE("Language: JavaScript\n" 20493 "IndentWidth: 12", 20494 IndentWidth, 12u); 20495 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20496 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20497 "IndentWidth: 34", 20498 &Style), 20499 ParseError::Unsuitable); 20500 EXPECT_EQ(23u, Style.IndentWidth); 20501 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20502 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20503 20504 CHECK_PARSE("BasedOnStyle: LLVM\n" 20505 "IndentWidth: 67", 20506 IndentWidth, 67u); 20507 20508 CHECK_PARSE("---\n" 20509 "Language: JavaScript\n" 20510 "IndentWidth: 12\n" 20511 "---\n" 20512 "Language: Cpp\n" 20513 "IndentWidth: 34\n" 20514 "...\n", 20515 IndentWidth, 12u); 20516 20517 Style.Language = FormatStyle::LK_Cpp; 20518 CHECK_PARSE("---\n" 20519 "Language: JavaScript\n" 20520 "IndentWidth: 12\n" 20521 "---\n" 20522 "Language: Cpp\n" 20523 "IndentWidth: 34\n" 20524 "...\n", 20525 IndentWidth, 34u); 20526 CHECK_PARSE("---\n" 20527 "IndentWidth: 78\n" 20528 "---\n" 20529 "Language: JavaScript\n" 20530 "IndentWidth: 56\n" 20531 "...\n", 20532 IndentWidth, 78u); 20533 20534 Style.ColumnLimit = 123; 20535 Style.IndentWidth = 234; 20536 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20537 Style.TabWidth = 345; 20538 EXPECT_FALSE(parseConfiguration("---\n" 20539 "IndentWidth: 456\n" 20540 "BreakBeforeBraces: Allman\n" 20541 "---\n" 20542 "Language: JavaScript\n" 20543 "IndentWidth: 111\n" 20544 "TabWidth: 111\n" 20545 "---\n" 20546 "Language: Cpp\n" 20547 "BreakBeforeBraces: Stroustrup\n" 20548 "TabWidth: 789\n" 20549 "...\n", 20550 &Style)); 20551 EXPECT_EQ(123u, Style.ColumnLimit); 20552 EXPECT_EQ(456u, Style.IndentWidth); 20553 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20554 EXPECT_EQ(789u, Style.TabWidth); 20555 20556 EXPECT_EQ(parseConfiguration("---\n" 20557 "Language: JavaScript\n" 20558 "IndentWidth: 56\n" 20559 "---\n" 20560 "IndentWidth: 78\n" 20561 "...\n", 20562 &Style), 20563 ParseError::Error); 20564 EXPECT_EQ(parseConfiguration("---\n" 20565 "Language: JavaScript\n" 20566 "IndentWidth: 56\n" 20567 "---\n" 20568 "Language: JavaScript\n" 20569 "IndentWidth: 78\n" 20570 "...\n", 20571 &Style), 20572 ParseError::Error); 20573 20574 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20575 } 20576 20577 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20578 FormatStyle Style = {}; 20579 Style.Language = FormatStyle::LK_JavaScript; 20580 Style.BreakBeforeTernaryOperators = true; 20581 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20582 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20583 20584 Style.BreakBeforeTernaryOperators = true; 20585 EXPECT_EQ(0, parseConfiguration("---\n" 20586 "BasedOnStyle: Google\n" 20587 "---\n" 20588 "Language: JavaScript\n" 20589 "IndentWidth: 76\n" 20590 "...\n", 20591 &Style) 20592 .value()); 20593 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20594 EXPECT_EQ(76u, Style.IndentWidth); 20595 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20596 } 20597 20598 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20599 FormatStyle Style = getLLVMStyle(); 20600 std::string YAML = configurationAsText(Style); 20601 FormatStyle ParsedStyle = {}; 20602 ParsedStyle.Language = FormatStyle::LK_Cpp; 20603 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20604 EXPECT_EQ(Style, ParsedStyle); 20605 } 20606 20607 TEST_F(FormatTest, WorksFor8bitEncodings) { 20608 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20609 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20610 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20611 "\"\xef\xee\xf0\xf3...\"", 20612 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20613 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20614 "\xef\xee\xf0\xf3...\"", 20615 getLLVMStyleWithColumns(12))); 20616 } 20617 20618 TEST_F(FormatTest, HandlesUTF8BOM) { 20619 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20620 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20621 format("\xef\xbb\xbf#include <iostream>")); 20622 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20623 format("\xef\xbb\xbf\n#include <iostream>")); 20624 } 20625 20626 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20627 #if !defined(_MSC_VER) 20628 20629 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20630 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20631 getLLVMStyleWithColumns(35)); 20632 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20633 getLLVMStyleWithColumns(31)); 20634 verifyFormat("// Однажды в студёную зимнюю пору...", 20635 getLLVMStyleWithColumns(36)); 20636 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20637 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20638 getLLVMStyleWithColumns(39)); 20639 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20640 getLLVMStyleWithColumns(35)); 20641 } 20642 20643 TEST_F(FormatTest, SplitsUTF8Strings) { 20644 // Non-printable characters' width is currently considered to be the length in 20645 // bytes in UTF8. The characters can be displayed in very different manner 20646 // (zero-width, single width with a substitution glyph, expanded to their code 20647 // (e.g. "<8d>"), so there's no single correct way to handle them. 20648 EXPECT_EQ("\"aaaaÄ\"\n" 20649 "\"\xc2\x8d\";", 20650 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20651 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20652 "\"\xc2\x8d\";", 20653 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20654 EXPECT_EQ("\"Однажды, в \"\n" 20655 "\"студёную \"\n" 20656 "\"зимнюю \"\n" 20657 "\"пору,\"", 20658 format("\"Однажды, в студёную зимнюю пору,\"", 20659 getLLVMStyleWithColumns(13))); 20660 EXPECT_EQ( 20661 "\"一 二 三 \"\n" 20662 "\"四 五六 \"\n" 20663 "\"七 八 九 \"\n" 20664 "\"十\"", 20665 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20666 EXPECT_EQ("\"一\t\"\n" 20667 "\"二 \t\"\n" 20668 "\"三 四 \"\n" 20669 "\"五\t\"\n" 20670 "\"六 \t\"\n" 20671 "\"七 \"\n" 20672 "\"八九十\tqq\"", 20673 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20674 getLLVMStyleWithColumns(11))); 20675 20676 // UTF8 character in an escape sequence. 20677 EXPECT_EQ("\"aaaaaa\"\n" 20678 "\"\\\xC2\x8D\"", 20679 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20680 } 20681 20682 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20683 EXPECT_EQ("const char *sssss =\n" 20684 " \"一二三四五六七八\\\n" 20685 " 九 十\";", 20686 format("const char *sssss = \"一二三四五六七八\\\n" 20687 " 九 十\";", 20688 getLLVMStyleWithColumns(30))); 20689 } 20690 20691 TEST_F(FormatTest, SplitsUTF8LineComments) { 20692 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20693 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20694 EXPECT_EQ("// Я из лесу\n" 20695 "// вышел; был\n" 20696 "// сильный\n" 20697 "// мороз.", 20698 format("// Я из лесу вышел; был сильный мороз.", 20699 getLLVMStyleWithColumns(13))); 20700 EXPECT_EQ("// 一二三\n" 20701 "// 四五六七\n" 20702 "// 八 九\n" 20703 "// 十", 20704 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20705 } 20706 20707 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20708 EXPECT_EQ("/* Гляжу,\n" 20709 " * поднимается\n" 20710 " * медленно в\n" 20711 " * гору\n" 20712 " * Лошадка,\n" 20713 " * везущая\n" 20714 " * хворосту\n" 20715 " * воз. */", 20716 format("/* Гляжу, поднимается медленно в гору\n" 20717 " * Лошадка, везущая хворосту воз. */", 20718 getLLVMStyleWithColumns(13))); 20719 EXPECT_EQ( 20720 "/* 一二三\n" 20721 " * 四五六七\n" 20722 " * 八 九\n" 20723 " * 十 */", 20724 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20725 EXPECT_EQ("/* \n" 20726 " * \n" 20727 " * - */", 20728 format("/* - */", getLLVMStyleWithColumns(12))); 20729 } 20730 20731 #endif // _MSC_VER 20732 20733 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20734 FormatStyle Style = getLLVMStyle(); 20735 20736 Style.ConstructorInitializerIndentWidth = 4; 20737 verifyFormat( 20738 "SomeClass::Constructor()\n" 20739 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20740 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20741 Style); 20742 20743 Style.ConstructorInitializerIndentWidth = 2; 20744 verifyFormat( 20745 "SomeClass::Constructor()\n" 20746 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20747 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20748 Style); 20749 20750 Style.ConstructorInitializerIndentWidth = 0; 20751 verifyFormat( 20752 "SomeClass::Constructor()\n" 20753 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20754 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20755 Style); 20756 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20757 verifyFormat( 20758 "SomeLongTemplateVariableName<\n" 20759 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20760 Style); 20761 verifyFormat("bool smaller = 1 < " 20762 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20763 " " 20764 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20765 Style); 20766 20767 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20768 verifyFormat("SomeClass::Constructor() :\n" 20769 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20770 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20771 Style); 20772 } 20773 20774 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20775 FormatStyle Style = getLLVMStyle(); 20776 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20777 Style.ConstructorInitializerIndentWidth = 4; 20778 verifyFormat("SomeClass::Constructor()\n" 20779 " : a(a)\n" 20780 " , b(b)\n" 20781 " , c(c) {}", 20782 Style); 20783 verifyFormat("SomeClass::Constructor()\n" 20784 " : a(a) {}", 20785 Style); 20786 20787 Style.ColumnLimit = 0; 20788 verifyFormat("SomeClass::Constructor()\n" 20789 " : a(a) {}", 20790 Style); 20791 verifyFormat("SomeClass::Constructor() noexcept\n" 20792 " : a(a) {}", 20793 Style); 20794 verifyFormat("SomeClass::Constructor()\n" 20795 " : a(a)\n" 20796 " , b(b)\n" 20797 " , c(c) {}", 20798 Style); 20799 verifyFormat("SomeClass::Constructor()\n" 20800 " : a(a) {\n" 20801 " foo();\n" 20802 " bar();\n" 20803 "}", 20804 Style); 20805 20806 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20807 verifyFormat("SomeClass::Constructor()\n" 20808 " : a(a)\n" 20809 " , b(b)\n" 20810 " , c(c) {\n}", 20811 Style); 20812 verifyFormat("SomeClass::Constructor()\n" 20813 " : a(a) {\n}", 20814 Style); 20815 20816 Style.ColumnLimit = 80; 20817 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20818 Style.ConstructorInitializerIndentWidth = 2; 20819 verifyFormat("SomeClass::Constructor()\n" 20820 " : a(a)\n" 20821 " , b(b)\n" 20822 " , c(c) {}", 20823 Style); 20824 20825 Style.ConstructorInitializerIndentWidth = 0; 20826 verifyFormat("SomeClass::Constructor()\n" 20827 ": a(a)\n" 20828 ", b(b)\n" 20829 ", c(c) {}", 20830 Style); 20831 20832 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20833 Style.ConstructorInitializerIndentWidth = 4; 20834 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20835 verifyFormat( 20836 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20837 Style); 20838 verifyFormat( 20839 "SomeClass::Constructor()\n" 20840 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20841 Style); 20842 Style.ConstructorInitializerIndentWidth = 4; 20843 Style.ColumnLimit = 60; 20844 verifyFormat("SomeClass::Constructor()\n" 20845 " : aaaaaaaa(aaaaaaaa)\n" 20846 " , aaaaaaaa(aaaaaaaa)\n" 20847 " , aaaaaaaa(aaaaaaaa) {}", 20848 Style); 20849 } 20850 20851 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20852 FormatStyle Style = getLLVMStyle(); 20853 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20854 Style.ConstructorInitializerIndentWidth = 4; 20855 verifyFormat("SomeClass::Constructor()\n" 20856 " : a{a}\n" 20857 " , b{b} {}", 20858 Style); 20859 verifyFormat("SomeClass::Constructor()\n" 20860 " : a{a}\n" 20861 "#if CONDITION\n" 20862 " , b{b}\n" 20863 "#endif\n" 20864 "{\n}", 20865 Style); 20866 Style.ConstructorInitializerIndentWidth = 2; 20867 verifyFormat("SomeClass::Constructor()\n" 20868 "#if CONDITION\n" 20869 " : a{a}\n" 20870 "#endif\n" 20871 " , b{b}\n" 20872 " , c{c} {\n}", 20873 Style); 20874 Style.ConstructorInitializerIndentWidth = 0; 20875 verifyFormat("SomeClass::Constructor()\n" 20876 ": a{a}\n" 20877 "#ifdef CONDITION\n" 20878 ", b{b}\n" 20879 "#else\n" 20880 ", c{c}\n" 20881 "#endif\n" 20882 ", d{d} {\n}", 20883 Style); 20884 Style.ConstructorInitializerIndentWidth = 4; 20885 verifyFormat("SomeClass::Constructor()\n" 20886 " : a{a}\n" 20887 "#if WINDOWS\n" 20888 "#if DEBUG\n" 20889 " , b{0}\n" 20890 "#else\n" 20891 " , b{1}\n" 20892 "#endif\n" 20893 "#else\n" 20894 "#if DEBUG\n" 20895 " , b{2}\n" 20896 "#else\n" 20897 " , b{3}\n" 20898 "#endif\n" 20899 "#endif\n" 20900 "{\n}", 20901 Style); 20902 verifyFormat("SomeClass::Constructor()\n" 20903 " : a{a}\n" 20904 "#if WINDOWS\n" 20905 " , b{0}\n" 20906 "#if DEBUG\n" 20907 " , c{0}\n" 20908 "#else\n" 20909 " , c{1}\n" 20910 "#endif\n" 20911 "#else\n" 20912 "#if DEBUG\n" 20913 " , c{2}\n" 20914 "#else\n" 20915 " , c{3}\n" 20916 "#endif\n" 20917 " , b{1}\n" 20918 "#endif\n" 20919 "{\n}", 20920 Style); 20921 } 20922 20923 TEST_F(FormatTest, Destructors) { 20924 verifyFormat("void F(int &i) { i.~int(); }"); 20925 verifyFormat("void F(int &i) { i->~int(); }"); 20926 } 20927 20928 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20929 FormatStyle Style = getWebKitStyle(); 20930 20931 // Don't indent in outer namespaces. 20932 verifyFormat("namespace outer {\n" 20933 "int i;\n" 20934 "namespace inner {\n" 20935 " int i;\n" 20936 "} // namespace inner\n" 20937 "} // namespace outer\n" 20938 "namespace other_outer {\n" 20939 "int i;\n" 20940 "}", 20941 Style); 20942 20943 // Don't indent case labels. 20944 verifyFormat("switch (variable) {\n" 20945 "case 1:\n" 20946 "case 2:\n" 20947 " doSomething();\n" 20948 " break;\n" 20949 "default:\n" 20950 " ++variable;\n" 20951 "}", 20952 Style); 20953 20954 // Wrap before binary operators. 20955 EXPECT_EQ("void f()\n" 20956 "{\n" 20957 " if (aaaaaaaaaaaaaaaa\n" 20958 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20959 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20960 " return;\n" 20961 "}", 20962 format("void f() {\n" 20963 "if (aaaaaaaaaaaaaaaa\n" 20964 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20965 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20966 "return;\n" 20967 "}", 20968 Style)); 20969 20970 // Allow functions on a single line. 20971 verifyFormat("void f() { return; }", Style); 20972 20973 // Allow empty blocks on a single line and insert a space in empty blocks. 20974 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20975 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20976 // However, don't merge non-empty short loops. 20977 EXPECT_EQ("while (true) {\n" 20978 " continue;\n" 20979 "}", 20980 format("while (true) { continue; }", Style)); 20981 20982 // Constructor initializers are formatted one per line with the "," on the 20983 // new line. 20984 verifyFormat("Constructor()\n" 20985 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20986 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20987 " aaaaaaaaaaaaaa)\n" 20988 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20989 "{\n" 20990 "}", 20991 Style); 20992 verifyFormat("SomeClass::Constructor()\n" 20993 " : a(a)\n" 20994 "{\n" 20995 "}", 20996 Style); 20997 EXPECT_EQ("SomeClass::Constructor()\n" 20998 " : a(a)\n" 20999 "{\n" 21000 "}", 21001 format("SomeClass::Constructor():a(a){}", Style)); 21002 verifyFormat("SomeClass::Constructor()\n" 21003 " : a(a)\n" 21004 " , b(b)\n" 21005 " , c(c)\n" 21006 "{\n" 21007 "}", 21008 Style); 21009 verifyFormat("SomeClass::Constructor()\n" 21010 " : a(a)\n" 21011 "{\n" 21012 " foo();\n" 21013 " bar();\n" 21014 "}", 21015 Style); 21016 21017 // Access specifiers should be aligned left. 21018 verifyFormat("class C {\n" 21019 "public:\n" 21020 " int i;\n" 21021 "};", 21022 Style); 21023 21024 // Do not align comments. 21025 verifyFormat("int a; // Do not\n" 21026 "double b; // align comments.", 21027 Style); 21028 21029 // Do not align operands. 21030 EXPECT_EQ("ASSERT(aaaa\n" 21031 " || bbbb);", 21032 format("ASSERT ( aaaa\n||bbbb);", Style)); 21033 21034 // Accept input's line breaks. 21035 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21036 " || bbbbbbbbbbbbbbb) {\n" 21037 " i++;\n" 21038 "}", 21039 format("if (aaaaaaaaaaaaaaa\n" 21040 "|| bbbbbbbbbbbbbbb) { i++; }", 21041 Style)); 21042 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21043 " i++;\n" 21044 "}", 21045 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21046 21047 // Don't automatically break all macro definitions (llvm.org/PR17842). 21048 verifyFormat("#define aNumber 10", Style); 21049 // However, generally keep the line breaks that the user authored. 21050 EXPECT_EQ("#define aNumber \\\n" 21051 " 10", 21052 format("#define aNumber \\\n" 21053 " 10", 21054 Style)); 21055 21056 // Keep empty and one-element array literals on a single line. 21057 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21058 " copyItems:YES];", 21059 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21060 "copyItems:YES];", 21061 Style)); 21062 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21063 " copyItems:YES];", 21064 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21065 " copyItems:YES];", 21066 Style)); 21067 // FIXME: This does not seem right, there should be more indentation before 21068 // the array literal's entries. Nested blocks have the same problem. 21069 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21070 " @\"a\",\n" 21071 " @\"a\"\n" 21072 "]\n" 21073 " copyItems:YES];", 21074 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21075 " @\"a\",\n" 21076 " @\"a\"\n" 21077 " ]\n" 21078 " copyItems:YES];", 21079 Style)); 21080 EXPECT_EQ( 21081 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21082 " copyItems:YES];", 21083 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21084 " copyItems:YES];", 21085 Style)); 21086 21087 verifyFormat("[self.a b:c c:d];", Style); 21088 EXPECT_EQ("[self.a b:c\n" 21089 " c:d];", 21090 format("[self.a b:c\n" 21091 "c:d];", 21092 Style)); 21093 } 21094 21095 TEST_F(FormatTest, FormatsLambdas) { 21096 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21097 verifyFormat( 21098 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21099 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21100 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21101 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21102 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21103 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21104 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21105 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21106 verifyFormat("int x = f(*+[] {});"); 21107 verifyFormat("void f() {\n" 21108 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21109 "}\n"); 21110 verifyFormat("void f() {\n" 21111 " other(x.begin(), //\n" 21112 " x.end(), //\n" 21113 " [&](int, int) { return 1; });\n" 21114 "}\n"); 21115 verifyFormat("void f() {\n" 21116 " other.other.other.other.other(\n" 21117 " x.begin(), x.end(),\n" 21118 " [something, rather](int, int, int, int, int, int, int) { " 21119 "return 1; });\n" 21120 "}\n"); 21121 verifyFormat( 21122 "void f() {\n" 21123 " other.other.other.other.other(\n" 21124 " x.begin(), x.end(),\n" 21125 " [something, rather](int, int, int, int, int, int, int) {\n" 21126 " //\n" 21127 " });\n" 21128 "}\n"); 21129 verifyFormat("SomeFunction([]() { // A cool function...\n" 21130 " return 43;\n" 21131 "});"); 21132 EXPECT_EQ("SomeFunction([]() {\n" 21133 "#define A a\n" 21134 " return 43;\n" 21135 "});", 21136 format("SomeFunction([](){\n" 21137 "#define A a\n" 21138 "return 43;\n" 21139 "});")); 21140 verifyFormat("void f() {\n" 21141 " SomeFunction([](decltype(x), A *a) {});\n" 21142 " SomeFunction([](typeof(x), A *a) {});\n" 21143 " SomeFunction([](_Atomic(x), A *a) {});\n" 21144 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21145 "}"); 21146 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21147 " [](const aaaaaaaaaa &a) { return a; });"); 21148 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21149 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21150 "});"); 21151 verifyFormat("Constructor()\n" 21152 " : Field([] { // comment\n" 21153 " int i;\n" 21154 " }) {}"); 21155 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21156 " return some_parameter.size();\n" 21157 "};"); 21158 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21159 " [](const string &s) { return s; };"); 21160 verifyFormat("int i = aaaaaa ? 1 //\n" 21161 " : [] {\n" 21162 " return 2; //\n" 21163 " }();"); 21164 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21165 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21166 " return x == 2; // force break\n" 21167 " });"); 21168 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21169 " [=](int iiiiiiiiiiii) {\n" 21170 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21171 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21172 " });", 21173 getLLVMStyleWithColumns(60)); 21174 21175 verifyFormat("SomeFunction({[&] {\n" 21176 " // comment\n" 21177 " },\n" 21178 " [&] {\n" 21179 " // comment\n" 21180 " }});"); 21181 verifyFormat("SomeFunction({[&] {\n" 21182 " // comment\n" 21183 "}});"); 21184 verifyFormat( 21185 "virtual aaaaaaaaaaaaaaaa(\n" 21186 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21187 " aaaaa aaaaaaaaa);"); 21188 21189 // Lambdas with return types. 21190 verifyFormat("int c = []() -> int { return 2; }();\n"); 21191 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21192 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21193 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21194 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21195 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21196 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21197 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21198 verifyFormat("[a, a]() -> a<1> {};"); 21199 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21200 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21201 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21202 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21203 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21204 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21205 verifyFormat("[]() -> foo<!5> { return {}; };"); 21206 verifyFormat("[]() -> foo<~5> { return {}; };"); 21207 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21208 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21209 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21210 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21211 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21212 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21213 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21214 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21215 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21216 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21217 verifyFormat("namespace bar {\n" 21218 "// broken:\n" 21219 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21220 "} // namespace bar"); 21221 verifyFormat("namespace bar {\n" 21222 "// broken:\n" 21223 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21224 "} // namespace bar"); 21225 verifyFormat("namespace bar {\n" 21226 "// broken:\n" 21227 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21228 "} // namespace bar"); 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> { return {}; }};\n" 21244 "} // namespace bar"); 21245 verifyFormat("namespace bar {\n" 21246 "// broken:\n" 21247 "auto foo{[]() -> foo<~5> { 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 || 2> { return {}; }};\n" 21256 "} // namespace bar"); 21257 verifyFormat("namespace bar {\n" 21258 "// broken:\n" 21259 "auto foo{[]() -> foo<5 & 2> { 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<2 ? 1 : 0> { return {}; }};\n" 21288 "} // namespace bar"); 21289 verifyFormat("[]() -> a<1> {};"); 21290 verifyFormat("[]() -> a<1> { ; };"); 21291 verifyFormat("[]() -> a<1> { ; }();"); 21292 verifyFormat("[a, a]() -> a<true> {};"); 21293 verifyFormat("[]() -> a<true> {};"); 21294 verifyFormat("[]() -> a<true> { ; };"); 21295 verifyFormat("[]() -> a<true> { ; }();"); 21296 verifyFormat("[a, a]() -> a<false> {};"); 21297 verifyFormat("[]() -> a<false> {};"); 21298 verifyFormat("[]() -> a<false> { ; };"); 21299 verifyFormat("[]() -> a<false> { ; }();"); 21300 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21301 verifyFormat("namespace bar {\n" 21302 "auto foo{[]() -> foo<false> { ; }};\n" 21303 "} // namespace bar"); 21304 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21305 " int j) -> int {\n" 21306 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21307 "};"); 21308 verifyFormat( 21309 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21310 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21311 " return aaaaaaaaaaaaaaaaa;\n" 21312 " });", 21313 getLLVMStyleWithColumns(70)); 21314 verifyFormat("[]() //\n" 21315 " -> int {\n" 21316 " return 1; //\n" 21317 "};"); 21318 verifyFormat("[]() -> Void<T...> {};"); 21319 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21320 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21321 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21322 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21323 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21324 verifyFormat("return int{[x = x]() { return x; }()};"); 21325 21326 // Lambdas with explicit template argument lists. 21327 verifyFormat( 21328 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21329 verifyFormat("auto L = []<class T>(T) {\n" 21330 " {\n" 21331 " f();\n" 21332 " g();\n" 21333 " }\n" 21334 "};\n"); 21335 verifyFormat("auto L = []<class... T>(T...) {\n" 21336 " {\n" 21337 " f();\n" 21338 " g();\n" 21339 " }\n" 21340 "};\n"); 21341 verifyFormat("auto L = []<typename... T>(T...) {\n" 21342 " {\n" 21343 " f();\n" 21344 " g();\n" 21345 " }\n" 21346 "};\n"); 21347 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21348 " {\n" 21349 " f();\n" 21350 " g();\n" 21351 " }\n" 21352 "};\n"); 21353 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21354 " {\n" 21355 " f();\n" 21356 " g();\n" 21357 " }\n" 21358 "};\n"); 21359 21360 // Multiple lambdas in the same parentheses change indentation rules. These 21361 // lambdas are forced to start on new lines. 21362 verifyFormat("SomeFunction(\n" 21363 " []() {\n" 21364 " //\n" 21365 " },\n" 21366 " []() {\n" 21367 " //\n" 21368 " });"); 21369 21370 // A lambda passed as arg0 is always pushed to the next line. 21371 verifyFormat("SomeFunction(\n" 21372 " [this] {\n" 21373 " //\n" 21374 " },\n" 21375 " 1);\n"); 21376 21377 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21378 // the arg0 case above. 21379 auto Style = getGoogleStyle(); 21380 Style.BinPackArguments = false; 21381 verifyFormat("SomeFunction(\n" 21382 " a,\n" 21383 " [this] {\n" 21384 " //\n" 21385 " },\n" 21386 " b);\n", 21387 Style); 21388 verifyFormat("SomeFunction(\n" 21389 " a,\n" 21390 " [this] {\n" 21391 " //\n" 21392 " },\n" 21393 " b);\n"); 21394 21395 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21396 // the BinPackArguments value (as long as the code is wide enough). 21397 verifyFormat( 21398 "something->SomeFunction(\n" 21399 " a,\n" 21400 " [this] {\n" 21401 " " 21402 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21403 " },\n" 21404 " b);\n"); 21405 21406 // A multi-line lambda is pulled up as long as the introducer fits on the 21407 // previous line and there are no further args. 21408 verifyFormat("function(1, [this, that] {\n" 21409 " //\n" 21410 "});\n"); 21411 verifyFormat("function([this, that] {\n" 21412 " //\n" 21413 "});\n"); 21414 // FIXME: this format is not ideal and we should consider forcing the first 21415 // arg onto its own line. 21416 verifyFormat("function(a, b, c, //\n" 21417 " d, [this, that] {\n" 21418 " //\n" 21419 " });\n"); 21420 21421 // Multiple lambdas are treated correctly even when there is a short arg0. 21422 verifyFormat("SomeFunction(\n" 21423 " 1,\n" 21424 " [this] {\n" 21425 " //\n" 21426 " },\n" 21427 " [this] {\n" 21428 " //\n" 21429 " },\n" 21430 " 1);\n"); 21431 21432 // More complex introducers. 21433 verifyFormat("return [i, args...] {};"); 21434 21435 // Not lambdas. 21436 verifyFormat("constexpr char hello[]{\"hello\"};"); 21437 verifyFormat("double &operator[](int i) { return 0; }\n" 21438 "int i;"); 21439 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21440 verifyFormat("int i = a[a][a]->f();"); 21441 verifyFormat("int i = (*b)[a]->f();"); 21442 21443 // Other corner cases. 21444 verifyFormat("void f() {\n" 21445 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21446 " );\n" 21447 "}"); 21448 21449 // Lambdas created through weird macros. 21450 verifyFormat("void f() {\n" 21451 " MACRO((const AA &a) { return 1; });\n" 21452 " MACRO((AA &a) { return 1; });\n" 21453 "}"); 21454 21455 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21456 " doo_dah();\n" 21457 " doo_dah();\n" 21458 " })) {\n" 21459 "}"); 21460 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21461 " doo_dah();\n" 21462 " doo_dah();\n" 21463 " })) {\n" 21464 "}"); 21465 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21466 " doo_dah();\n" 21467 " doo_dah();\n" 21468 " })) {\n" 21469 "}"); 21470 verifyFormat("auto lambda = []() {\n" 21471 " int a = 2\n" 21472 "#if A\n" 21473 " + 2\n" 21474 "#endif\n" 21475 " ;\n" 21476 "};"); 21477 21478 // Lambdas with complex multiline introducers. 21479 verifyFormat( 21480 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21481 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21482 " -> ::std::unordered_set<\n" 21483 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21484 " //\n" 21485 " });"); 21486 21487 FormatStyle DoNotMerge = getLLVMStyle(); 21488 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21489 verifyFormat("auto c = []() {\n" 21490 " return b;\n" 21491 "};", 21492 "auto c = []() { return b; };", DoNotMerge); 21493 verifyFormat("auto c = []() {\n" 21494 "};", 21495 " auto c = []() {};", DoNotMerge); 21496 21497 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21498 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21499 verifyFormat("auto c = []() {\n" 21500 " return b;\n" 21501 "};", 21502 "auto c = []() {\n" 21503 " return b;\n" 21504 " };", 21505 MergeEmptyOnly); 21506 verifyFormat("auto c = []() {};", 21507 "auto c = []() {\n" 21508 "};", 21509 MergeEmptyOnly); 21510 21511 FormatStyle MergeInline = getLLVMStyle(); 21512 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21513 verifyFormat("auto c = []() {\n" 21514 " return b;\n" 21515 "};", 21516 "auto c = []() { return b; };", MergeInline); 21517 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21518 MergeInline); 21519 verifyFormat("function([]() { return b; }, a)", 21520 "function([]() { return b; }, a)", MergeInline); 21521 verifyFormat("function(a, []() { return b; })", 21522 "function(a, []() { return b; })", MergeInline); 21523 21524 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21525 // AllowShortLambdasOnASingleLine 21526 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21527 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21528 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21529 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21530 FormatStyle::ShortLambdaStyle::SLS_None; 21531 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21532 " []()\n" 21533 " {\n" 21534 " return 17;\n" 21535 " });", 21536 LLVMWithBeforeLambdaBody); 21537 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21538 " []()\n" 21539 " {\n" 21540 " });", 21541 LLVMWithBeforeLambdaBody); 21542 verifyFormat("auto fct_SLS_None = []()\n" 21543 "{\n" 21544 " return 17;\n" 21545 "};", 21546 LLVMWithBeforeLambdaBody); 21547 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21548 " []()\n" 21549 " {\n" 21550 " return Call(\n" 21551 " []()\n" 21552 " {\n" 21553 " return 17;\n" 21554 " });\n" 21555 " });", 21556 LLVMWithBeforeLambdaBody); 21557 verifyFormat("void Fct() {\n" 21558 " return {[]()\n" 21559 " {\n" 21560 " return 17;\n" 21561 " }};\n" 21562 "}", 21563 LLVMWithBeforeLambdaBody); 21564 21565 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21566 FormatStyle::ShortLambdaStyle::SLS_Empty; 21567 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21568 " []()\n" 21569 " {\n" 21570 " return 17;\n" 21571 " });", 21572 LLVMWithBeforeLambdaBody); 21573 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21574 LLVMWithBeforeLambdaBody); 21575 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21576 "ongFunctionName_SLS_Empty(\n" 21577 " []() {});", 21578 LLVMWithBeforeLambdaBody); 21579 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21580 " []()\n" 21581 " {\n" 21582 " return 17;\n" 21583 " });", 21584 LLVMWithBeforeLambdaBody); 21585 verifyFormat("auto fct_SLS_Empty = []()\n" 21586 "{\n" 21587 " return 17;\n" 21588 "};", 21589 LLVMWithBeforeLambdaBody); 21590 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21591 " []()\n" 21592 " {\n" 21593 " return Call([]() {});\n" 21594 " });", 21595 LLVMWithBeforeLambdaBody); 21596 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21597 " []()\n" 21598 " {\n" 21599 " return Call([]() {});\n" 21600 " });", 21601 LLVMWithBeforeLambdaBody); 21602 verifyFormat( 21603 "FctWithLongLineInLambda_SLS_Empty(\n" 21604 " []()\n" 21605 " {\n" 21606 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21607 " AndShouldNotBeConsiderAsInline,\n" 21608 " LambdaBodyMustBeBreak);\n" 21609 " });", 21610 LLVMWithBeforeLambdaBody); 21611 21612 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21613 FormatStyle::ShortLambdaStyle::SLS_Inline; 21614 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21615 LLVMWithBeforeLambdaBody); 21616 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21617 LLVMWithBeforeLambdaBody); 21618 verifyFormat("auto fct_SLS_Inline = []()\n" 21619 "{\n" 21620 " return 17;\n" 21621 "};", 21622 LLVMWithBeforeLambdaBody); 21623 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21624 "17; }); });", 21625 LLVMWithBeforeLambdaBody); 21626 verifyFormat( 21627 "FctWithLongLineInLambda_SLS_Inline(\n" 21628 " []()\n" 21629 " {\n" 21630 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21631 " AndShouldNotBeConsiderAsInline,\n" 21632 " LambdaBodyMustBeBreak);\n" 21633 " });", 21634 LLVMWithBeforeLambdaBody); 21635 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21636 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21637 " []() { return 17; });", 21638 LLVMWithBeforeLambdaBody); 21639 verifyFormat( 21640 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21641 LLVMWithBeforeLambdaBody); 21642 21643 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21644 FormatStyle::ShortLambdaStyle::SLS_All; 21645 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21646 LLVMWithBeforeLambdaBody); 21647 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21648 LLVMWithBeforeLambdaBody); 21649 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21650 LLVMWithBeforeLambdaBody); 21651 verifyFormat("FctWithOneParam_SLS_All(\n" 21652 " []()\n" 21653 " {\n" 21654 " // A cool function...\n" 21655 " return 43;\n" 21656 " });", 21657 LLVMWithBeforeLambdaBody); 21658 verifyFormat("FctWithMultipleParams_SLS_All(" 21659 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21660 " []() { return 17; });", 21661 LLVMWithBeforeLambdaBody); 21662 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21663 LLVMWithBeforeLambdaBody); 21664 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21665 LLVMWithBeforeLambdaBody); 21666 verifyFormat( 21667 "FctWithLongLineInLambda_SLS_All(\n" 21668 " []()\n" 21669 " {\n" 21670 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21671 " AndShouldNotBeConsiderAsInline,\n" 21672 " LambdaBodyMustBeBreak);\n" 21673 " });", 21674 LLVMWithBeforeLambdaBody); 21675 verifyFormat( 21676 "auto fct_SLS_All = []()\n" 21677 "{\n" 21678 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21679 " AndShouldNotBeConsiderAsInline,\n" 21680 " LambdaBodyMustBeBreak);\n" 21681 "};", 21682 LLVMWithBeforeLambdaBody); 21683 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21684 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21685 LLVMWithBeforeLambdaBody); 21686 verifyFormat( 21687 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21688 " FirstParam,\n" 21689 " SecondParam,\n" 21690 " ThirdParam,\n" 21691 " FourthParam);", 21692 LLVMWithBeforeLambdaBody); 21693 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21694 " []() { return " 21695 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21696 " FirstParam,\n" 21697 " SecondParam,\n" 21698 " ThirdParam,\n" 21699 " FourthParam);", 21700 LLVMWithBeforeLambdaBody); 21701 verifyFormat( 21702 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21703 " SecondParam,\n" 21704 " ThirdParam,\n" 21705 " FourthParam,\n" 21706 " []() { return SomeValueNotSoLong; });", 21707 LLVMWithBeforeLambdaBody); 21708 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21709 " []()\n" 21710 " {\n" 21711 " return " 21712 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21713 "eConsiderAsInline;\n" 21714 " });", 21715 LLVMWithBeforeLambdaBody); 21716 verifyFormat( 21717 "FctWithLongLineInLambda_SLS_All(\n" 21718 " []()\n" 21719 " {\n" 21720 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21721 " AndShouldNotBeConsiderAsInline,\n" 21722 " LambdaBodyMustBeBreak);\n" 21723 " });", 21724 LLVMWithBeforeLambdaBody); 21725 verifyFormat("FctWithTwoParams_SLS_All(\n" 21726 " []()\n" 21727 " {\n" 21728 " // A cool function...\n" 21729 " return 43;\n" 21730 " },\n" 21731 " 87);", 21732 LLVMWithBeforeLambdaBody); 21733 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21734 LLVMWithBeforeLambdaBody); 21735 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21736 LLVMWithBeforeLambdaBody); 21737 verifyFormat( 21738 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21739 LLVMWithBeforeLambdaBody); 21740 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21741 "}); }, x);", 21742 LLVMWithBeforeLambdaBody); 21743 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21744 " []()\n" 21745 " {\n" 21746 " // A cool function...\n" 21747 " return Call([]() { return 17; });\n" 21748 " });", 21749 LLVMWithBeforeLambdaBody); 21750 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21751 " []()\n" 21752 " {\n" 21753 " return Call(\n" 21754 " []()\n" 21755 " {\n" 21756 " // A cool function...\n" 21757 " return 17;\n" 21758 " });\n" 21759 " });", 21760 LLVMWithBeforeLambdaBody); 21761 21762 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21763 FormatStyle::ShortLambdaStyle::SLS_None; 21764 21765 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21766 "{\n" 21767 " return MyAssignment::SelectFromList(this);\n" 21768 "};\n", 21769 LLVMWithBeforeLambdaBody); 21770 21771 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21772 "{\n" 21773 " return MyAssignment::SelectFromList(this);\n" 21774 "};\n", 21775 LLVMWithBeforeLambdaBody); 21776 21777 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21778 "{\n" 21779 " return MyAssignment::SelectFromList(this);\n" 21780 "};\n", 21781 LLVMWithBeforeLambdaBody); 21782 21783 verifyFormat("namespace test {\n" 21784 "class Test {\n" 21785 "public:\n" 21786 " Test() = default;\n" 21787 "};\n" 21788 "} // namespace test", 21789 LLVMWithBeforeLambdaBody); 21790 21791 // Lambdas with different indentation styles. 21792 Style = getLLVMStyleWithColumns(100); 21793 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21794 " return promise.then(\n" 21795 " [this, &someVariable, someObject = " 21796 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21797 " return someObject.startAsyncAction().then(\n" 21798 " [this, &someVariable](AsyncActionResult result) " 21799 "mutable { result.processMore(); });\n" 21800 " });\n" 21801 "}\n", 21802 format("SomeResult doSomething(SomeObject promise) {\n" 21803 " return promise.then([this, &someVariable, someObject = " 21804 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21805 " return someObject.startAsyncAction().then([this, " 21806 "&someVariable](AsyncActionResult result) mutable {\n" 21807 " result.processMore();\n" 21808 " });\n" 21809 " });\n" 21810 "}\n", 21811 Style)); 21812 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21813 verifyFormat("test() {\n" 21814 " ([]() -> {\n" 21815 " int b = 32;\n" 21816 " return 3;\n" 21817 " }).foo();\n" 21818 "}", 21819 Style); 21820 verifyFormat("test() {\n" 21821 " []() -> {\n" 21822 " int b = 32;\n" 21823 " return 3;\n" 21824 " }\n" 21825 "}", 21826 Style); 21827 verifyFormat("std::sort(v.begin(), v.end(),\n" 21828 " [](const auto &someLongArgumentName, const auto " 21829 "&someOtherLongArgumentName) {\n" 21830 " return someLongArgumentName.someMemberVariable < " 21831 "someOtherLongArgumentName.someMemberVariable;\n" 21832 "});", 21833 Style); 21834 verifyFormat("test() {\n" 21835 " (\n" 21836 " []() -> {\n" 21837 " int b = 32;\n" 21838 " return 3;\n" 21839 " },\n" 21840 " foo, bar)\n" 21841 " .foo();\n" 21842 "}", 21843 Style); 21844 verifyFormat("test() {\n" 21845 " ([]() -> {\n" 21846 " int b = 32;\n" 21847 " return 3;\n" 21848 " })\n" 21849 " .foo()\n" 21850 " .bar();\n" 21851 "}", 21852 Style); 21853 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21854 " return promise.then(\n" 21855 " [this, &someVariable, someObject = " 21856 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21857 " return someObject.startAsyncAction().then(\n" 21858 " [this, &someVariable](AsyncActionResult result) mutable { " 21859 "result.processMore(); });\n" 21860 " });\n" 21861 "}\n", 21862 format("SomeResult doSomething(SomeObject promise) {\n" 21863 " return promise.then([this, &someVariable, someObject = " 21864 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21865 " return someObject.startAsyncAction().then([this, " 21866 "&someVariable](AsyncActionResult result) mutable {\n" 21867 " result.processMore();\n" 21868 " });\n" 21869 " });\n" 21870 "}\n", 21871 Style)); 21872 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21873 " return promise.then([this, &someVariable] {\n" 21874 " return someObject.startAsyncAction().then(\n" 21875 " [this, &someVariable](AsyncActionResult result) mutable { " 21876 "result.processMore(); });\n" 21877 " });\n" 21878 "}\n", 21879 format("SomeResult doSomething(SomeObject promise) {\n" 21880 " return promise.then([this, &someVariable] {\n" 21881 " return someObject.startAsyncAction().then([this, " 21882 "&someVariable](AsyncActionResult result) mutable {\n" 21883 " result.processMore();\n" 21884 " });\n" 21885 " });\n" 21886 "}\n", 21887 Style)); 21888 Style = getGoogleStyle(); 21889 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21890 EXPECT_EQ("#define A \\\n" 21891 " [] { \\\n" 21892 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21893 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21894 " }", 21895 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21896 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21897 Style)); 21898 // TODO: The current formatting has a minor issue that's not worth fixing 21899 // right now whereby the closing brace is indented relative to the signature 21900 // instead of being aligned. This only happens with macros. 21901 } 21902 21903 TEST_F(FormatTest, LambdaWithLineComments) { 21904 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21905 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21906 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21907 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21908 FormatStyle::ShortLambdaStyle::SLS_All; 21909 21910 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21911 verifyFormat("auto k = []() // comment\n" 21912 "{ return; }", 21913 LLVMWithBeforeLambdaBody); 21914 verifyFormat("auto k = []() /* comment */ { return; }", 21915 LLVMWithBeforeLambdaBody); 21916 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21917 LLVMWithBeforeLambdaBody); 21918 verifyFormat("auto k = []() // X\n" 21919 "{ return; }", 21920 LLVMWithBeforeLambdaBody); 21921 verifyFormat( 21922 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21923 "{ return; }", 21924 LLVMWithBeforeLambdaBody); 21925 } 21926 21927 TEST_F(FormatTest, EmptyLinesInLambdas) { 21928 verifyFormat("auto lambda = []() {\n" 21929 " x(); //\n" 21930 "};", 21931 "auto lambda = []() {\n" 21932 "\n" 21933 " x(); //\n" 21934 "\n" 21935 "};"); 21936 } 21937 21938 TEST_F(FormatTest, FormatsBlocks) { 21939 FormatStyle ShortBlocks = getLLVMStyle(); 21940 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21941 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21942 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21943 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21944 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21945 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21946 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21947 21948 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21949 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21950 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21951 21952 verifyFormat("[operation setCompletionBlock:^{\n" 21953 " [self onOperationDone];\n" 21954 "}];"); 21955 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21956 " [self onOperationDone];\n" 21957 "}]};"); 21958 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21959 " f();\n" 21960 "}];"); 21961 verifyFormat("int a = [operation block:^int(int *i) {\n" 21962 " return 1;\n" 21963 "}];"); 21964 verifyFormat("[myObject doSomethingWith:arg1\n" 21965 " aaa:^int(int *a) {\n" 21966 " return 1;\n" 21967 " }\n" 21968 " bbb:f(a * bbbbbbbb)];"); 21969 21970 verifyFormat("[operation setCompletionBlock:^{\n" 21971 " [self.delegate newDataAvailable];\n" 21972 "}];", 21973 getLLVMStyleWithColumns(60)); 21974 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21975 " NSString *path = [self sessionFilePath];\n" 21976 " if (path) {\n" 21977 " // ...\n" 21978 " }\n" 21979 "});"); 21980 verifyFormat("[[SessionService sharedService]\n" 21981 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21982 " if (window) {\n" 21983 " [self windowDidLoad:window];\n" 21984 " } else {\n" 21985 " [self errorLoadingWindow];\n" 21986 " }\n" 21987 " }];"); 21988 verifyFormat("void (^largeBlock)(void) = ^{\n" 21989 " // ...\n" 21990 "};\n", 21991 getLLVMStyleWithColumns(40)); 21992 verifyFormat("[[SessionService sharedService]\n" 21993 " loadWindowWithCompletionBlock: //\n" 21994 " ^(SessionWindow *window) {\n" 21995 " if (window) {\n" 21996 " [self windowDidLoad:window];\n" 21997 " } else {\n" 21998 " [self errorLoadingWindow];\n" 21999 " }\n" 22000 " }];", 22001 getLLVMStyleWithColumns(60)); 22002 verifyFormat("[myObject doSomethingWith:arg1\n" 22003 " firstBlock:^(Foo *a) {\n" 22004 " // ...\n" 22005 " int i;\n" 22006 " }\n" 22007 " secondBlock:^(Bar *b) {\n" 22008 " // ...\n" 22009 " int i;\n" 22010 " }\n" 22011 " thirdBlock:^Foo(Bar *b) {\n" 22012 " // ...\n" 22013 " int i;\n" 22014 " }];"); 22015 verifyFormat("[myObject doSomethingWith:arg1\n" 22016 " firstBlock:-1\n" 22017 " secondBlock:^(Bar *b) {\n" 22018 " // ...\n" 22019 " int i;\n" 22020 " }];"); 22021 22022 verifyFormat("f(^{\n" 22023 " @autoreleasepool {\n" 22024 " if (a) {\n" 22025 " g();\n" 22026 " }\n" 22027 " }\n" 22028 "});"); 22029 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22030 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22031 "};"); 22032 22033 FormatStyle FourIndent = getLLVMStyle(); 22034 FourIndent.ObjCBlockIndentWidth = 4; 22035 verifyFormat("[operation setCompletionBlock:^{\n" 22036 " [self onOperationDone];\n" 22037 "}];", 22038 FourIndent); 22039 } 22040 22041 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22042 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22043 22044 verifyFormat("[[SessionService sharedService] " 22045 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22046 " if (window) {\n" 22047 " [self windowDidLoad:window];\n" 22048 " } else {\n" 22049 " [self errorLoadingWindow];\n" 22050 " }\n" 22051 "}];", 22052 ZeroColumn); 22053 EXPECT_EQ("[[SessionService sharedService]\n" 22054 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22055 " if (window) {\n" 22056 " [self windowDidLoad:window];\n" 22057 " } else {\n" 22058 " [self errorLoadingWindow];\n" 22059 " }\n" 22060 " }];", 22061 format("[[SessionService sharedService]\n" 22062 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22063 " if (window) {\n" 22064 " [self windowDidLoad:window];\n" 22065 " } else {\n" 22066 " [self errorLoadingWindow];\n" 22067 " }\n" 22068 "}];", 22069 ZeroColumn)); 22070 verifyFormat("[myObject doSomethingWith:arg1\n" 22071 " firstBlock:^(Foo *a) {\n" 22072 " // ...\n" 22073 " int i;\n" 22074 " }\n" 22075 " secondBlock:^(Bar *b) {\n" 22076 " // ...\n" 22077 " int i;\n" 22078 " }\n" 22079 " thirdBlock:^Foo(Bar *b) {\n" 22080 " // ...\n" 22081 " int i;\n" 22082 " }];", 22083 ZeroColumn); 22084 verifyFormat("f(^{\n" 22085 " @autoreleasepool {\n" 22086 " if (a) {\n" 22087 " g();\n" 22088 " }\n" 22089 " }\n" 22090 "});", 22091 ZeroColumn); 22092 verifyFormat("void (^largeBlock)(void) = ^{\n" 22093 " // ...\n" 22094 "};", 22095 ZeroColumn); 22096 22097 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22098 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22099 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22100 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22101 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22102 " int i;\n" 22103 "};", 22104 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22105 } 22106 22107 TEST_F(FormatTest, SupportsCRLF) { 22108 EXPECT_EQ("int a;\r\n" 22109 "int b;\r\n" 22110 "int c;\r\n", 22111 format("int a;\r\n" 22112 " int b;\r\n" 22113 " int c;\r\n", 22114 getLLVMStyle())); 22115 EXPECT_EQ("int a;\r\n" 22116 "int b;\r\n" 22117 "int c;\r\n", 22118 format("int a;\r\n" 22119 " int b;\n" 22120 " int c;\r\n", 22121 getLLVMStyle())); 22122 EXPECT_EQ("int a;\n" 22123 "int b;\n" 22124 "int c;\n", 22125 format("int a;\r\n" 22126 " int b;\n" 22127 " int c;\n", 22128 getLLVMStyle())); 22129 EXPECT_EQ("\"aaaaaaa \"\r\n" 22130 "\"bbbbbbb\";\r\n", 22131 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22132 EXPECT_EQ("#define A \\\r\n" 22133 " b; \\\r\n" 22134 " c; \\\r\n" 22135 " d;\r\n", 22136 format("#define A \\\r\n" 22137 " b; \\\r\n" 22138 " c; d; \r\n", 22139 getGoogleStyle())); 22140 22141 EXPECT_EQ("/*\r\n" 22142 "multi line block comments\r\n" 22143 "should not introduce\r\n" 22144 "an extra carriage return\r\n" 22145 "*/\r\n", 22146 format("/*\r\n" 22147 "multi line block comments\r\n" 22148 "should not introduce\r\n" 22149 "an extra carriage return\r\n" 22150 "*/\r\n")); 22151 EXPECT_EQ("/*\r\n" 22152 "\r\n" 22153 "*/", 22154 format("/*\r\n" 22155 " \r\r\r\n" 22156 "*/")); 22157 22158 FormatStyle style = getLLVMStyle(); 22159 22160 style.DeriveLineEnding = true; 22161 style.UseCRLF = false; 22162 EXPECT_EQ("union FooBarBazQux {\n" 22163 " int foo;\n" 22164 " int bar;\n" 22165 " int baz;\n" 22166 "};", 22167 format("union FooBarBazQux {\r\n" 22168 " int foo;\n" 22169 " int bar;\r\n" 22170 " int baz;\n" 22171 "};", 22172 style)); 22173 style.UseCRLF = true; 22174 EXPECT_EQ("union FooBarBazQux {\r\n" 22175 " int foo;\r\n" 22176 " int bar;\r\n" 22177 " int baz;\r\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 22186 style.DeriveLineEnding = false; 22187 style.UseCRLF = false; 22188 EXPECT_EQ("union FooBarBazQux {\n" 22189 " int foo;\n" 22190 " int bar;\n" 22191 " int baz;\n" 22192 " int qux;\n" 22193 "};", 22194 format("union FooBarBazQux {\r\n" 22195 " int foo;\n" 22196 " int bar;\r\n" 22197 " int baz;\n" 22198 " int qux;\r\n" 22199 "};", 22200 style)); 22201 style.UseCRLF = true; 22202 EXPECT_EQ("union FooBarBazQux {\r\n" 22203 " int foo;\r\n" 22204 " int bar;\r\n" 22205 " int baz;\r\n" 22206 " int qux;\r\n" 22207 "};", 22208 format("union FooBarBazQux {\r\n" 22209 " int foo;\n" 22210 " int bar;\r\n" 22211 " int baz;\n" 22212 " int qux;\n" 22213 "};", 22214 style)); 22215 22216 style.DeriveLineEnding = true; 22217 style.UseCRLF = false; 22218 EXPECT_EQ("union FooBarBazQux {\r\n" 22219 " int foo;\r\n" 22220 " int bar;\r\n" 22221 " int baz;\r\n" 22222 " int qux;\r\n" 22223 "};", 22224 format("union FooBarBazQux {\r\n" 22225 " int foo;\n" 22226 " int bar;\r\n" 22227 " int baz;\n" 22228 " int qux;\r\n" 22229 "};", 22230 style)); 22231 style.UseCRLF = true; 22232 EXPECT_EQ("union FooBarBazQux {\n" 22233 " int foo;\n" 22234 " int bar;\n" 22235 " int baz;\n" 22236 " int qux;\n" 22237 "};", 22238 format("union FooBarBazQux {\r\n" 22239 " int foo;\n" 22240 " int bar;\r\n" 22241 " int baz;\n" 22242 " int qux;\n" 22243 "};", 22244 style)); 22245 } 22246 22247 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22248 verifyFormat("MY_CLASS(C) {\n" 22249 " int i;\n" 22250 " int j;\n" 22251 "};"); 22252 } 22253 22254 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22255 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22256 TwoIndent.ContinuationIndentWidth = 2; 22257 22258 EXPECT_EQ("int i =\n" 22259 " longFunction(\n" 22260 " arg);", 22261 format("int i = longFunction(arg);", TwoIndent)); 22262 22263 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22264 SixIndent.ContinuationIndentWidth = 6; 22265 22266 EXPECT_EQ("int i =\n" 22267 " longFunction(\n" 22268 " arg);", 22269 format("int i = longFunction(arg);", SixIndent)); 22270 } 22271 22272 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22273 FormatStyle Style = getLLVMStyle(); 22274 verifyFormat("int Foo::getter(\n" 22275 " //\n" 22276 ") const {\n" 22277 " return foo;\n" 22278 "}", 22279 Style); 22280 verifyFormat("void Foo::setter(\n" 22281 " //\n" 22282 ") {\n" 22283 " foo = 1;\n" 22284 "}", 22285 Style); 22286 } 22287 22288 TEST_F(FormatTest, SpacesInAngles) { 22289 FormatStyle Spaces = getLLVMStyle(); 22290 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22291 22292 verifyFormat("vector< ::std::string > x1;", Spaces); 22293 verifyFormat("Foo< int, Bar > x2;", Spaces); 22294 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22295 22296 verifyFormat("static_cast< int >(arg);", Spaces); 22297 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22298 verifyFormat("f< int, float >();", Spaces); 22299 verifyFormat("template <> g() {}", Spaces); 22300 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22301 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22302 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22303 Spaces); 22304 22305 Spaces.Standard = FormatStyle::LS_Cpp03; 22306 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22307 verifyFormat("A< A< int > >();", Spaces); 22308 22309 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22310 verifyFormat("A<A<int> >();", Spaces); 22311 22312 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22313 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22314 Spaces); 22315 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22316 Spaces); 22317 22318 verifyFormat("A<A<int> >();", Spaces); 22319 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22320 verifyFormat("A< A< int > >();", Spaces); 22321 22322 Spaces.Standard = FormatStyle::LS_Cpp11; 22323 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22324 verifyFormat("A< A< int > >();", Spaces); 22325 22326 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22327 verifyFormat("vector<::std::string> x4;", Spaces); 22328 verifyFormat("vector<int> x5;", Spaces); 22329 verifyFormat("Foo<int, Bar> x6;", Spaces); 22330 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22331 22332 verifyFormat("A<A<int>>();", Spaces); 22333 22334 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22335 verifyFormat("vector<::std::string> x4;", Spaces); 22336 verifyFormat("vector< ::std::string > x4;", Spaces); 22337 verifyFormat("vector<int> x5;", Spaces); 22338 verifyFormat("vector< int > x5;", Spaces); 22339 verifyFormat("Foo<int, Bar> x6;", Spaces); 22340 verifyFormat("Foo< int, Bar > x6;", Spaces); 22341 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22342 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22343 22344 verifyFormat("A<A<int>>();", Spaces); 22345 verifyFormat("A< A< int > >();", Spaces); 22346 verifyFormat("A<A<int > >();", Spaces); 22347 verifyFormat("A< A< int>>();", Spaces); 22348 22349 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22350 verifyFormat("// clang-format off\n" 22351 "foo<<<1, 1>>>();\n" 22352 "// clang-format on\n", 22353 Spaces); 22354 verifyFormat("// clang-format off\n" 22355 "foo< < <1, 1> > >();\n" 22356 "// clang-format on\n", 22357 Spaces); 22358 } 22359 22360 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22361 FormatStyle Style = getLLVMStyle(); 22362 Style.SpaceAfterTemplateKeyword = false; 22363 verifyFormat("template<int> void foo();", Style); 22364 } 22365 22366 TEST_F(FormatTest, TripleAngleBrackets) { 22367 verifyFormat("f<<<1, 1>>>();"); 22368 verifyFormat("f<<<1, 1, 1, s>>>();"); 22369 verifyFormat("f<<<a, b, c, d>>>();"); 22370 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22371 verifyFormat("f<param><<<1, 1>>>();"); 22372 verifyFormat("f<1><<<1, 1>>>();"); 22373 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22374 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22375 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22376 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22377 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22378 } 22379 22380 TEST_F(FormatTest, MergeLessLessAtEnd) { 22381 verifyFormat("<<"); 22382 EXPECT_EQ("< < <", format("\\\n<<<")); 22383 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22384 "aaallvm::outs() <<"); 22385 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22386 "aaaallvm::outs()\n <<"); 22387 } 22388 22389 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22390 std::string code = "#if A\n" 22391 "#if B\n" 22392 "a.\n" 22393 "#endif\n" 22394 " a = 1;\n" 22395 "#else\n" 22396 "#endif\n" 22397 "#if C\n" 22398 "#else\n" 22399 "#endif\n"; 22400 EXPECT_EQ(code, format(code)); 22401 } 22402 22403 TEST_F(FormatTest, HandleConflictMarkers) { 22404 // Git/SVN conflict markers. 22405 EXPECT_EQ("int a;\n" 22406 "void f() {\n" 22407 " callme(some(parameter1,\n" 22408 "<<<<<<< text by the vcs\n" 22409 " parameter2),\n" 22410 "||||||| text by the vcs\n" 22411 " parameter2),\n" 22412 " parameter3,\n" 22413 "======= text by the vcs\n" 22414 " parameter2, parameter3),\n" 22415 ">>>>>>> text by the vcs\n" 22416 " otherparameter);\n", 22417 format("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,\n" 22427 " parameter3),\n" 22428 ">>>>>>> text by the vcs\n" 22429 " otherparameter);\n")); 22430 22431 // Perforce markers. 22432 EXPECT_EQ("void f() {\n" 22433 " function(\n" 22434 ">>>> text by the vcs\n" 22435 " parameter,\n" 22436 "==== text by the vcs\n" 22437 " parameter,\n" 22438 "==== text by the vcs\n" 22439 " parameter,\n" 22440 "<<<< text by the vcs\n" 22441 " parameter);\n", 22442 format("void f() {\n" 22443 " function(\n" 22444 ">>>> text by the vcs\n" 22445 " parameter,\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 22453 EXPECT_EQ("<<<<<<<\n" 22454 "|||||||\n" 22455 "=======\n" 22456 ">>>>>>>", 22457 format("<<<<<<<\n" 22458 "|||||||\n" 22459 "=======\n" 22460 ">>>>>>>")); 22461 22462 EXPECT_EQ("<<<<<<<\n" 22463 "|||||||\n" 22464 "int i;\n" 22465 "=======\n" 22466 ">>>>>>>", 22467 format("<<<<<<<\n" 22468 "|||||||\n" 22469 "int i;\n" 22470 "=======\n" 22471 ">>>>>>>")); 22472 22473 // FIXME: Handle parsing of macros around conflict markers correctly: 22474 EXPECT_EQ("#define Macro \\\n" 22475 "<<<<<<<\n" 22476 "Something \\\n" 22477 "|||||||\n" 22478 "Else \\\n" 22479 "=======\n" 22480 "Other \\\n" 22481 ">>>>>>>\n" 22482 " End int i;\n", 22483 format("#define Macro \\\n" 22484 "<<<<<<<\n" 22485 " Something \\\n" 22486 "|||||||\n" 22487 " Else \\\n" 22488 "=======\n" 22489 " Other \\\n" 22490 ">>>>>>>\n" 22491 " End\n" 22492 "int i;\n")); 22493 22494 verifyFormat(R"(==== 22495 #ifdef A 22496 a 22497 #else 22498 b 22499 #endif 22500 )"); 22501 } 22502 22503 TEST_F(FormatTest, DisableRegions) { 22504 EXPECT_EQ("int i;\n" 22505 "// clang-format off\n" 22506 " int j;\n" 22507 "// clang-format on\n" 22508 "int k;", 22509 format(" int i;\n" 22510 " // clang-format off\n" 22511 " int j;\n" 22512 " // clang-format on\n" 22513 " int k;")); 22514 EXPECT_EQ("int i;\n" 22515 "/* clang-format off */\n" 22516 " int j;\n" 22517 "/* clang-format on */\n" 22518 "int k;", 22519 format(" int i;\n" 22520 " /* clang-format off */\n" 22521 " int j;\n" 22522 " /* clang-format on */\n" 22523 " int k;")); 22524 22525 // Don't reflow comments within disabled regions. 22526 EXPECT_EQ("// clang-format off\n" 22527 "// long long long long long long line\n" 22528 "/* clang-format on */\n" 22529 "/* long long long\n" 22530 " * long long long\n" 22531 " * line */\n" 22532 "int i;\n" 22533 "/* clang-format off */\n" 22534 "/* long long long long long long line */\n", 22535 format("// clang-format off\n" 22536 "// long long long long long long line\n" 22537 "/* clang-format on */\n" 22538 "/* long long long long long long line */\n" 22539 "int i;\n" 22540 "/* clang-format off */\n" 22541 "/* long long long long long long line */\n", 22542 getLLVMStyleWithColumns(20))); 22543 } 22544 22545 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22546 format("? ) ="); 22547 verifyNoCrash("#define a\\\n /**/}"); 22548 } 22549 22550 TEST_F(FormatTest, FormatsTableGenCode) { 22551 FormatStyle Style = getLLVMStyle(); 22552 Style.Language = FormatStyle::LK_TableGen; 22553 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22554 } 22555 22556 TEST_F(FormatTest, ArrayOfTemplates) { 22557 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22558 format("auto a = new unique_ptr<int > [ 10];")); 22559 22560 FormatStyle Spaces = getLLVMStyle(); 22561 Spaces.SpacesInSquareBrackets = true; 22562 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22563 format("auto a = new unique_ptr<int > [10];", Spaces)); 22564 } 22565 22566 TEST_F(FormatTest, ArrayAsTemplateType) { 22567 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22568 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22569 22570 FormatStyle Spaces = getLLVMStyle(); 22571 Spaces.SpacesInSquareBrackets = true; 22572 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22573 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22574 } 22575 22576 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22577 22578 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22579 llvm::vfs::InMemoryFileSystem FS; 22580 auto Style1 = getStyle("file", "", "Google", "", &FS); 22581 ASSERT_TRUE((bool)Style1); 22582 ASSERT_EQ(*Style1, getGoogleStyle()); 22583 } 22584 22585 TEST(FormatStyle, GetStyleOfFile) { 22586 llvm::vfs::InMemoryFileSystem FS; 22587 // Test 1: format file in the same directory. 22588 ASSERT_TRUE( 22589 FS.addFile("/a/.clang-format", 0, 22590 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22591 ASSERT_TRUE( 22592 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22593 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22594 ASSERT_TRUE((bool)Style1); 22595 ASSERT_EQ(*Style1, getLLVMStyle()); 22596 22597 // Test 2.1: fallback to default. 22598 ASSERT_TRUE( 22599 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22600 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22601 ASSERT_TRUE((bool)Style2); 22602 ASSERT_EQ(*Style2, getMozillaStyle()); 22603 22604 // Test 2.2: no format on 'none' fallback style. 22605 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22606 ASSERT_TRUE((bool)Style2); 22607 ASSERT_EQ(*Style2, getNoStyle()); 22608 22609 // Test 2.3: format if config is found with no based style while fallback is 22610 // 'none'. 22611 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22612 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22613 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22614 ASSERT_TRUE((bool)Style2); 22615 ASSERT_EQ(*Style2, getLLVMStyle()); 22616 22617 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22618 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22619 ASSERT_TRUE((bool)Style2); 22620 ASSERT_EQ(*Style2, getLLVMStyle()); 22621 22622 // Test 3: format file in parent directory. 22623 ASSERT_TRUE( 22624 FS.addFile("/c/.clang-format", 0, 22625 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22626 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22627 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22628 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22629 ASSERT_TRUE((bool)Style3); 22630 ASSERT_EQ(*Style3, getGoogleStyle()); 22631 22632 // Test 4: error on invalid fallback style 22633 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22634 ASSERT_FALSE((bool)Style4); 22635 llvm::consumeError(Style4.takeError()); 22636 22637 // Test 5: error on invalid yaml on command line 22638 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22639 ASSERT_FALSE((bool)Style5); 22640 llvm::consumeError(Style5.takeError()); 22641 22642 // Test 6: error on invalid style 22643 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22644 ASSERT_FALSE((bool)Style6); 22645 llvm::consumeError(Style6.takeError()); 22646 22647 // Test 7: found config file, error on parsing it 22648 ASSERT_TRUE( 22649 FS.addFile("/d/.clang-format", 0, 22650 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22651 "InvalidKey: InvalidValue"))); 22652 ASSERT_TRUE( 22653 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22654 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22655 ASSERT_FALSE((bool)Style7a); 22656 llvm::consumeError(Style7a.takeError()); 22657 22658 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22659 ASSERT_TRUE((bool)Style7b); 22660 22661 // Test 8: inferred per-language defaults apply. 22662 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22663 ASSERT_TRUE((bool)StyleTd); 22664 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22665 22666 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22667 // fallback style. 22668 ASSERT_TRUE(FS.addFile( 22669 "/e/sub/.clang-format", 0, 22670 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22671 "ColumnLimit: 20"))); 22672 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22673 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22674 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22675 ASSERT_TRUE(static_cast<bool>(Style9)); 22676 ASSERT_EQ(*Style9, [] { 22677 auto Style = getNoStyle(); 22678 Style.ColumnLimit = 20; 22679 return Style; 22680 }()); 22681 22682 // Test 9.1.2: propagate more than one level with no parent file. 22683 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22684 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22685 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22686 llvm::MemoryBuffer::getMemBuffer( 22687 "BasedOnStyle: InheritParentConfig\n" 22688 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22689 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22690 22691 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22692 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22693 ASSERT_TRUE(static_cast<bool>(Style9)); 22694 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22695 auto Style = getNoStyle(); 22696 Style.ColumnLimit = 20; 22697 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22698 return Style; 22699 }()); 22700 22701 // Test 9.2: with LLVM fallback style 22702 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22703 ASSERT_TRUE(static_cast<bool>(Style9)); 22704 ASSERT_EQ(*Style9, [] { 22705 auto Style = getLLVMStyle(); 22706 Style.ColumnLimit = 20; 22707 return Style; 22708 }()); 22709 22710 // Test 9.3: with a parent file 22711 ASSERT_TRUE( 22712 FS.addFile("/e/.clang-format", 0, 22713 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22714 "UseTab: Always"))); 22715 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22716 ASSERT_TRUE(static_cast<bool>(Style9)); 22717 ASSERT_EQ(*Style9, [] { 22718 auto Style = getGoogleStyle(); 22719 Style.ColumnLimit = 20; 22720 Style.UseTab = FormatStyle::UT_Always; 22721 return Style; 22722 }()); 22723 22724 // Test 9.4: propagate more than one level with a parent file. 22725 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22726 auto Style = getGoogleStyle(); 22727 Style.ColumnLimit = 20; 22728 Style.UseTab = FormatStyle::UT_Always; 22729 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22730 return Style; 22731 }(); 22732 22733 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22734 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22735 ASSERT_TRUE(static_cast<bool>(Style9)); 22736 ASSERT_EQ(*Style9, SubSubStyle); 22737 22738 // Test 9.5: use InheritParentConfig as style name 22739 Style9 = 22740 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22741 ASSERT_TRUE(static_cast<bool>(Style9)); 22742 ASSERT_EQ(*Style9, SubSubStyle); 22743 22744 // Test 9.6: use command line style with inheritance 22745 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22746 "none", "", &FS); 22747 ASSERT_TRUE(static_cast<bool>(Style9)); 22748 ASSERT_EQ(*Style9, SubSubStyle); 22749 22750 // Test 9.7: use command line style with inheritance and own config 22751 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22752 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22753 "/e/sub/code.cpp", "none", "", &FS); 22754 ASSERT_TRUE(static_cast<bool>(Style9)); 22755 ASSERT_EQ(*Style9, SubSubStyle); 22756 22757 // Test 9.8: use inheritance from a file without BasedOnStyle 22758 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22759 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22760 ASSERT_TRUE( 22761 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22762 llvm::MemoryBuffer::getMemBuffer( 22763 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22764 // Make sure we do not use the fallback style 22765 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22766 ASSERT_TRUE(static_cast<bool>(Style9)); 22767 ASSERT_EQ(*Style9, [] { 22768 auto Style = getLLVMStyle(); 22769 Style.ColumnLimit = 123; 22770 return Style; 22771 }()); 22772 22773 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22774 ASSERT_TRUE(static_cast<bool>(Style9)); 22775 ASSERT_EQ(*Style9, [] { 22776 auto Style = getLLVMStyle(); 22777 Style.ColumnLimit = 123; 22778 Style.IndentWidth = 7; 22779 return Style; 22780 }()); 22781 22782 // Test 9.9: use inheritance from a specific config file. 22783 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22784 "none", "", &FS); 22785 ASSERT_TRUE(static_cast<bool>(Style9)); 22786 ASSERT_EQ(*Style9, SubSubStyle); 22787 } 22788 22789 TEST(FormatStyle, GetStyleOfSpecificFile) { 22790 llvm::vfs::InMemoryFileSystem FS; 22791 // Specify absolute path to a format file in a parent directory. 22792 ASSERT_TRUE( 22793 FS.addFile("/e/.clang-format", 0, 22794 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22795 ASSERT_TRUE( 22796 FS.addFile("/e/explicit.clang-format", 0, 22797 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22798 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22799 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22800 auto Style = getStyle("file:/e/explicit.clang-format", 22801 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22802 ASSERT_TRUE(static_cast<bool>(Style)); 22803 ASSERT_EQ(*Style, getGoogleStyle()); 22804 22805 // Specify relative path to a format file. 22806 ASSERT_TRUE( 22807 FS.addFile("../../e/explicit.clang-format", 0, 22808 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22809 Style = getStyle("file:../../e/explicit.clang-format", 22810 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22811 ASSERT_TRUE(static_cast<bool>(Style)); 22812 ASSERT_EQ(*Style, getGoogleStyle()); 22813 22814 // Specify path to a format file that does not exist. 22815 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22816 "LLVM", "", &FS); 22817 ASSERT_FALSE(static_cast<bool>(Style)); 22818 llvm::consumeError(Style.takeError()); 22819 22820 // Specify path to a file on the filesystem. 22821 SmallString<128> FormatFilePath; 22822 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22823 "FormatFileTest", "tpl", FormatFilePath); 22824 EXPECT_FALSE((bool)ECF); 22825 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22826 EXPECT_FALSE((bool)ECF); 22827 FormatFileTest << "BasedOnStyle: Google\n"; 22828 FormatFileTest.close(); 22829 22830 SmallString<128> TestFilePath; 22831 std::error_code ECT = 22832 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22833 EXPECT_FALSE((bool)ECT); 22834 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22835 CodeFileTest << "int i;\n"; 22836 CodeFileTest.close(); 22837 22838 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22839 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22840 22841 llvm::sys::fs::remove(FormatFilePath.c_str()); 22842 llvm::sys::fs::remove(TestFilePath.c_str()); 22843 ASSERT_TRUE(static_cast<bool>(Style)); 22844 ASSERT_EQ(*Style, getGoogleStyle()); 22845 } 22846 22847 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22848 // Column limit is 20. 22849 std::string Code = "Type *a =\n" 22850 " new Type();\n" 22851 "g(iiiii, 0, jjjjj,\n" 22852 " 0, kkkkk, 0, mm);\n" 22853 "int bad = format ;"; 22854 std::string Expected = "auto a = new Type();\n" 22855 "g(iiiii, nullptr,\n" 22856 " jjjjj, nullptr,\n" 22857 " kkkkk, nullptr,\n" 22858 " mm);\n" 22859 "int bad = format ;"; 22860 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22861 tooling::Replacements Replaces = toReplacements( 22862 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22863 "auto "), 22864 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22865 "nullptr"), 22866 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22867 "nullptr"), 22868 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22869 "nullptr")}); 22870 22871 FormatStyle Style = getLLVMStyle(); 22872 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22873 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22874 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22875 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22876 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22877 EXPECT_TRUE(static_cast<bool>(Result)); 22878 EXPECT_EQ(Expected, *Result); 22879 } 22880 22881 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22882 std::string Code = "#include \"a.h\"\n" 22883 "#include \"c.h\"\n" 22884 "\n" 22885 "int main() {\n" 22886 " return 0;\n" 22887 "}"; 22888 std::string Expected = "#include \"a.h\"\n" 22889 "#include \"b.h\"\n" 22890 "#include \"c.h\"\n" 22891 "\n" 22892 "int main() {\n" 22893 " return 0;\n" 22894 "}"; 22895 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22896 tooling::Replacements Replaces = toReplacements( 22897 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22898 "#include \"b.h\"\n")}); 22899 22900 FormatStyle Style = getLLVMStyle(); 22901 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22902 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22903 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22904 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22905 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22906 EXPECT_TRUE(static_cast<bool>(Result)); 22907 EXPECT_EQ(Expected, *Result); 22908 } 22909 22910 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22911 EXPECT_EQ("using std::cin;\n" 22912 "using std::cout;", 22913 format("using std::cout;\n" 22914 "using std::cin;", 22915 getGoogleStyle())); 22916 } 22917 22918 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22919 FormatStyle Style = getLLVMStyle(); 22920 Style.Standard = FormatStyle::LS_Cpp03; 22921 // cpp03 recognize this string as identifier u8 and literal character 'a' 22922 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22923 } 22924 22925 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22926 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22927 // all modes, including C++11, C++14 and C++17 22928 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22929 } 22930 22931 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22932 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22933 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22934 } 22935 22936 TEST_F(FormatTest, StructuredBindings) { 22937 // Structured bindings is a C++17 feature. 22938 // all modes, including C++11, C++14 and C++17 22939 verifyFormat("auto [a, b] = f();"); 22940 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22941 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22942 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22943 EXPECT_EQ("auto const volatile [a, b] = f();", 22944 format("auto const volatile[a, b] = f();")); 22945 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22946 EXPECT_EQ("auto &[a, b, c] = f();", 22947 format("auto &[ a , b,c ] = f();")); 22948 EXPECT_EQ("auto &&[a, b, c] = f();", 22949 format("auto &&[ a , b,c ] = f();")); 22950 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22951 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22952 format("auto const volatile &&[a, b] = f();")); 22953 EXPECT_EQ("auto const &&[a, b] = f();", 22954 format("auto const && [a, b] = f();")); 22955 EXPECT_EQ("const auto &[a, b] = f();", 22956 format("const auto & [a, b] = f();")); 22957 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22958 format("const auto volatile &&[a, b] = f();")); 22959 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22960 format("volatile const auto &&[a, b] = f();")); 22961 EXPECT_EQ("const auto &&[a, b] = f();", 22962 format("const auto && [a, b] = f();")); 22963 22964 // Make sure we don't mistake structured bindings for lambdas. 22965 FormatStyle PointerMiddle = getLLVMStyle(); 22966 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22967 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22968 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22969 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22970 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22971 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22972 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22973 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22974 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22975 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22976 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22977 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22978 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22979 22980 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22981 format("for (const auto && [a, b] : some_range) {\n}")); 22982 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22983 format("for (const auto & [a, b] : some_range) {\n}")); 22984 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22985 format("for (const auto[a, b] : some_range) {\n}")); 22986 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22987 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22988 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22989 EXPECT_EQ("auto const &[x, y](expr);", 22990 format("auto const & [x,y] (expr);")); 22991 EXPECT_EQ("auto const &&[x, y](expr);", 22992 format("auto const && [x,y] (expr);")); 22993 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22994 EXPECT_EQ("auto const &[x, y]{expr};", 22995 format("auto const & [x,y] {expr};")); 22996 EXPECT_EQ("auto const &&[x, y]{expr};", 22997 format("auto const && [x,y] {expr};")); 22998 22999 FormatStyle Spaces = getLLVMStyle(); 23000 Spaces.SpacesInSquareBrackets = true; 23001 verifyFormat("auto [ a, b ] = f();", Spaces); 23002 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23003 verifyFormat("auto &[ a, b ] = f();", Spaces); 23004 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23005 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23006 } 23007 23008 TEST_F(FormatTest, FileAndCode) { 23009 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23010 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23011 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23012 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23013 EXPECT_EQ(FormatStyle::LK_ObjC, 23014 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23015 EXPECT_EQ( 23016 FormatStyle::LK_ObjC, 23017 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23018 EXPECT_EQ(FormatStyle::LK_ObjC, 23019 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23020 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23021 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23022 EXPECT_EQ(FormatStyle::LK_ObjC, 23023 guessLanguage("foo", "@interface Foo\n@end\n")); 23024 EXPECT_EQ(FormatStyle::LK_ObjC, 23025 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23026 EXPECT_EQ( 23027 FormatStyle::LK_ObjC, 23028 guessLanguage("foo.h", 23029 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23030 EXPECT_EQ( 23031 FormatStyle::LK_Cpp, 23032 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23033 // Only one of the two preprocessor regions has ObjC-like code. 23034 EXPECT_EQ(FormatStyle::LK_ObjC, 23035 guessLanguage("foo.h", "#if A\n" 23036 "#define B() C\n" 23037 "#else\n" 23038 "#define B() [NSString a:@\"\"]\n" 23039 "#endif\n")); 23040 } 23041 23042 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23043 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23044 EXPECT_EQ(FormatStyle::LK_ObjC, 23045 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23046 EXPECT_EQ(FormatStyle::LK_Cpp, 23047 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23048 EXPECT_EQ( 23049 FormatStyle::LK_Cpp, 23050 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23051 EXPECT_EQ(FormatStyle::LK_ObjC, 23052 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23053 EXPECT_EQ(FormatStyle::LK_Cpp, 23054 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23055 EXPECT_EQ(FormatStyle::LK_ObjC, 23056 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23057 EXPECT_EQ(FormatStyle::LK_Cpp, 23058 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23059 EXPECT_EQ(FormatStyle::LK_Cpp, 23060 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23061 EXPECT_EQ(FormatStyle::LK_ObjC, 23062 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23063 EXPECT_EQ(FormatStyle::LK_Cpp, 23064 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23065 EXPECT_EQ( 23066 FormatStyle::LK_Cpp, 23067 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23068 EXPECT_EQ( 23069 FormatStyle::LK_Cpp, 23070 guessLanguage("foo.h", 23071 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23072 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23073 } 23074 23075 TEST_F(FormatTest, GuessLanguageWithCaret) { 23076 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23077 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23078 EXPECT_EQ(FormatStyle::LK_ObjC, 23079 guessLanguage("foo.h", "int(^)(char, float);")); 23080 EXPECT_EQ(FormatStyle::LK_ObjC, 23081 guessLanguage("foo.h", "int(^foo)(char, float);")); 23082 EXPECT_EQ(FormatStyle::LK_ObjC, 23083 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23084 EXPECT_EQ(FormatStyle::LK_ObjC, 23085 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23086 EXPECT_EQ( 23087 FormatStyle::LK_ObjC, 23088 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23089 } 23090 23091 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23092 EXPECT_EQ(FormatStyle::LK_Cpp, 23093 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23094 EXPECT_EQ(FormatStyle::LK_Cpp, 23095 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23096 EXPECT_EQ(FormatStyle::LK_Cpp, 23097 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23098 } 23099 23100 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23101 // ASM symbolic names are identifiers that must be surrounded by [] without 23102 // space in between: 23103 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23104 23105 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23106 verifyFormat(R"(// 23107 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23108 )"); 23109 23110 // A list of several ASM symbolic names. 23111 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23112 23113 // ASM symbolic names in inline ASM with inputs and outputs. 23114 verifyFormat(R"(// 23115 asm("cmoveq %1, %2, %[result]" 23116 : [result] "=r"(result) 23117 : "r"(test), "r"(new), "[result]"(old)); 23118 )"); 23119 23120 // ASM symbolic names in inline ASM with no outputs. 23121 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23122 } 23123 23124 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23125 EXPECT_EQ(FormatStyle::LK_Cpp, 23126 guessLanguage("foo.h", "void f() {\n" 23127 " asm (\"mov %[e], %[d]\"\n" 23128 " : [d] \"=rm\" (d)\n" 23129 " [e] \"rm\" (*e));\n" 23130 "}")); 23131 EXPECT_EQ(FormatStyle::LK_Cpp, 23132 guessLanguage("foo.h", "void f() {\n" 23133 " _asm (\"mov %[e], %[d]\"\n" 23134 " : [d] \"=rm\" (d)\n" 23135 " [e] \"rm\" (*e));\n" 23136 "}")); 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 volatile (\"mov %[e], %[d]\"\n" 23158 " : [d] \"=rm\" (d)\n" 23159 " [e] \"rm\" (*e));\n" 23160 "}")); 23161 } 23162 23163 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23164 EXPECT_EQ(FormatStyle::LK_Cpp, 23165 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23166 EXPECT_EQ(FormatStyle::LK_ObjC, 23167 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23168 EXPECT_EQ( 23169 FormatStyle::LK_Cpp, 23170 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23171 EXPECT_EQ( 23172 FormatStyle::LK_ObjC, 23173 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23174 } 23175 23176 TEST_F(FormatTest, TypenameMacros) { 23177 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23178 23179 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23180 FormatStyle Google = getGoogleStyleWithColumns(0); 23181 Google.TypenameMacros = TypenameMacros; 23182 verifyFormat("struct foo {\n" 23183 " int bar;\n" 23184 " TAILQ_ENTRY(a) bleh;\n" 23185 "};", 23186 Google); 23187 23188 FormatStyle Macros = getLLVMStyle(); 23189 Macros.TypenameMacros = TypenameMacros; 23190 23191 verifyFormat("STACK_OF(int) a;", Macros); 23192 verifyFormat("STACK_OF(int) *a;", Macros); 23193 verifyFormat("STACK_OF(int const *) *a;", Macros); 23194 verifyFormat("STACK_OF(int *const) *a;", Macros); 23195 verifyFormat("STACK_OF(int, string) a;", Macros); 23196 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23197 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23198 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23199 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23200 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23201 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23202 23203 Macros.PointerAlignment = FormatStyle::PAS_Left; 23204 verifyFormat("STACK_OF(int)* a;", Macros); 23205 verifyFormat("STACK_OF(int*)* a;", Macros); 23206 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23207 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23208 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23209 } 23210 23211 TEST_F(FormatTest, AtomicQualifier) { 23212 // Check that we treate _Atomic as a type and not a function call 23213 FormatStyle Google = getGoogleStyleWithColumns(0); 23214 verifyFormat("struct foo {\n" 23215 " int a1;\n" 23216 " _Atomic(a) a2;\n" 23217 " _Atomic(_Atomic(int) *const) a3;\n" 23218 "};", 23219 Google); 23220 verifyFormat("_Atomic(uint64_t) a;"); 23221 verifyFormat("_Atomic(uint64_t) *a;"); 23222 verifyFormat("_Atomic(uint64_t const *) *a;"); 23223 verifyFormat("_Atomic(uint64_t *const) *a;"); 23224 verifyFormat("_Atomic(const uint64_t *) *a;"); 23225 verifyFormat("_Atomic(uint64_t) a;"); 23226 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23227 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23228 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23229 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23230 23231 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23232 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23233 FormatStyle Style = getLLVMStyle(); 23234 Style.PointerAlignment = FormatStyle::PAS_Left; 23235 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23236 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23237 verifyFormat("_Atomic(int)* a;", Style); 23238 verifyFormat("_Atomic(int*)* a;", Style); 23239 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23240 23241 Style.SpacesInCStyleCastParentheses = true; 23242 Style.SpacesInParentheses = false; 23243 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23244 Style.SpacesInCStyleCastParentheses = false; 23245 Style.SpacesInParentheses = true; 23246 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23247 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23248 } 23249 23250 TEST_F(FormatTest, AmbersandInLamda) { 23251 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23252 FormatStyle AlignStyle = getLLVMStyle(); 23253 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23254 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23255 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23256 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23257 } 23258 23259 TEST_F(FormatTest, SpacesInConditionalStatement) { 23260 FormatStyle Spaces = getLLVMStyle(); 23261 Spaces.IfMacros.clear(); 23262 Spaces.IfMacros.push_back("MYIF"); 23263 Spaces.SpacesInConditionalStatement = true; 23264 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23265 verifyFormat("if ( !a )\n return;", Spaces); 23266 verifyFormat("if ( a )\n return;", Spaces); 23267 verifyFormat("if constexpr ( a )\n return;", Spaces); 23268 verifyFormat("MYIF ( a )\n return;", Spaces); 23269 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23270 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23271 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23272 verifyFormat("while ( a )\n return;", Spaces); 23273 verifyFormat("while ( (a && b) )\n return;", Spaces); 23274 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23275 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23276 // Check that space on the left of "::" is inserted as expected at beginning 23277 // of condition. 23278 verifyFormat("while ( ::func() )\n return;", Spaces); 23279 23280 // Check impact of ControlStatementsExceptControlMacros is honored. 23281 Spaces.SpaceBeforeParens = 23282 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23283 verifyFormat("MYIF( a )\n return;", Spaces); 23284 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23285 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23286 } 23287 23288 TEST_F(FormatTest, AlternativeOperators) { 23289 // Test case for ensuring alternate operators are not 23290 // combined with their right most neighbour. 23291 verifyFormat("int a and b;"); 23292 verifyFormat("int a and_eq b;"); 23293 verifyFormat("int a bitand b;"); 23294 verifyFormat("int a bitor b;"); 23295 verifyFormat("int a compl b;"); 23296 verifyFormat("int a not b;"); 23297 verifyFormat("int a not_eq b;"); 23298 verifyFormat("int a or b;"); 23299 verifyFormat("int a xor b;"); 23300 verifyFormat("int a xor_eq b;"); 23301 verifyFormat("return this not_eq bitand other;"); 23302 verifyFormat("bool operator not_eq(const X bitand other)"); 23303 23304 verifyFormat("int a and 5;"); 23305 verifyFormat("int a and_eq 5;"); 23306 verifyFormat("int a bitand 5;"); 23307 verifyFormat("int a bitor 5;"); 23308 verifyFormat("int a compl 5;"); 23309 verifyFormat("int a not 5;"); 23310 verifyFormat("int a not_eq 5;"); 23311 verifyFormat("int a or 5;"); 23312 verifyFormat("int a xor 5;"); 23313 verifyFormat("int a xor_eq 5;"); 23314 23315 verifyFormat("int a compl(5);"); 23316 verifyFormat("int a not(5);"); 23317 23318 /* FIXME handle alternate tokens 23319 * https://en.cppreference.com/w/cpp/language/operator_alternative 23320 // alternative tokens 23321 verifyFormat("compl foo();"); // ~foo(); 23322 verifyFormat("foo() <%%>;"); // foo(); 23323 verifyFormat("void foo() <%%>;"); // void foo(){} 23324 verifyFormat("int a <:1:>;"); // int a[1];[ 23325 verifyFormat("%:define ABC abc"); // #define ABC abc 23326 verifyFormat("%:%:"); // ## 23327 */ 23328 } 23329 23330 TEST_F(FormatTest, STLWhileNotDefineChed) { 23331 verifyFormat("#if defined(while)\n" 23332 "#define while EMIT WARNING C4005\n" 23333 "#endif // while"); 23334 } 23335 23336 TEST_F(FormatTest, OperatorSpacing) { 23337 FormatStyle Style = getLLVMStyle(); 23338 Style.PointerAlignment = FormatStyle::PAS_Right; 23339 verifyFormat("Foo::operator*();", Style); 23340 verifyFormat("Foo::operator void *();", Style); 23341 verifyFormat("Foo::operator void **();", Style); 23342 verifyFormat("Foo::operator void *&();", Style); 23343 verifyFormat("Foo::operator void *&&();", Style); 23344 verifyFormat("Foo::operator void const *();", Style); 23345 verifyFormat("Foo::operator void const **();", Style); 23346 verifyFormat("Foo::operator void const *&();", Style); 23347 verifyFormat("Foo::operator void const *&&();", Style); 23348 verifyFormat("Foo::operator()(void *);", Style); 23349 verifyFormat("Foo::operator*(void *);", Style); 23350 verifyFormat("Foo::operator*();", Style); 23351 verifyFormat("Foo::operator**();", Style); 23352 verifyFormat("Foo::operator&();", Style); 23353 verifyFormat("Foo::operator<int> *();", Style); 23354 verifyFormat("Foo::operator<Foo> *();", Style); 23355 verifyFormat("Foo::operator<int> **();", Style); 23356 verifyFormat("Foo::operator<Foo> **();", Style); 23357 verifyFormat("Foo::operator<int> &();", Style); 23358 verifyFormat("Foo::operator<Foo> &();", Style); 23359 verifyFormat("Foo::operator<int> &&();", Style); 23360 verifyFormat("Foo::operator<Foo> &&();", Style); 23361 verifyFormat("Foo::operator<int> *&();", Style); 23362 verifyFormat("Foo::operator<Foo> *&();", Style); 23363 verifyFormat("Foo::operator<int> *&&();", Style); 23364 verifyFormat("Foo::operator<Foo> *&&();", Style); 23365 verifyFormat("operator*(int (*)(), class Foo);", Style); 23366 23367 verifyFormat("Foo::operator&();", Style); 23368 verifyFormat("Foo::operator void &();", Style); 23369 verifyFormat("Foo::operator void const &();", Style); 23370 verifyFormat("Foo::operator()(void &);", Style); 23371 verifyFormat("Foo::operator&(void &);", Style); 23372 verifyFormat("Foo::operator&();", Style); 23373 verifyFormat("operator&(int (&)(), class Foo);", Style); 23374 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23375 23376 verifyFormat("Foo::operator&&();", Style); 23377 verifyFormat("Foo::operator**();", Style); 23378 verifyFormat("Foo::operator void &&();", Style); 23379 verifyFormat("Foo::operator void const &&();", Style); 23380 verifyFormat("Foo::operator()(void &&);", Style); 23381 verifyFormat("Foo::operator&&(void &&);", Style); 23382 verifyFormat("Foo::operator&&();", Style); 23383 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23384 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23385 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23386 Style); 23387 verifyFormat("operator void **()", Style); 23388 verifyFormat("operator const FooRight<Object> &()", Style); 23389 verifyFormat("operator const FooRight<Object> *()", Style); 23390 verifyFormat("operator const FooRight<Object> **()", Style); 23391 verifyFormat("operator const FooRight<Object> *&()", Style); 23392 verifyFormat("operator const FooRight<Object> *&&()", Style); 23393 23394 Style.PointerAlignment = FormatStyle::PAS_Left; 23395 verifyFormat("Foo::operator*();", Style); 23396 verifyFormat("Foo::operator**();", Style); 23397 verifyFormat("Foo::operator void*();", Style); 23398 verifyFormat("Foo::operator void**();", Style); 23399 verifyFormat("Foo::operator void*&();", Style); 23400 verifyFormat("Foo::operator void*&&();", Style); 23401 verifyFormat("Foo::operator void const*();", Style); 23402 verifyFormat("Foo::operator void const**();", Style); 23403 verifyFormat("Foo::operator void const*&();", Style); 23404 verifyFormat("Foo::operator void const*&&();", Style); 23405 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23406 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23407 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23408 verifyFormat("Foo::operator()(void*);", Style); 23409 verifyFormat("Foo::operator*(void*);", Style); 23410 verifyFormat("Foo::operator*();", Style); 23411 verifyFormat("Foo::operator<int>*();", Style); 23412 verifyFormat("Foo::operator<Foo>*();", Style); 23413 verifyFormat("Foo::operator<int>**();", Style); 23414 verifyFormat("Foo::operator<Foo>**();", Style); 23415 verifyFormat("Foo::operator<Foo>*&();", Style); 23416 verifyFormat("Foo::operator<int>&();", Style); 23417 verifyFormat("Foo::operator<Foo>&();", Style); 23418 verifyFormat("Foo::operator<int>&&();", Style); 23419 verifyFormat("Foo::operator<Foo>&&();", Style); 23420 verifyFormat("Foo::operator<int>*&();", Style); 23421 verifyFormat("Foo::operator<Foo>*&();", Style); 23422 verifyFormat("operator*(int (*)(), class Foo);", Style); 23423 23424 verifyFormat("Foo::operator&();", Style); 23425 verifyFormat("Foo::operator void&();", Style); 23426 verifyFormat("Foo::operator void const&();", Style); 23427 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23428 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23429 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23430 verifyFormat("Foo::operator()(void&);", Style); 23431 verifyFormat("Foo::operator&(void&);", Style); 23432 verifyFormat("Foo::operator&();", Style); 23433 verifyFormat("operator&(int (&)(), class Foo);", Style); 23434 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23435 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23436 23437 verifyFormat("Foo::operator&&();", Style); 23438 verifyFormat("Foo::operator void&&();", Style); 23439 verifyFormat("Foo::operator void const&&();", Style); 23440 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23441 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23442 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23443 verifyFormat("Foo::operator()(void&&);", Style); 23444 verifyFormat("Foo::operator&&(void&&);", Style); 23445 verifyFormat("Foo::operator&&();", Style); 23446 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23447 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23448 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23449 Style); 23450 verifyFormat("operator void**()", Style); 23451 verifyFormat("operator const FooLeft<Object>&()", Style); 23452 verifyFormat("operator const FooLeft<Object>*()", Style); 23453 verifyFormat("operator const FooLeft<Object>**()", Style); 23454 verifyFormat("operator const FooLeft<Object>*&()", Style); 23455 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23456 23457 // PR45107 23458 verifyFormat("operator Vector<String>&();", Style); 23459 verifyFormat("operator const Vector<String>&();", Style); 23460 verifyFormat("operator foo::Bar*();", Style); 23461 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23462 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23463 Style); 23464 23465 Style.PointerAlignment = FormatStyle::PAS_Middle; 23466 verifyFormat("Foo::operator*();", Style); 23467 verifyFormat("Foo::operator void *();", Style); 23468 verifyFormat("Foo::operator()(void *);", Style); 23469 verifyFormat("Foo::operator*(void *);", Style); 23470 verifyFormat("Foo::operator*();", Style); 23471 verifyFormat("operator*(int (*)(), class Foo);", Style); 23472 23473 verifyFormat("Foo::operator&();", Style); 23474 verifyFormat("Foo::operator void &();", Style); 23475 verifyFormat("Foo::operator void const &();", Style); 23476 verifyFormat("Foo::operator()(void &);", Style); 23477 verifyFormat("Foo::operator&(void &);", Style); 23478 verifyFormat("Foo::operator&();", Style); 23479 verifyFormat("operator&(int (&)(), class Foo);", Style); 23480 23481 verifyFormat("Foo::operator&&();", Style); 23482 verifyFormat("Foo::operator void &&();", Style); 23483 verifyFormat("Foo::operator void const &&();", Style); 23484 verifyFormat("Foo::operator()(void &&);", Style); 23485 verifyFormat("Foo::operator&&(void &&);", Style); 23486 verifyFormat("Foo::operator&&();", Style); 23487 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23488 } 23489 23490 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23491 FormatStyle Style = getLLVMStyle(); 23492 // PR46157 23493 verifyFormat("foo(operator+, -42);", Style); 23494 verifyFormat("foo(operator++, -42);", Style); 23495 verifyFormat("foo(operator--, -42);", Style); 23496 verifyFormat("foo(-42, operator--);", Style); 23497 verifyFormat("foo(-42, operator, );", Style); 23498 verifyFormat("foo(operator, , -42);", Style); 23499 } 23500 23501 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23502 FormatStyle Style = getLLVMStyle(); 23503 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23504 23505 // Don't use the helpers here, since 'mess up' will change the whitespace 23506 // and these are all whitespace sensitive by definition 23507 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23508 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23509 EXPECT_EQ( 23510 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23511 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23512 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23513 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23514 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23515 " Still=Intentional);", 23516 format("FOO(String-ized&Messy+But,: :\n" 23517 " Still=Intentional);", 23518 Style)); 23519 Style.AlignConsecutiveAssignments.Enabled = true; 23520 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23521 " Still=Intentional);", 23522 format("FOO(String-ized=&Messy+But,: :\n" 23523 " Still=Intentional);", 23524 Style)); 23525 23526 Style.ColumnLimit = 21; 23527 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23528 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23529 } 23530 23531 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23532 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23533 // test its interaction with line wrapping 23534 FormatStyle Style = getLLVMStyleWithColumns(80); 23535 verifyFormat("namespace {\n" 23536 "int i;\n" 23537 "int j;\n" 23538 "} // namespace", 23539 Style); 23540 23541 verifyFormat("namespace AAA {\n" 23542 "int i;\n" 23543 "int j;\n" 23544 "} // namespace AAA", 23545 Style); 23546 23547 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23548 "int i;\n" 23549 "int j;\n" 23550 "} // namespace Averyveryveryverylongnamespace", 23551 format("namespace Averyveryveryverylongnamespace {\n" 23552 "int i;\n" 23553 "int j;\n" 23554 "}", 23555 Style)); 23556 23557 EXPECT_EQ( 23558 "namespace " 23559 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23560 " went::mad::now {\n" 23561 "int i;\n" 23562 "int j;\n" 23563 "} // namespace\n" 23564 " // " 23565 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23566 "went::mad::now", 23567 format("namespace " 23568 "would::it::save::you::a::lot::of::time::if_::i::" 23569 "just::gave::up::and_::went::mad::now {\n" 23570 "int i;\n" 23571 "int j;\n" 23572 "}", 23573 Style)); 23574 23575 // This used to duplicate the comment again and again on subsequent runs 23576 EXPECT_EQ( 23577 "namespace " 23578 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23579 " went::mad::now {\n" 23580 "int i;\n" 23581 "int j;\n" 23582 "} // namespace\n" 23583 " // " 23584 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23585 "went::mad::now", 23586 format("namespace " 23587 "would::it::save::you::a::lot::of::time::if_::i::" 23588 "just::gave::up::and_::went::mad::now {\n" 23589 "int i;\n" 23590 "int j;\n" 23591 "} // namespace\n" 23592 " // " 23593 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23594 "and_::went::mad::now", 23595 Style)); 23596 } 23597 23598 TEST_F(FormatTest, LikelyUnlikely) { 23599 FormatStyle Style = getLLVMStyle(); 23600 23601 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23602 " return 29;\n" 23603 "}", 23604 Style); 23605 23606 verifyFormat("if (argc > 5) [[likely]] {\n" 23607 " return 29;\n" 23608 "}", 23609 Style); 23610 23611 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23612 " return 29;\n" 23613 "} else [[likely]] {\n" 23614 " return 42;\n" 23615 "}\n", 23616 Style); 23617 23618 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23619 " return 29;\n" 23620 "} else if (argc > 10) [[likely]] {\n" 23621 " return 99;\n" 23622 "} else {\n" 23623 " return 42;\n" 23624 "}\n", 23625 Style); 23626 23627 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23628 " return 29;\n" 23629 "}", 23630 Style); 23631 23632 verifyFormat("if (argc > 5) [[unlikely]]\n" 23633 " return 29;\n", 23634 Style); 23635 verifyFormat("if (argc > 5) [[likely]]\n" 23636 " return 29;\n", 23637 Style); 23638 23639 Style.AttributeMacros.push_back("UNLIKELY"); 23640 Style.AttributeMacros.push_back("LIKELY"); 23641 verifyFormat("if (argc > 5) UNLIKELY\n" 23642 " return 29;\n", 23643 Style); 23644 23645 verifyFormat("if (argc > 5) UNLIKELY {\n" 23646 " return 29;\n" 23647 "}", 23648 Style); 23649 verifyFormat("if (argc > 5) UNLIKELY {\n" 23650 " return 29;\n" 23651 "} else [[likely]] {\n" 23652 " return 42;\n" 23653 "}\n", 23654 Style); 23655 verifyFormat("if (argc > 5) UNLIKELY {\n" 23656 " return 29;\n" 23657 "} else LIKELY {\n" 23658 " return 42;\n" 23659 "}\n", 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 } 23668 23669 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23670 verifyFormat("Constructor()\n" 23671 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23672 " aaaa(aaaaaaaaaaaaaaaaaa, " 23673 "aaaaaaaaaaaaaaaaaat))"); 23674 verifyFormat("Constructor()\n" 23675 " : aaaaaaaaaaaaa(aaaaaa), " 23676 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23677 23678 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23679 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23680 verifyFormat("Constructor()\n" 23681 " : aaaaaa(aaaaaa),\n" 23682 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23683 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23684 StyleWithWhitespacePenalty); 23685 verifyFormat("Constructor()\n" 23686 " : aaaaaaaaaaaaa(aaaaaa), " 23687 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23688 StyleWithWhitespacePenalty); 23689 } 23690 23691 TEST_F(FormatTest, LLVMDefaultStyle) { 23692 FormatStyle Style = getLLVMStyle(); 23693 verifyFormat("extern \"C\" {\n" 23694 "int foo();\n" 23695 "}", 23696 Style); 23697 } 23698 TEST_F(FormatTest, GNUDefaultStyle) { 23699 FormatStyle Style = getGNUStyle(); 23700 verifyFormat("extern \"C\"\n" 23701 "{\n" 23702 " int foo ();\n" 23703 "}", 23704 Style); 23705 } 23706 TEST_F(FormatTest, MozillaDefaultStyle) { 23707 FormatStyle Style = getMozillaStyle(); 23708 verifyFormat("extern \"C\"\n" 23709 "{\n" 23710 " int foo();\n" 23711 "}", 23712 Style); 23713 } 23714 TEST_F(FormatTest, GoogleDefaultStyle) { 23715 FormatStyle Style = getGoogleStyle(); 23716 verifyFormat("extern \"C\" {\n" 23717 "int foo();\n" 23718 "}", 23719 Style); 23720 } 23721 TEST_F(FormatTest, ChromiumDefaultStyle) { 23722 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23723 verifyFormat("extern \"C\" {\n" 23724 "int foo();\n" 23725 "}", 23726 Style); 23727 } 23728 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23729 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23730 verifyFormat("extern \"C\"\n" 23731 "{\n" 23732 " int foo();\n" 23733 "}", 23734 Style); 23735 } 23736 TEST_F(FormatTest, WebKitDefaultStyle) { 23737 FormatStyle Style = getWebKitStyle(); 23738 verifyFormat("extern \"C\" {\n" 23739 "int foo();\n" 23740 "}", 23741 Style); 23742 } 23743 23744 TEST_F(FormatTest, Concepts) { 23745 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23746 FormatStyle::BBCDS_Always); 23747 verifyFormat("template <typename T>\n" 23748 "concept True = true;"); 23749 23750 verifyFormat("template <typename T>\n" 23751 "concept C = ((false || foo()) && C2<T>) ||\n" 23752 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23753 getLLVMStyleWithColumns(60)); 23754 23755 verifyFormat("template <typename T>\n" 23756 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23757 "sizeof(T) <= 8;"); 23758 23759 verifyFormat("template <typename T>\n" 23760 "concept DelayedCheck = true && requires(T t) {\n" 23761 " t.bar();\n" 23762 " t.baz();\n" 23763 " } && sizeof(T) <= 8;"); 23764 23765 verifyFormat("template <typename T>\n" 23766 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23767 " t.bar();\n" 23768 " t.baz();\n" 23769 " } && sizeof(T) <= 8;"); 23770 23771 verifyFormat("template <typename T>\n" 23772 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23773 "sizeof(T) <= 8;"); 23774 23775 verifyFormat("template <typename T>\n" 23776 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23777 "&& sizeof(T) <= 8;"); 23778 23779 verifyFormat( 23780 "template <typename T>\n" 23781 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23782 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23783 23784 verifyFormat("template <typename T>\n" 23785 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23786 "&& sizeof(T) <= 8;"); 23787 23788 verifyFormat( 23789 "template <typename T>\n" 23790 "concept DelayedCheck = (bool)(0) ||\n" 23791 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23792 23793 verifyFormat("template <typename T>\n" 23794 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23795 "&& sizeof(T) <= 8;"); 23796 23797 verifyFormat("template <typename T>\n" 23798 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23799 "sizeof(T) <= 8;"); 23800 23801 verifyFormat("template <typename T>\n" 23802 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23803 " requires(T t) {\n" 23804 " t.bar();\n" 23805 " t.baz();\n" 23806 " } && sizeof(T) <= 8 && !(4 < 3);", 23807 getLLVMStyleWithColumns(60)); 23808 23809 verifyFormat("template <typename T>\n" 23810 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23811 23812 verifyFormat("template <typename T>\n" 23813 "concept C = foo();"); 23814 23815 verifyFormat("template <typename T>\n" 23816 "concept C = foo(T());"); 23817 23818 verifyFormat("template <typename T>\n" 23819 "concept C = foo(T{});"); 23820 23821 verifyFormat("template <typename T>\n" 23822 "concept Size = V<sizeof(T)>::Value > 5;"); 23823 23824 verifyFormat("template <typename T>\n" 23825 "concept True = S<T>::Value;"); 23826 23827 verifyFormat( 23828 "template <typename T>\n" 23829 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23830 " sizeof(T) <= 8;"); 23831 23832 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23833 // the lambda l square. 23834 verifyFormat("template <typename T>\n" 23835 "concept C = [] -> bool { return true; }() && requires(T t) { " 23836 "t.bar(); } &&\n" 23837 " sizeof(T) <= 8;"); 23838 23839 verifyFormat( 23840 "template <typename T>\n" 23841 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23842 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23843 23844 verifyFormat("template <typename T>\n" 23845 "concept C = decltype([]() { return std::true_type{}; " 23846 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23847 getLLVMStyleWithColumns(120)); 23848 23849 verifyFormat("template <typename T>\n" 23850 "concept C = decltype([]() -> std::true_type { return {}; " 23851 "}())::value &&\n" 23852 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23853 23854 verifyFormat("template <typename T>\n" 23855 "concept C = true;\n" 23856 "Foo Bar;"); 23857 23858 verifyFormat("template <typename T>\n" 23859 "concept Hashable = requires(T a) {\n" 23860 " { std::hash<T>{}(a) } -> " 23861 "std::convertible_to<std::size_t>;\n" 23862 " };"); 23863 23864 verifyFormat( 23865 "template <typename T>\n" 23866 "concept EqualityComparable = requires(T a, T b) {\n" 23867 " { a == b } -> std::same_as<bool>;\n" 23868 " };"); 23869 23870 verifyFormat( 23871 "template <typename T>\n" 23872 "concept EqualityComparable = requires(T a, T b) {\n" 23873 " { a == b } -> std::same_as<bool>;\n" 23874 " { a != b } -> std::same_as<bool>;\n" 23875 " };"); 23876 23877 verifyFormat("template <typename T>\n" 23878 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23879 " { a == b };\n" 23880 " { a != b };\n" 23881 " };"); 23882 23883 verifyFormat("template <typename T>\n" 23884 "concept HasSizeT = requires { typename T::size_t; };"); 23885 23886 verifyFormat("template <typename T>\n" 23887 "concept Semiregular =\n" 23888 " DefaultConstructible<T> && CopyConstructible<T> && " 23889 "CopyAssignable<T> &&\n" 23890 " requires(T a, std::size_t n) {\n" 23891 " requires Same<T *, decltype(&a)>;\n" 23892 " { a.~T() } noexcept;\n" 23893 " requires Same<T *, decltype(new T)>;\n" 23894 " requires Same<T *, decltype(new T[n])>;\n" 23895 " { delete new T; };\n" 23896 " { delete new T[n]; };\n" 23897 " };"); 23898 23899 verifyFormat("template <typename T>\n" 23900 "concept Semiregular =\n" 23901 " requires(T a, std::size_t n) {\n" 23902 " requires Same<T *, decltype(&a)>;\n" 23903 " { a.~T() } noexcept;\n" 23904 " requires Same<T *, decltype(new T)>;\n" 23905 " requires Same<T *, decltype(new T[n])>;\n" 23906 " { delete new T; };\n" 23907 " { delete new T[n]; };\n" 23908 " { new T } -> std::same_as<T *>;\n" 23909 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23910 "CopyAssignable<T>;"); 23911 23912 verifyFormat( 23913 "template <typename T>\n" 23914 "concept Semiregular =\n" 23915 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23916 " requires Same<T *, decltype(&a)>;\n" 23917 " { a.~T() } noexcept;\n" 23918 " requires Same<T *, decltype(new T)>;\n" 23919 " requires Same<T *, decltype(new " 23920 "T[n])>;\n" 23921 " { delete new T; };\n" 23922 " { delete new T[n]; };\n" 23923 " } && CopyConstructible<T> && " 23924 "CopyAssignable<T>;"); 23925 23926 verifyFormat("template <typename T>\n" 23927 "concept Two = requires(T t) {\n" 23928 " { t.foo() } -> std::same_as<Bar>;\n" 23929 " } && requires(T &&t) {\n" 23930 " { t.foo() } -> std::same_as<Bar &&>;\n" 23931 " };"); 23932 23933 verifyFormat( 23934 "template <typename T>\n" 23935 "concept C = requires(T x) {\n" 23936 " { *x } -> std::convertible_to<typename T::inner>;\n" 23937 " { x + 1 } noexcept -> std::same_as<int>;\n" 23938 " { x * 1 } -> std::convertible_to<T>;\n" 23939 " };"); 23940 23941 verifyFormat( 23942 "template <typename T, typename U = T>\n" 23943 "concept Swappable = requires(T &&t, U &&u) {\n" 23944 " swap(std::forward<T>(t), std::forward<U>(u));\n" 23945 " swap(std::forward<U>(u), std::forward<T>(t));\n" 23946 " };"); 23947 23948 verifyFormat("template <typename T, typename U>\n" 23949 "concept Common = requires(T &&t, U &&u) {\n" 23950 " typename CommonType<T, U>;\n" 23951 " { CommonType<T, U>(std::forward<T>(t)) };\n" 23952 " };"); 23953 23954 verifyFormat("template <typename T, typename U>\n" 23955 "concept Common = requires(T &&t, U &&u) {\n" 23956 " typename CommonType<T, U>;\n" 23957 " { CommonType<T, U>{std::forward<T>(t)} };\n" 23958 " };"); 23959 23960 verifyFormat( 23961 "template <typename T>\n" 23962 "concept C = requires(T t) {\n" 23963 " requires Bar<T> && Foo<T>;\n" 23964 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23965 " };"); 23966 23967 verifyFormat("template <typename T>\n" 23968 "concept HasFoo = requires(T t) {\n" 23969 " { t.foo() };\n" 23970 " t.foo();\n" 23971 " };\n" 23972 "template <typename T>\n" 23973 "concept HasBar = requires(T t) {\n" 23974 " { t.bar() };\n" 23975 " t.bar();\n" 23976 " };"); 23977 23978 verifyFormat("template <typename T>\n" 23979 "concept Large = sizeof(T) > 10;"); 23980 23981 verifyFormat("template <typename T, typename U>\n" 23982 "concept FooableWith = requires(T t, U u) {\n" 23983 " typename T::foo_type;\n" 23984 " { t.foo(u) } -> typename T::foo_type;\n" 23985 " t++;\n" 23986 " };\n" 23987 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 23988 23989 verifyFormat("template <typename T>\n" 23990 "concept Context = is_specialization_of_v<context, T>;"); 23991 23992 verifyFormat("template <typename T>\n" 23993 "concept Node = std::is_object_v<T>;"); 23994 23995 verifyFormat("template <class T>\n" 23996 "concept integral = __is_integral(T);"); 23997 23998 verifyFormat("template <class T>\n" 23999 "concept is2D = __array_extent(T, 1) == 2;"); 24000 24001 verifyFormat("template <class T>\n" 24002 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24003 24004 verifyFormat("template <class T, class T2>\n" 24005 "concept Same = __is_same_as<T, T2>;"); 24006 24007 auto Style = getLLVMStyle(); 24008 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24009 24010 verifyFormat( 24011 "template <typename T>\n" 24012 "concept C = requires(T t) {\n" 24013 " requires Bar<T> && Foo<T>;\n" 24014 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24015 " };", 24016 Style); 24017 24018 verifyFormat("template <typename T>\n" 24019 "concept HasFoo = requires(T t) {\n" 24020 " { t.foo() };\n" 24021 " t.foo();\n" 24022 " };\n" 24023 "template <typename T>\n" 24024 "concept HasBar = requires(T t) {\n" 24025 " { t.bar() };\n" 24026 " t.bar();\n" 24027 " };", 24028 Style); 24029 24030 verifyFormat("template <typename T> concept True = true;", Style); 24031 24032 verifyFormat("template <typename T>\n" 24033 "concept C = decltype([]() -> std::true_type { return {}; " 24034 "}())::value &&\n" 24035 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24036 Style); 24037 24038 verifyFormat("template <typename T>\n" 24039 "concept Semiregular =\n" 24040 " DefaultConstructible<T> && CopyConstructible<T> && " 24041 "CopyAssignable<T> &&\n" 24042 " requires(T a, std::size_t n) {\n" 24043 " requires Same<T *, decltype(&a)>;\n" 24044 " { a.~T() } noexcept;\n" 24045 " requires Same<T *, decltype(new T)>;\n" 24046 " requires Same<T *, decltype(new T[n])>;\n" 24047 " { delete new T; };\n" 24048 " { delete new T[n]; };\n" 24049 " };", 24050 Style); 24051 24052 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24053 24054 verifyFormat("template <typename T> concept C =\n" 24055 " requires(T t) {\n" 24056 " requires Bar<T> && Foo<T>;\n" 24057 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24058 " };", 24059 Style); 24060 24061 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24062 " { t.foo() };\n" 24063 " t.foo();\n" 24064 " };\n" 24065 "template <typename T> concept HasBar = requires(T t) {\n" 24066 " { t.bar() };\n" 24067 " t.bar();\n" 24068 " };", 24069 Style); 24070 24071 verifyFormat("template <typename T> concept True = true;", Style); 24072 24073 verifyFormat( 24074 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24075 " return {};\n" 24076 " }())::value &&\n" 24077 " requires(T t) { t.bar(); } && " 24078 "sizeof(T) <= 8;", 24079 Style); 24080 24081 verifyFormat("template <typename T> concept Semiregular =\n" 24082 " DefaultConstructible<T> && CopyConstructible<T> && " 24083 "CopyAssignable<T> &&\n" 24084 " requires(T a, std::size_t n) {\n" 24085 " requires Same<T *, decltype(&a)>;\n" 24086 " { a.~T() } noexcept;\n" 24087 " requires Same<T *, decltype(new T)>;\n" 24088 " requires Same<T *, decltype(new T[n])>;\n" 24089 " { delete new T; };\n" 24090 " { delete new T[n]; };\n" 24091 " };", 24092 Style); 24093 24094 // The following tests are invalid C++, we just want to make sure we don't 24095 // assert. 24096 verifyFormat("template <typename T>\n" 24097 "concept C = requires C2<T>;"); 24098 24099 verifyFormat("template <typename T>\n" 24100 "concept C = 5 + 4;"); 24101 24102 verifyFormat("template <typename T>\n" 24103 "concept C =\n" 24104 "class X;"); 24105 24106 verifyFormat("template <typename T>\n" 24107 "concept C = [] && true;"); 24108 24109 verifyFormat("template <typename T>\n" 24110 "concept C = [] && requires(T t) { typename T::size_type; };"); 24111 } 24112 24113 TEST_F(FormatTest, RequiresClausesPositions) { 24114 auto Style = getLLVMStyle(); 24115 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24116 EXPECT_EQ(Style.IndentRequiresClause, true); 24117 24118 verifyFormat("template <typename T>\n" 24119 " requires(Foo<T> && std::trait<T>)\n" 24120 "struct Bar;", 24121 Style); 24122 24123 verifyFormat("template <typename T>\n" 24124 " requires(Foo<T> && std::trait<T>)\n" 24125 "class Bar {\n" 24126 "public:\n" 24127 " Bar(T t);\n" 24128 " bool baz();\n" 24129 "};", 24130 Style); 24131 24132 verifyFormat( 24133 "template <typename T>\n" 24134 " requires requires(T &&t) {\n" 24135 " typename T::I;\n" 24136 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24137 " }\n" 24138 "Bar(T) -> Bar<typename T::I>;", 24139 Style); 24140 24141 verifyFormat("template <typename T>\n" 24142 " requires(Foo<T> && std::trait<T>)\n" 24143 "constexpr T MyGlobal;", 24144 Style); 24145 24146 verifyFormat("template <typename T>\n" 24147 " requires Foo<T> && requires(T t) {\n" 24148 " { t.baz() } -> std::same_as<bool>;\n" 24149 " requires std::same_as<T::Factor, int>;\n" 24150 " }\n" 24151 "inline int bar(T t) {\n" 24152 " return t.baz() ? T::Factor : 5;\n" 24153 "}", 24154 Style); 24155 24156 verifyFormat("template <typename T>\n" 24157 "inline int bar(T t)\n" 24158 " requires Foo<T> && requires(T t) {\n" 24159 " { t.baz() } -> std::same_as<bool>;\n" 24160 " requires std::same_as<T::Factor, int>;\n" 24161 " }\n" 24162 "{\n" 24163 " return t.baz() ? T::Factor : 5;\n" 24164 "}", 24165 Style); 24166 24167 verifyFormat("template <typename T>\n" 24168 " requires F<T>\n" 24169 "int bar(T t) {\n" 24170 " return 5;\n" 24171 "}", 24172 Style); 24173 24174 verifyFormat("template <typename T>\n" 24175 "int bar(T t)\n" 24176 " requires F<T>\n" 24177 "{\n" 24178 " return 5;\n" 24179 "}", 24180 Style); 24181 24182 verifyFormat("template <typename T>\n" 24183 "int bar(T t)\n" 24184 " requires F<T>;", 24185 Style); 24186 24187 Style.IndentRequiresClause = false; 24188 verifyFormat("template <typename T>\n" 24189 "requires F<T>\n" 24190 "int bar(T t) {\n" 24191 " return 5;\n" 24192 "}", 24193 Style); 24194 24195 verifyFormat("template <typename T>\n" 24196 "int bar(T t)\n" 24197 "requires F<T>\n" 24198 "{\n" 24199 " return 5;\n" 24200 "}", 24201 Style); 24202 24203 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24204 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24205 "template <typename T> requires Foo<T> void bar() {}\n" 24206 "template <typename T> void bar() requires Foo<T> {}\n" 24207 "template <typename T> void bar() requires Foo<T>;\n" 24208 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24209 Style); 24210 24211 auto ColumnStyle = Style; 24212 ColumnStyle.ColumnLimit = 40; 24213 verifyFormat("template <typename AAAAAAA>\n" 24214 "requires Foo<T> struct Bar {};\n" 24215 "template <typename AAAAAAA>\n" 24216 "requires Foo<T> void bar() {}\n" 24217 "template <typename AAAAAAA>\n" 24218 "void bar() requires Foo<T> {}\n" 24219 "template <typename AAAAAAA>\n" 24220 "requires Foo<T> Baz(T) -> Baz<T>;", 24221 ColumnStyle); 24222 24223 verifyFormat("template <typename T>\n" 24224 "requires Foo<AAAAAAA> struct Bar {};\n" 24225 "template <typename T>\n" 24226 "requires Foo<AAAAAAA> void bar() {}\n" 24227 "template <typename T>\n" 24228 "void bar() requires Foo<AAAAAAA> {}\n" 24229 "template <typename T>\n" 24230 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24231 ColumnStyle); 24232 24233 verifyFormat("template <typename AAAAAAA>\n" 24234 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24235 "struct Bar {};\n" 24236 "template <typename AAAAAAA>\n" 24237 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24238 "void bar() {}\n" 24239 "template <typename AAAAAAA>\n" 24240 "void bar()\n" 24241 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24242 "template <typename AAAAAAA>\n" 24243 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24244 "template <typename AAAAAAA>\n" 24245 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24246 "Bar(T) -> Bar<T>;", 24247 ColumnStyle); 24248 24249 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24250 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24251 24252 verifyFormat("template <typename T>\n" 24253 "requires Foo<T> struct Bar {};\n" 24254 "template <typename T>\n" 24255 "requires Foo<T> void bar() {}\n" 24256 "template <typename T>\n" 24257 "void bar()\n" 24258 "requires Foo<T> {}\n" 24259 "template <typename T>\n" 24260 "void bar()\n" 24261 "requires Foo<T>;\n" 24262 "template <typename T>\n" 24263 "requires Foo<T> Bar(T) -> Bar<T>;", 24264 Style); 24265 24266 verifyFormat("template <typename AAAAAAA>\n" 24267 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24268 "struct Bar {};\n" 24269 "template <typename AAAAAAA>\n" 24270 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24271 "void bar() {}\n" 24272 "template <typename AAAAAAA>\n" 24273 "void bar()\n" 24274 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24275 "template <typename AAAAAAA>\n" 24276 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24277 "template <typename AAAAAAA>\n" 24278 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24279 "Bar(T) -> Bar<T>;", 24280 ColumnStyle); 24281 24282 Style.IndentRequiresClause = true; 24283 ColumnStyle.IndentRequiresClause = true; 24284 24285 verifyFormat("template <typename T>\n" 24286 " requires Foo<T> struct Bar {};\n" 24287 "template <typename T>\n" 24288 " requires Foo<T> void bar() {}\n" 24289 "template <typename T>\n" 24290 "void bar()\n" 24291 " requires Foo<T> {}\n" 24292 "template <typename T>\n" 24293 " requires Foo<T> Bar(T) -> Bar<T>;", 24294 Style); 24295 24296 verifyFormat("template <typename AAAAAAA>\n" 24297 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24298 "struct Bar {};\n" 24299 "template <typename AAAAAAA>\n" 24300 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24301 "void bar() {}\n" 24302 "template <typename AAAAAAA>\n" 24303 "void bar()\n" 24304 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24305 "template <typename AAAAAAA>\n" 24306 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24307 "template <typename AAAAAAA>\n" 24308 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24309 "Bar(T) -> Bar<T>;", 24310 ColumnStyle); 24311 24312 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24313 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24314 24315 verifyFormat("template <typename T> requires Foo<T>\n" 24316 "struct Bar {};\n" 24317 "template <typename T> requires Foo<T>\n" 24318 "void bar() {}\n" 24319 "template <typename T>\n" 24320 "void bar() requires Foo<T>\n" 24321 "{}\n" 24322 "template <typename T> void bar() requires Foo<T>;\n" 24323 "template <typename T> requires Foo<T>\n" 24324 "Bar(T) -> Bar<T>;", 24325 Style); 24326 24327 verifyFormat("template <typename AAAAAAA>\n" 24328 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24329 "struct Bar {};\n" 24330 "template <typename AAAAAAA>\n" 24331 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24332 "void bar() {}\n" 24333 "template <typename AAAAAAA>\n" 24334 "void bar()\n" 24335 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24336 "{}\n" 24337 "template <typename AAAAAAA>\n" 24338 "requires Foo<AAAAAAAA>\n" 24339 "Bar(T) -> Bar<T>;\n" 24340 "template <typename AAAAAAA>\n" 24341 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24342 "Bar(T) -> Bar<T>;", 24343 ColumnStyle); 24344 } 24345 24346 TEST_F(FormatTest, RequiresClauses) { 24347 verifyFormat("struct [[nodiscard]] zero_t {\n" 24348 " template <class T>\n" 24349 " requires requires { number_zero_v<T>; }\n" 24350 " [[nodiscard]] constexpr operator T() const {\n" 24351 " return number_zero_v<T>;\n" 24352 " }\n" 24353 "};"); 24354 24355 auto Style = getLLVMStyle(); 24356 24357 verifyFormat( 24358 "template <typename T>\n" 24359 " requires is_default_constructible_v<hash<T>> and\n" 24360 " is_copy_constructible_v<hash<T>> and\n" 24361 " is_move_constructible_v<hash<T>> and\n" 24362 " is_copy_assignable_v<hash<T>> and " 24363 "is_move_assignable_v<hash<T>> and\n" 24364 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24365 " is_callable_v<hash<T>(T)> and\n" 24366 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24367 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24368 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24369 "struct S {};", 24370 Style); 24371 24372 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24373 verifyFormat( 24374 "template <typename T>\n" 24375 " requires is_default_constructible_v<hash<T>>\n" 24376 " and is_copy_constructible_v<hash<T>>\n" 24377 " and is_move_constructible_v<hash<T>>\n" 24378 " and is_copy_assignable_v<hash<T>> and " 24379 "is_move_assignable_v<hash<T>>\n" 24380 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24381 " and is_callable_v<hash<T>(T)>\n" 24382 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24383 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24384 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24385 "&>()))>\n" 24386 "struct S {};", 24387 Style); 24388 24389 // Not a clause, but we once hit an assert. 24390 verifyFormat("#if 0\n" 24391 "#else\n" 24392 "foo();\n" 24393 "#endif\n" 24394 "bar(requires);"); 24395 } 24396 24397 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24398 FormatStyle Style = getLLVMStyle(); 24399 StringRef Source = "void Foo::slot() {\n" 24400 " unsigned char MyChar = 'x';\n" 24401 " emit signal(MyChar);\n" 24402 " Q_EMIT signal(MyChar);\n" 24403 "}"; 24404 24405 EXPECT_EQ(Source, format(Source, Style)); 24406 24407 Style.AlignConsecutiveDeclarations.Enabled = true; 24408 EXPECT_EQ("void Foo::slot() {\n" 24409 " unsigned char MyChar = 'x';\n" 24410 " emit signal(MyChar);\n" 24411 " Q_EMIT signal(MyChar);\n" 24412 "}", 24413 format(Source, Style)); 24414 24415 Style.StatementAttributeLikeMacros.push_back("emit"); 24416 EXPECT_EQ(Source, format(Source, Style)); 24417 24418 Style.StatementAttributeLikeMacros = {}; 24419 EXPECT_EQ("void Foo::slot() {\n" 24420 " unsigned char MyChar = 'x';\n" 24421 " emit signal(MyChar);\n" 24422 " Q_EMIT signal(MyChar);\n" 24423 "}", 24424 format(Source, Style)); 24425 } 24426 24427 TEST_F(FormatTest, IndentAccessModifiers) { 24428 FormatStyle Style = getLLVMStyle(); 24429 Style.IndentAccessModifiers = true; 24430 // Members are *two* levels below the record; 24431 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24432 verifyFormat("class C {\n" 24433 " int i;\n" 24434 "};\n", 24435 Style); 24436 verifyFormat("union C {\n" 24437 " int i;\n" 24438 " unsigned u;\n" 24439 "};\n", 24440 Style); 24441 // Access modifiers should be indented one level below the record. 24442 verifyFormat("class C {\n" 24443 " public:\n" 24444 " int i;\n" 24445 "};\n", 24446 Style); 24447 verifyFormat("struct S {\n" 24448 " private:\n" 24449 " class C {\n" 24450 " int j;\n" 24451 "\n" 24452 " public:\n" 24453 " C();\n" 24454 " };\n" 24455 "\n" 24456 " public:\n" 24457 " int i;\n" 24458 "};\n", 24459 Style); 24460 // Enumerations are not records and should be unaffected. 24461 Style.AllowShortEnumsOnASingleLine = false; 24462 verifyFormat("enum class E {\n" 24463 " A,\n" 24464 " B\n" 24465 "};\n", 24466 Style); 24467 // Test with a different indentation width; 24468 // also proves that the result is Style.AccessModifierOffset agnostic. 24469 Style.IndentWidth = 3; 24470 verifyFormat("class C {\n" 24471 " public:\n" 24472 " int i;\n" 24473 "};\n", 24474 Style); 24475 } 24476 24477 TEST_F(FormatTest, LimitlessStringsAndComments) { 24478 auto Style = getLLVMStyleWithColumns(0); 24479 constexpr StringRef Code = 24480 "/**\n" 24481 " * This is a multiline comment with quite some long lines, at least for " 24482 "the LLVM Style.\n" 24483 " * We will redo this with strings and line comments. Just to check if " 24484 "everything is working.\n" 24485 " */\n" 24486 "bool foo() {\n" 24487 " /* Single line multi line comment. */\n" 24488 " const std::string String = \"This is a multiline string with quite " 24489 "some long lines, at least for the LLVM Style.\"\n" 24490 " \"We already did it with multi line " 24491 "comments, and we will do it with line comments. Just to check if " 24492 "everything is working.\";\n" 24493 " // This is a line comment (block) with quite some long lines, at " 24494 "least for the LLVM Style.\n" 24495 " // We already did this with multi line comments and strings. Just to " 24496 "check if everything is working.\n" 24497 " const std::string SmallString = \"Hello World\";\n" 24498 " // Small line comment\n" 24499 " return String.size() > SmallString.size();\n" 24500 "}"; 24501 EXPECT_EQ(Code, format(Code, Style)); 24502 } 24503 24504 TEST_F(FormatTest, FormatDecayCopy) { 24505 // error cases from unit tests 24506 verifyFormat("foo(auto())"); 24507 verifyFormat("foo(auto{})"); 24508 verifyFormat("foo(auto({}))"); 24509 verifyFormat("foo(auto{{}})"); 24510 24511 verifyFormat("foo(auto(1))"); 24512 verifyFormat("foo(auto{1})"); 24513 verifyFormat("foo(new auto(1))"); 24514 verifyFormat("foo(new auto{1})"); 24515 verifyFormat("decltype(auto(1)) x;"); 24516 verifyFormat("decltype(auto{1}) x;"); 24517 verifyFormat("auto(x);"); 24518 verifyFormat("auto{x};"); 24519 verifyFormat("new auto{x};"); 24520 verifyFormat("auto{x} = y;"); 24521 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24522 // the user's own fault 24523 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24524 // clearly the user's own fault 24525 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24526 } 24527 24528 TEST_F(FormatTest, Cpp20ModulesSupport) { 24529 FormatStyle Style = getLLVMStyle(); 24530 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24531 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24532 24533 verifyFormat("export import foo;", Style); 24534 verifyFormat("export import foo:bar;", Style); 24535 verifyFormat("export import foo.bar;", Style); 24536 verifyFormat("export import foo.bar:baz;", Style); 24537 verifyFormat("export import :bar;", Style); 24538 verifyFormat("export module foo:bar;", Style); 24539 verifyFormat("export module foo;", Style); 24540 verifyFormat("export module foo.bar;", Style); 24541 verifyFormat("export module foo.bar:baz;", Style); 24542 verifyFormat("export import <string_view>;", Style); 24543 24544 verifyFormat("export type_name var;", Style); 24545 verifyFormat("template <class T> export using A = B<T>;", Style); 24546 verifyFormat("export using A = B;", Style); 24547 verifyFormat("export int func() {\n" 24548 " foo();\n" 24549 "}", 24550 Style); 24551 verifyFormat("export struct {\n" 24552 " int foo;\n" 24553 "};", 24554 Style); 24555 verifyFormat("export {\n" 24556 " int foo;\n" 24557 "};", 24558 Style); 24559 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24560 24561 verifyFormat("import bar;", Style); 24562 verifyFormat("import foo.bar;", Style); 24563 verifyFormat("import foo:bar;", Style); 24564 verifyFormat("import :bar;", Style); 24565 verifyFormat("import <ctime>;", Style); 24566 verifyFormat("import \"header\";", Style); 24567 24568 verifyFormat("module foo;", Style); 24569 verifyFormat("module foo:bar;", Style); 24570 verifyFormat("module foo.bar;", Style); 24571 verifyFormat("module;", Style); 24572 24573 verifyFormat("export namespace hi {\n" 24574 "const char *sayhi();\n" 24575 "}", 24576 Style); 24577 24578 verifyFormat("module :private;", Style); 24579 verifyFormat("import <foo/bar.h>;", Style); 24580 verifyFormat("import foo...bar;", Style); 24581 verifyFormat("import ..........;", Style); 24582 verifyFormat("module foo:private;", Style); 24583 verifyFormat("import a", Style); 24584 verifyFormat("module a", Style); 24585 verifyFormat("export import a", Style); 24586 verifyFormat("export module a", Style); 24587 24588 verifyFormat("import", Style); 24589 verifyFormat("module", Style); 24590 verifyFormat("export", Style); 24591 } 24592 24593 TEST_F(FormatTest, CoroutineForCoawait) { 24594 FormatStyle Style = getLLVMStyle(); 24595 verifyFormat("for co_await (auto x : range())\n ;"); 24596 verifyFormat("for (auto i : arr) {\n" 24597 "}", 24598 Style); 24599 verifyFormat("for co_await (auto i : arr) {\n" 24600 "}", 24601 Style); 24602 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24603 "}", 24604 Style); 24605 } 24606 24607 TEST_F(FormatTest, CoroutineCoAwait) { 24608 verifyFormat("int x = co_await foo();"); 24609 verifyFormat("int x = (co_await foo());"); 24610 verifyFormat("co_await (42);"); 24611 verifyFormat("void operator co_await(int);"); 24612 verifyFormat("void operator co_await(a);"); 24613 verifyFormat("co_await a;"); 24614 verifyFormat("co_await missing_await_resume{};"); 24615 verifyFormat("co_await a; // comment"); 24616 verifyFormat("void test0() { co_await a; }"); 24617 verifyFormat("co_await co_await co_await foo();"); 24618 verifyFormat("co_await foo().bar();"); 24619 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24620 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24621 "foo(); }(x, y);"); 24622 24623 FormatStyle Style = getLLVMStyleWithColumns(40); 24624 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24625 " co_return co_await foo();\n" 24626 "}(x, y);", 24627 Style); 24628 verifyFormat("co_await;"); 24629 } 24630 24631 TEST_F(FormatTest, CoroutineCoYield) { 24632 verifyFormat("int x = co_yield foo();"); 24633 verifyFormat("int x = (co_yield foo());"); 24634 verifyFormat("co_yield (42);"); 24635 verifyFormat("co_yield {42};"); 24636 verifyFormat("co_yield 42;"); 24637 verifyFormat("co_yield n++;"); 24638 verifyFormat("co_yield ++n;"); 24639 verifyFormat("co_yield;"); 24640 } 24641 24642 TEST_F(FormatTest, CoroutineCoReturn) { 24643 verifyFormat("co_return (42);"); 24644 verifyFormat("co_return;"); 24645 verifyFormat("co_return {};"); 24646 verifyFormat("co_return x;"); 24647 verifyFormat("co_return co_await foo();"); 24648 verifyFormat("co_return co_yield foo();"); 24649 } 24650 24651 TEST_F(FormatTest, EmptyShortBlock) { 24652 auto Style = getLLVMStyle(); 24653 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24654 24655 verifyFormat("try {\n" 24656 " doA();\n" 24657 "} catch (Exception &e) {\n" 24658 " e.printStackTrace();\n" 24659 "}\n", 24660 Style); 24661 24662 verifyFormat("try {\n" 24663 " doA();\n" 24664 "} catch (Exception &e) {}\n", 24665 Style); 24666 } 24667 24668 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24669 auto Style = getLLVMStyle(); 24670 24671 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24672 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24673 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24674 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24675 24676 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24677 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24678 } 24679 24680 TEST_F(FormatTest, InsertBraces) { 24681 FormatStyle Style = getLLVMStyle(); 24682 Style.InsertBraces = true; 24683 24684 verifyFormat("// clang-format off\n" 24685 "// comment\n" 24686 "if (a) f();\n" 24687 "// clang-format on\n" 24688 "if (b) {\n" 24689 " g();\n" 24690 "}", 24691 "// clang-format off\n" 24692 "// comment\n" 24693 "if (a) f();\n" 24694 "// clang-format on\n" 24695 "if (b) g();", 24696 Style); 24697 24698 verifyFormat("if (a) {\n" 24699 " switch (b) {\n" 24700 " case 1:\n" 24701 " c = 0;\n" 24702 " break;\n" 24703 " default:\n" 24704 " c = 1;\n" 24705 " }\n" 24706 "}", 24707 "if (a)\n" 24708 " switch (b) {\n" 24709 " case 1:\n" 24710 " c = 0;\n" 24711 " break;\n" 24712 " default:\n" 24713 " c = 1;\n" 24714 " }", 24715 Style); 24716 24717 verifyFormat("for (auto node : nodes) {\n" 24718 " if (node) {\n" 24719 " break;\n" 24720 " }\n" 24721 "}", 24722 "for (auto node : nodes)\n" 24723 " if (node)\n" 24724 " break;", 24725 Style); 24726 24727 verifyFormat("for (auto node : nodes) {\n" 24728 " if (node)\n" 24729 "}", 24730 "for (auto node : nodes)\n" 24731 " if (node)", 24732 Style); 24733 24734 verifyFormat("do {\n" 24735 " --a;\n" 24736 "} while (a);", 24737 "do\n" 24738 " --a;\n" 24739 "while (a);", 24740 Style); 24741 24742 verifyFormat("if (i) {\n" 24743 " ++i;\n" 24744 "} else {\n" 24745 " --i;\n" 24746 "}", 24747 "if (i)\n" 24748 " ++i;\n" 24749 "else {\n" 24750 " --i;\n" 24751 "}", 24752 Style); 24753 24754 verifyFormat("void f() {\n" 24755 " while (j--) {\n" 24756 " while (i) {\n" 24757 " --i;\n" 24758 " }\n" 24759 " }\n" 24760 "}", 24761 "void f() {\n" 24762 " while (j--)\n" 24763 " while (i)\n" 24764 " --i;\n" 24765 "}", 24766 Style); 24767 24768 verifyFormat("f({\n" 24769 " if (a) {\n" 24770 " g();\n" 24771 " }\n" 24772 "});", 24773 "f({\n" 24774 " if (a)\n" 24775 " g();\n" 24776 "});", 24777 Style); 24778 24779 verifyFormat("if (a) {\n" 24780 " f();\n" 24781 "} else if (b) {\n" 24782 " g();\n" 24783 "} else {\n" 24784 " h();\n" 24785 "}", 24786 "if (a)\n" 24787 " f();\n" 24788 "else if (b)\n" 24789 " g();\n" 24790 "else\n" 24791 " h();", 24792 Style); 24793 24794 verifyFormat("if (a) {\n" 24795 " f();\n" 24796 "}\n" 24797 "// comment\n" 24798 "/* comment */", 24799 "if (a)\n" 24800 " f();\n" 24801 "// comment\n" 24802 "/* comment */", 24803 Style); 24804 24805 verifyFormat("if (a) {\n" 24806 " // foo\n" 24807 " // bar\n" 24808 " f();\n" 24809 "}", 24810 "if (a)\n" 24811 " // foo\n" 24812 " // bar\n" 24813 " f();", 24814 Style); 24815 24816 verifyFormat("if (a) { // comment\n" 24817 " // comment\n" 24818 " f();\n" 24819 "}", 24820 "if (a) // comment\n" 24821 " // comment\n" 24822 " f();", 24823 Style); 24824 24825 verifyFormat("if (a) {\n" 24826 " f(); // comment\n" 24827 "}", 24828 "if (a)\n" 24829 " f(); // comment", 24830 Style); 24831 24832 verifyFormat("if (a) {\n" 24833 " f();\n" 24834 "}\n" 24835 "#undef A\n" 24836 "#undef B", 24837 "if (a)\n" 24838 " f();\n" 24839 "#undef A\n" 24840 "#undef B", 24841 Style); 24842 24843 verifyFormat("if (a)\n" 24844 "#ifdef A\n" 24845 " f();\n" 24846 "#else\n" 24847 " g();\n" 24848 "#endif", 24849 Style); 24850 24851 verifyFormat("#if 0\n" 24852 "#elif 1\n" 24853 "#endif\n" 24854 "void f() {\n" 24855 " if (a) {\n" 24856 " g();\n" 24857 " }\n" 24858 "}", 24859 "#if 0\n" 24860 "#elif 1\n" 24861 "#endif\n" 24862 "void f() {\n" 24863 " if (a) g();\n" 24864 "}", 24865 Style); 24866 24867 Style.ColumnLimit = 15; 24868 24869 verifyFormat("#define A \\\n" 24870 " if (a) \\\n" 24871 " f();", 24872 Style); 24873 24874 verifyFormat("if (a + b >\n" 24875 " c) {\n" 24876 " f();\n" 24877 "}", 24878 "if (a + b > c)\n" 24879 " f();", 24880 Style); 24881 } 24882 24883 TEST_F(FormatTest, RemoveBraces) { 24884 FormatStyle Style = getLLVMStyle(); 24885 Style.RemoveBracesLLVM = true; 24886 24887 // The following eight test cases are fully-braced versions of the examples at 24888 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24889 // statement-bodies-of-if-else-loop-statements". 24890 24891 // 1. Omit the braces, since the body is simple and clearly associated with 24892 // the if. 24893 verifyFormat("if (isa<FunctionDecl>(D))\n" 24894 " handleFunctionDecl(D);\n" 24895 "else if (isa<VarDecl>(D))\n" 24896 " handleVarDecl(D);", 24897 "if (isa<FunctionDecl>(D)) {\n" 24898 " handleFunctionDecl(D);\n" 24899 "} else if (isa<VarDecl>(D)) {\n" 24900 " handleVarDecl(D);\n" 24901 "}", 24902 Style); 24903 24904 // 2. Here we document the condition itself and not the body. 24905 verifyFormat("if (isa<VarDecl>(D)) {\n" 24906 " // It is necessary that we explain the situation with this\n" 24907 " // surprisingly long comment, so it would be unclear\n" 24908 " // without the braces whether the following statement is in\n" 24909 " // the scope of the `if`.\n" 24910 " // Because the condition is documented, we can't really\n" 24911 " // hoist this comment that applies to the body above the\n" 24912 " // if.\n" 24913 " handleOtherDecl(D);\n" 24914 "}", 24915 Style); 24916 24917 // 3. Use braces on the outer `if` to avoid a potential dangling else 24918 // situation. 24919 verifyFormat("if (isa<VarDecl>(D)) {\n" 24920 " for (auto *A : D.attrs())\n" 24921 " if (shouldProcessAttr(A))\n" 24922 " handleAttr(A);\n" 24923 "}", 24924 "if (isa<VarDecl>(D)) {\n" 24925 " for (auto *A : D.attrs()) {\n" 24926 " if (shouldProcessAttr(A)) {\n" 24927 " handleAttr(A);\n" 24928 " }\n" 24929 " }\n" 24930 "}", 24931 Style); 24932 24933 // 4. Use braces for the `if` block to keep it uniform with the else block. 24934 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24935 " handleFunctionDecl(D);\n" 24936 "} else {\n" 24937 " // In this else case, it is necessary that we explain the\n" 24938 " // situation with this surprisingly long comment, so it\n" 24939 " // would be unclear without the braces whether the\n" 24940 " // following statement is in the scope of the `if`.\n" 24941 " handleOtherDecl(D);\n" 24942 "}", 24943 Style); 24944 24945 // 5. This should also omit braces. The `for` loop contains only a single 24946 // statement, so it shouldn't have braces. The `if` also only contains a 24947 // single simple statement (the for loop), so it also should omit braces. 24948 verifyFormat("if (isa<FunctionDecl>(D))\n" 24949 " for (auto *A : D.attrs())\n" 24950 " handleAttr(A);", 24951 "if (isa<FunctionDecl>(D)) {\n" 24952 " for (auto *A : D.attrs()) {\n" 24953 " handleAttr(A);\n" 24954 " }\n" 24955 "}", 24956 Style); 24957 24958 // 6. Use braces for the outer `if` since the nested `for` is braced. 24959 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24960 " for (auto *A : D.attrs()) {\n" 24961 " // In this for loop body, it is necessary that we explain\n" 24962 " // the situation with this surprisingly long comment,\n" 24963 " // forcing braces on the `for` block.\n" 24964 " handleAttr(A);\n" 24965 " }\n" 24966 "}", 24967 Style); 24968 24969 // 7. Use braces on the outer block because there are more than two levels of 24970 // nesting. 24971 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24972 " for (auto *A : D.attrs())\n" 24973 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 24974 " handleAttrOnDecl(D, A, i);\n" 24975 "}", 24976 "if (isa<FunctionDecl>(D)) {\n" 24977 " for (auto *A : D.attrs()) {\n" 24978 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 24979 " handleAttrOnDecl(D, A, i);\n" 24980 " }\n" 24981 " }\n" 24982 "}", 24983 Style); 24984 24985 // 8. Use braces on the outer block because of a nested `if`, otherwise the 24986 // compiler would warn: `add explicit braces to avoid dangling else` 24987 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24988 " if (shouldProcess(D))\n" 24989 " handleVarDecl(D);\n" 24990 " else\n" 24991 " markAsIgnored(D);\n" 24992 "}", 24993 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24994 " if (shouldProcess(D)) {\n" 24995 " handleVarDecl(D);\n" 24996 " } else {\n" 24997 " markAsIgnored(D);\n" 24998 " }\n" 24999 "}", 25000 Style); 25001 25002 verifyFormat("// clang-format off\n" 25003 "// comment\n" 25004 "while (i > 0) { --i; }\n" 25005 "// clang-format on\n" 25006 "while (j < 0)\n" 25007 " ++j;", 25008 "// clang-format off\n" 25009 "// comment\n" 25010 "while (i > 0) { --i; }\n" 25011 "// clang-format on\n" 25012 "while (j < 0) { ++j; }", 25013 Style); 25014 25015 verifyFormat("if (a)\n" 25016 " b; // comment\n" 25017 "else if (c)\n" 25018 " d; /* comment */\n" 25019 "else\n" 25020 " e;", 25021 "if (a) {\n" 25022 " b; // comment\n" 25023 "} else if (c) {\n" 25024 " d; /* comment */\n" 25025 "} else {\n" 25026 " e;\n" 25027 "}", 25028 Style); 25029 25030 verifyFormat("if (a) {\n" 25031 " b;\n" 25032 " c;\n" 25033 "} else if (d) {\n" 25034 " e;\n" 25035 "}", 25036 Style); 25037 25038 verifyFormat("if (a) {\n" 25039 "#undef NDEBUG\n" 25040 " b;\n" 25041 "} else {\n" 25042 " c;\n" 25043 "}", 25044 Style); 25045 25046 verifyFormat("if (a) {\n" 25047 " // comment\n" 25048 "} else if (b) {\n" 25049 " c;\n" 25050 "}", 25051 Style); 25052 25053 verifyFormat("if (a) {\n" 25054 " b;\n" 25055 "} else {\n" 25056 " { c; }\n" 25057 "}", 25058 Style); 25059 25060 verifyFormat("if (a) {\n" 25061 " if (b) // comment\n" 25062 " c;\n" 25063 "} else if (d) {\n" 25064 " e;\n" 25065 "}", 25066 "if (a) {\n" 25067 " if (b) { // comment\n" 25068 " c;\n" 25069 " }\n" 25070 "} else if (d) {\n" 25071 " e;\n" 25072 "}", 25073 Style); 25074 25075 verifyFormat("if (a) {\n" 25076 " if (b) {\n" 25077 " c;\n" 25078 " // comment\n" 25079 " } else if (d) {\n" 25080 " e;\n" 25081 " }\n" 25082 "}", 25083 Style); 25084 25085 verifyFormat("if (a) {\n" 25086 " if (b)\n" 25087 " c;\n" 25088 "}", 25089 "if (a) {\n" 25090 " if (b) {\n" 25091 " c;\n" 25092 " }\n" 25093 "}", 25094 Style); 25095 25096 verifyFormat("if (a)\n" 25097 " if (b)\n" 25098 " c;\n" 25099 " else\n" 25100 " d;\n" 25101 "else\n" 25102 " e;", 25103 "if (a) {\n" 25104 " if (b) {\n" 25105 " c;\n" 25106 " } else {\n" 25107 " d;\n" 25108 " }\n" 25109 "} else {\n" 25110 " e;\n" 25111 "}", 25112 Style); 25113 25114 verifyFormat("if (a) {\n" 25115 " // comment\n" 25116 " if (b)\n" 25117 " c;\n" 25118 " else if (d)\n" 25119 " e;\n" 25120 "} else {\n" 25121 " g;\n" 25122 "}", 25123 "if (a) {\n" 25124 " // comment\n" 25125 " if (b) {\n" 25126 " c;\n" 25127 " } else if (d) {\n" 25128 " e;\n" 25129 " }\n" 25130 "} else {\n" 25131 " g;\n" 25132 "}", 25133 Style); 25134 25135 verifyFormat("if (a)\n" 25136 " b;\n" 25137 "else if (c)\n" 25138 " d;\n" 25139 "else\n" 25140 " e;", 25141 "if (a) {\n" 25142 " b;\n" 25143 "} else {\n" 25144 " if (c) {\n" 25145 " d;\n" 25146 " } else {\n" 25147 " e;\n" 25148 " }\n" 25149 "}", 25150 Style); 25151 25152 verifyFormat("if (a) {\n" 25153 " if (b)\n" 25154 " c;\n" 25155 " else if (d)\n" 25156 " e;\n" 25157 "} else {\n" 25158 " g;\n" 25159 "}", 25160 "if (a) {\n" 25161 " if (b)\n" 25162 " c;\n" 25163 " else {\n" 25164 " if (d)\n" 25165 " e;\n" 25166 " }\n" 25167 "} else {\n" 25168 " g;\n" 25169 "}", 25170 Style); 25171 25172 verifyFormat("if (a)\n" 25173 " b;\n" 25174 "else if (c)\n" 25175 " while (d)\n" 25176 " e;\n" 25177 "// comment", 25178 "if (a)\n" 25179 "{\n" 25180 " b;\n" 25181 "} else if (c) {\n" 25182 " while (d) {\n" 25183 " e;\n" 25184 " }\n" 25185 "}\n" 25186 "// comment", 25187 Style); 25188 25189 verifyFormat("if (a) {\n" 25190 " b;\n" 25191 "} else if (c) {\n" 25192 " d;\n" 25193 "} else {\n" 25194 " e;\n" 25195 " g;\n" 25196 "}", 25197 Style); 25198 25199 verifyFormat("if (a) {\n" 25200 " b;\n" 25201 "} else if (c) {\n" 25202 " d;\n" 25203 "} else {\n" 25204 " e;\n" 25205 "} // comment", 25206 Style); 25207 25208 verifyFormat("int abs = [](int i) {\n" 25209 " if (i >= 0)\n" 25210 " return i;\n" 25211 " return -i;\n" 25212 "};", 25213 "int abs = [](int i) {\n" 25214 " if (i >= 0) {\n" 25215 " return i;\n" 25216 " }\n" 25217 " return -i;\n" 25218 "};", 25219 Style); 25220 25221 verifyFormat("if (a)\n" 25222 " foo();\n" 25223 "else\n" 25224 " bar();", 25225 "if (a)\n" 25226 "{\n" 25227 " foo();\n" 25228 "}\n" 25229 "else\n" 25230 "{\n" 25231 " bar();\n" 25232 "}", 25233 Style); 25234 25235 verifyFormat("if (a) {\n" 25236 "Label:\n" 25237 "}", 25238 Style); 25239 25240 verifyFormat("if (a) {\n" 25241 "Label:\n" 25242 " f();\n" 25243 "}", 25244 Style); 25245 25246 verifyFormat("if (a) {\n" 25247 " f();\n" 25248 "Label:\n" 25249 "}", 25250 Style); 25251 25252 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 25253 #if 0 25254 Style.ColumnLimit = 65; 25255 25256 verifyFormat("if (condition) {\n" 25257 " ff(Indices,\n" 25258 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25259 "} else {\n" 25260 " ff(Indices,\n" 25261 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25262 "}", 25263 Style); 25264 25265 Style.ColumnLimit = 20; 25266 25267 verifyFormat("if (a) {\n" 25268 " b = c + // 1 -\n" 25269 " d;\n" 25270 "}", 25271 Style); 25272 25273 verifyFormat("if (a) {\n" 25274 " b = c >= 0 ? d\n" 25275 " : e;\n" 25276 "}", 25277 "if (a) {\n" 25278 " b = c >= 0 ? d : e;\n" 25279 "}", 25280 Style); 25281 #endif 25282 25283 Style.ColumnLimit = 20; 25284 25285 verifyFormat("if (a)\n" 25286 " b = c > 0 ? d : e;", 25287 "if (a) {\n" 25288 " b = c > 0 ? d : e;\n" 25289 "}", 25290 Style); 25291 25292 Style.ColumnLimit = 0; 25293 25294 verifyFormat("if (a)\n" 25295 " b234567890223456789032345678904234567890 = " 25296 "c234567890223456789032345678904234567890;", 25297 "if (a) {\n" 25298 " b234567890223456789032345678904234567890 = " 25299 "c234567890223456789032345678904234567890;\n" 25300 "}", 25301 Style); 25302 } 25303 25304 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25305 auto Style = getLLVMStyle(); 25306 25307 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25308 "void functionDecl(int a, int b, int c);"; 25309 25310 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25311 "paramF, paramG, paramH, paramI);\n" 25312 "void functionDecl(int argumentA, int argumentB, int " 25313 "argumentC, int argumentD, int argumentE);"; 25314 25315 verifyFormat(Short, Style); 25316 25317 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25318 "paramF, paramG, paramH,\n" 25319 " paramI);\n" 25320 "void functionDecl(int argumentA, int argumentB, int " 25321 "argumentC, int argumentD,\n" 25322 " int argumentE);"; 25323 25324 verifyFormat(NoBreak, Medium, Style); 25325 verifyFormat(NoBreak, 25326 "functionCall(\n" 25327 " paramA,\n" 25328 " paramB,\n" 25329 " paramC,\n" 25330 " paramD,\n" 25331 " paramE,\n" 25332 " paramF,\n" 25333 " paramG,\n" 25334 " paramH,\n" 25335 " paramI\n" 25336 ");\n" 25337 "void functionDecl(\n" 25338 " int argumentA,\n" 25339 " int argumentB,\n" 25340 " int argumentC,\n" 25341 " int argumentD,\n" 25342 " int argumentE\n" 25343 ");", 25344 Style); 25345 25346 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25347 " nestedLongFunctionCall(argument1, " 25348 "argument2, argument3,\n" 25349 " argument4, " 25350 "argument5));", 25351 Style); 25352 25353 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25354 25355 verifyFormat(Short, Style); 25356 verifyFormat( 25357 "functionCall(\n" 25358 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25359 "paramI\n" 25360 ");\n" 25361 "void functionDecl(\n" 25362 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25363 "argumentE\n" 25364 ");", 25365 Medium, Style); 25366 25367 Style.AllowAllArgumentsOnNextLine = false; 25368 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25369 25370 verifyFormat(Short, Style); 25371 verifyFormat( 25372 "functionCall(\n" 25373 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25374 "paramI\n" 25375 ");\n" 25376 "void functionDecl(\n" 25377 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25378 "argumentE\n" 25379 ");", 25380 Medium, Style); 25381 25382 Style.BinPackArguments = false; 25383 Style.BinPackParameters = false; 25384 25385 verifyFormat(Short, Style); 25386 25387 verifyFormat("functionCall(\n" 25388 " paramA,\n" 25389 " paramB,\n" 25390 " paramC,\n" 25391 " paramD,\n" 25392 " paramE,\n" 25393 " paramF,\n" 25394 " paramG,\n" 25395 " paramH,\n" 25396 " paramI\n" 25397 ");\n" 25398 "void functionDecl(\n" 25399 " int argumentA,\n" 25400 " int argumentB,\n" 25401 " int argumentC,\n" 25402 " int argumentD,\n" 25403 " int argumentE\n" 25404 ");", 25405 Medium, Style); 25406 25407 verifyFormat("outerFunctionCall(\n" 25408 " nestedFunctionCall(argument1),\n" 25409 " nestedLongFunctionCall(\n" 25410 " argument1,\n" 25411 " argument2,\n" 25412 " argument3,\n" 25413 " argument4,\n" 25414 " argument5\n" 25415 " )\n" 25416 ");", 25417 Style); 25418 25419 verifyFormat("int a = (int)b;", Style); 25420 verifyFormat("int a = (int)b;", 25421 "int a = (\n" 25422 " int\n" 25423 ") b;", 25424 Style); 25425 25426 verifyFormat("return (true);", Style); 25427 verifyFormat("return (true);", 25428 "return (\n" 25429 " true\n" 25430 ");", 25431 Style); 25432 25433 verifyFormat("void foo();", Style); 25434 verifyFormat("void foo();", 25435 "void foo(\n" 25436 ");", 25437 Style); 25438 25439 verifyFormat("void foo() {}", Style); 25440 verifyFormat("void foo() {}", 25441 "void foo(\n" 25442 ") {\n" 25443 "}", 25444 Style); 25445 25446 verifyFormat("auto string = std::string();", Style); 25447 verifyFormat("auto string = std::string();", 25448 "auto string = std::string(\n" 25449 ");", 25450 Style); 25451 25452 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25453 verifyFormat("void (*functionPointer)() = nullptr;", 25454 "void (\n" 25455 " *functionPointer\n" 25456 ")\n" 25457 "(\n" 25458 ") = nullptr;", 25459 Style); 25460 } 25461 25462 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25463 auto Style = getLLVMStyle(); 25464 25465 verifyFormat("if (foo()) {\n" 25466 " return;\n" 25467 "}", 25468 Style); 25469 25470 verifyFormat("if (quitelongarg !=\n" 25471 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25472 "comment\n" 25473 " return;\n" 25474 "}", 25475 Style); 25476 25477 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25478 25479 verifyFormat("if (foo()) {\n" 25480 " return;\n" 25481 "}", 25482 Style); 25483 25484 verifyFormat("if (quitelongarg !=\n" 25485 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25486 "comment\n" 25487 " return;\n" 25488 "}", 25489 Style); 25490 } 25491 25492 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25493 auto Style = getLLVMStyle(); 25494 25495 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25496 " doSomething();\n" 25497 "}", 25498 Style); 25499 25500 verifyFormat("for (int myReallyLongCountVariable = 0; " 25501 "myReallyLongCountVariable < count;\n" 25502 " myReallyLongCountVariable++) {\n" 25503 " doSomething();\n" 25504 "}", 25505 Style); 25506 25507 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25508 25509 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25510 " doSomething();\n" 25511 "}", 25512 Style); 25513 25514 verifyFormat("for (int myReallyLongCountVariable = 0; " 25515 "myReallyLongCountVariable < count;\n" 25516 " myReallyLongCountVariable++) {\n" 25517 " doSomething();\n" 25518 "}", 25519 Style); 25520 } 25521 25522 TEST_F(FormatTest, UnderstandsDigraphs) { 25523 verifyFormat("int arr<:5:> = {};"); 25524 verifyFormat("int arr[5] = <%%>;"); 25525 verifyFormat("int arr<:::qualified_variable:> = {};"); 25526 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25527 verifyFormat("%:include <header>"); 25528 verifyFormat("%:define A x##y"); 25529 verifyFormat("#define A x%:%:y"); 25530 } 25531 25532 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 25533 auto Style = getLLVMStyle(); 25534 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 25535 Style.AlignConsecutiveAssignments.Enabled = true; 25536 Style.AlignConsecutiveDeclarations.Enabled = true; 25537 25538 // The AlignArray code is incorrect for non square Arrays and can cause 25539 // crashes, these tests assert that the array is not changed but will 25540 // also act as regression tests for when it is properly fixed 25541 verifyFormat("struct test demo[] = {\n" 25542 " {1, 2},\n" 25543 " {3, 4, 5},\n" 25544 " {6, 7, 8}\n" 25545 "};", 25546 Style); 25547 verifyFormat("struct test demo[] = {\n" 25548 " {1, 2, 3, 4, 5},\n" 25549 " {3, 4, 5},\n" 25550 " {6, 7, 8}\n" 25551 "};", 25552 Style); 25553 verifyFormat("struct test demo[] = {\n" 25554 " {1, 2, 3, 4, 5},\n" 25555 " {3, 4, 5},\n" 25556 " {6, 7, 8, 9, 10, 11, 12}\n" 25557 "};", 25558 Style); 25559 verifyFormat("struct test demo[] = {\n" 25560 " {1, 2, 3},\n" 25561 " {3, 4, 5},\n" 25562 " {6, 7, 8, 9, 10, 11, 12}\n" 25563 "};", 25564 Style); 25565 25566 verifyFormat("S{\n" 25567 " {},\n" 25568 " {},\n" 25569 " {a, b}\n" 25570 "};", 25571 Style); 25572 verifyFormat("S{\n" 25573 " {},\n" 25574 " {},\n" 25575 " {a, b},\n" 25576 "};", 25577 Style); 25578 verifyFormat("void foo() {\n" 25579 " auto thing = test{\n" 25580 " {\n" 25581 " {13}, {something}, // A\n" 25582 " }\n" 25583 " };\n" 25584 "}", 25585 "void foo() {\n" 25586 " auto thing = test{\n" 25587 " {\n" 25588 " {13},\n" 25589 " {something}, // A\n" 25590 " }\n" 25591 " };\n" 25592 "}", 25593 Style); 25594 } 25595 25596 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 25597 auto Style = getLLVMStyle(); 25598 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 25599 Style.AlignConsecutiveAssignments.Enabled = true; 25600 Style.AlignConsecutiveDeclarations.Enabled = true; 25601 25602 // The AlignArray code is incorrect for non square Arrays and can cause 25603 // crashes, these tests assert that the array is not changed but will 25604 // also act as regression tests for when it is properly fixed 25605 verifyFormat("struct test demo[] = {\n" 25606 " {1, 2},\n" 25607 " {3, 4, 5},\n" 25608 " {6, 7, 8}\n" 25609 "};", 25610 Style); 25611 verifyFormat("struct test demo[] = {\n" 25612 " {1, 2, 3, 4, 5},\n" 25613 " {3, 4, 5},\n" 25614 " {6, 7, 8}\n" 25615 "};", 25616 Style); 25617 verifyFormat("struct test demo[] = {\n" 25618 " {1, 2, 3, 4, 5},\n" 25619 " {3, 4, 5},\n" 25620 " {6, 7, 8, 9, 10, 11, 12}\n" 25621 "};", 25622 Style); 25623 verifyFormat("struct test demo[] = {\n" 25624 " {1, 2, 3},\n" 25625 " {3, 4, 5},\n" 25626 " {6, 7, 8, 9, 10, 11, 12}\n" 25627 "};", 25628 Style); 25629 25630 verifyFormat("S{\n" 25631 " {},\n" 25632 " {},\n" 25633 " {a, b}\n" 25634 "};", 25635 Style); 25636 verifyFormat("S{\n" 25637 " {},\n" 25638 " {},\n" 25639 " {a, b},\n" 25640 "};", 25641 Style); 25642 verifyFormat("void foo() {\n" 25643 " auto thing = test{\n" 25644 " {\n" 25645 " {13}, {something}, // A\n" 25646 " }\n" 25647 " };\n" 25648 "}", 25649 "void foo() {\n" 25650 " auto thing = test{\n" 25651 " {\n" 25652 " {13},\n" 25653 " {something}, // A\n" 25654 " }\n" 25655 " };\n" 25656 "}", 25657 Style); 25658 } 25659 25660 TEST_F(FormatTest, FormatsVariableTemplates) { 25661 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 25662 verifyFormat("template <typename T> " 25663 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 25664 } 25665 25666 } // namespace 25667 } // namespace format 25668 } // namespace clang 25669