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.AllowShortBlocksOnASingleLine = 1577 FormatStyle::SBS_Empty; 1578 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1579 FormatStyle::SIS_WithoutElse; 1580 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1581 verifyFormat("if (i) break;", AllowSimpleBracedStatements); 1582 verifyFormat("if (i > 0) {\n" 1583 " return i;\n" 1584 "}", 1585 AllowSimpleBracedStatements); 1586 1587 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1588 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1589 // Not IF to avoid any confusion that IF is somehow special. 1590 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1591 AllowSimpleBracedStatements.ColumnLimit = 40; 1592 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1593 FormatStyle::SBS_Always; 1594 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1595 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1596 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1597 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1598 1599 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1600 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1601 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1602 verifyFormat("if consteval {}", AllowSimpleBracedStatements); 1603 verifyFormat("if !consteval {}", AllowSimpleBracedStatements); 1604 verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements); 1605 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1606 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1607 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1608 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1609 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1610 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1611 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1612 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1613 verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements); 1614 verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1615 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1616 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1617 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1618 verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements); 1619 verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1620 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1621 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1622 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1623 AllowSimpleBracedStatements); 1624 verifyFormat("if (true) {\n" 1625 " ffffffffffffffffffffffff();\n" 1626 "}", 1627 AllowSimpleBracedStatements); 1628 verifyFormat("if (true) {\n" 1629 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1630 "}", 1631 AllowSimpleBracedStatements); 1632 verifyFormat("if (true) { //\n" 1633 " f();\n" 1634 "}", 1635 AllowSimpleBracedStatements); 1636 verifyFormat("if (true) {\n" 1637 " f();\n" 1638 " f();\n" 1639 "}", 1640 AllowSimpleBracedStatements); 1641 verifyFormat("if (true) {\n" 1642 " f();\n" 1643 "} else {\n" 1644 " f();\n" 1645 "}", 1646 AllowSimpleBracedStatements); 1647 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1648 AllowSimpleBracedStatements); 1649 verifyFormat("MYIF (true) {\n" 1650 " ffffffffffffffffffffffff();\n" 1651 "}", 1652 AllowSimpleBracedStatements); 1653 verifyFormat("MYIF (true) {\n" 1654 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1655 "}", 1656 AllowSimpleBracedStatements); 1657 verifyFormat("MYIF (true) { //\n" 1658 " f();\n" 1659 "}", 1660 AllowSimpleBracedStatements); 1661 verifyFormat("MYIF (true) {\n" 1662 " f();\n" 1663 " f();\n" 1664 "}", 1665 AllowSimpleBracedStatements); 1666 verifyFormat("MYIF (true) {\n" 1667 " f();\n" 1668 "} else {\n" 1669 " f();\n" 1670 "}", 1671 AllowSimpleBracedStatements); 1672 1673 verifyFormat("struct A2 {\n" 1674 " int X;\n" 1675 "};", 1676 AllowSimpleBracedStatements); 1677 verifyFormat("typedef struct A2 {\n" 1678 " int X;\n" 1679 "} A2_t;", 1680 AllowSimpleBracedStatements); 1681 verifyFormat("template <int> struct A2 {\n" 1682 " struct B {};\n" 1683 "};", 1684 AllowSimpleBracedStatements); 1685 1686 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1687 FormatStyle::SIS_Never; 1688 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1689 verifyFormat("if (true) {\n" 1690 " f();\n" 1691 "}", 1692 AllowSimpleBracedStatements); 1693 verifyFormat("if (true) {\n" 1694 " f();\n" 1695 "} else {\n" 1696 " f();\n" 1697 "}", 1698 AllowSimpleBracedStatements); 1699 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1700 verifyFormat("MYIF (true) {\n" 1701 " f();\n" 1702 "}", 1703 AllowSimpleBracedStatements); 1704 verifyFormat("MYIF (true) {\n" 1705 " f();\n" 1706 "} else {\n" 1707 " f();\n" 1708 "}", 1709 AllowSimpleBracedStatements); 1710 1711 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1712 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1713 verifyFormat("while (true) {\n" 1714 " f();\n" 1715 "}", 1716 AllowSimpleBracedStatements); 1717 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1718 verifyFormat("for (;;) {\n" 1719 " f();\n" 1720 "}", 1721 AllowSimpleBracedStatements); 1722 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1723 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1724 " f();\n" 1725 "}", 1726 AllowSimpleBracedStatements); 1727 1728 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1729 FormatStyle::SIS_WithoutElse; 1730 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1731 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1732 FormatStyle::BWACS_Always; 1733 1734 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1735 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1736 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1737 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1738 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1739 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1740 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1741 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1742 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1743 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1744 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1745 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1746 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1747 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1748 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1749 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1750 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1751 AllowSimpleBracedStatements); 1752 verifyFormat("if (true)\n" 1753 "{\n" 1754 " ffffffffffffffffffffffff();\n" 1755 "}", 1756 AllowSimpleBracedStatements); 1757 verifyFormat("if (true)\n" 1758 "{\n" 1759 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1760 "}", 1761 AllowSimpleBracedStatements); 1762 verifyFormat("if (true)\n" 1763 "{ //\n" 1764 " f();\n" 1765 "}", 1766 AllowSimpleBracedStatements); 1767 verifyFormat("if (true)\n" 1768 "{\n" 1769 " f();\n" 1770 " f();\n" 1771 "}", 1772 AllowSimpleBracedStatements); 1773 verifyFormat("if (true)\n" 1774 "{\n" 1775 " f();\n" 1776 "} else\n" 1777 "{\n" 1778 " f();\n" 1779 "}", 1780 AllowSimpleBracedStatements); 1781 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1782 AllowSimpleBracedStatements); 1783 verifyFormat("MYIF (true)\n" 1784 "{\n" 1785 " ffffffffffffffffffffffff();\n" 1786 "}", 1787 AllowSimpleBracedStatements); 1788 verifyFormat("MYIF (true)\n" 1789 "{\n" 1790 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1791 "}", 1792 AllowSimpleBracedStatements); 1793 verifyFormat("MYIF (true)\n" 1794 "{ //\n" 1795 " f();\n" 1796 "}", 1797 AllowSimpleBracedStatements); 1798 verifyFormat("MYIF (true)\n" 1799 "{\n" 1800 " f();\n" 1801 " f();\n" 1802 "}", 1803 AllowSimpleBracedStatements); 1804 verifyFormat("MYIF (true)\n" 1805 "{\n" 1806 " f();\n" 1807 "} else\n" 1808 "{\n" 1809 " f();\n" 1810 "}", 1811 AllowSimpleBracedStatements); 1812 1813 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1814 FormatStyle::SIS_Never; 1815 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1816 verifyFormat("if (true)\n" 1817 "{\n" 1818 " f();\n" 1819 "}", 1820 AllowSimpleBracedStatements); 1821 verifyFormat("if (true)\n" 1822 "{\n" 1823 " f();\n" 1824 "} else\n" 1825 "{\n" 1826 " f();\n" 1827 "}", 1828 AllowSimpleBracedStatements); 1829 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1830 verifyFormat("MYIF (true)\n" 1831 "{\n" 1832 " f();\n" 1833 "}", 1834 AllowSimpleBracedStatements); 1835 verifyFormat("MYIF (true)\n" 1836 "{\n" 1837 " f();\n" 1838 "} else\n" 1839 "{\n" 1840 " f();\n" 1841 "}", 1842 AllowSimpleBracedStatements); 1843 1844 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1845 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1846 verifyFormat("while (true)\n" 1847 "{\n" 1848 " f();\n" 1849 "}", 1850 AllowSimpleBracedStatements); 1851 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1852 verifyFormat("for (;;)\n" 1853 "{\n" 1854 " f();\n" 1855 "}", 1856 AllowSimpleBracedStatements); 1857 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1858 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1859 "{\n" 1860 " f();\n" 1861 "}", 1862 AllowSimpleBracedStatements); 1863 } 1864 1865 TEST_F(FormatTest, UnderstandsMacros) { 1866 verifyFormat("#define A (parentheses)"); 1867 verifyFormat("/* comment */ #define A (parentheses)"); 1868 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1869 // Even the partial code should never be merged. 1870 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1871 "#", 1872 format("/* comment */ #define A (parentheses)\n" 1873 "#")); 1874 verifyFormat("/* comment */ #define A (parentheses)\n" 1875 "#\n"); 1876 verifyFormat("/* comment */ #define A (parentheses)\n" 1877 "#define B (parentheses)"); 1878 verifyFormat("#define true ((int)1)"); 1879 verifyFormat("#define and(x)"); 1880 verifyFormat("#define if(x) x"); 1881 verifyFormat("#define return(x) (x)"); 1882 verifyFormat("#define while(x) for (; x;)"); 1883 verifyFormat("#define xor(x) (^(x))"); 1884 verifyFormat("#define __except(x)"); 1885 verifyFormat("#define __try(x)"); 1886 1887 // https://llvm.org/PR54348. 1888 verifyFormat( 1889 "#define A" 1890 " " 1891 "\\\n" 1892 " class & {}"); 1893 1894 FormatStyle Style = getLLVMStyle(); 1895 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1896 Style.BraceWrapping.AfterFunction = true; 1897 // Test that a macro definition never gets merged with the following 1898 // definition. 1899 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1900 verifyFormat("#define AAA " 1901 " \\\n" 1902 " N " 1903 " \\\n" 1904 " {\n" 1905 "#define BBB }\n", 1906 Style); 1907 // verifyFormat("#define AAA N { //\n", Style); 1908 1909 verifyFormat("MACRO(return)"); 1910 verifyFormat("MACRO(co_await)"); 1911 verifyFormat("MACRO(co_return)"); 1912 verifyFormat("MACRO(co_yield)"); 1913 verifyFormat("MACRO(return, something)"); 1914 verifyFormat("MACRO(co_return, something)"); 1915 verifyFormat("MACRO(something##something)"); 1916 verifyFormat("MACRO(return##something)"); 1917 verifyFormat("MACRO(co_return##something)"); 1918 } 1919 1920 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1921 FormatStyle Style = getLLVMStyleWithColumns(60); 1922 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1923 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1924 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1925 EXPECT_EQ("#define A \\\n" 1926 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1927 " { \\\n" 1928 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1929 " }\n" 1930 "X;", 1931 format("#define A \\\n" 1932 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1933 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1934 " }\n" 1935 "X;", 1936 Style)); 1937 } 1938 1939 TEST_F(FormatTest, ParseIfElse) { 1940 verifyFormat("if (true)\n" 1941 " if (true)\n" 1942 " if (true)\n" 1943 " f();\n" 1944 " else\n" 1945 " g();\n" 1946 " else\n" 1947 " h();\n" 1948 "else\n" 1949 " i();"); 1950 verifyFormat("if (true)\n" 1951 " if (true)\n" 1952 " if (true) {\n" 1953 " if (true)\n" 1954 " f();\n" 1955 " } else {\n" 1956 " g();\n" 1957 " }\n" 1958 " else\n" 1959 " h();\n" 1960 "else {\n" 1961 " i();\n" 1962 "}"); 1963 verifyFormat("if (true)\n" 1964 " if constexpr (true)\n" 1965 " if (true) {\n" 1966 " if constexpr (true)\n" 1967 " f();\n" 1968 " } else {\n" 1969 " g();\n" 1970 " }\n" 1971 " else\n" 1972 " h();\n" 1973 "else {\n" 1974 " i();\n" 1975 "}"); 1976 verifyFormat("if (true)\n" 1977 " if CONSTEXPR (true)\n" 1978 " if (true) {\n" 1979 " if CONSTEXPR (true)\n" 1980 " f();\n" 1981 " } else {\n" 1982 " g();\n" 1983 " }\n" 1984 " else\n" 1985 " h();\n" 1986 "else {\n" 1987 " i();\n" 1988 "}"); 1989 verifyFormat("void f() {\n" 1990 " if (a) {\n" 1991 " } else {\n" 1992 " }\n" 1993 "}"); 1994 } 1995 1996 TEST_F(FormatTest, ElseIf) { 1997 verifyFormat("if (a) {\n} else if (b) {\n}"); 1998 verifyFormat("if (a)\n" 1999 " f();\n" 2000 "else if (b)\n" 2001 " g();\n" 2002 "else\n" 2003 " h();"); 2004 verifyFormat("if (a)\n" 2005 " f();\n" 2006 "else // comment\n" 2007 " if (b) {\n" 2008 " g();\n" 2009 " h();\n" 2010 " }"); 2011 verifyFormat("if constexpr (a)\n" 2012 " f();\n" 2013 "else if constexpr (b)\n" 2014 " g();\n" 2015 "else\n" 2016 " h();"); 2017 verifyFormat("if CONSTEXPR (a)\n" 2018 " f();\n" 2019 "else if CONSTEXPR (b)\n" 2020 " g();\n" 2021 "else\n" 2022 " h();"); 2023 verifyFormat("if (a) {\n" 2024 " f();\n" 2025 "}\n" 2026 "// or else ..\n" 2027 "else {\n" 2028 " g()\n" 2029 "}"); 2030 2031 verifyFormat("if (a) {\n" 2032 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2033 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2034 "}"); 2035 verifyFormat("if (a) {\n" 2036 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2037 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2038 "}"); 2039 verifyFormat("if (a) {\n" 2040 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2041 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2042 "}"); 2043 verifyFormat("if (a) {\n" 2044 "} else if (\n" 2045 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2046 "}", 2047 getLLVMStyleWithColumns(62)); 2048 verifyFormat("if (a) {\n" 2049 "} else if constexpr (\n" 2050 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2051 "}", 2052 getLLVMStyleWithColumns(62)); 2053 verifyFormat("if (a) {\n" 2054 "} else if CONSTEXPR (\n" 2055 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2056 "}", 2057 getLLVMStyleWithColumns(62)); 2058 } 2059 2060 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2061 FormatStyle Style = getLLVMStyle(); 2062 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2063 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2064 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2065 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2066 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2067 verifyFormat("int *f1(int &a) const &;", Style); 2068 verifyFormat("int *f1(int &a) const & = 0;", Style); 2069 verifyFormat("int *a = f1();", Style); 2070 verifyFormat("int &b = f2();", Style); 2071 verifyFormat("int &&c = f3();", Style); 2072 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2073 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2074 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2075 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2076 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2077 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2078 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2079 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2080 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2081 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2082 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2083 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2084 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2085 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2086 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2087 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2088 verifyFormat( 2089 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2090 " res2 = [](int &a) { return 0000000000000; };", 2091 Style); 2092 2093 Style.AlignConsecutiveDeclarations.Enabled = true; 2094 verifyFormat("Const unsigned int *c;\n" 2095 "const unsigned int *d;\n" 2096 "Const unsigned int &e;\n" 2097 "const unsigned int &f;\n" 2098 "const unsigned &&g;\n" 2099 "Const unsigned h;", 2100 Style); 2101 2102 Style.PointerAlignment = FormatStyle::PAS_Left; 2103 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2104 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2105 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2106 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2107 verifyFormat("int* f1(int& a) const& = 0;", Style); 2108 verifyFormat("int* a = f1();", Style); 2109 verifyFormat("int& b = f2();", Style); 2110 verifyFormat("int&& c = f3();", Style); 2111 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2112 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2113 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2114 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2115 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2116 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2117 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2118 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2119 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2120 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2121 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2122 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2123 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2124 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2125 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2126 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2127 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2128 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2129 verifyFormat( 2130 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2131 " res2 = [](int& a) { return 0000000000000; };", 2132 Style); 2133 2134 Style.AlignConsecutiveDeclarations.Enabled = true; 2135 verifyFormat("Const unsigned int* c;\n" 2136 "const unsigned int* d;\n" 2137 "Const unsigned int& e;\n" 2138 "const unsigned int& f;\n" 2139 "const unsigned&& g;\n" 2140 "Const unsigned h;", 2141 Style); 2142 2143 Style.PointerAlignment = FormatStyle::PAS_Right; 2144 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2145 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2146 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2147 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2148 verifyFormat("int *a = f1();", Style); 2149 verifyFormat("int& b = f2();", Style); 2150 verifyFormat("int&& c = f3();", Style); 2151 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2152 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2153 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2154 2155 Style.AlignConsecutiveDeclarations.Enabled = true; 2156 verifyFormat("Const unsigned int *c;\n" 2157 "const unsigned int *d;\n" 2158 "Const unsigned int& e;\n" 2159 "const unsigned int& f;\n" 2160 "const unsigned g;\n" 2161 "Const unsigned h;", 2162 Style); 2163 2164 Style.PointerAlignment = FormatStyle::PAS_Left; 2165 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2166 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2167 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2168 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2169 verifyFormat("int* a = f1();", Style); 2170 verifyFormat("int & b = f2();", Style); 2171 verifyFormat("int && c = f3();", Style); 2172 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2173 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2174 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2175 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2176 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2177 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2178 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2179 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2180 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2181 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2182 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2183 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2184 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2185 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2186 verifyFormat( 2187 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2188 " res2 = [](int & a) { return 0000000000000; };", 2189 Style); 2190 2191 Style.AlignConsecutiveDeclarations.Enabled = true; 2192 verifyFormat("Const unsigned int* c;\n" 2193 "const unsigned int* d;\n" 2194 "Const unsigned int & e;\n" 2195 "const unsigned int & f;\n" 2196 "const unsigned && g;\n" 2197 "Const unsigned h;", 2198 Style); 2199 2200 Style.PointerAlignment = FormatStyle::PAS_Middle; 2201 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2202 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2203 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2204 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2205 verifyFormat("int * a = f1();", Style); 2206 verifyFormat("int &b = f2();", Style); 2207 verifyFormat("int &&c = f3();", Style); 2208 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2209 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2210 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2211 2212 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2213 // specifically handled 2214 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2215 } 2216 2217 TEST_F(FormatTest, FormatsForLoop) { 2218 verifyFormat( 2219 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2220 " ++VeryVeryLongLoopVariable)\n" 2221 " ;"); 2222 verifyFormat("for (;;)\n" 2223 " f();"); 2224 verifyFormat("for (;;) {\n}"); 2225 verifyFormat("for (;;) {\n" 2226 " f();\n" 2227 "}"); 2228 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2229 2230 verifyFormat( 2231 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2232 " E = UnwrappedLines.end();\n" 2233 " I != E; ++I) {\n}"); 2234 2235 verifyFormat( 2236 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2237 " ++IIIII) {\n}"); 2238 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2239 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2240 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2241 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2242 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2243 " E = FD->getDeclsInPrototypeScope().end();\n" 2244 " I != E; ++I) {\n}"); 2245 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2246 " I = Container.begin(),\n" 2247 " E = Container.end();\n" 2248 " I != E; ++I) {\n}", 2249 getLLVMStyleWithColumns(76)); 2250 2251 verifyFormat( 2252 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2253 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2254 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2255 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2256 " ++aaaaaaaaaaa) {\n}"); 2257 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2258 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2259 " ++i) {\n}"); 2260 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2261 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2262 "}"); 2263 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2264 " aaaaaaaaaa);\n" 2265 " iter; ++iter) {\n" 2266 "}"); 2267 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2268 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2269 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2270 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2271 2272 // These should not be formatted as Objective-C for-in loops. 2273 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2274 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2275 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2276 verifyFormat( 2277 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2278 2279 FormatStyle NoBinPacking = getLLVMStyle(); 2280 NoBinPacking.BinPackParameters = false; 2281 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2282 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2283 " aaaaaaaaaaaaaaaa,\n" 2284 " aaaaaaaaaaaaaaaa,\n" 2285 " aaaaaaaaaaaaaaaa);\n" 2286 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2287 "}", 2288 NoBinPacking); 2289 verifyFormat( 2290 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2291 " E = UnwrappedLines.end();\n" 2292 " I != E;\n" 2293 " ++I) {\n}", 2294 NoBinPacking); 2295 2296 FormatStyle AlignLeft = getLLVMStyle(); 2297 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2298 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2299 } 2300 2301 TEST_F(FormatTest, RangeBasedForLoops) { 2302 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2304 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2305 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2306 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2308 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2309 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2310 } 2311 2312 TEST_F(FormatTest, ForEachLoops) { 2313 FormatStyle Style = getLLVMStyle(); 2314 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2315 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2316 verifyFormat("void f() {\n" 2317 " for (;;) {\n" 2318 " }\n" 2319 " foreach (Item *item, itemlist) {\n" 2320 " }\n" 2321 " Q_FOREACH (Item *item, itemlist) {\n" 2322 " }\n" 2323 " BOOST_FOREACH (Item *item, itemlist) {\n" 2324 " }\n" 2325 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2326 "}", 2327 Style); 2328 verifyFormat("void f() {\n" 2329 " for (;;)\n" 2330 " int j = 1;\n" 2331 " Q_FOREACH (int v, vec)\n" 2332 " v *= 2;\n" 2333 " for (;;) {\n" 2334 " int j = 1;\n" 2335 " }\n" 2336 " Q_FOREACH (int v, vec) {\n" 2337 " v *= 2;\n" 2338 " }\n" 2339 "}", 2340 Style); 2341 2342 FormatStyle ShortBlocks = getLLVMStyle(); 2343 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2344 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2345 verifyFormat("void f() {\n" 2346 " for (;;)\n" 2347 " int j = 1;\n" 2348 " Q_FOREACH (int &v, vec)\n" 2349 " v *= 2;\n" 2350 " for (;;) {\n" 2351 " int j = 1;\n" 2352 " }\n" 2353 " Q_FOREACH (int &v, vec) {\n" 2354 " int j = 1;\n" 2355 " }\n" 2356 "}", 2357 ShortBlocks); 2358 2359 FormatStyle ShortLoops = getLLVMStyle(); 2360 ShortLoops.AllowShortLoopsOnASingleLine = true; 2361 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2362 verifyFormat("void f() {\n" 2363 " for (;;) int j = 1;\n" 2364 " Q_FOREACH (int &v, vec) int j = 1;\n" 2365 " for (;;) {\n" 2366 " int j = 1;\n" 2367 " }\n" 2368 " Q_FOREACH (int &v, vec) {\n" 2369 " int j = 1;\n" 2370 " }\n" 2371 "}", 2372 ShortLoops); 2373 2374 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2375 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2376 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2377 verifyFormat("void f() {\n" 2378 " for (;;) int j = 1;\n" 2379 " Q_FOREACH (int &v, vec) int j = 1;\n" 2380 " for (;;) { int j = 1; }\n" 2381 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2382 "}", 2383 ShortBlocksAndLoops); 2384 2385 Style.SpaceBeforeParens = 2386 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2387 verifyFormat("void f() {\n" 2388 " for (;;) {\n" 2389 " }\n" 2390 " foreach(Item *item, itemlist) {\n" 2391 " }\n" 2392 " Q_FOREACH(Item *item, itemlist) {\n" 2393 " }\n" 2394 " BOOST_FOREACH(Item *item, itemlist) {\n" 2395 " }\n" 2396 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2397 "}", 2398 Style); 2399 2400 // As function-like macros. 2401 verifyFormat("#define foreach(x, y)\n" 2402 "#define Q_FOREACH(x, y)\n" 2403 "#define BOOST_FOREACH(x, y)\n" 2404 "#define UNKNOWN_FOREACH(x, y)\n"); 2405 2406 // Not as function-like macros. 2407 verifyFormat("#define foreach (x, y)\n" 2408 "#define Q_FOREACH (x, y)\n" 2409 "#define BOOST_FOREACH (x, y)\n" 2410 "#define UNKNOWN_FOREACH (x, y)\n"); 2411 2412 // handle microsoft non standard extension 2413 verifyFormat("for each (char c in x->MyStringProperty)"); 2414 } 2415 2416 TEST_F(FormatTest, FormatsWhileLoop) { 2417 verifyFormat("while (true) {\n}"); 2418 verifyFormat("while (true)\n" 2419 " f();"); 2420 verifyFormat("while () {\n}"); 2421 verifyFormat("while () {\n" 2422 " f();\n" 2423 "}"); 2424 } 2425 2426 TEST_F(FormatTest, FormatsDoWhile) { 2427 verifyFormat("do {\n" 2428 " do_something();\n" 2429 "} while (something());"); 2430 verifyFormat("do\n" 2431 " do_something();\n" 2432 "while (something());"); 2433 } 2434 2435 TEST_F(FormatTest, FormatsSwitchStatement) { 2436 verifyFormat("switch (x) {\n" 2437 "case 1:\n" 2438 " f();\n" 2439 " break;\n" 2440 "case kFoo:\n" 2441 "case ns::kBar:\n" 2442 "case kBaz:\n" 2443 " break;\n" 2444 "default:\n" 2445 " g();\n" 2446 " break;\n" 2447 "}"); 2448 verifyFormat("switch (x) {\n" 2449 "case 1: {\n" 2450 " f();\n" 2451 " break;\n" 2452 "}\n" 2453 "case 2: {\n" 2454 " break;\n" 2455 "}\n" 2456 "}"); 2457 verifyFormat("switch (x) {\n" 2458 "case 1: {\n" 2459 " f();\n" 2460 " {\n" 2461 " g();\n" 2462 " h();\n" 2463 " }\n" 2464 " break;\n" 2465 "}\n" 2466 "}"); 2467 verifyFormat("switch (x) {\n" 2468 "case 1: {\n" 2469 " f();\n" 2470 " if (foo) {\n" 2471 " g();\n" 2472 " h();\n" 2473 " }\n" 2474 " break;\n" 2475 "}\n" 2476 "}"); 2477 verifyFormat("switch (x) {\n" 2478 "case 1: {\n" 2479 " f();\n" 2480 " g();\n" 2481 "} break;\n" 2482 "}"); 2483 verifyFormat("switch (test)\n" 2484 " ;"); 2485 verifyFormat("switch (x) {\n" 2486 "default: {\n" 2487 " // Do nothing.\n" 2488 "}\n" 2489 "}"); 2490 verifyFormat("switch (x) {\n" 2491 "// comment\n" 2492 "// if 1, do f()\n" 2493 "case 1:\n" 2494 " f();\n" 2495 "}"); 2496 verifyFormat("switch (x) {\n" 2497 "case 1:\n" 2498 " // Do amazing stuff\n" 2499 " {\n" 2500 " f();\n" 2501 " g();\n" 2502 " }\n" 2503 " break;\n" 2504 "}"); 2505 verifyFormat("#define A \\\n" 2506 " switch (x) { \\\n" 2507 " case a: \\\n" 2508 " foo = b; \\\n" 2509 " }", 2510 getLLVMStyleWithColumns(20)); 2511 verifyFormat("#define OPERATION_CASE(name) \\\n" 2512 " case OP_name: \\\n" 2513 " return operations::Operation##name\n", 2514 getLLVMStyleWithColumns(40)); 2515 verifyFormat("switch (x) {\n" 2516 "case 1:;\n" 2517 "default:;\n" 2518 " int i;\n" 2519 "}"); 2520 2521 verifyGoogleFormat("switch (x) {\n" 2522 " case 1:\n" 2523 " f();\n" 2524 " break;\n" 2525 " case kFoo:\n" 2526 " case ns::kBar:\n" 2527 " case kBaz:\n" 2528 " break;\n" 2529 " default:\n" 2530 " g();\n" 2531 " break;\n" 2532 "}"); 2533 verifyGoogleFormat("switch (x) {\n" 2534 " case 1: {\n" 2535 " f();\n" 2536 " break;\n" 2537 " }\n" 2538 "}"); 2539 verifyGoogleFormat("switch (test)\n" 2540 " ;"); 2541 2542 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2543 " case OP_name: \\\n" 2544 " return operations::Operation##name\n"); 2545 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2546 " // Get the correction operation class.\n" 2547 " switch (OpCode) {\n" 2548 " CASE(Add);\n" 2549 " CASE(Subtract);\n" 2550 " default:\n" 2551 " return operations::Unknown;\n" 2552 " }\n" 2553 "#undef OPERATION_CASE\n" 2554 "}"); 2555 verifyFormat("DEBUG({\n" 2556 " switch (x) {\n" 2557 " case A:\n" 2558 " f();\n" 2559 " break;\n" 2560 " // fallthrough\n" 2561 " case B:\n" 2562 " g();\n" 2563 " break;\n" 2564 " }\n" 2565 "});"); 2566 EXPECT_EQ("DEBUG({\n" 2567 " switch (x) {\n" 2568 " case A:\n" 2569 " f();\n" 2570 " break;\n" 2571 " // On B:\n" 2572 " case B:\n" 2573 " g();\n" 2574 " break;\n" 2575 " }\n" 2576 "});", 2577 format("DEBUG({\n" 2578 " switch (x) {\n" 2579 " case A:\n" 2580 " f();\n" 2581 " break;\n" 2582 " // On B:\n" 2583 " case B:\n" 2584 " g();\n" 2585 " break;\n" 2586 " }\n" 2587 "});", 2588 getLLVMStyle())); 2589 EXPECT_EQ("switch (n) {\n" 2590 "case 0: {\n" 2591 " return false;\n" 2592 "}\n" 2593 "default: {\n" 2594 " return true;\n" 2595 "}\n" 2596 "}", 2597 format("switch (n)\n" 2598 "{\n" 2599 "case 0: {\n" 2600 " return false;\n" 2601 "}\n" 2602 "default: {\n" 2603 " return true;\n" 2604 "}\n" 2605 "}", 2606 getLLVMStyle())); 2607 verifyFormat("switch (a) {\n" 2608 "case (b):\n" 2609 " return;\n" 2610 "}"); 2611 2612 verifyFormat("switch (a) {\n" 2613 "case some_namespace::\n" 2614 " some_constant:\n" 2615 " return;\n" 2616 "}", 2617 getLLVMStyleWithColumns(34)); 2618 2619 verifyFormat("switch (a) {\n" 2620 "[[likely]] case 1:\n" 2621 " return;\n" 2622 "}"); 2623 verifyFormat("switch (a) {\n" 2624 "[[likely]] [[other::likely]] case 1:\n" 2625 " return;\n" 2626 "}"); 2627 verifyFormat("switch (x) {\n" 2628 "case 1:\n" 2629 " return;\n" 2630 "[[likely]] case 2:\n" 2631 " return;\n" 2632 "}"); 2633 verifyFormat("switch (a) {\n" 2634 "case 1:\n" 2635 "[[likely]] case 2:\n" 2636 " return;\n" 2637 "}"); 2638 FormatStyle Attributes = getLLVMStyle(); 2639 Attributes.AttributeMacros.push_back("LIKELY"); 2640 Attributes.AttributeMacros.push_back("OTHER_LIKELY"); 2641 verifyFormat("switch (a) {\n" 2642 "LIKELY case b:\n" 2643 " return;\n" 2644 "}", 2645 Attributes); 2646 verifyFormat("switch (a) {\n" 2647 "LIKELY OTHER_LIKELY() case b:\n" 2648 " return;\n" 2649 "}", 2650 Attributes); 2651 verifyFormat("switch (a) {\n" 2652 "case 1:\n" 2653 " return;\n" 2654 "LIKELY case 2:\n" 2655 " return;\n" 2656 "}", 2657 Attributes); 2658 verifyFormat("switch (a) {\n" 2659 "case 1:\n" 2660 "LIKELY case 2:\n" 2661 " return;\n" 2662 "}", 2663 Attributes); 2664 2665 FormatStyle Style = getLLVMStyle(); 2666 Style.IndentCaseLabels = true; 2667 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2668 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2669 Style.BraceWrapping.AfterCaseLabel = true; 2670 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2671 EXPECT_EQ("switch (n)\n" 2672 "{\n" 2673 " case 0:\n" 2674 " {\n" 2675 " return false;\n" 2676 " }\n" 2677 " default:\n" 2678 " {\n" 2679 " return true;\n" 2680 " }\n" 2681 "}", 2682 format("switch (n) {\n" 2683 " case 0: {\n" 2684 " return false;\n" 2685 " }\n" 2686 " default: {\n" 2687 " return true;\n" 2688 " }\n" 2689 "}", 2690 Style)); 2691 Style.BraceWrapping.AfterCaseLabel = false; 2692 EXPECT_EQ("switch (n)\n" 2693 "{\n" 2694 " case 0: {\n" 2695 " return false;\n" 2696 " }\n" 2697 " default: {\n" 2698 " return true;\n" 2699 " }\n" 2700 "}", 2701 format("switch (n) {\n" 2702 " case 0:\n" 2703 " {\n" 2704 " return false;\n" 2705 " }\n" 2706 " default:\n" 2707 " {\n" 2708 " return true;\n" 2709 " }\n" 2710 "}", 2711 Style)); 2712 Style.IndentCaseLabels = false; 2713 Style.IndentCaseBlocks = true; 2714 EXPECT_EQ("switch (n)\n" 2715 "{\n" 2716 "case 0:\n" 2717 " {\n" 2718 " return false;\n" 2719 " }\n" 2720 "case 1:\n" 2721 " break;\n" 2722 "default:\n" 2723 " {\n" 2724 " return true;\n" 2725 " }\n" 2726 "}", 2727 format("switch (n) {\n" 2728 "case 0: {\n" 2729 " return false;\n" 2730 "}\n" 2731 "case 1:\n" 2732 " break;\n" 2733 "default: {\n" 2734 " return true;\n" 2735 "}\n" 2736 "}", 2737 Style)); 2738 Style.IndentCaseLabels = true; 2739 Style.IndentCaseBlocks = true; 2740 EXPECT_EQ("switch (n)\n" 2741 "{\n" 2742 " case 0:\n" 2743 " {\n" 2744 " return false;\n" 2745 " }\n" 2746 " case 1:\n" 2747 " break;\n" 2748 " default:\n" 2749 " {\n" 2750 " return true;\n" 2751 " }\n" 2752 "}", 2753 format("switch (n) {\n" 2754 "case 0: {\n" 2755 " return false;\n" 2756 "}\n" 2757 "case 1:\n" 2758 " break;\n" 2759 "default: {\n" 2760 " return true;\n" 2761 "}\n" 2762 "}", 2763 Style)); 2764 } 2765 2766 TEST_F(FormatTest, CaseRanges) { 2767 verifyFormat("switch (x) {\n" 2768 "case 'A' ... 'Z':\n" 2769 "case 1 ... 5:\n" 2770 "case a ... b:\n" 2771 " break;\n" 2772 "}"); 2773 } 2774 2775 TEST_F(FormatTest, ShortEnums) { 2776 FormatStyle Style = getLLVMStyle(); 2777 EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine); 2778 EXPECT_FALSE(Style.BraceWrapping.AfterEnum); 2779 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2780 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2781 Style.AllowShortEnumsOnASingleLine = false; 2782 verifyFormat("enum {\n" 2783 " A,\n" 2784 " B,\n" 2785 " C\n" 2786 "} ShortEnum1, ShortEnum2;", 2787 Style); 2788 verifyFormat("typedef enum {\n" 2789 " A,\n" 2790 " B,\n" 2791 " C\n" 2792 "} ShortEnum1, ShortEnum2;", 2793 Style); 2794 verifyFormat("enum {\n" 2795 " A,\n" 2796 "} ShortEnum1, ShortEnum2;", 2797 Style); 2798 verifyFormat("typedef enum {\n" 2799 " A,\n" 2800 "} ShortEnum1, ShortEnum2;", 2801 Style); 2802 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2803 Style.BraceWrapping.AfterEnum = true; 2804 verifyFormat("enum\n" 2805 "{\n" 2806 " A,\n" 2807 " B,\n" 2808 " C\n" 2809 "} ShortEnum1, ShortEnum2;", 2810 Style); 2811 verifyFormat("typedef enum\n" 2812 "{\n" 2813 " A,\n" 2814 " B,\n" 2815 " C\n" 2816 "} ShortEnum1, ShortEnum2;", 2817 Style); 2818 } 2819 2820 TEST_F(FormatTest, ShortCaseLabels) { 2821 FormatStyle Style = getLLVMStyle(); 2822 Style.AllowShortCaseLabelsOnASingleLine = true; 2823 verifyFormat("switch (a) {\n" 2824 "case 1: x = 1; break;\n" 2825 "case 2: return;\n" 2826 "case 3:\n" 2827 "case 4:\n" 2828 "case 5: return;\n" 2829 "case 6: // comment\n" 2830 " return;\n" 2831 "case 7:\n" 2832 " // comment\n" 2833 " return;\n" 2834 "case 8:\n" 2835 " x = 8; // comment\n" 2836 " break;\n" 2837 "default: y = 1; break;\n" 2838 "}", 2839 Style); 2840 verifyFormat("switch (a) {\n" 2841 "case 0: return; // comment\n" 2842 "case 1: break; // comment\n" 2843 "case 2: return;\n" 2844 "// comment\n" 2845 "case 3: return;\n" 2846 "// comment 1\n" 2847 "// comment 2\n" 2848 "// comment 3\n" 2849 "case 4: break; /* comment */\n" 2850 "case 5:\n" 2851 " // comment\n" 2852 " break;\n" 2853 "case 6: /* comment */ x = 1; break;\n" 2854 "case 7: x = /* comment */ 1; break;\n" 2855 "case 8:\n" 2856 " x = 1; /* comment */\n" 2857 " break;\n" 2858 "case 9:\n" 2859 " break; // comment line 1\n" 2860 " // comment line 2\n" 2861 "}", 2862 Style); 2863 EXPECT_EQ("switch (a) {\n" 2864 "case 1:\n" 2865 " x = 8;\n" 2866 " // fall through\n" 2867 "case 2: x = 8;\n" 2868 "// comment\n" 2869 "case 3:\n" 2870 " return; /* comment line 1\n" 2871 " * comment line 2 */\n" 2872 "case 4: i = 8;\n" 2873 "// something else\n" 2874 "#if FOO\n" 2875 "case 5: break;\n" 2876 "#endif\n" 2877 "}", 2878 format("switch (a) {\n" 2879 "case 1: x = 8;\n" 2880 " // fall through\n" 2881 "case 2:\n" 2882 " x = 8;\n" 2883 "// comment\n" 2884 "case 3:\n" 2885 " return; /* comment line 1\n" 2886 " * comment line 2 */\n" 2887 "case 4:\n" 2888 " i = 8;\n" 2889 "// something else\n" 2890 "#if FOO\n" 2891 "case 5: break;\n" 2892 "#endif\n" 2893 "}", 2894 Style)); 2895 EXPECT_EQ("switch (a) {\n" 2896 "case 0:\n" 2897 " return; // long long long long long long long long long long " 2898 "long long comment\n" 2899 " // line\n" 2900 "}", 2901 format("switch (a) {\n" 2902 "case 0: return; // long long long long long long long long " 2903 "long long long long comment line\n" 2904 "}", 2905 Style)); 2906 EXPECT_EQ("switch (a) {\n" 2907 "case 0:\n" 2908 " return; /* long long long long long long long long long long " 2909 "long long comment\n" 2910 " line */\n" 2911 "}", 2912 format("switch (a) {\n" 2913 "case 0: return; /* long long long long long long long long " 2914 "long long long long comment line */\n" 2915 "}", 2916 Style)); 2917 verifyFormat("switch (a) {\n" 2918 "#if FOO\n" 2919 "case 0: return 0;\n" 2920 "#endif\n" 2921 "}", 2922 Style); 2923 verifyFormat("switch (a) {\n" 2924 "case 1: {\n" 2925 "}\n" 2926 "case 2: {\n" 2927 " return;\n" 2928 "}\n" 2929 "case 3: {\n" 2930 " x = 1;\n" 2931 " return;\n" 2932 "}\n" 2933 "case 4:\n" 2934 " if (x)\n" 2935 " return;\n" 2936 "}", 2937 Style); 2938 Style.ColumnLimit = 21; 2939 verifyFormat("switch (a) {\n" 2940 "case 1: x = 1; break;\n" 2941 "case 2: return;\n" 2942 "case 3:\n" 2943 "case 4:\n" 2944 "case 5: return;\n" 2945 "default:\n" 2946 " y = 1;\n" 2947 " break;\n" 2948 "}", 2949 Style); 2950 Style.ColumnLimit = 80; 2951 Style.AllowShortCaseLabelsOnASingleLine = false; 2952 Style.IndentCaseLabels = true; 2953 EXPECT_EQ("switch (n) {\n" 2954 " default /*comments*/:\n" 2955 " return true;\n" 2956 " case 0:\n" 2957 " return false;\n" 2958 "}", 2959 format("switch (n) {\n" 2960 "default/*comments*/:\n" 2961 " return true;\n" 2962 "case 0:\n" 2963 " return false;\n" 2964 "}", 2965 Style)); 2966 Style.AllowShortCaseLabelsOnASingleLine = true; 2967 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2968 Style.BraceWrapping.AfterCaseLabel = true; 2969 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2970 EXPECT_EQ("switch (n)\n" 2971 "{\n" 2972 " case 0:\n" 2973 " {\n" 2974 " return false;\n" 2975 " }\n" 2976 " default:\n" 2977 " {\n" 2978 " return true;\n" 2979 " }\n" 2980 "}", 2981 format("switch (n) {\n" 2982 " case 0: {\n" 2983 " return false;\n" 2984 " }\n" 2985 " default:\n" 2986 " {\n" 2987 " return true;\n" 2988 " }\n" 2989 "}", 2990 Style)); 2991 } 2992 2993 TEST_F(FormatTest, FormatsLabels) { 2994 verifyFormat("void f() {\n" 2995 " some_code();\n" 2996 "test_label:\n" 2997 " some_other_code();\n" 2998 " {\n" 2999 " some_more_code();\n" 3000 " another_label:\n" 3001 " some_more_code();\n" 3002 " }\n" 3003 "}"); 3004 verifyFormat("{\n" 3005 " some_code();\n" 3006 "test_label:\n" 3007 " some_other_code();\n" 3008 "}"); 3009 verifyFormat("{\n" 3010 " some_code();\n" 3011 "test_label:;\n" 3012 " int i = 0;\n" 3013 "}"); 3014 FormatStyle Style = getLLVMStyle(); 3015 Style.IndentGotoLabels = false; 3016 verifyFormat("void f() {\n" 3017 " some_code();\n" 3018 "test_label:\n" 3019 " some_other_code();\n" 3020 " {\n" 3021 " some_more_code();\n" 3022 "another_label:\n" 3023 " some_more_code();\n" 3024 " }\n" 3025 "}", 3026 Style); 3027 verifyFormat("{\n" 3028 " some_code();\n" 3029 "test_label:\n" 3030 " some_other_code();\n" 3031 "}", 3032 Style); 3033 verifyFormat("{\n" 3034 " some_code();\n" 3035 "test_label:;\n" 3036 " int i = 0;\n" 3037 "}"); 3038 } 3039 3040 TEST_F(FormatTest, MultiLineControlStatements) { 3041 FormatStyle Style = getLLVMStyleWithColumns(20); 3042 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3043 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3044 // Short lines should keep opening brace on same line. 3045 EXPECT_EQ("if (foo) {\n" 3046 " bar();\n" 3047 "}", 3048 format("if(foo){bar();}", Style)); 3049 EXPECT_EQ("if (foo) {\n" 3050 " bar();\n" 3051 "} else {\n" 3052 " baz();\n" 3053 "}", 3054 format("if(foo){bar();}else{baz();}", Style)); 3055 EXPECT_EQ("if (foo && bar) {\n" 3056 " baz();\n" 3057 "}", 3058 format("if(foo&&bar){baz();}", Style)); 3059 EXPECT_EQ("if (foo) {\n" 3060 " bar();\n" 3061 "} else if (baz) {\n" 3062 " quux();\n" 3063 "}", 3064 format("if(foo){bar();}else if(baz){quux();}", Style)); 3065 EXPECT_EQ( 3066 "if (foo) {\n" 3067 " bar();\n" 3068 "} else if (baz) {\n" 3069 " quux();\n" 3070 "} else {\n" 3071 " foobar();\n" 3072 "}", 3073 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 3074 EXPECT_EQ("for (;;) {\n" 3075 " foo();\n" 3076 "}", 3077 format("for(;;){foo();}")); 3078 EXPECT_EQ("while (1) {\n" 3079 " foo();\n" 3080 "}", 3081 format("while(1){foo();}", Style)); 3082 EXPECT_EQ("switch (foo) {\n" 3083 "case bar:\n" 3084 " return;\n" 3085 "}", 3086 format("switch(foo){case bar:return;}", Style)); 3087 EXPECT_EQ("try {\n" 3088 " foo();\n" 3089 "} catch (...) {\n" 3090 " bar();\n" 3091 "}", 3092 format("try{foo();}catch(...){bar();}", Style)); 3093 EXPECT_EQ("do {\n" 3094 " foo();\n" 3095 "} while (bar &&\n" 3096 " baz);", 3097 format("do{foo();}while(bar&&baz);", Style)); 3098 // Long lines should put opening brace on new line. 3099 verifyFormat("void f() {\n" 3100 " if (a1 && a2 &&\n" 3101 " a3)\n" 3102 " {\n" 3103 " quux();\n" 3104 " }\n" 3105 "}", 3106 "void f(){if(a1&&a2&&a3){quux();}}", Style); 3107 EXPECT_EQ("if (foo && bar &&\n" 3108 " baz)\n" 3109 "{\n" 3110 " quux();\n" 3111 "}", 3112 format("if(foo&&bar&&baz){quux();}", Style)); 3113 EXPECT_EQ("if (foo && bar &&\n" 3114 " baz)\n" 3115 "{\n" 3116 " quux();\n" 3117 "}", 3118 format("if (foo && bar &&\n" 3119 " baz) {\n" 3120 " quux();\n" 3121 "}", 3122 Style)); 3123 EXPECT_EQ("if (foo) {\n" 3124 " bar();\n" 3125 "} else if (baz ||\n" 3126 " quux)\n" 3127 "{\n" 3128 " foobar();\n" 3129 "}", 3130 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3131 EXPECT_EQ( 3132 "if (foo) {\n" 3133 " bar();\n" 3134 "} else if (baz ||\n" 3135 " quux)\n" 3136 "{\n" 3137 " foobar();\n" 3138 "} else {\n" 3139 " barbaz();\n" 3140 "}", 3141 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3142 Style)); 3143 EXPECT_EQ("for (int i = 0;\n" 3144 " i < 10; ++i)\n" 3145 "{\n" 3146 " foo();\n" 3147 "}", 3148 format("for(int i=0;i<10;++i){foo();}", Style)); 3149 EXPECT_EQ("foreach (int i,\n" 3150 " list)\n" 3151 "{\n" 3152 " foo();\n" 3153 "}", 3154 format("foreach(int i, list){foo();}", Style)); 3155 Style.ColumnLimit = 3156 40; // to concentrate at brace wrapping, not line wrap due to column limit 3157 EXPECT_EQ("foreach (int i, list) {\n" 3158 " foo();\n" 3159 "}", 3160 format("foreach(int i, list){foo();}", Style)); 3161 Style.ColumnLimit = 3162 20; // to concentrate at brace wrapping, not line wrap due to column limit 3163 EXPECT_EQ("while (foo || bar ||\n" 3164 " baz)\n" 3165 "{\n" 3166 " quux();\n" 3167 "}", 3168 format("while(foo||bar||baz){quux();}", Style)); 3169 EXPECT_EQ("switch (\n" 3170 " foo = barbaz)\n" 3171 "{\n" 3172 "case quux:\n" 3173 " return;\n" 3174 "}", 3175 format("switch(foo=barbaz){case quux:return;}", Style)); 3176 EXPECT_EQ("try {\n" 3177 " foo();\n" 3178 "} catch (\n" 3179 " Exception &bar)\n" 3180 "{\n" 3181 " baz();\n" 3182 "}", 3183 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3184 Style.ColumnLimit = 3185 40; // to concentrate at brace wrapping, not line wrap due to column limit 3186 EXPECT_EQ("try {\n" 3187 " foo();\n" 3188 "} catch (Exception &bar) {\n" 3189 " baz();\n" 3190 "}", 3191 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3192 Style.ColumnLimit = 3193 20; // to concentrate at brace wrapping, not line wrap due to column limit 3194 3195 Style.BraceWrapping.BeforeElse = true; 3196 EXPECT_EQ( 3197 "if (foo) {\n" 3198 " bar();\n" 3199 "}\n" 3200 "else if (baz ||\n" 3201 " quux)\n" 3202 "{\n" 3203 " foobar();\n" 3204 "}\n" 3205 "else {\n" 3206 " barbaz();\n" 3207 "}", 3208 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3209 Style)); 3210 3211 Style.BraceWrapping.BeforeCatch = true; 3212 EXPECT_EQ("try {\n" 3213 " foo();\n" 3214 "}\n" 3215 "catch (...) {\n" 3216 " baz();\n" 3217 "}", 3218 format("try{foo();}catch(...){baz();}", Style)); 3219 3220 Style.BraceWrapping.AfterFunction = true; 3221 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3222 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3223 Style.ColumnLimit = 80; 3224 verifyFormat("void shortfunction() { bar(); }", Style); 3225 3226 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3227 verifyFormat("void shortfunction()\n" 3228 "{\n" 3229 " bar();\n" 3230 "}", 3231 Style); 3232 } 3233 3234 TEST_F(FormatTest, BeforeWhile) { 3235 FormatStyle Style = getLLVMStyle(); 3236 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3237 3238 verifyFormat("do {\n" 3239 " foo();\n" 3240 "} while (1);", 3241 Style); 3242 Style.BraceWrapping.BeforeWhile = true; 3243 verifyFormat("do {\n" 3244 " foo();\n" 3245 "}\n" 3246 "while (1);", 3247 Style); 3248 } 3249 3250 //===----------------------------------------------------------------------===// 3251 // Tests for classes, namespaces, etc. 3252 //===----------------------------------------------------------------------===// 3253 3254 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3255 verifyFormat("class A {};"); 3256 } 3257 3258 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3259 verifyFormat("class A {\n" 3260 "public:\n" 3261 "public: // comment\n" 3262 "protected:\n" 3263 "private:\n" 3264 " void f() {}\n" 3265 "};"); 3266 verifyFormat("export class A {\n" 3267 "public:\n" 3268 "public: // comment\n" 3269 "protected:\n" 3270 "private:\n" 3271 " void f() {}\n" 3272 "};"); 3273 verifyGoogleFormat("class A {\n" 3274 " public:\n" 3275 " protected:\n" 3276 " private:\n" 3277 " void f() {}\n" 3278 "};"); 3279 verifyGoogleFormat("export class A {\n" 3280 " public:\n" 3281 " protected:\n" 3282 " private:\n" 3283 " void f() {}\n" 3284 "};"); 3285 verifyFormat("class A {\n" 3286 "public slots:\n" 3287 " void f1() {}\n" 3288 "public Q_SLOTS:\n" 3289 " void f2() {}\n" 3290 "protected slots:\n" 3291 " void f3() {}\n" 3292 "protected Q_SLOTS:\n" 3293 " void f4() {}\n" 3294 "private slots:\n" 3295 " void f5() {}\n" 3296 "private Q_SLOTS:\n" 3297 " void f6() {}\n" 3298 "signals:\n" 3299 " void g1();\n" 3300 "Q_SIGNALS:\n" 3301 " void g2();\n" 3302 "};"); 3303 3304 // Don't interpret 'signals' the wrong way. 3305 verifyFormat("signals.set();"); 3306 verifyFormat("for (Signals signals : f()) {\n}"); 3307 verifyFormat("{\n" 3308 " signals.set(); // This needs indentation.\n" 3309 "}"); 3310 verifyFormat("void f() {\n" 3311 "label:\n" 3312 " signals.baz();\n" 3313 "}"); 3314 verifyFormat("private[1];"); 3315 verifyFormat("testArray[public] = 1;"); 3316 verifyFormat("public();"); 3317 verifyFormat("myFunc(public);"); 3318 verifyFormat("std::vector<int> testVec = {private};"); 3319 verifyFormat("private.p = 1;"); 3320 verifyFormat("void function(private...){};"); 3321 verifyFormat("if (private && public)\n"); 3322 verifyFormat("private &= true;"); 3323 verifyFormat("int x = private * public;"); 3324 verifyFormat("public *= private;"); 3325 verifyFormat("int x = public + private;"); 3326 verifyFormat("private++;"); 3327 verifyFormat("++private;"); 3328 verifyFormat("public += private;"); 3329 verifyFormat("public = public - private;"); 3330 verifyFormat("public->foo();"); 3331 verifyFormat("private--;"); 3332 verifyFormat("--private;"); 3333 verifyFormat("public -= 1;"); 3334 verifyFormat("if (!private && !public)\n"); 3335 verifyFormat("public != private;"); 3336 verifyFormat("int x = public / private;"); 3337 verifyFormat("public /= 2;"); 3338 verifyFormat("public = public % 2;"); 3339 verifyFormat("public %= 2;"); 3340 verifyFormat("if (public < private)\n"); 3341 verifyFormat("public << private;"); 3342 verifyFormat("public <<= private;"); 3343 verifyFormat("if (public > private)\n"); 3344 verifyFormat("public >> private;"); 3345 verifyFormat("public >>= private;"); 3346 verifyFormat("public ^ private;"); 3347 verifyFormat("public ^= private;"); 3348 verifyFormat("public | private;"); 3349 verifyFormat("public |= private;"); 3350 verifyFormat("auto x = private ? 1 : 2;"); 3351 verifyFormat("if (public == private)\n"); 3352 verifyFormat("void foo(public, private)"); 3353 verifyFormat("public::foo();"); 3354 3355 verifyFormat("class A {\n" 3356 "public:\n" 3357 " std::unique_ptr<int *[]> b() { return nullptr; }\n" 3358 "\n" 3359 "private:\n" 3360 " int c;\n" 3361 "};"); 3362 } 3363 3364 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3365 EXPECT_EQ("class A {\n" 3366 "public:\n" 3367 " void f();\n" 3368 "\n" 3369 "private:\n" 3370 " void g() {}\n" 3371 " // test\n" 3372 "protected:\n" 3373 " int h;\n" 3374 "};", 3375 format("class A {\n" 3376 "public:\n" 3377 "void f();\n" 3378 "private:\n" 3379 "void g() {}\n" 3380 "// test\n" 3381 "protected:\n" 3382 "int h;\n" 3383 "};")); 3384 EXPECT_EQ("class A {\n" 3385 "protected:\n" 3386 "public:\n" 3387 " void f();\n" 3388 "};", 3389 format("class A {\n" 3390 "protected:\n" 3391 "\n" 3392 "public:\n" 3393 "\n" 3394 " void f();\n" 3395 "};")); 3396 3397 // Even ensure proper spacing inside macros. 3398 EXPECT_EQ("#define B \\\n" 3399 " class A { \\\n" 3400 " protected: \\\n" 3401 " public: \\\n" 3402 " void f(); \\\n" 3403 " };", 3404 format("#define B \\\n" 3405 " class A { \\\n" 3406 " protected: \\\n" 3407 " \\\n" 3408 " public: \\\n" 3409 " \\\n" 3410 " void f(); \\\n" 3411 " };", 3412 getGoogleStyle())); 3413 // But don't remove empty lines after macros ending in access specifiers. 3414 EXPECT_EQ("#define A private:\n" 3415 "\n" 3416 "int i;", 3417 format("#define A private:\n" 3418 "\n" 3419 "int i;")); 3420 } 3421 3422 TEST_F(FormatTest, FormatsClasses) { 3423 verifyFormat("class A : public B {};"); 3424 verifyFormat("class A : public ::B {};"); 3425 3426 verifyFormat( 3427 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3428 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3429 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3430 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3431 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3432 verifyFormat( 3433 "class A : public B, public C, public D, public E, public F {};"); 3434 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3435 " public C,\n" 3436 " public D,\n" 3437 " public E,\n" 3438 " public F,\n" 3439 " public G {};"); 3440 3441 verifyFormat("class\n" 3442 " ReallyReallyLongClassName {\n" 3443 " int i;\n" 3444 "};", 3445 getLLVMStyleWithColumns(32)); 3446 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3447 " aaaaaaaaaaaaaaaa> {};"); 3448 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3449 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3450 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3451 verifyFormat("template <class R, class C>\n" 3452 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3453 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3454 verifyFormat("class ::A::B {};"); 3455 } 3456 3457 TEST_F(FormatTest, BreakInheritanceStyle) { 3458 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3459 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3460 FormatStyle::BILS_BeforeComma; 3461 verifyFormat("class MyClass : public X {};", 3462 StyleWithInheritanceBreakBeforeComma); 3463 verifyFormat("class MyClass\n" 3464 " : public X\n" 3465 " , public Y {};", 3466 StyleWithInheritanceBreakBeforeComma); 3467 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3468 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3469 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3470 StyleWithInheritanceBreakBeforeComma); 3471 verifyFormat("struct aaaaaaaaaaaaa\n" 3472 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3473 " aaaaaaaaaaaaaaaa> {};", 3474 StyleWithInheritanceBreakBeforeComma); 3475 3476 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3477 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3478 FormatStyle::BILS_AfterColon; 3479 verifyFormat("class MyClass : public X {};", 3480 StyleWithInheritanceBreakAfterColon); 3481 verifyFormat("class MyClass : public X, public Y {};", 3482 StyleWithInheritanceBreakAfterColon); 3483 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3484 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3485 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3486 StyleWithInheritanceBreakAfterColon); 3487 verifyFormat("struct aaaaaaaaaaaaa :\n" 3488 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3489 " aaaaaaaaaaaaaaaa> {};", 3490 StyleWithInheritanceBreakAfterColon); 3491 3492 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3493 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3494 FormatStyle::BILS_AfterComma; 3495 verifyFormat("class MyClass : public X {};", 3496 StyleWithInheritanceBreakAfterComma); 3497 verifyFormat("class MyClass : public X,\n" 3498 " public Y {};", 3499 StyleWithInheritanceBreakAfterComma); 3500 verifyFormat( 3501 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3502 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3503 "{};", 3504 StyleWithInheritanceBreakAfterComma); 3505 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3506 " aaaaaaaaaaaaaaaa> {};", 3507 StyleWithInheritanceBreakAfterComma); 3508 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3509 " : public OnceBreak,\n" 3510 " public AlwaysBreak,\n" 3511 " EvenBasesFitInOneLine {};", 3512 StyleWithInheritanceBreakAfterComma); 3513 } 3514 3515 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3516 verifyFormat("class A {\n} a, b;"); 3517 verifyFormat("struct A {\n} a, b;"); 3518 verifyFormat("union A {\n} a, b;"); 3519 3520 verifyFormat("constexpr class A {\n} a, b;"); 3521 verifyFormat("constexpr struct A {\n} a, b;"); 3522 verifyFormat("constexpr union A {\n} a, b;"); 3523 3524 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3525 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3526 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3527 3528 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3529 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3530 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3531 3532 verifyFormat("namespace ns {\n" 3533 "class {\n" 3534 "} a, b;\n" 3535 "} // namespace ns"); 3536 verifyFormat("namespace ns {\n" 3537 "const class {\n" 3538 "} a, b;\n" 3539 "} // namespace ns"); 3540 verifyFormat("namespace ns {\n" 3541 "constexpr class C {\n" 3542 "} a, b;\n" 3543 "} // namespace ns"); 3544 verifyFormat("namespace ns {\n" 3545 "class { /* comment */\n" 3546 "} a, b;\n" 3547 "} // namespace ns"); 3548 verifyFormat("namespace ns {\n" 3549 "const class { /* comment */\n" 3550 "} a, b;\n" 3551 "} // namespace ns"); 3552 } 3553 3554 TEST_F(FormatTest, FormatsEnum) { 3555 verifyFormat("enum {\n" 3556 " Zero,\n" 3557 " One = 1,\n" 3558 " Two = One + 1,\n" 3559 " Three = (One + Two),\n" 3560 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3561 " Five = (One, Two, Three, Four, 5)\n" 3562 "};"); 3563 verifyGoogleFormat("enum {\n" 3564 " Zero,\n" 3565 " One = 1,\n" 3566 " Two = One + 1,\n" 3567 " Three = (One + Two),\n" 3568 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3569 " Five = (One, Two, Three, Four, 5)\n" 3570 "};"); 3571 verifyFormat("enum Enum {};"); 3572 verifyFormat("enum {};"); 3573 verifyFormat("enum X E {} d;"); 3574 verifyFormat("enum __attribute__((...)) E {} d;"); 3575 verifyFormat("enum __declspec__((...)) E {} d;"); 3576 verifyFormat("enum [[nodiscard]] E {} d;"); 3577 verifyFormat("enum {\n" 3578 " Bar = Foo<int, int>::value\n" 3579 "};", 3580 getLLVMStyleWithColumns(30)); 3581 3582 verifyFormat("enum ShortEnum { A, B, C };"); 3583 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3584 3585 EXPECT_EQ("enum KeepEmptyLines {\n" 3586 " ONE,\n" 3587 "\n" 3588 " TWO,\n" 3589 "\n" 3590 " THREE\n" 3591 "}", 3592 format("enum KeepEmptyLines {\n" 3593 " ONE,\n" 3594 "\n" 3595 " TWO,\n" 3596 "\n" 3597 "\n" 3598 " THREE\n" 3599 "}")); 3600 verifyFormat("enum E { // comment\n" 3601 " ONE,\n" 3602 " TWO\n" 3603 "};\n" 3604 "int i;"); 3605 3606 FormatStyle EightIndent = getLLVMStyle(); 3607 EightIndent.IndentWidth = 8; 3608 verifyFormat("enum {\n" 3609 " VOID,\n" 3610 " CHAR,\n" 3611 " SHORT,\n" 3612 " INT,\n" 3613 " LONG,\n" 3614 " SIGNED,\n" 3615 " UNSIGNED,\n" 3616 " BOOL,\n" 3617 " FLOAT,\n" 3618 " DOUBLE,\n" 3619 " COMPLEX\n" 3620 "};", 3621 EightIndent); 3622 3623 verifyFormat("enum [[nodiscard]] E {\n" 3624 " ONE,\n" 3625 " TWO,\n" 3626 "};"); 3627 verifyFormat("enum [[nodiscard]] E {\n" 3628 " // Comment 1\n" 3629 " ONE,\n" 3630 " // Comment 2\n" 3631 " TWO,\n" 3632 "};"); 3633 3634 // Not enums. 3635 verifyFormat("enum X f() {\n" 3636 " a();\n" 3637 " return 42;\n" 3638 "}"); 3639 verifyFormat("enum X Type::f() {\n" 3640 " a();\n" 3641 " return 42;\n" 3642 "}"); 3643 verifyFormat("enum ::X f() {\n" 3644 " a();\n" 3645 " return 42;\n" 3646 "}"); 3647 verifyFormat("enum ns::X f() {\n" 3648 " a();\n" 3649 " return 42;\n" 3650 "}"); 3651 } 3652 3653 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3654 verifyFormat("enum Type {\n" 3655 " One = 0; // These semicolons should be commas.\n" 3656 " Two = 1;\n" 3657 "};"); 3658 verifyFormat("namespace n {\n" 3659 "enum Type {\n" 3660 " One,\n" 3661 " Two, // missing };\n" 3662 " int i;\n" 3663 "}\n" 3664 "void g() {}"); 3665 } 3666 3667 TEST_F(FormatTest, FormatsEnumStruct) { 3668 verifyFormat("enum struct {\n" 3669 " Zero,\n" 3670 " One = 1,\n" 3671 " Two = One + 1,\n" 3672 " Three = (One + Two),\n" 3673 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3674 " Five = (One, Two, Three, Four, 5)\n" 3675 "};"); 3676 verifyFormat("enum struct Enum {};"); 3677 verifyFormat("enum struct {};"); 3678 verifyFormat("enum struct X E {} d;"); 3679 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3680 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3681 verifyFormat("enum struct [[nodiscard]] E {} d;"); 3682 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3683 3684 verifyFormat("enum struct [[nodiscard]] E {\n" 3685 " ONE,\n" 3686 " TWO,\n" 3687 "};"); 3688 verifyFormat("enum struct [[nodiscard]] E {\n" 3689 " // Comment 1\n" 3690 " ONE,\n" 3691 " // Comment 2\n" 3692 " TWO,\n" 3693 "};"); 3694 } 3695 3696 TEST_F(FormatTest, FormatsEnumClass) { 3697 verifyFormat("enum class {\n" 3698 " Zero,\n" 3699 " One = 1,\n" 3700 " Two = One + 1,\n" 3701 " Three = (One + Two),\n" 3702 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3703 " Five = (One, Two, Three, Four, 5)\n" 3704 "};"); 3705 verifyFormat("enum class Enum {};"); 3706 verifyFormat("enum class {};"); 3707 verifyFormat("enum class X E {} d;"); 3708 verifyFormat("enum class __attribute__((...)) E {} d;"); 3709 verifyFormat("enum class __declspec__((...)) E {} d;"); 3710 verifyFormat("enum class [[nodiscard]] E {} d;"); 3711 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3712 3713 verifyFormat("enum class [[nodiscard]] E {\n" 3714 " ONE,\n" 3715 " TWO,\n" 3716 "};"); 3717 verifyFormat("enum class [[nodiscard]] E {\n" 3718 " // Comment 1\n" 3719 " ONE,\n" 3720 " // Comment 2\n" 3721 " TWO,\n" 3722 "};"); 3723 } 3724 3725 TEST_F(FormatTest, FormatsEnumTypes) { 3726 verifyFormat("enum X : int {\n" 3727 " A, // Force multiple lines.\n" 3728 " B\n" 3729 "};"); 3730 verifyFormat("enum X : int { A, B };"); 3731 verifyFormat("enum X : std::uint32_t { A, B };"); 3732 } 3733 3734 TEST_F(FormatTest, FormatsTypedefEnum) { 3735 FormatStyle Style = getLLVMStyleWithColumns(40); 3736 verifyFormat("typedef enum {} EmptyEnum;"); 3737 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3738 verifyFormat("typedef enum {\n" 3739 " ZERO = 0,\n" 3740 " ONE = 1,\n" 3741 " TWO = 2,\n" 3742 " THREE = 3\n" 3743 "} LongEnum;", 3744 Style); 3745 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3746 Style.BraceWrapping.AfterEnum = true; 3747 verifyFormat("typedef enum {} EmptyEnum;"); 3748 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3749 verifyFormat("typedef enum\n" 3750 "{\n" 3751 " ZERO = 0,\n" 3752 " ONE = 1,\n" 3753 " TWO = 2,\n" 3754 " THREE = 3\n" 3755 "} LongEnum;", 3756 Style); 3757 } 3758 3759 TEST_F(FormatTest, FormatsNSEnums) { 3760 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3761 verifyGoogleFormat( 3762 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3763 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3764 " // Information about someDecentlyLongValue.\n" 3765 " someDecentlyLongValue,\n" 3766 " // Information about anotherDecentlyLongValue.\n" 3767 " anotherDecentlyLongValue,\n" 3768 " // Information about aThirdDecentlyLongValue.\n" 3769 " aThirdDecentlyLongValue\n" 3770 "};"); 3771 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3772 " // Information about someDecentlyLongValue.\n" 3773 " someDecentlyLongValue,\n" 3774 " // Information about anotherDecentlyLongValue.\n" 3775 " anotherDecentlyLongValue,\n" 3776 " // Information about aThirdDecentlyLongValue.\n" 3777 " aThirdDecentlyLongValue\n" 3778 "};"); 3779 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3780 " a = 1,\n" 3781 " b = 2,\n" 3782 " c = 3,\n" 3783 "};"); 3784 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3785 " a = 1,\n" 3786 " b = 2,\n" 3787 " c = 3,\n" 3788 "};"); 3789 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3790 " a = 1,\n" 3791 " b = 2,\n" 3792 " c = 3,\n" 3793 "};"); 3794 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3795 " a = 1,\n" 3796 " b = 2,\n" 3797 " c = 3,\n" 3798 "};"); 3799 } 3800 3801 TEST_F(FormatTest, FormatsBitfields) { 3802 verifyFormat("struct Bitfields {\n" 3803 " unsigned sClass : 8;\n" 3804 " unsigned ValueKind : 2;\n" 3805 "};"); 3806 verifyFormat("struct A {\n" 3807 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3808 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3809 "};"); 3810 verifyFormat("struct MyStruct {\n" 3811 " uchar data;\n" 3812 " uchar : 8;\n" 3813 " uchar : 8;\n" 3814 " uchar other;\n" 3815 "};"); 3816 FormatStyle Style = getLLVMStyle(); 3817 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3818 verifyFormat("struct Bitfields {\n" 3819 " unsigned sClass:8;\n" 3820 " unsigned ValueKind:2;\n" 3821 " uchar other;\n" 3822 "};", 3823 Style); 3824 verifyFormat("struct A {\n" 3825 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3826 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3827 "};", 3828 Style); 3829 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3830 verifyFormat("struct Bitfields {\n" 3831 " unsigned sClass :8;\n" 3832 " unsigned ValueKind :2;\n" 3833 " uchar other;\n" 3834 "};", 3835 Style); 3836 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3837 verifyFormat("struct Bitfields {\n" 3838 " unsigned sClass: 8;\n" 3839 " unsigned ValueKind: 2;\n" 3840 " uchar other;\n" 3841 "};", 3842 Style); 3843 } 3844 3845 TEST_F(FormatTest, FormatsNamespaces) { 3846 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3847 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3848 3849 verifyFormat("namespace some_namespace {\n" 3850 "class A {};\n" 3851 "void f() { f(); }\n" 3852 "}", 3853 LLVMWithNoNamespaceFix); 3854 verifyFormat("#define M(x) x##x\n" 3855 "namespace M(x) {\n" 3856 "class A {};\n" 3857 "void f() { f(); }\n" 3858 "}", 3859 LLVMWithNoNamespaceFix); 3860 verifyFormat("#define M(x) x##x\n" 3861 "namespace N::inline M(x) {\n" 3862 "class A {};\n" 3863 "void f() { f(); }\n" 3864 "}", 3865 LLVMWithNoNamespaceFix); 3866 verifyFormat("#define M(x) x##x\n" 3867 "namespace M(x)::inline N {\n" 3868 "class A {};\n" 3869 "void f() { f(); }\n" 3870 "}", 3871 LLVMWithNoNamespaceFix); 3872 verifyFormat("#define M(x) x##x\n" 3873 "namespace N::M(x) {\n" 3874 "class A {};\n" 3875 "void f() { f(); }\n" 3876 "}", 3877 LLVMWithNoNamespaceFix); 3878 verifyFormat("#define M(x) x##x\n" 3879 "namespace M::N(x) {\n" 3880 "class A {};\n" 3881 "void f() { f(); }\n" 3882 "}", 3883 LLVMWithNoNamespaceFix); 3884 verifyFormat("namespace N::inline D {\n" 3885 "class A {};\n" 3886 "void f() { f(); }\n" 3887 "}", 3888 LLVMWithNoNamespaceFix); 3889 verifyFormat("namespace N::inline D::E {\n" 3890 "class A {};\n" 3891 "void f() { f(); }\n" 3892 "}", 3893 LLVMWithNoNamespaceFix); 3894 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3895 "class A {};\n" 3896 "void f() { f(); }\n" 3897 "}", 3898 LLVMWithNoNamespaceFix); 3899 verifyFormat("/* something */ namespace some_namespace {\n" 3900 "class A {};\n" 3901 "void f() { f(); }\n" 3902 "}", 3903 LLVMWithNoNamespaceFix); 3904 verifyFormat("namespace {\n" 3905 "class A {};\n" 3906 "void f() { f(); }\n" 3907 "}", 3908 LLVMWithNoNamespaceFix); 3909 verifyFormat("/* something */ namespace {\n" 3910 "class A {};\n" 3911 "void f() { f(); }\n" 3912 "}", 3913 LLVMWithNoNamespaceFix); 3914 verifyFormat("inline namespace X {\n" 3915 "class A {};\n" 3916 "void f() { f(); }\n" 3917 "}", 3918 LLVMWithNoNamespaceFix); 3919 verifyFormat("/* something */ inline namespace X {\n" 3920 "class A {};\n" 3921 "void f() { f(); }\n" 3922 "}", 3923 LLVMWithNoNamespaceFix); 3924 verifyFormat("export namespace X {\n" 3925 "class A {};\n" 3926 "void f() { f(); }\n" 3927 "}", 3928 LLVMWithNoNamespaceFix); 3929 verifyFormat("using namespace some_namespace;\n" 3930 "class A {};\n" 3931 "void f() { f(); }", 3932 LLVMWithNoNamespaceFix); 3933 3934 // This code is more common than we thought; if we 3935 // layout this correctly the semicolon will go into 3936 // its own line, which is undesirable. 3937 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3938 verifyFormat("namespace {\n" 3939 "class A {};\n" 3940 "};", 3941 LLVMWithNoNamespaceFix); 3942 3943 verifyFormat("namespace {\n" 3944 "int SomeVariable = 0; // comment\n" 3945 "} // namespace", 3946 LLVMWithNoNamespaceFix); 3947 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3948 "#define HEADER_GUARD\n" 3949 "namespace my_namespace {\n" 3950 "int i;\n" 3951 "} // my_namespace\n" 3952 "#endif // HEADER_GUARD", 3953 format("#ifndef HEADER_GUARD\n" 3954 " #define HEADER_GUARD\n" 3955 " namespace my_namespace {\n" 3956 "int i;\n" 3957 "} // my_namespace\n" 3958 "#endif // HEADER_GUARD", 3959 LLVMWithNoNamespaceFix)); 3960 3961 EXPECT_EQ("namespace A::B {\n" 3962 "class C {};\n" 3963 "}", 3964 format("namespace A::B {\n" 3965 "class C {};\n" 3966 "}", 3967 LLVMWithNoNamespaceFix)); 3968 3969 FormatStyle Style = getLLVMStyle(); 3970 Style.NamespaceIndentation = FormatStyle::NI_All; 3971 EXPECT_EQ("namespace out {\n" 3972 " int i;\n" 3973 " namespace in {\n" 3974 " int i;\n" 3975 " } // namespace in\n" 3976 "} // namespace out", 3977 format("namespace out {\n" 3978 "int i;\n" 3979 "namespace in {\n" 3980 "int i;\n" 3981 "} // namespace in\n" 3982 "} // namespace out", 3983 Style)); 3984 3985 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3986 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3987 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3988 FormatStyle::SFS_Inline; 3989 verifyFormat("namespace {\n" 3990 " void f() {\n" 3991 " return;\n" 3992 " }\n" 3993 "} // namespace\n", 3994 ShortInlineFunctions); 3995 verifyFormat("namespace { /* comment */\n" 3996 " void f() {\n" 3997 " return;\n" 3998 " }\n" 3999 "} // namespace\n", 4000 ShortInlineFunctions); 4001 verifyFormat("namespace { // comment\n" 4002 " void f() {\n" 4003 " return;\n" 4004 " }\n" 4005 "} // namespace\n", 4006 ShortInlineFunctions); 4007 verifyFormat("namespace {\n" 4008 " int some_int;\n" 4009 " void f() {\n" 4010 " return;\n" 4011 " }\n" 4012 "} // namespace\n", 4013 ShortInlineFunctions); 4014 verifyFormat("namespace interface {\n" 4015 " void f() {\n" 4016 " return;\n" 4017 " }\n" 4018 "} // namespace interface\n", 4019 ShortInlineFunctions); 4020 verifyFormat("namespace {\n" 4021 " class X {\n" 4022 " void f() { return; }\n" 4023 " };\n" 4024 "} // namespace\n", 4025 ShortInlineFunctions); 4026 verifyFormat("namespace {\n" 4027 " class X { /* comment */\n" 4028 " void f() { return; }\n" 4029 " };\n" 4030 "} // namespace\n", 4031 ShortInlineFunctions); 4032 verifyFormat("namespace {\n" 4033 " class X { // comment\n" 4034 " void f() { return; }\n" 4035 " };\n" 4036 "} // namespace\n", 4037 ShortInlineFunctions); 4038 verifyFormat("namespace {\n" 4039 " struct X {\n" 4040 " void f() { return; }\n" 4041 " };\n" 4042 "} // namespace\n", 4043 ShortInlineFunctions); 4044 verifyFormat("namespace {\n" 4045 " union X {\n" 4046 " void f() { return; }\n" 4047 " };\n" 4048 "} // namespace\n", 4049 ShortInlineFunctions); 4050 verifyFormat("extern \"C\" {\n" 4051 "void f() {\n" 4052 " return;\n" 4053 "}\n" 4054 "} // namespace\n", 4055 ShortInlineFunctions); 4056 verifyFormat("namespace {\n" 4057 " class X {\n" 4058 " void f() { return; }\n" 4059 " } x;\n" 4060 "} // namespace\n", 4061 ShortInlineFunctions); 4062 verifyFormat("namespace {\n" 4063 " [[nodiscard]] class X {\n" 4064 " void f() { return; }\n" 4065 " };\n" 4066 "} // namespace\n", 4067 ShortInlineFunctions); 4068 verifyFormat("namespace {\n" 4069 " static class X {\n" 4070 " void f() { return; }\n" 4071 " } x;\n" 4072 "} // namespace\n", 4073 ShortInlineFunctions); 4074 verifyFormat("namespace {\n" 4075 " constexpr class X {\n" 4076 " void f() { return; }\n" 4077 " } x;\n" 4078 "} // namespace\n", 4079 ShortInlineFunctions); 4080 4081 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4082 verifyFormat("extern \"C\" {\n" 4083 " void f() {\n" 4084 " return;\n" 4085 " }\n" 4086 "} // namespace\n", 4087 ShortInlineFunctions); 4088 4089 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4090 EXPECT_EQ("namespace out {\n" 4091 "int i;\n" 4092 "namespace in {\n" 4093 " int i;\n" 4094 "} // namespace in\n" 4095 "} // namespace out", 4096 format("namespace out {\n" 4097 "int i;\n" 4098 "namespace in {\n" 4099 "int i;\n" 4100 "} // namespace in\n" 4101 "} // namespace out", 4102 Style)); 4103 4104 Style.NamespaceIndentation = FormatStyle::NI_None; 4105 verifyFormat("template <class T>\n" 4106 "concept a_concept = X<>;\n" 4107 "namespace B {\n" 4108 "struct b_struct {};\n" 4109 "} // namespace B\n", 4110 Style); 4111 verifyFormat("template <int I>\n" 4112 "constexpr void foo()\n" 4113 " requires(I == 42)\n" 4114 "{}\n" 4115 "namespace ns {\n" 4116 "void foo() {}\n" 4117 "} // namespace ns\n", 4118 Style); 4119 } 4120 4121 TEST_F(FormatTest, NamespaceMacros) { 4122 FormatStyle Style = getLLVMStyle(); 4123 Style.NamespaceMacros.push_back("TESTSUITE"); 4124 4125 verifyFormat("TESTSUITE(A) {\n" 4126 "int foo();\n" 4127 "} // TESTSUITE(A)", 4128 Style); 4129 4130 verifyFormat("TESTSUITE(A, B) {\n" 4131 "int foo();\n" 4132 "} // TESTSUITE(A)", 4133 Style); 4134 4135 // Properly indent according to NamespaceIndentation style 4136 Style.NamespaceIndentation = FormatStyle::NI_All; 4137 verifyFormat("TESTSUITE(A) {\n" 4138 " int foo();\n" 4139 "} // TESTSUITE(A)", 4140 Style); 4141 verifyFormat("TESTSUITE(A) {\n" 4142 " namespace B {\n" 4143 " int foo();\n" 4144 " } // namespace B\n" 4145 "} // TESTSUITE(A)", 4146 Style); 4147 verifyFormat("namespace A {\n" 4148 " TESTSUITE(B) {\n" 4149 " int foo();\n" 4150 " } // TESTSUITE(B)\n" 4151 "} // namespace A", 4152 Style); 4153 4154 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4155 verifyFormat("TESTSUITE(A) {\n" 4156 "TESTSUITE(B) {\n" 4157 " int foo();\n" 4158 "} // TESTSUITE(B)\n" 4159 "} // TESTSUITE(A)", 4160 Style); 4161 verifyFormat("TESTSUITE(A) {\n" 4162 "namespace B {\n" 4163 " int foo();\n" 4164 "} // namespace B\n" 4165 "} // TESTSUITE(A)", 4166 Style); 4167 verifyFormat("namespace A {\n" 4168 "TESTSUITE(B) {\n" 4169 " int foo();\n" 4170 "} // TESTSUITE(B)\n" 4171 "} // namespace A", 4172 Style); 4173 4174 // Properly merge namespace-macros blocks in CompactNamespaces mode 4175 Style.NamespaceIndentation = FormatStyle::NI_None; 4176 Style.CompactNamespaces = true; 4177 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4178 "}} // TESTSUITE(A::B)", 4179 Style); 4180 4181 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4182 "}} // TESTSUITE(out::in)", 4183 format("TESTSUITE(out) {\n" 4184 "TESTSUITE(in) {\n" 4185 "} // TESTSUITE(in)\n" 4186 "} // TESTSUITE(out)", 4187 Style)); 4188 4189 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4190 "}} // TESTSUITE(out::in)", 4191 format("TESTSUITE(out) {\n" 4192 "TESTSUITE(in) {\n" 4193 "} // TESTSUITE(in)\n" 4194 "} // TESTSUITE(out)", 4195 Style)); 4196 4197 // Do not merge different namespaces/macros 4198 EXPECT_EQ("namespace out {\n" 4199 "TESTSUITE(in) {\n" 4200 "} // TESTSUITE(in)\n" 4201 "} // namespace out", 4202 format("namespace out {\n" 4203 "TESTSUITE(in) {\n" 4204 "} // TESTSUITE(in)\n" 4205 "} // namespace out", 4206 Style)); 4207 EXPECT_EQ("TESTSUITE(out) {\n" 4208 "namespace in {\n" 4209 "} // namespace in\n" 4210 "} // TESTSUITE(out)", 4211 format("TESTSUITE(out) {\n" 4212 "namespace in {\n" 4213 "} // namespace in\n" 4214 "} // TESTSUITE(out)", 4215 Style)); 4216 Style.NamespaceMacros.push_back("FOOBAR"); 4217 EXPECT_EQ("TESTSUITE(out) {\n" 4218 "FOOBAR(in) {\n" 4219 "} // FOOBAR(in)\n" 4220 "} // TESTSUITE(out)", 4221 format("TESTSUITE(out) {\n" 4222 "FOOBAR(in) {\n" 4223 "} // FOOBAR(in)\n" 4224 "} // TESTSUITE(out)", 4225 Style)); 4226 } 4227 4228 TEST_F(FormatTest, FormatsCompactNamespaces) { 4229 FormatStyle Style = getLLVMStyle(); 4230 Style.CompactNamespaces = true; 4231 Style.NamespaceMacros.push_back("TESTSUITE"); 4232 4233 verifyFormat("namespace A { namespace B {\n" 4234 "}} // namespace A::B", 4235 Style); 4236 4237 EXPECT_EQ("namespace out { namespace in {\n" 4238 "}} // namespace out::in", 4239 format("namespace out {\n" 4240 "namespace in {\n" 4241 "} // namespace in\n" 4242 "} // namespace out", 4243 Style)); 4244 4245 // Only namespaces which have both consecutive opening and end get compacted 4246 EXPECT_EQ("namespace out {\n" 4247 "namespace in1 {\n" 4248 "} // namespace in1\n" 4249 "namespace in2 {\n" 4250 "} // namespace in2\n" 4251 "} // namespace out", 4252 format("namespace out {\n" 4253 "namespace in1 {\n" 4254 "} // namespace in1\n" 4255 "namespace in2 {\n" 4256 "} // namespace in2\n" 4257 "} // namespace out", 4258 Style)); 4259 4260 EXPECT_EQ("namespace out {\n" 4261 "int i;\n" 4262 "namespace in {\n" 4263 "int j;\n" 4264 "} // namespace in\n" 4265 "int k;\n" 4266 "} // namespace out", 4267 format("namespace out { int i;\n" 4268 "namespace in { int j; } // namespace in\n" 4269 "int k; } // namespace out", 4270 Style)); 4271 4272 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4273 "}}} // namespace A::B::C\n", 4274 format("namespace A { namespace B {\n" 4275 "namespace C {\n" 4276 "}} // namespace B::C\n" 4277 "} // namespace A\n", 4278 Style)); 4279 4280 Style.ColumnLimit = 40; 4281 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4282 "namespace bbbbbbbbbb {\n" 4283 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4284 format("namespace aaaaaaaaaa {\n" 4285 "namespace bbbbbbbbbb {\n" 4286 "} // namespace bbbbbbbbbb\n" 4287 "} // namespace aaaaaaaaaa", 4288 Style)); 4289 4290 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4291 "namespace cccccc {\n" 4292 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4293 format("namespace aaaaaa {\n" 4294 "namespace bbbbbb {\n" 4295 "namespace cccccc {\n" 4296 "} // namespace cccccc\n" 4297 "} // namespace bbbbbb\n" 4298 "} // namespace aaaaaa", 4299 Style)); 4300 Style.ColumnLimit = 80; 4301 4302 // Extra semicolon after 'inner' closing brace prevents merging 4303 EXPECT_EQ("namespace out { namespace in {\n" 4304 "}; } // namespace out::in", 4305 format("namespace out {\n" 4306 "namespace in {\n" 4307 "}; // namespace in\n" 4308 "} // namespace out", 4309 Style)); 4310 4311 // Extra semicolon after 'outer' closing brace is conserved 4312 EXPECT_EQ("namespace out { namespace in {\n" 4313 "}}; // namespace out::in", 4314 format("namespace out {\n" 4315 "namespace in {\n" 4316 "} // namespace in\n" 4317 "}; // namespace out", 4318 Style)); 4319 4320 Style.NamespaceIndentation = FormatStyle::NI_All; 4321 EXPECT_EQ("namespace out { namespace in {\n" 4322 " int i;\n" 4323 "}} // namespace out::in", 4324 format("namespace out {\n" 4325 "namespace in {\n" 4326 "int i;\n" 4327 "} // namespace in\n" 4328 "} // namespace out", 4329 Style)); 4330 EXPECT_EQ("namespace out { namespace mid {\n" 4331 " namespace in {\n" 4332 " int j;\n" 4333 " } // namespace in\n" 4334 " int k;\n" 4335 "}} // namespace out::mid", 4336 format("namespace out { namespace mid {\n" 4337 "namespace in { int j; } // namespace in\n" 4338 "int k; }} // namespace out::mid", 4339 Style)); 4340 4341 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4342 EXPECT_EQ("namespace out { namespace in {\n" 4343 " int i;\n" 4344 "}} // namespace out::in", 4345 format("namespace out {\n" 4346 "namespace in {\n" 4347 "int i;\n" 4348 "} // namespace in\n" 4349 "} // namespace out", 4350 Style)); 4351 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4352 " int i;\n" 4353 "}}} // namespace out::mid::in", 4354 format("namespace out {\n" 4355 "namespace mid {\n" 4356 "namespace in {\n" 4357 "int i;\n" 4358 "} // namespace in\n" 4359 "} // namespace mid\n" 4360 "} // namespace out", 4361 Style)); 4362 4363 Style.CompactNamespaces = true; 4364 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4365 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4366 Style.BraceWrapping.BeforeLambdaBody = true; 4367 verifyFormat("namespace out { namespace in {\n" 4368 "}} // namespace out::in", 4369 Style); 4370 EXPECT_EQ("namespace out { namespace in {\n" 4371 "}} // namespace out::in", 4372 format("namespace out {\n" 4373 "namespace in {\n" 4374 "} // namespace in\n" 4375 "} // namespace out", 4376 Style)); 4377 } 4378 4379 TEST_F(FormatTest, FormatsExternC) { 4380 verifyFormat("extern \"C\" {\nint a;"); 4381 verifyFormat("extern \"C\" {}"); 4382 verifyFormat("extern \"C\" {\n" 4383 "int foo();\n" 4384 "}"); 4385 verifyFormat("extern \"C\" int foo() {}"); 4386 verifyFormat("extern \"C\" int foo();"); 4387 verifyFormat("extern \"C\" int foo() {\n" 4388 " int i = 42;\n" 4389 " return i;\n" 4390 "}"); 4391 4392 FormatStyle Style = getLLVMStyle(); 4393 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4394 Style.BraceWrapping.AfterFunction = true; 4395 verifyFormat("extern \"C\" int foo() {}", Style); 4396 verifyFormat("extern \"C\" int foo();", Style); 4397 verifyFormat("extern \"C\" int foo()\n" 4398 "{\n" 4399 " int i = 42;\n" 4400 " return i;\n" 4401 "}", 4402 Style); 4403 4404 Style.BraceWrapping.AfterExternBlock = true; 4405 Style.BraceWrapping.SplitEmptyRecord = false; 4406 verifyFormat("extern \"C\"\n" 4407 "{}", 4408 Style); 4409 verifyFormat("extern \"C\"\n" 4410 "{\n" 4411 " int foo();\n" 4412 "}", 4413 Style); 4414 } 4415 4416 TEST_F(FormatTest, IndentExternBlockStyle) { 4417 FormatStyle Style = getLLVMStyle(); 4418 Style.IndentWidth = 2; 4419 4420 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4421 verifyFormat("extern \"C\" { /*9*/\n" 4422 "}", 4423 Style); 4424 verifyFormat("extern \"C\" {\n" 4425 " int foo10();\n" 4426 "}", 4427 Style); 4428 4429 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4430 verifyFormat("extern \"C\" { /*11*/\n" 4431 "}", 4432 Style); 4433 verifyFormat("extern \"C\" {\n" 4434 "int foo12();\n" 4435 "}", 4436 Style); 4437 4438 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4439 Style.BraceWrapping.AfterExternBlock = true; 4440 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4441 verifyFormat("extern \"C\"\n" 4442 "{ /*13*/\n" 4443 "}", 4444 Style); 4445 verifyFormat("extern \"C\"\n{\n" 4446 " int foo14();\n" 4447 "}", 4448 Style); 4449 4450 Style.BraceWrapping.AfterExternBlock = false; 4451 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4452 verifyFormat("extern \"C\" { /*15*/\n" 4453 "}", 4454 Style); 4455 verifyFormat("extern \"C\" {\n" 4456 "int foo16();\n" 4457 "}", 4458 Style); 4459 4460 Style.BraceWrapping.AfterExternBlock = true; 4461 verifyFormat("extern \"C\"\n" 4462 "{ /*13*/\n" 4463 "}", 4464 Style); 4465 verifyFormat("extern \"C\"\n" 4466 "{\n" 4467 "int foo14();\n" 4468 "}", 4469 Style); 4470 4471 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4472 verifyFormat("extern \"C\"\n" 4473 "{ /*13*/\n" 4474 "}", 4475 Style); 4476 verifyFormat("extern \"C\"\n" 4477 "{\n" 4478 " int foo14();\n" 4479 "}", 4480 Style); 4481 } 4482 4483 TEST_F(FormatTest, FormatsInlineASM) { 4484 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4485 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4486 verifyFormat( 4487 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4488 " \"cpuid\\n\\t\"\n" 4489 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4490 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4491 " : \"a\"(value));"); 4492 EXPECT_EQ( 4493 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4494 " __asm {\n" 4495 " mov edx,[that] // vtable in edx\n" 4496 " mov eax,methodIndex\n" 4497 " call [edx][eax*4] // stdcall\n" 4498 " }\n" 4499 "}", 4500 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4501 " __asm {\n" 4502 " mov edx,[that] // vtable in edx\n" 4503 " mov eax,methodIndex\n" 4504 " call [edx][eax*4] // stdcall\n" 4505 " }\n" 4506 "}")); 4507 EXPECT_EQ("_asm {\n" 4508 " xor eax, eax;\n" 4509 " cpuid;\n" 4510 "}", 4511 format("_asm {\n" 4512 " xor eax, eax;\n" 4513 " cpuid;\n" 4514 "}")); 4515 verifyFormat("void function() {\n" 4516 " // comment\n" 4517 " asm(\"\");\n" 4518 "}"); 4519 EXPECT_EQ("__asm {\n" 4520 "}\n" 4521 "int i;", 4522 format("__asm {\n" 4523 "}\n" 4524 "int i;")); 4525 } 4526 4527 TEST_F(FormatTest, FormatTryCatch) { 4528 verifyFormat("try {\n" 4529 " throw a * b;\n" 4530 "} catch (int a) {\n" 4531 " // Do nothing.\n" 4532 "} catch (...) {\n" 4533 " exit(42);\n" 4534 "}"); 4535 4536 // Function-level try statements. 4537 verifyFormat("int f() try { return 4; } catch (...) {\n" 4538 " return 5;\n" 4539 "}"); 4540 verifyFormat("class A {\n" 4541 " int a;\n" 4542 " A() try : a(0) {\n" 4543 " } catch (...) {\n" 4544 " throw;\n" 4545 " }\n" 4546 "};\n"); 4547 verifyFormat("class A {\n" 4548 " int a;\n" 4549 " A() try : a(0), b{1} {\n" 4550 " } catch (...) {\n" 4551 " throw;\n" 4552 " }\n" 4553 "};\n"); 4554 verifyFormat("class A {\n" 4555 " int a;\n" 4556 " A() try : a(0), b{1}, c{2} {\n" 4557 " } catch (...) {\n" 4558 " throw;\n" 4559 " }\n" 4560 "};\n"); 4561 verifyFormat("class A {\n" 4562 " int a;\n" 4563 " A() try : a(0), b{1}, c{2} {\n" 4564 " { // New scope.\n" 4565 " }\n" 4566 " } catch (...) {\n" 4567 " throw;\n" 4568 " }\n" 4569 "};\n"); 4570 4571 // Incomplete try-catch blocks. 4572 verifyIncompleteFormat("try {} catch ("); 4573 } 4574 4575 TEST_F(FormatTest, FormatTryAsAVariable) { 4576 verifyFormat("int try;"); 4577 verifyFormat("int try, size;"); 4578 verifyFormat("try = foo();"); 4579 verifyFormat("if (try < size) {\n return true;\n}"); 4580 4581 verifyFormat("int catch;"); 4582 verifyFormat("int catch, size;"); 4583 verifyFormat("catch = foo();"); 4584 verifyFormat("if (catch < size) {\n return true;\n}"); 4585 4586 FormatStyle Style = getLLVMStyle(); 4587 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4588 Style.BraceWrapping.AfterFunction = true; 4589 Style.BraceWrapping.BeforeCatch = true; 4590 verifyFormat("try {\n" 4591 " int bar = 1;\n" 4592 "}\n" 4593 "catch (...) {\n" 4594 " int bar = 1;\n" 4595 "}", 4596 Style); 4597 verifyFormat("#if NO_EX\n" 4598 "try\n" 4599 "#endif\n" 4600 "{\n" 4601 "}\n" 4602 "#if NO_EX\n" 4603 "catch (...) {\n" 4604 "}", 4605 Style); 4606 verifyFormat("try /* abc */ {\n" 4607 " int bar = 1;\n" 4608 "}\n" 4609 "catch (...) {\n" 4610 " int bar = 1;\n" 4611 "}", 4612 Style); 4613 verifyFormat("try\n" 4614 "// abc\n" 4615 "{\n" 4616 " int bar = 1;\n" 4617 "}\n" 4618 "catch (...) {\n" 4619 " int bar = 1;\n" 4620 "}", 4621 Style); 4622 } 4623 4624 TEST_F(FormatTest, FormatSEHTryCatch) { 4625 verifyFormat("__try {\n" 4626 " int a = b * c;\n" 4627 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4628 " // Do nothing.\n" 4629 "}"); 4630 4631 verifyFormat("__try {\n" 4632 " int a = b * c;\n" 4633 "} __finally {\n" 4634 " // Do nothing.\n" 4635 "}"); 4636 4637 verifyFormat("DEBUG({\n" 4638 " __try {\n" 4639 " } __finally {\n" 4640 " }\n" 4641 "});\n"); 4642 } 4643 4644 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4645 verifyFormat("try {\n" 4646 " f();\n" 4647 "} catch {\n" 4648 " g();\n" 4649 "}"); 4650 verifyFormat("try {\n" 4651 " f();\n" 4652 "} catch (A a) MACRO(x) {\n" 4653 " g();\n" 4654 "} catch (B b) MACRO(x) {\n" 4655 " g();\n" 4656 "}"); 4657 } 4658 4659 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4660 FormatStyle Style = getLLVMStyle(); 4661 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4662 FormatStyle::BS_WebKit}) { 4663 Style.BreakBeforeBraces = BraceStyle; 4664 verifyFormat("try {\n" 4665 " // something\n" 4666 "} catch (...) {\n" 4667 " // something\n" 4668 "}", 4669 Style); 4670 } 4671 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4672 verifyFormat("try {\n" 4673 " // something\n" 4674 "}\n" 4675 "catch (...) {\n" 4676 " // something\n" 4677 "}", 4678 Style); 4679 verifyFormat("__try {\n" 4680 " // something\n" 4681 "}\n" 4682 "__finally {\n" 4683 " // something\n" 4684 "}", 4685 Style); 4686 verifyFormat("@try {\n" 4687 " // something\n" 4688 "}\n" 4689 "@finally {\n" 4690 " // something\n" 4691 "}", 4692 Style); 4693 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4694 verifyFormat("try\n" 4695 "{\n" 4696 " // something\n" 4697 "}\n" 4698 "catch (...)\n" 4699 "{\n" 4700 " // something\n" 4701 "}", 4702 Style); 4703 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4704 verifyFormat("try\n" 4705 " {\n" 4706 " // something white\n" 4707 " }\n" 4708 "catch (...)\n" 4709 " {\n" 4710 " // something white\n" 4711 " }", 4712 Style); 4713 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4714 verifyFormat("try\n" 4715 " {\n" 4716 " // something\n" 4717 " }\n" 4718 "catch (...)\n" 4719 " {\n" 4720 " // something\n" 4721 " }", 4722 Style); 4723 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4724 Style.BraceWrapping.BeforeCatch = true; 4725 verifyFormat("try {\n" 4726 " // something\n" 4727 "}\n" 4728 "catch (...) {\n" 4729 " // something\n" 4730 "}", 4731 Style); 4732 } 4733 4734 TEST_F(FormatTest, StaticInitializers) { 4735 verifyFormat("static SomeClass SC = {1, 'a'};"); 4736 4737 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4738 " 100000000, " 4739 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4740 4741 // Here, everything other than the "}" would fit on a line. 4742 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4743 " 10000000000000000000000000};"); 4744 EXPECT_EQ("S s = {a,\n" 4745 "\n" 4746 " b};", 4747 format("S s = {\n" 4748 " a,\n" 4749 "\n" 4750 " b\n" 4751 "};")); 4752 4753 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4754 // line. However, the formatting looks a bit off and this probably doesn't 4755 // happen often in practice. 4756 verifyFormat("static int Variable[1] = {\n" 4757 " {1000000000000000000000000000000000000}};", 4758 getLLVMStyleWithColumns(40)); 4759 } 4760 4761 TEST_F(FormatTest, DesignatedInitializers) { 4762 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4763 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4764 " .bbbbbbbbbb = 2,\n" 4765 " .cccccccccc = 3,\n" 4766 " .dddddddddd = 4,\n" 4767 " .eeeeeeeeee = 5};"); 4768 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4769 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4770 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4771 " .ccccccccccccccccccccccccccc = 3,\n" 4772 " .ddddddddddddddddddddddddddd = 4,\n" 4773 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4774 4775 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4776 4777 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4778 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4779 " [2] = bbbbbbbbbb,\n" 4780 " [3] = cccccccccc,\n" 4781 " [4] = dddddddddd,\n" 4782 " [5] = eeeeeeeeee};"); 4783 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4784 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4785 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4786 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4787 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4788 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4789 } 4790 4791 TEST_F(FormatTest, NestedStaticInitializers) { 4792 verifyFormat("static A x = {{{}}};\n"); 4793 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4794 " {init1, init2, init3, init4}}};", 4795 getLLVMStyleWithColumns(50)); 4796 4797 verifyFormat("somes Status::global_reps[3] = {\n" 4798 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4799 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4800 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4801 getLLVMStyleWithColumns(60)); 4802 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4803 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4804 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4805 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4806 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4807 " {rect.fRight - rect.fLeft, rect.fBottom - " 4808 "rect.fTop}};"); 4809 4810 verifyFormat( 4811 "SomeArrayOfSomeType a = {\n" 4812 " {{1, 2, 3},\n" 4813 " {1, 2, 3},\n" 4814 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4815 " 333333333333333333333333333333},\n" 4816 " {1, 2, 3},\n" 4817 " {1, 2, 3}}};"); 4818 verifyFormat( 4819 "SomeArrayOfSomeType a = {\n" 4820 " {{1, 2, 3}},\n" 4821 " {{1, 2, 3}},\n" 4822 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4823 " 333333333333333333333333333333}},\n" 4824 " {{1, 2, 3}},\n" 4825 " {{1, 2, 3}}};"); 4826 4827 verifyFormat("struct {\n" 4828 " unsigned bit;\n" 4829 " const char *const name;\n" 4830 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4831 " {kOsWin, \"Windows\"},\n" 4832 " {kOsLinux, \"Linux\"},\n" 4833 " {kOsCrOS, \"Chrome OS\"}};"); 4834 verifyFormat("struct {\n" 4835 " unsigned bit;\n" 4836 " const char *const name;\n" 4837 "} kBitsToOs[] = {\n" 4838 " {kOsMac, \"Mac\"},\n" 4839 " {kOsWin, \"Windows\"},\n" 4840 " {kOsLinux, \"Linux\"},\n" 4841 " {kOsCrOS, \"Chrome OS\"},\n" 4842 "};"); 4843 } 4844 4845 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4846 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4847 " \\\n" 4848 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4849 } 4850 4851 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4852 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4853 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4854 4855 // Do break defaulted and deleted functions. 4856 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4857 " default;", 4858 getLLVMStyleWithColumns(40)); 4859 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4860 " delete;", 4861 getLLVMStyleWithColumns(40)); 4862 } 4863 4864 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4865 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4866 getLLVMStyleWithColumns(40)); 4867 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4868 getLLVMStyleWithColumns(40)); 4869 EXPECT_EQ("#define Q \\\n" 4870 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4871 " \"aaaaaaaa.cpp\"", 4872 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4873 getLLVMStyleWithColumns(40))); 4874 } 4875 4876 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4877 EXPECT_EQ("# 123 \"A string literal\"", 4878 format(" # 123 \"A string literal\"")); 4879 } 4880 4881 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4882 EXPECT_EQ("#;", format("#;")); 4883 verifyFormat("#\n;\n;\n;"); 4884 } 4885 4886 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4887 EXPECT_EQ("#line 42 \"test\"\n", 4888 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4889 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4890 getLLVMStyleWithColumns(12))); 4891 } 4892 4893 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4894 EXPECT_EQ("#line 42 \"test\"", 4895 format("# \\\n line \\\n 42 \\\n \"test\"")); 4896 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4897 } 4898 4899 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4900 verifyFormat("#define A \\x20"); 4901 verifyFormat("#define A \\ x20"); 4902 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4903 verifyFormat("#define A ''"); 4904 verifyFormat("#define A ''qqq"); 4905 verifyFormat("#define A `qqq"); 4906 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4907 EXPECT_EQ("const char *c = STRINGIFY(\n" 4908 "\\na : b);", 4909 format("const char * c = STRINGIFY(\n" 4910 "\\na : b);")); 4911 4912 verifyFormat("a\r\\"); 4913 verifyFormat("a\v\\"); 4914 verifyFormat("a\f\\"); 4915 } 4916 4917 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4918 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4919 style.IndentWidth = 4; 4920 style.PPIndentWidth = 1; 4921 4922 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4923 verifyFormat("#ifdef __linux__\n" 4924 "void foo() {\n" 4925 " int x = 0;\n" 4926 "}\n" 4927 "#define FOO\n" 4928 "#endif\n" 4929 "void bar() {\n" 4930 " int y = 0;\n" 4931 "}\n", 4932 style); 4933 4934 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4935 verifyFormat("#ifdef __linux__\n" 4936 "void foo() {\n" 4937 " int x = 0;\n" 4938 "}\n" 4939 "# define FOO foo\n" 4940 "#endif\n" 4941 "void bar() {\n" 4942 " int y = 0;\n" 4943 "}\n", 4944 style); 4945 4946 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4947 verifyFormat("#ifdef __linux__\n" 4948 "void foo() {\n" 4949 " int x = 0;\n" 4950 "}\n" 4951 " #define FOO foo\n" 4952 "#endif\n" 4953 "void bar() {\n" 4954 " int y = 0;\n" 4955 "}\n", 4956 style); 4957 } 4958 4959 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4960 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4961 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4962 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4963 // FIXME: We never break before the macro name. 4964 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4965 4966 verifyFormat("#define A A\n#define A A"); 4967 verifyFormat("#define A(X) A\n#define A A"); 4968 4969 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4970 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4971 } 4972 4973 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4974 EXPECT_EQ("// somecomment\n" 4975 "#include \"a.h\"\n" 4976 "#define A( \\\n" 4977 " A, B)\n" 4978 "#include \"b.h\"\n" 4979 "// somecomment\n", 4980 format(" // somecomment\n" 4981 " #include \"a.h\"\n" 4982 "#define A(A,\\\n" 4983 " B)\n" 4984 " #include \"b.h\"\n" 4985 " // somecomment\n", 4986 getLLVMStyleWithColumns(13))); 4987 } 4988 4989 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4990 4991 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4992 EXPECT_EQ("#define A \\\n" 4993 " c; \\\n" 4994 " e;\n" 4995 "f;", 4996 format("#define A c; e;\n" 4997 "f;", 4998 getLLVMStyleWithColumns(14))); 4999 } 5000 5001 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 5002 5003 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 5004 EXPECT_EQ("int x,\n" 5005 "#define A\n" 5006 " y;", 5007 format("int x,\n#define A\ny;")); 5008 } 5009 5010 TEST_F(FormatTest, HashInMacroDefinition) { 5011 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 5012 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 5013 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 5014 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 5015 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 5016 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 5017 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 5018 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 5019 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 5020 verifyFormat("#define A \\\n" 5021 " { \\\n" 5022 " f(#c); \\\n" 5023 " }", 5024 getLLVMStyleWithColumns(11)); 5025 5026 verifyFormat("#define A(X) \\\n" 5027 " void function##X()", 5028 getLLVMStyleWithColumns(22)); 5029 5030 verifyFormat("#define A(a, b, c) \\\n" 5031 " void a##b##c()", 5032 getLLVMStyleWithColumns(22)); 5033 5034 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 5035 } 5036 5037 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 5038 EXPECT_EQ("#define A (x)", format("#define A (x)")); 5039 EXPECT_EQ("#define A(x)", format("#define A(x)")); 5040 5041 FormatStyle Style = getLLVMStyle(); 5042 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 5043 verifyFormat("#define true ((foo)1)", Style); 5044 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 5045 verifyFormat("#define false((foo)0)", Style); 5046 } 5047 5048 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 5049 EXPECT_EQ("#define A b;", format("#define A \\\n" 5050 " \\\n" 5051 " b;", 5052 getLLVMStyleWithColumns(25))); 5053 EXPECT_EQ("#define A \\\n" 5054 " \\\n" 5055 " a; \\\n" 5056 " b;", 5057 format("#define A \\\n" 5058 " \\\n" 5059 " a; \\\n" 5060 " b;", 5061 getLLVMStyleWithColumns(11))); 5062 EXPECT_EQ("#define A \\\n" 5063 " a; \\\n" 5064 " \\\n" 5065 " b;", 5066 format("#define A \\\n" 5067 " a; \\\n" 5068 " \\\n" 5069 " b;", 5070 getLLVMStyleWithColumns(11))); 5071 } 5072 5073 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5074 verifyIncompleteFormat("#define A :"); 5075 verifyFormat("#define SOMECASES \\\n" 5076 " case 1: \\\n" 5077 " case 2\n", 5078 getLLVMStyleWithColumns(20)); 5079 verifyFormat("#define MACRO(a) \\\n" 5080 " if (a) \\\n" 5081 " f(); \\\n" 5082 " else \\\n" 5083 " g()", 5084 getLLVMStyleWithColumns(18)); 5085 verifyFormat("#define A template <typename T>"); 5086 verifyIncompleteFormat("#define STR(x) #x\n" 5087 "f(STR(this_is_a_string_literal{));"); 5088 verifyFormat("#pragma omp threadprivate( \\\n" 5089 " y)), // expected-warning", 5090 getLLVMStyleWithColumns(28)); 5091 verifyFormat("#d, = };"); 5092 verifyFormat("#if \"a"); 5093 verifyIncompleteFormat("({\n" 5094 "#define b \\\n" 5095 " } \\\n" 5096 " a\n" 5097 "a", 5098 getLLVMStyleWithColumns(15)); 5099 verifyFormat("#define A \\\n" 5100 " { \\\n" 5101 " {\n" 5102 "#define B \\\n" 5103 " } \\\n" 5104 " }", 5105 getLLVMStyleWithColumns(15)); 5106 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5107 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5108 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5109 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5110 } 5111 5112 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5113 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5114 EXPECT_EQ("class A : public QObject {\n" 5115 " Q_OBJECT\n" 5116 "\n" 5117 " A() {}\n" 5118 "};", 5119 format("class A : public QObject {\n" 5120 " Q_OBJECT\n" 5121 "\n" 5122 " A() {\n}\n" 5123 "} ;")); 5124 EXPECT_EQ("MACRO\n" 5125 "/*static*/ int i;", 5126 format("MACRO\n" 5127 " /*static*/ int i;")); 5128 EXPECT_EQ("SOME_MACRO\n" 5129 "namespace {\n" 5130 "void f();\n" 5131 "} // namespace", 5132 format("SOME_MACRO\n" 5133 " namespace {\n" 5134 "void f( );\n" 5135 "} // namespace")); 5136 // Only if the identifier contains at least 5 characters. 5137 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5138 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5139 // Only if everything is upper case. 5140 EXPECT_EQ("class A : public QObject {\n" 5141 " Q_Object A() {}\n" 5142 "};", 5143 format("class A : public QObject {\n" 5144 " Q_Object\n" 5145 " A() {\n}\n" 5146 "} ;")); 5147 5148 // Only if the next line can actually start an unwrapped line. 5149 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5150 format("SOME_WEIRD_LOG_MACRO\n" 5151 "<< SomeThing;")); 5152 5153 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5154 "(n, buffers))\n", 5155 getChromiumStyle(FormatStyle::LK_Cpp)); 5156 5157 // See PR41483 5158 EXPECT_EQ("/**/ FOO(a)\n" 5159 "FOO(b)", 5160 format("/**/ FOO(a)\n" 5161 "FOO(b)")); 5162 } 5163 5164 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5165 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5166 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5167 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5168 "class X {};\n" 5169 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5170 "int *createScopDetectionPass() { return 0; }", 5171 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5172 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5173 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5174 " class X {};\n" 5175 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5176 " int *createScopDetectionPass() { return 0; }")); 5177 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5178 // braces, so that inner block is indented one level more. 5179 EXPECT_EQ("int q() {\n" 5180 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5181 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5182 " IPC_END_MESSAGE_MAP()\n" 5183 "}", 5184 format("int q() {\n" 5185 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5186 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5187 " IPC_END_MESSAGE_MAP()\n" 5188 "}")); 5189 5190 // Same inside macros. 5191 EXPECT_EQ("#define LIST(L) \\\n" 5192 " L(A) \\\n" 5193 " L(B) \\\n" 5194 " L(C)", 5195 format("#define LIST(L) \\\n" 5196 " L(A) \\\n" 5197 " L(B) \\\n" 5198 " L(C)", 5199 getGoogleStyle())); 5200 5201 // These must not be recognized as macros. 5202 EXPECT_EQ("int q() {\n" 5203 " f(x);\n" 5204 " f(x) {}\n" 5205 " f(x)->g();\n" 5206 " f(x)->*g();\n" 5207 " f(x).g();\n" 5208 " f(x) = x;\n" 5209 " f(x) += x;\n" 5210 " f(x) -= x;\n" 5211 " f(x) *= x;\n" 5212 " f(x) /= x;\n" 5213 " f(x) %= x;\n" 5214 " f(x) &= x;\n" 5215 " f(x) |= x;\n" 5216 " f(x) ^= x;\n" 5217 " f(x) >>= x;\n" 5218 " f(x) <<= x;\n" 5219 " f(x)[y].z();\n" 5220 " LOG(INFO) << x;\n" 5221 " ifstream(x) >> x;\n" 5222 "}\n", 5223 format("int q() {\n" 5224 " f(x)\n;\n" 5225 " f(x)\n {}\n" 5226 " f(x)\n->g();\n" 5227 " f(x)\n->*g();\n" 5228 " f(x)\n.g();\n" 5229 " f(x)\n = x;\n" 5230 " f(x)\n += x;\n" 5231 " f(x)\n -= x;\n" 5232 " f(x)\n *= x;\n" 5233 " f(x)\n /= x;\n" 5234 " f(x)\n %= x;\n" 5235 " f(x)\n &= x;\n" 5236 " f(x)\n |= x;\n" 5237 " f(x)\n ^= x;\n" 5238 " f(x)\n >>= x;\n" 5239 " f(x)\n <<= x;\n" 5240 " f(x)\n[y].z();\n" 5241 " LOG(INFO)\n << x;\n" 5242 " ifstream(x)\n >> x;\n" 5243 "}\n")); 5244 EXPECT_EQ("int q() {\n" 5245 " F(x)\n" 5246 " if (1) {\n" 5247 " }\n" 5248 " F(x)\n" 5249 " while (1) {\n" 5250 " }\n" 5251 " F(x)\n" 5252 " G(x);\n" 5253 " F(x)\n" 5254 " try {\n" 5255 " Q();\n" 5256 " } catch (...) {\n" 5257 " }\n" 5258 "}\n", 5259 format("int q() {\n" 5260 "F(x)\n" 5261 "if (1) {}\n" 5262 "F(x)\n" 5263 "while (1) {}\n" 5264 "F(x)\n" 5265 "G(x);\n" 5266 "F(x)\n" 5267 "try { Q(); } catch (...) {}\n" 5268 "}\n")); 5269 EXPECT_EQ("class A {\n" 5270 " A() : t(0) {}\n" 5271 " A(int i) noexcept() : {}\n" 5272 " A(X x)\n" // FIXME: function-level try blocks are broken. 5273 " try : t(0) {\n" 5274 " } catch (...) {\n" 5275 " }\n" 5276 "};", 5277 format("class A {\n" 5278 " A()\n : t(0) {}\n" 5279 " A(int i)\n noexcept() : {}\n" 5280 " A(X x)\n" 5281 " try : t(0) {} catch (...) {}\n" 5282 "};")); 5283 FormatStyle Style = getLLVMStyle(); 5284 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5285 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5286 Style.BraceWrapping.AfterFunction = true; 5287 EXPECT_EQ("void f()\n" 5288 "try\n" 5289 "{\n" 5290 "}", 5291 format("void f() try {\n" 5292 "}", 5293 Style)); 5294 EXPECT_EQ("class SomeClass {\n" 5295 "public:\n" 5296 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5297 "};", 5298 format("class SomeClass {\n" 5299 "public:\n" 5300 " SomeClass()\n" 5301 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5302 "};")); 5303 EXPECT_EQ("class SomeClass {\n" 5304 "public:\n" 5305 " SomeClass()\n" 5306 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5307 "};", 5308 format("class SomeClass {\n" 5309 "public:\n" 5310 " SomeClass()\n" 5311 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5312 "};", 5313 getLLVMStyleWithColumns(40))); 5314 5315 verifyFormat("MACRO(>)"); 5316 5317 // Some macros contain an implicit semicolon. 5318 Style = getLLVMStyle(); 5319 Style.StatementMacros.push_back("FOO"); 5320 verifyFormat("FOO(a) int b = 0;"); 5321 verifyFormat("FOO(a)\n" 5322 "int b = 0;", 5323 Style); 5324 verifyFormat("FOO(a);\n" 5325 "int b = 0;", 5326 Style); 5327 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5328 "int b = 0;", 5329 Style); 5330 verifyFormat("FOO()\n" 5331 "int b = 0;", 5332 Style); 5333 verifyFormat("FOO\n" 5334 "int b = 0;", 5335 Style); 5336 verifyFormat("void f() {\n" 5337 " FOO(a)\n" 5338 " return a;\n" 5339 "}", 5340 Style); 5341 verifyFormat("FOO(a)\n" 5342 "FOO(b)", 5343 Style); 5344 verifyFormat("int a = 0;\n" 5345 "FOO(b)\n" 5346 "int c = 0;", 5347 Style); 5348 verifyFormat("int a = 0;\n" 5349 "int x = FOO(a)\n" 5350 "int b = 0;", 5351 Style); 5352 verifyFormat("void foo(int a) { FOO(a) }\n" 5353 "uint32_t bar() {}", 5354 Style); 5355 } 5356 5357 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5358 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5359 5360 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5361 ZeroColumn); 5362 } 5363 5364 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5365 verifyFormat("#define A \\\n" 5366 " f({ \\\n" 5367 " g(); \\\n" 5368 " });", 5369 getLLVMStyleWithColumns(11)); 5370 } 5371 5372 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5373 FormatStyle Style = getLLVMStyleWithColumns(40); 5374 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5375 verifyFormat("#ifdef _WIN32\n" 5376 "#define A 0\n" 5377 "#ifdef VAR2\n" 5378 "#define B 1\n" 5379 "#include <someheader.h>\n" 5380 "#define MACRO \\\n" 5381 " some_very_long_func_aaaaaaaaaa();\n" 5382 "#endif\n" 5383 "#else\n" 5384 "#define A 1\n" 5385 "#endif", 5386 Style); 5387 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5388 verifyFormat("#ifdef _WIN32\n" 5389 "# define A 0\n" 5390 "# ifdef VAR2\n" 5391 "# define B 1\n" 5392 "# include <someheader.h>\n" 5393 "# define MACRO \\\n" 5394 " some_very_long_func_aaaaaaaaaa();\n" 5395 "# endif\n" 5396 "#else\n" 5397 "# define A 1\n" 5398 "#endif", 5399 Style); 5400 verifyFormat("#if A\n" 5401 "# define MACRO \\\n" 5402 " void a(int x) { \\\n" 5403 " b(); \\\n" 5404 " c(); \\\n" 5405 " d(); \\\n" 5406 " e(); \\\n" 5407 " f(); \\\n" 5408 " }\n" 5409 "#endif", 5410 Style); 5411 // Comments before include guard. 5412 verifyFormat("// file comment\n" 5413 "// file comment\n" 5414 "#ifndef HEADER_H\n" 5415 "#define HEADER_H\n" 5416 "code();\n" 5417 "#endif", 5418 Style); 5419 // Test with include guards. 5420 verifyFormat("#ifndef HEADER_H\n" 5421 "#define HEADER_H\n" 5422 "code();\n" 5423 "#endif", 5424 Style); 5425 // Include guards must have a #define with the same variable immediately 5426 // after #ifndef. 5427 verifyFormat("#ifndef NOT_GUARD\n" 5428 "# define FOO\n" 5429 "code();\n" 5430 "#endif", 5431 Style); 5432 5433 // Include guards must cover the entire file. 5434 verifyFormat("code();\n" 5435 "code();\n" 5436 "#ifndef NOT_GUARD\n" 5437 "# define NOT_GUARD\n" 5438 "code();\n" 5439 "#endif", 5440 Style); 5441 verifyFormat("#ifndef NOT_GUARD\n" 5442 "# define NOT_GUARD\n" 5443 "code();\n" 5444 "#endif\n" 5445 "code();", 5446 Style); 5447 // Test with trailing blank lines. 5448 verifyFormat("#ifndef HEADER_H\n" 5449 "#define HEADER_H\n" 5450 "code();\n" 5451 "#endif\n", 5452 Style); 5453 // Include guards don't have #else. 5454 verifyFormat("#ifndef NOT_GUARD\n" 5455 "# define NOT_GUARD\n" 5456 "code();\n" 5457 "#else\n" 5458 "#endif", 5459 Style); 5460 verifyFormat("#ifndef NOT_GUARD\n" 5461 "# define NOT_GUARD\n" 5462 "code();\n" 5463 "#elif FOO\n" 5464 "#endif", 5465 Style); 5466 // Non-identifier #define after potential include guard. 5467 verifyFormat("#ifndef FOO\n" 5468 "# define 1\n" 5469 "#endif\n", 5470 Style); 5471 // #if closes past last non-preprocessor line. 5472 verifyFormat("#ifndef FOO\n" 5473 "#define FOO\n" 5474 "#if 1\n" 5475 "int i;\n" 5476 "# define A 0\n" 5477 "#endif\n" 5478 "#endif\n", 5479 Style); 5480 // Don't crash if there is an #elif directive without a condition. 5481 verifyFormat("#if 1\n" 5482 "int x;\n" 5483 "#elif\n" 5484 "int y;\n" 5485 "#else\n" 5486 "int z;\n" 5487 "#endif", 5488 Style); 5489 // FIXME: This doesn't handle the case where there's code between the 5490 // #ifndef and #define but all other conditions hold. This is because when 5491 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5492 // previous code line yet, so we can't detect it. 5493 EXPECT_EQ("#ifndef NOT_GUARD\n" 5494 "code();\n" 5495 "#define NOT_GUARD\n" 5496 "code();\n" 5497 "#endif", 5498 format("#ifndef NOT_GUARD\n" 5499 "code();\n" 5500 "# define NOT_GUARD\n" 5501 "code();\n" 5502 "#endif", 5503 Style)); 5504 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5505 // be outside an include guard. Examples are #pragma once and 5506 // #pragma GCC diagnostic, or anything else that does not change the meaning 5507 // of the file if it's included multiple times. 5508 EXPECT_EQ("#ifdef WIN32\n" 5509 "# pragma once\n" 5510 "#endif\n" 5511 "#ifndef HEADER_H\n" 5512 "# define HEADER_H\n" 5513 "code();\n" 5514 "#endif", 5515 format("#ifdef WIN32\n" 5516 "# pragma once\n" 5517 "#endif\n" 5518 "#ifndef HEADER_H\n" 5519 "#define HEADER_H\n" 5520 "code();\n" 5521 "#endif", 5522 Style)); 5523 // FIXME: This does not detect when there is a single non-preprocessor line 5524 // in front of an include-guard-like structure where other conditions hold 5525 // because ScopedLineState hides the line. 5526 EXPECT_EQ("code();\n" 5527 "#ifndef HEADER_H\n" 5528 "#define HEADER_H\n" 5529 "code();\n" 5530 "#endif", 5531 format("code();\n" 5532 "#ifndef HEADER_H\n" 5533 "# define HEADER_H\n" 5534 "code();\n" 5535 "#endif", 5536 Style)); 5537 // Keep comments aligned with #, otherwise indent comments normally. These 5538 // tests cannot use verifyFormat because messUp manipulates leading 5539 // whitespace. 5540 { 5541 const char *Expected = "" 5542 "void f() {\n" 5543 "#if 1\n" 5544 "// Preprocessor aligned.\n" 5545 "# define A 0\n" 5546 " // Code. Separated by blank line.\n" 5547 "\n" 5548 "# define B 0\n" 5549 " // Code. Not aligned with #\n" 5550 "# define C 0\n" 5551 "#endif"; 5552 const char *ToFormat = "" 5553 "void f() {\n" 5554 "#if 1\n" 5555 "// Preprocessor aligned.\n" 5556 "# define A 0\n" 5557 "// Code. Separated by blank line.\n" 5558 "\n" 5559 "# define B 0\n" 5560 " // Code. Not aligned with #\n" 5561 "# define C 0\n" 5562 "#endif"; 5563 EXPECT_EQ(Expected, format(ToFormat, Style)); 5564 EXPECT_EQ(Expected, format(Expected, Style)); 5565 } 5566 // Keep block quotes aligned. 5567 { 5568 const char *Expected = "" 5569 "void f() {\n" 5570 "#if 1\n" 5571 "/* Preprocessor aligned. */\n" 5572 "# define A 0\n" 5573 " /* Code. Separated by blank line. */\n" 5574 "\n" 5575 "# define B 0\n" 5576 " /* Code. Not aligned with # */\n" 5577 "# define C 0\n" 5578 "#endif"; 5579 const char *ToFormat = "" 5580 "void f() {\n" 5581 "#if 1\n" 5582 "/* Preprocessor aligned. */\n" 5583 "# define A 0\n" 5584 "/* Code. Separated by blank line. */\n" 5585 "\n" 5586 "# define B 0\n" 5587 " /* Code. Not aligned with # */\n" 5588 "# define C 0\n" 5589 "#endif"; 5590 EXPECT_EQ(Expected, format(ToFormat, Style)); 5591 EXPECT_EQ(Expected, format(Expected, Style)); 5592 } 5593 // Keep comments aligned with un-indented directives. 5594 { 5595 const char *Expected = "" 5596 "void f() {\n" 5597 "// Preprocessor aligned.\n" 5598 "#define A 0\n" 5599 " // Code. Separated by blank line.\n" 5600 "\n" 5601 "#define B 0\n" 5602 " // Code. Not aligned with #\n" 5603 "#define C 0\n"; 5604 const char *ToFormat = "" 5605 "void f() {\n" 5606 "// Preprocessor aligned.\n" 5607 "#define A 0\n" 5608 "// Code. Separated by blank line.\n" 5609 "\n" 5610 "#define B 0\n" 5611 " // Code. Not aligned with #\n" 5612 "#define C 0\n"; 5613 EXPECT_EQ(Expected, format(ToFormat, Style)); 5614 EXPECT_EQ(Expected, format(Expected, Style)); 5615 } 5616 // Test AfterHash with tabs. 5617 { 5618 FormatStyle Tabbed = Style; 5619 Tabbed.UseTab = FormatStyle::UT_Always; 5620 Tabbed.IndentWidth = 8; 5621 Tabbed.TabWidth = 8; 5622 verifyFormat("#ifdef _WIN32\n" 5623 "#\tdefine A 0\n" 5624 "#\tifdef VAR2\n" 5625 "#\t\tdefine B 1\n" 5626 "#\t\tinclude <someheader.h>\n" 5627 "#\t\tdefine MACRO \\\n" 5628 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5629 "#\tendif\n" 5630 "#else\n" 5631 "#\tdefine A 1\n" 5632 "#endif", 5633 Tabbed); 5634 } 5635 5636 // Regression test: Multiline-macro inside include guards. 5637 verifyFormat("#ifndef HEADER_H\n" 5638 "#define HEADER_H\n" 5639 "#define A() \\\n" 5640 " int i; \\\n" 5641 " int j;\n" 5642 "#endif // HEADER_H", 5643 getLLVMStyleWithColumns(20)); 5644 5645 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5646 // Basic before hash indent tests 5647 verifyFormat("#ifdef _WIN32\n" 5648 " #define A 0\n" 5649 " #ifdef VAR2\n" 5650 " #define B 1\n" 5651 " #include <someheader.h>\n" 5652 " #define MACRO \\\n" 5653 " some_very_long_func_aaaaaaaaaa();\n" 5654 " #endif\n" 5655 "#else\n" 5656 " #define A 1\n" 5657 "#endif", 5658 Style); 5659 verifyFormat("#if A\n" 5660 " #define MACRO \\\n" 5661 " void a(int x) { \\\n" 5662 " b(); \\\n" 5663 " c(); \\\n" 5664 " d(); \\\n" 5665 " e(); \\\n" 5666 " f(); \\\n" 5667 " }\n" 5668 "#endif", 5669 Style); 5670 // Keep comments aligned with indented directives. These 5671 // tests cannot use verifyFormat because messUp manipulates leading 5672 // whitespace. 5673 { 5674 const char *Expected = "void f() {\n" 5675 "// Aligned to preprocessor.\n" 5676 "#if 1\n" 5677 " // Aligned to code.\n" 5678 " int a;\n" 5679 " #if 1\n" 5680 " // Aligned to preprocessor.\n" 5681 " #define A 0\n" 5682 " // Aligned to code.\n" 5683 " int b;\n" 5684 " #endif\n" 5685 "#endif\n" 5686 "}"; 5687 const char *ToFormat = "void f() {\n" 5688 "// Aligned to preprocessor.\n" 5689 "#if 1\n" 5690 "// Aligned to code.\n" 5691 "int a;\n" 5692 "#if 1\n" 5693 "// Aligned to preprocessor.\n" 5694 "#define A 0\n" 5695 "// Aligned to code.\n" 5696 "int b;\n" 5697 "#endif\n" 5698 "#endif\n" 5699 "}"; 5700 EXPECT_EQ(Expected, format(ToFormat, Style)); 5701 EXPECT_EQ(Expected, format(Expected, Style)); 5702 } 5703 { 5704 const char *Expected = "void f() {\n" 5705 "/* Aligned to preprocessor. */\n" 5706 "#if 1\n" 5707 " /* Aligned to code. */\n" 5708 " int a;\n" 5709 " #if 1\n" 5710 " /* Aligned to preprocessor. */\n" 5711 " #define A 0\n" 5712 " /* Aligned to code. */\n" 5713 " int b;\n" 5714 " #endif\n" 5715 "#endif\n" 5716 "}"; 5717 const char *ToFormat = "void f() {\n" 5718 "/* Aligned to preprocessor. */\n" 5719 "#if 1\n" 5720 "/* Aligned to code. */\n" 5721 "int a;\n" 5722 "#if 1\n" 5723 "/* Aligned to preprocessor. */\n" 5724 "#define A 0\n" 5725 "/* Aligned to code. */\n" 5726 "int b;\n" 5727 "#endif\n" 5728 "#endif\n" 5729 "}"; 5730 EXPECT_EQ(Expected, format(ToFormat, Style)); 5731 EXPECT_EQ(Expected, format(Expected, Style)); 5732 } 5733 5734 // Test single comment before preprocessor 5735 verifyFormat("// Comment\n" 5736 "\n" 5737 "#if 1\n" 5738 "#endif", 5739 Style); 5740 } 5741 5742 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5743 verifyFormat("{\n { a #c; }\n}"); 5744 } 5745 5746 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5747 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5748 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5749 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5750 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5751 } 5752 5753 TEST_F(FormatTest, EscapedNewlines) { 5754 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5755 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5756 format("#define A \\\nint i;\\\n int j;", Narrow)); 5757 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5758 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5759 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5760 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5761 5762 FormatStyle AlignLeft = getLLVMStyle(); 5763 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5764 EXPECT_EQ("#define MACRO(x) \\\n" 5765 "private: \\\n" 5766 " int x(int a);\n", 5767 format("#define MACRO(x) \\\n" 5768 "private: \\\n" 5769 " int x(int a);\n", 5770 AlignLeft)); 5771 5772 // CRLF line endings 5773 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5774 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5775 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5776 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5777 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5778 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5779 EXPECT_EQ("#define MACRO(x) \\\r\n" 5780 "private: \\\r\n" 5781 " int x(int a);\r\n", 5782 format("#define MACRO(x) \\\r\n" 5783 "private: \\\r\n" 5784 " int x(int a);\r\n", 5785 AlignLeft)); 5786 5787 FormatStyle DontAlign = getLLVMStyle(); 5788 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5789 DontAlign.MaxEmptyLinesToKeep = 3; 5790 // FIXME: can't use verifyFormat here because the newline before 5791 // "public:" is not inserted the first time it's reformatted 5792 EXPECT_EQ("#define A \\\n" 5793 " class Foo { \\\n" 5794 " void bar(); \\\n" 5795 "\\\n" 5796 "\\\n" 5797 "\\\n" 5798 " public: \\\n" 5799 " void baz(); \\\n" 5800 " };", 5801 format("#define A \\\n" 5802 " class Foo { \\\n" 5803 " void bar(); \\\n" 5804 "\\\n" 5805 "\\\n" 5806 "\\\n" 5807 " public: \\\n" 5808 " void baz(); \\\n" 5809 " };", 5810 DontAlign)); 5811 } 5812 5813 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5814 verifyFormat("#define A \\\n" 5815 " int v( \\\n" 5816 " a); \\\n" 5817 " int i;", 5818 getLLVMStyleWithColumns(11)); 5819 } 5820 5821 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5822 EXPECT_EQ( 5823 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5824 " \\\n" 5825 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5826 "\n" 5827 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5828 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5829 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5830 "\\\n" 5831 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5832 " \n" 5833 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5834 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5835 } 5836 5837 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5838 EXPECT_EQ("int\n" 5839 "#define A\n" 5840 " a;", 5841 format("int\n#define A\na;")); 5842 verifyFormat("functionCallTo(\n" 5843 " someOtherFunction(\n" 5844 " withSomeParameters, whichInSequence,\n" 5845 " areLongerThanALine(andAnotherCall,\n" 5846 "#define A B\n" 5847 " withMoreParamters,\n" 5848 " whichStronglyInfluenceTheLayout),\n" 5849 " andMoreParameters),\n" 5850 " trailing);", 5851 getLLVMStyleWithColumns(69)); 5852 verifyFormat("Foo::Foo()\n" 5853 "#ifdef BAR\n" 5854 " : baz(0)\n" 5855 "#endif\n" 5856 "{\n" 5857 "}"); 5858 verifyFormat("void f() {\n" 5859 " if (true)\n" 5860 "#ifdef A\n" 5861 " f(42);\n" 5862 " x();\n" 5863 "#else\n" 5864 " g();\n" 5865 " x();\n" 5866 "#endif\n" 5867 "}"); 5868 verifyFormat("void f(param1, param2,\n" 5869 " param3,\n" 5870 "#ifdef A\n" 5871 " param4(param5,\n" 5872 "#ifdef A1\n" 5873 " param6,\n" 5874 "#ifdef A2\n" 5875 " param7),\n" 5876 "#else\n" 5877 " param8),\n" 5878 " param9,\n" 5879 "#endif\n" 5880 " param10,\n" 5881 "#endif\n" 5882 " param11)\n" 5883 "#else\n" 5884 " param12)\n" 5885 "#endif\n" 5886 "{\n" 5887 " x();\n" 5888 "}", 5889 getLLVMStyleWithColumns(28)); 5890 verifyFormat("#if 1\n" 5891 "int i;"); 5892 verifyFormat("#if 1\n" 5893 "#endif\n" 5894 "#if 1\n" 5895 "#else\n" 5896 "#endif\n"); 5897 verifyFormat("DEBUG({\n" 5898 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5900 "});\n" 5901 "#if a\n" 5902 "#else\n" 5903 "#endif"); 5904 5905 verifyIncompleteFormat("void f(\n" 5906 "#if A\n" 5907 ");\n" 5908 "#else\n" 5909 "#endif"); 5910 } 5911 5912 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5913 verifyFormat("#endif\n" 5914 "#if B"); 5915 } 5916 5917 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5918 FormatStyle SingleLine = getLLVMStyle(); 5919 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5920 verifyFormat("#if 0\n" 5921 "#elif 1\n" 5922 "#endif\n" 5923 "void foo() {\n" 5924 " if (test) foo2();\n" 5925 "}", 5926 SingleLine); 5927 } 5928 5929 TEST_F(FormatTest, LayoutBlockInsideParens) { 5930 verifyFormat("functionCall({ int i; });"); 5931 verifyFormat("functionCall({\n" 5932 " int i;\n" 5933 " int j;\n" 5934 "});"); 5935 verifyFormat("functionCall(\n" 5936 " {\n" 5937 " int i;\n" 5938 " int j;\n" 5939 " },\n" 5940 " aaaa, bbbb, cccc);"); 5941 verifyFormat("functionA(functionB({\n" 5942 " int i;\n" 5943 " int j;\n" 5944 " }),\n" 5945 " aaaa, bbbb, cccc);"); 5946 verifyFormat("functionCall(\n" 5947 " {\n" 5948 " int i;\n" 5949 " int j;\n" 5950 " },\n" 5951 " aaaa, bbbb, // comment\n" 5952 " cccc);"); 5953 verifyFormat("functionA(functionB({\n" 5954 " int i;\n" 5955 " int j;\n" 5956 " }),\n" 5957 " aaaa, bbbb, // comment\n" 5958 " cccc);"); 5959 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5960 verifyFormat("functionCall(aaaa, bbbb, {\n" 5961 " int i;\n" 5962 " int j;\n" 5963 "});"); 5964 verifyFormat( 5965 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5966 " {\n" 5967 " int i; // break\n" 5968 " },\n" 5969 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5970 " ccccccccccccccccc));"); 5971 verifyFormat("DEBUG({\n" 5972 " if (a)\n" 5973 " f();\n" 5974 "});"); 5975 } 5976 5977 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5978 EXPECT_EQ("SOME_MACRO { int i; }\n" 5979 "int i;", 5980 format(" SOME_MACRO {int i;} int i;")); 5981 } 5982 5983 TEST_F(FormatTest, LayoutNestedBlocks) { 5984 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5985 " struct s {\n" 5986 " int i;\n" 5987 " };\n" 5988 " s kBitsToOs[] = {{10}};\n" 5989 " for (int i = 0; i < 10; ++i)\n" 5990 " return;\n" 5991 "}"); 5992 verifyFormat("call(parameter, {\n" 5993 " something();\n" 5994 " // Comment using all columns.\n" 5995 " somethingelse();\n" 5996 "});", 5997 getLLVMStyleWithColumns(40)); 5998 verifyFormat("DEBUG( //\n" 5999 " { f(); }, a);"); 6000 verifyFormat("DEBUG( //\n" 6001 " {\n" 6002 " f(); //\n" 6003 " },\n" 6004 " a);"); 6005 6006 EXPECT_EQ("call(parameter, {\n" 6007 " something();\n" 6008 " // Comment too\n" 6009 " // looooooooooong.\n" 6010 " somethingElse();\n" 6011 "});", 6012 format("call(parameter, {\n" 6013 " something();\n" 6014 " // Comment too looooooooooong.\n" 6015 " somethingElse();\n" 6016 "});", 6017 getLLVMStyleWithColumns(29))); 6018 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 6019 EXPECT_EQ("DEBUG({ // comment\n" 6020 " int i;\n" 6021 "});", 6022 format("DEBUG({ // comment\n" 6023 "int i;\n" 6024 "});")); 6025 EXPECT_EQ("DEBUG({\n" 6026 " int i;\n" 6027 "\n" 6028 " // comment\n" 6029 " int j;\n" 6030 "});", 6031 format("DEBUG({\n" 6032 " int i;\n" 6033 "\n" 6034 " // comment\n" 6035 " int j;\n" 6036 "});")); 6037 6038 verifyFormat("DEBUG({\n" 6039 " if (a)\n" 6040 " return;\n" 6041 "});"); 6042 verifyGoogleFormat("DEBUG({\n" 6043 " if (a) return;\n" 6044 "});"); 6045 FormatStyle Style = getGoogleStyle(); 6046 Style.ColumnLimit = 45; 6047 verifyFormat("Debug(\n" 6048 " aaaaa,\n" 6049 " {\n" 6050 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 6051 " },\n" 6052 " a);", 6053 Style); 6054 6055 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 6056 6057 verifyNoCrash("^{v^{a}}"); 6058 } 6059 6060 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6061 EXPECT_EQ("#define MACRO() \\\n" 6062 " Debug(aaa, /* force line break */ \\\n" 6063 " { \\\n" 6064 " int i; \\\n" 6065 " int j; \\\n" 6066 " })", 6067 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6068 " { int i; int j; })", 6069 getGoogleStyle())); 6070 6071 EXPECT_EQ("#define A \\\n" 6072 " [] { \\\n" 6073 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6074 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6075 " }", 6076 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6077 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6078 getGoogleStyle())); 6079 } 6080 6081 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6082 EXPECT_EQ("{}", format("{}")); 6083 verifyFormat("enum E {};"); 6084 verifyFormat("enum E {}"); 6085 FormatStyle Style = getLLVMStyle(); 6086 Style.SpaceInEmptyBlock = true; 6087 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6088 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6089 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6090 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6091 Style.BraceWrapping.BeforeElse = false; 6092 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6093 verifyFormat("if (a)\n" 6094 "{\n" 6095 "} else if (b)\n" 6096 "{\n" 6097 "} else\n" 6098 "{ }", 6099 Style); 6100 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6101 verifyFormat("if (a) {\n" 6102 "} else if (b) {\n" 6103 "} else {\n" 6104 "}", 6105 Style); 6106 Style.BraceWrapping.BeforeElse = true; 6107 verifyFormat("if (a) { }\n" 6108 "else if (b) { }\n" 6109 "else { }", 6110 Style); 6111 } 6112 6113 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6114 FormatStyle Style = getLLVMStyle(); 6115 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6116 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6117 verifyFormat("FOO_BEGIN\n" 6118 " FOO_ENTRY\n" 6119 "FOO_END", 6120 Style); 6121 verifyFormat("FOO_BEGIN\n" 6122 " NESTED_FOO_BEGIN\n" 6123 " NESTED_FOO_ENTRY\n" 6124 " NESTED_FOO_END\n" 6125 "FOO_END", 6126 Style); 6127 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6128 " int x;\n" 6129 " x = 1;\n" 6130 "FOO_END(Baz)", 6131 Style); 6132 } 6133 6134 //===----------------------------------------------------------------------===// 6135 // Line break tests. 6136 //===----------------------------------------------------------------------===// 6137 6138 TEST_F(FormatTest, PreventConfusingIndents) { 6139 verifyFormat( 6140 "void f() {\n" 6141 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6142 " parameter, parameter, parameter)),\n" 6143 " SecondLongCall(parameter));\n" 6144 "}"); 6145 verifyFormat( 6146 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6147 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6148 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6149 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6150 verifyFormat( 6151 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6152 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6153 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6154 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6155 verifyFormat( 6156 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6157 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6158 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6159 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6160 verifyFormat("int a = bbbb && ccc &&\n" 6161 " fffff(\n" 6162 "#define A Just forcing a new line\n" 6163 " ddd);"); 6164 } 6165 6166 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6167 verifyFormat( 6168 "bool aaaaaaa =\n" 6169 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6170 " bbbbbbbb();"); 6171 verifyFormat( 6172 "bool aaaaaaa =\n" 6173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6174 " bbbbbbbb();"); 6175 6176 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6177 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6178 " ccccccccc == ddddddddddd;"); 6179 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6180 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6181 " ccccccccc == ddddddddddd;"); 6182 verifyFormat( 6183 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6184 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6185 " ccccccccc == ddddddddddd;"); 6186 6187 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6188 " aaaaaa) &&\n" 6189 " bbbbbb && cccccc;"); 6190 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6191 " aaaaaa) >>\n" 6192 " bbbbbb;"); 6193 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6194 " SourceMgr.getSpellingColumnNumber(\n" 6195 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6196 " 1);"); 6197 6198 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6199 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6200 " cccccc) {\n}"); 6201 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6202 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6203 " cccccc) {\n}"); 6204 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6205 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6206 " cccccc) {\n}"); 6207 verifyFormat("b = a &&\n" 6208 " // Comment\n" 6209 " b.c && d;"); 6210 6211 // If the LHS of a comparison is not a binary expression itself, the 6212 // additional linebreak confuses many people. 6213 verifyFormat( 6214 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6215 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6216 "}"); 6217 verifyFormat( 6218 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6219 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6220 "}"); 6221 verifyFormat( 6222 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6224 "}"); 6225 verifyFormat( 6226 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6227 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6228 "}"); 6229 // Even explicit parentheses stress the precedence enough to make the 6230 // additional break unnecessary. 6231 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6232 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6233 "}"); 6234 // This cases is borderline, but with the indentation it is still readable. 6235 verifyFormat( 6236 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6237 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6238 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6239 "}", 6240 getLLVMStyleWithColumns(75)); 6241 6242 // If the LHS is a binary expression, we should still use the additional break 6243 // as otherwise the formatting hides the operator precedence. 6244 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6245 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6246 " 5) {\n" 6247 "}"); 6248 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6249 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6250 " 5) {\n" 6251 "}"); 6252 6253 FormatStyle OnePerLine = getLLVMStyle(); 6254 OnePerLine.BinPackParameters = false; 6255 verifyFormat( 6256 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6257 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6258 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6259 OnePerLine); 6260 6261 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6262 " .aaa(aaaaaaaaaaaaa) *\n" 6263 " aaaaaaa +\n" 6264 " aaaaaaa;", 6265 getLLVMStyleWithColumns(40)); 6266 } 6267 6268 TEST_F(FormatTest, ExpressionIndentation) { 6269 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6270 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6271 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6272 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6273 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6274 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6275 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6276 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6277 " ccccccccccccccccccccccccccccccccccccccccc;"); 6278 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6279 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6280 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6281 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6282 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6283 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6284 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6285 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6286 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6287 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6288 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6289 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6290 verifyFormat("if () {\n" 6291 "} else if (aaaaa && bbbbb > // break\n" 6292 " ccccc) {\n" 6293 "}"); 6294 verifyFormat("if () {\n" 6295 "} else if constexpr (aaaaa && bbbbb > // break\n" 6296 " ccccc) {\n" 6297 "}"); 6298 verifyFormat("if () {\n" 6299 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6300 " ccccc) {\n" 6301 "}"); 6302 verifyFormat("if () {\n" 6303 "} else if (aaaaa &&\n" 6304 " bbbbb > // break\n" 6305 " ccccc &&\n" 6306 " ddddd) {\n" 6307 "}"); 6308 6309 // Presence of a trailing comment used to change indentation of b. 6310 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6311 " b;\n" 6312 "return aaaaaaaaaaaaaaaaaaa +\n" 6313 " b; //", 6314 getLLVMStyleWithColumns(30)); 6315 } 6316 6317 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6318 // Not sure what the best system is here. Like this, the LHS can be found 6319 // immediately above an operator (everything with the same or a higher 6320 // indent). The RHS is aligned right of the operator and so compasses 6321 // everything until something with the same indent as the operator is found. 6322 // FIXME: Is this a good system? 6323 FormatStyle Style = getLLVMStyle(); 6324 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6325 verifyFormat( 6326 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6327 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6328 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6329 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6330 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6331 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6332 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6333 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6334 " > ccccccccccccccccccccccccccccccccccccccccc;", 6335 Style); 6336 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6337 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6338 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6339 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6340 Style); 6341 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6342 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6343 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6344 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6345 Style); 6346 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6347 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6348 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6349 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6350 Style); 6351 verifyFormat("if () {\n" 6352 "} else if (aaaaa\n" 6353 " && bbbbb // break\n" 6354 " > ccccc) {\n" 6355 "}", 6356 Style); 6357 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6358 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6359 Style); 6360 verifyFormat("return (a)\n" 6361 " // comment\n" 6362 " + b;", 6363 Style); 6364 verifyFormat( 6365 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6366 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6367 " + cc;", 6368 Style); 6369 6370 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6371 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6372 Style); 6373 6374 // Forced by comments. 6375 verifyFormat( 6376 "unsigned ContentSize =\n" 6377 " sizeof(int16_t) // DWARF ARange version number\n" 6378 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6379 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6380 " + sizeof(int8_t); // Segment Size (in bytes)"); 6381 6382 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6383 " == boost::fusion::at_c<1>(iiii).second;", 6384 Style); 6385 6386 Style.ColumnLimit = 60; 6387 verifyFormat("zzzzzzzzzz\n" 6388 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6389 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6390 Style); 6391 6392 Style.ColumnLimit = 80; 6393 Style.IndentWidth = 4; 6394 Style.TabWidth = 4; 6395 Style.UseTab = FormatStyle::UT_Always; 6396 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6397 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6398 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6399 "\t&& (someOtherLongishConditionPart1\n" 6400 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6401 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6402 "(someOtherLongishConditionPart1 || " 6403 "someOtherEvenLongerNestedConditionPart2);", 6404 Style)); 6405 } 6406 6407 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6408 FormatStyle Style = getLLVMStyle(); 6409 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6410 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6411 6412 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6413 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6414 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6415 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6416 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6417 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6418 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6419 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6420 " > ccccccccccccccccccccccccccccccccccccccccc;", 6421 Style); 6422 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6423 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6424 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6425 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6426 Style); 6427 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6428 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6429 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6430 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6431 Style); 6432 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6433 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6434 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6435 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6436 Style); 6437 verifyFormat("if () {\n" 6438 "} else if (aaaaa\n" 6439 " && bbbbb // break\n" 6440 " > ccccc) {\n" 6441 "}", 6442 Style); 6443 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6444 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6445 Style); 6446 verifyFormat("return (a)\n" 6447 " // comment\n" 6448 " + b;", 6449 Style); 6450 verifyFormat( 6451 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6452 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6453 " + cc;", 6454 Style); 6455 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6456 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6457 " : 3333333333333333;", 6458 Style); 6459 verifyFormat( 6460 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6461 " : ccccccccccccccc ? dddddddddddddddddd\n" 6462 " : eeeeeeeeeeeeeeeeee)\n" 6463 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6464 " : 3333333333333333;", 6465 Style); 6466 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6467 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6468 Style); 6469 6470 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6471 " == boost::fusion::at_c<1>(iiii).second;", 6472 Style); 6473 6474 Style.ColumnLimit = 60; 6475 verifyFormat("zzzzzzzzzzzzz\n" 6476 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6477 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6478 Style); 6479 6480 // Forced by comments. 6481 Style.ColumnLimit = 80; 6482 verifyFormat( 6483 "unsigned ContentSize\n" 6484 " = sizeof(int16_t) // DWARF ARange version number\n" 6485 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6486 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6487 " + sizeof(int8_t); // Segment Size (in bytes)", 6488 Style); 6489 6490 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6491 verifyFormat( 6492 "unsigned ContentSize =\n" 6493 " sizeof(int16_t) // DWARF ARange version number\n" 6494 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6495 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6496 " + sizeof(int8_t); // Segment Size (in bytes)", 6497 Style); 6498 6499 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6500 verifyFormat( 6501 "unsigned ContentSize =\n" 6502 " sizeof(int16_t) // DWARF ARange version number\n" 6503 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6504 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6505 " + sizeof(int8_t); // Segment Size (in bytes)", 6506 Style); 6507 } 6508 6509 TEST_F(FormatTest, EnforcedOperatorWraps) { 6510 // Here we'd like to wrap after the || operators, but a comment is forcing an 6511 // earlier wrap. 6512 verifyFormat("bool x = aaaaa //\n" 6513 " || bbbbb\n" 6514 " //\n" 6515 " || cccc;"); 6516 } 6517 6518 TEST_F(FormatTest, NoOperandAlignment) { 6519 FormatStyle Style = getLLVMStyle(); 6520 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6521 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6522 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6523 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6524 Style); 6525 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6526 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6527 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6528 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6529 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6530 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6531 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6532 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6533 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6534 " > ccccccccccccccccccccccccccccccccccccccccc;", 6535 Style); 6536 6537 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6538 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6539 " + cc;", 6540 Style); 6541 verifyFormat("int a = aa\n" 6542 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6543 " * cccccccccccccccccccccccccccccccccccc;\n", 6544 Style); 6545 6546 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6547 verifyFormat("return (a > b\n" 6548 " // comment1\n" 6549 " // comment2\n" 6550 " || c);", 6551 Style); 6552 } 6553 6554 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6555 FormatStyle Style = getLLVMStyle(); 6556 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6557 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6558 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6559 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6560 Style); 6561 } 6562 6563 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6564 FormatStyle Style = getLLVMStyleWithColumns(40); 6565 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6566 Style.BinPackArguments = false; 6567 verifyFormat("void test() {\n" 6568 " someFunction(\n" 6569 " this + argument + is + quite\n" 6570 " + long + so + it + gets + wrapped\n" 6571 " + but + remains + bin - packed);\n" 6572 "}", 6573 Style); 6574 verifyFormat("void test() {\n" 6575 " someFunction(arg1,\n" 6576 " this + argument + is\n" 6577 " + quite + long + so\n" 6578 " + it + gets + wrapped\n" 6579 " + but + remains + bin\n" 6580 " - packed,\n" 6581 " arg3);\n" 6582 "}", 6583 Style); 6584 verifyFormat("void test() {\n" 6585 " someFunction(\n" 6586 " arg1,\n" 6587 " this + argument + has\n" 6588 " + anotherFunc(nested,\n" 6589 " calls + whose\n" 6590 " + arguments\n" 6591 " + are + also\n" 6592 " + wrapped,\n" 6593 " in + addition)\n" 6594 " + to + being + bin - packed,\n" 6595 " arg3);\n" 6596 "}", 6597 Style); 6598 6599 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6600 verifyFormat("void test() {\n" 6601 " someFunction(\n" 6602 " arg1,\n" 6603 " this + argument + has +\n" 6604 " anotherFunc(nested,\n" 6605 " calls + whose +\n" 6606 " arguments +\n" 6607 " are + also +\n" 6608 " wrapped,\n" 6609 " in + addition) +\n" 6610 " to + being + bin - packed,\n" 6611 " arg3);\n" 6612 "}", 6613 Style); 6614 } 6615 6616 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6617 auto Style = getLLVMStyleWithColumns(45); 6618 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6619 verifyFormat("bool b =\n" 6620 " is_default_constructible_v<hash<T>> and\n" 6621 " is_copy_constructible_v<hash<T>> and\n" 6622 " is_move_constructible_v<hash<T>> and\n" 6623 " is_copy_assignable_v<hash<T>> and\n" 6624 " is_move_assignable_v<hash<T>> and\n" 6625 " is_destructible_v<hash<T>> and\n" 6626 " is_swappable_v<hash<T>> and\n" 6627 " is_callable_v<hash<T>(T)>;", 6628 Style); 6629 6630 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6631 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6632 " and is_copy_constructible_v<hash<T>>\n" 6633 " and is_move_constructible_v<hash<T>>\n" 6634 " and is_copy_assignable_v<hash<T>>\n" 6635 " and is_move_assignable_v<hash<T>>\n" 6636 " and is_destructible_v<hash<T>>\n" 6637 " and is_swappable_v<hash<T>>\n" 6638 " and is_callable_v<hash<T>(T)>;", 6639 Style); 6640 6641 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6642 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6643 " and is_copy_constructible_v<hash<T>>\n" 6644 " and is_move_constructible_v<hash<T>>\n" 6645 " and is_copy_assignable_v<hash<T>>\n" 6646 " and is_move_assignable_v<hash<T>>\n" 6647 " and is_destructible_v<hash<T>>\n" 6648 " and is_swappable_v<hash<T>>\n" 6649 " and is_callable_v<hash<T>(T)>;", 6650 Style); 6651 } 6652 6653 TEST_F(FormatTest, ConstructorInitializers) { 6654 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6655 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6656 getLLVMStyleWithColumns(45)); 6657 verifyFormat("Constructor()\n" 6658 " : Inttializer(FitsOnTheLine) {}", 6659 getLLVMStyleWithColumns(44)); 6660 verifyFormat("Constructor()\n" 6661 " : Inttializer(FitsOnTheLine) {}", 6662 getLLVMStyleWithColumns(43)); 6663 6664 verifyFormat("template <typename T>\n" 6665 "Constructor() : Initializer(FitsOnTheLine) {}", 6666 getLLVMStyleWithColumns(45)); 6667 6668 verifyFormat( 6669 "SomeClass::Constructor()\n" 6670 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6671 6672 verifyFormat( 6673 "SomeClass::Constructor()\n" 6674 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6675 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6676 verifyFormat( 6677 "SomeClass::Constructor()\n" 6678 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6679 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6680 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6681 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6682 " : aaaaaaaaaa(aaaaaa) {}"); 6683 6684 verifyFormat("Constructor()\n" 6685 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6686 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6687 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6688 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6689 6690 verifyFormat("Constructor()\n" 6691 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6692 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6693 6694 verifyFormat("Constructor(int Parameter = 0)\n" 6695 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6696 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6697 verifyFormat("Constructor()\n" 6698 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6699 "}", 6700 getLLVMStyleWithColumns(60)); 6701 verifyFormat("Constructor()\n" 6702 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6703 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6704 6705 // Here a line could be saved by splitting the second initializer onto two 6706 // lines, but that is not desirable. 6707 verifyFormat("Constructor()\n" 6708 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6709 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6710 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6711 6712 FormatStyle OnePerLine = getLLVMStyle(); 6713 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6714 verifyFormat("MyClass::MyClass()\n" 6715 " : a(a),\n" 6716 " b(b),\n" 6717 " c(c) {}", 6718 OnePerLine); 6719 verifyFormat("MyClass::MyClass()\n" 6720 " : a(a), // comment\n" 6721 " b(b),\n" 6722 " c(c) {}", 6723 OnePerLine); 6724 verifyFormat("MyClass::MyClass(int a)\n" 6725 " : b(a), // comment\n" 6726 " c(a + 1) { // lined up\n" 6727 "}", 6728 OnePerLine); 6729 verifyFormat("Constructor()\n" 6730 " : a(b, b, b) {}", 6731 OnePerLine); 6732 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6733 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6734 verifyFormat("SomeClass::Constructor()\n" 6735 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6736 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6737 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6738 OnePerLine); 6739 verifyFormat("SomeClass::Constructor()\n" 6740 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6741 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6742 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6743 OnePerLine); 6744 verifyFormat("MyClass::MyClass(int var)\n" 6745 " : some_var_(var), // 4 space indent\n" 6746 " some_other_var_(var + 1) { // lined up\n" 6747 "}", 6748 OnePerLine); 6749 verifyFormat("Constructor()\n" 6750 " : aaaaa(aaaaaa),\n" 6751 " aaaaa(aaaaaa),\n" 6752 " aaaaa(aaaaaa),\n" 6753 " aaaaa(aaaaaa),\n" 6754 " aaaaa(aaaaaa) {}", 6755 OnePerLine); 6756 verifyFormat("Constructor()\n" 6757 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6758 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6759 OnePerLine); 6760 OnePerLine.BinPackParameters = false; 6761 verifyFormat( 6762 "Constructor()\n" 6763 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6764 " aaaaaaaaaaa().aaa(),\n" 6765 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6766 OnePerLine); 6767 OnePerLine.ColumnLimit = 60; 6768 verifyFormat("Constructor()\n" 6769 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6770 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6771 OnePerLine); 6772 6773 EXPECT_EQ("Constructor()\n" 6774 " : // Comment forcing unwanted break.\n" 6775 " aaaa(aaaa) {}", 6776 format("Constructor() :\n" 6777 " // Comment forcing unwanted break.\n" 6778 " aaaa(aaaa) {}")); 6779 } 6780 6781 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6782 FormatStyle Style = getLLVMStyleWithColumns(60); 6783 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6784 Style.BinPackParameters = false; 6785 6786 for (int i = 0; i < 4; ++i) { 6787 // Test all combinations of parameters that should not have an effect. 6788 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6789 Style.AllowAllArgumentsOnNextLine = i & 2; 6790 6791 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6792 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6793 verifyFormat("Constructor()\n" 6794 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6795 Style); 6796 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6797 6798 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6799 verifyFormat("Constructor()\n" 6800 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6801 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6802 Style); 6803 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6804 6805 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6806 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6807 verifyFormat("Constructor()\n" 6808 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6809 Style); 6810 6811 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6812 verifyFormat("Constructor()\n" 6813 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6814 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6815 Style); 6816 6817 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6818 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6819 verifyFormat("Constructor() :\n" 6820 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6821 Style); 6822 6823 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6824 verifyFormat("Constructor() :\n" 6825 " aaaaaaaaaaaaaaaaaa(a),\n" 6826 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6827 Style); 6828 } 6829 6830 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6831 // AllowAllConstructorInitializersOnNextLine in all 6832 // BreakConstructorInitializers modes 6833 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6834 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6835 verifyFormat("SomeClassWithALongName::Constructor(\n" 6836 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6837 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6838 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6839 Style); 6840 6841 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6842 verifyFormat("SomeClassWithALongName::Constructor(\n" 6843 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6844 " int bbbbbbbbbbbbb,\n" 6845 " int cccccccccccccccc)\n" 6846 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6847 Style); 6848 6849 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6850 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6851 verifyFormat("SomeClassWithALongName::Constructor(\n" 6852 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6853 " int bbbbbbbbbbbbb)\n" 6854 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6855 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6856 Style); 6857 6858 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6859 6860 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6861 verifyFormat("SomeClassWithALongName::Constructor(\n" 6862 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6863 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6864 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6865 Style); 6866 6867 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6868 verifyFormat("SomeClassWithALongName::Constructor(\n" 6869 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6870 " int bbbbbbbbbbbbb,\n" 6871 " int cccccccccccccccc)\n" 6872 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6873 Style); 6874 6875 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6876 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6877 verifyFormat("SomeClassWithALongName::Constructor(\n" 6878 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6879 " int bbbbbbbbbbbbb)\n" 6880 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6881 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6882 Style); 6883 6884 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6885 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6886 verifyFormat("SomeClassWithALongName::Constructor(\n" 6887 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6888 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6889 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6890 Style); 6891 6892 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6893 verifyFormat("SomeClassWithALongName::Constructor(\n" 6894 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6895 " int bbbbbbbbbbbbb,\n" 6896 " int cccccccccccccccc) :\n" 6897 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6898 Style); 6899 6900 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6901 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6902 verifyFormat("SomeClassWithALongName::Constructor(\n" 6903 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6904 " int bbbbbbbbbbbbb) :\n" 6905 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6906 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6907 Style); 6908 } 6909 6910 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6911 FormatStyle Style = getLLVMStyleWithColumns(60); 6912 Style.BinPackArguments = false; 6913 for (int i = 0; i < 4; ++i) { 6914 // Test all combinations of parameters that should not have an effect. 6915 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6916 Style.PackConstructorInitializers = 6917 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6918 6919 Style.AllowAllArgumentsOnNextLine = true; 6920 verifyFormat("void foo() {\n" 6921 " FunctionCallWithReallyLongName(\n" 6922 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6923 "}", 6924 Style); 6925 Style.AllowAllArgumentsOnNextLine = false; 6926 verifyFormat("void foo() {\n" 6927 " FunctionCallWithReallyLongName(\n" 6928 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6929 " bbbbbbbbbbbb);\n" 6930 "}", 6931 Style); 6932 6933 Style.AllowAllArgumentsOnNextLine = true; 6934 verifyFormat("void foo() {\n" 6935 " auto VariableWithReallyLongName = {\n" 6936 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6937 "}", 6938 Style); 6939 Style.AllowAllArgumentsOnNextLine = false; 6940 verifyFormat("void foo() {\n" 6941 " auto VariableWithReallyLongName = {\n" 6942 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6943 " bbbbbbbbbbbb};\n" 6944 "}", 6945 Style); 6946 } 6947 6948 // This parameter should not affect declarations. 6949 Style.BinPackParameters = false; 6950 Style.AllowAllArgumentsOnNextLine = false; 6951 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6952 verifyFormat("void FunctionCallWithReallyLongName(\n" 6953 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6954 Style); 6955 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6956 verifyFormat("void FunctionCallWithReallyLongName(\n" 6957 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6958 " int bbbbbbbbbbbb);", 6959 Style); 6960 } 6961 6962 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6963 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6964 // and BAS_Align. 6965 FormatStyle Style = getLLVMStyleWithColumns(35); 6966 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6967 "void functionDecl(int A, int B, int C);"; 6968 Style.AllowAllArgumentsOnNextLine = false; 6969 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6970 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6971 " paramC);\n" 6972 "void functionDecl(int A, int B,\n" 6973 " int C);"), 6974 format(Input, Style)); 6975 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6976 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6977 " paramC);\n" 6978 "void functionDecl(int A, int B,\n" 6979 " int C);"), 6980 format(Input, Style)); 6981 // However, BAS_AlwaysBreak should take precedence over 6982 // AllowAllArgumentsOnNextLine. 6983 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6984 EXPECT_EQ(StringRef("functionCall(\n" 6985 " paramA, paramB, paramC);\n" 6986 "void functionDecl(\n" 6987 " int A, int B, int C);"), 6988 format(Input, Style)); 6989 6990 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6991 // first argument. 6992 Style.AllowAllArgumentsOnNextLine = true; 6993 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6994 EXPECT_EQ(StringRef("functionCall(\n" 6995 " paramA, paramB, paramC);\n" 6996 "void functionDecl(\n" 6997 " int A, int B, int C);"), 6998 format(Input, Style)); 6999 // It wouldn't fit on one line with aligned parameters so this setting 7000 // doesn't change anything for BAS_Align. 7001 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7002 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 7003 " paramC);\n" 7004 "void functionDecl(int A, int B,\n" 7005 " int C);"), 7006 format(Input, Style)); 7007 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7008 EXPECT_EQ(StringRef("functionCall(\n" 7009 " paramA, paramB, paramC);\n" 7010 "void functionDecl(\n" 7011 " int A, int B, int C);"), 7012 format(Input, Style)); 7013 } 7014 7015 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 7016 FormatStyle Style = getLLVMStyle(); 7017 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 7018 7019 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 7020 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 7021 getStyleWithColumns(Style, 45)); 7022 verifyFormat("Constructor() :\n" 7023 " Initializer(FitsOnTheLine) {}", 7024 getStyleWithColumns(Style, 44)); 7025 verifyFormat("Constructor() :\n" 7026 " Initializer(FitsOnTheLine) {}", 7027 getStyleWithColumns(Style, 43)); 7028 7029 verifyFormat("template <typename T>\n" 7030 "Constructor() : Initializer(FitsOnTheLine) {}", 7031 getStyleWithColumns(Style, 50)); 7032 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7033 verifyFormat( 7034 "SomeClass::Constructor() :\n" 7035 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7036 Style); 7037 7038 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 7039 verifyFormat( 7040 "SomeClass::Constructor() :\n" 7041 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7042 Style); 7043 7044 verifyFormat( 7045 "SomeClass::Constructor() :\n" 7046 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7047 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7048 Style); 7049 verifyFormat( 7050 "SomeClass::Constructor() :\n" 7051 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7052 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7053 Style); 7054 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7055 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 7056 " aaaaaaaaaa(aaaaaa) {}", 7057 Style); 7058 7059 verifyFormat("Constructor() :\n" 7060 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7061 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7062 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7063 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7064 Style); 7065 7066 verifyFormat("Constructor() :\n" 7067 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7068 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7069 Style); 7070 7071 verifyFormat("Constructor(int Parameter = 0) :\n" 7072 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7073 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7074 Style); 7075 verifyFormat("Constructor() :\n" 7076 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7077 "}", 7078 getStyleWithColumns(Style, 60)); 7079 verifyFormat("Constructor() :\n" 7080 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7081 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7082 Style); 7083 7084 // Here a line could be saved by splitting the second initializer onto two 7085 // lines, but that is not desirable. 7086 verifyFormat("Constructor() :\n" 7087 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7088 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7089 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7090 Style); 7091 7092 FormatStyle OnePerLine = Style; 7093 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7094 verifyFormat("SomeClass::Constructor() :\n" 7095 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7096 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7097 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7098 OnePerLine); 7099 verifyFormat("SomeClass::Constructor() :\n" 7100 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7101 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7102 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7103 OnePerLine); 7104 verifyFormat("MyClass::MyClass(int var) :\n" 7105 " some_var_(var), // 4 space indent\n" 7106 " some_other_var_(var + 1) { // lined up\n" 7107 "}", 7108 OnePerLine); 7109 verifyFormat("Constructor() :\n" 7110 " aaaaa(aaaaaa),\n" 7111 " aaaaa(aaaaaa),\n" 7112 " aaaaa(aaaaaa),\n" 7113 " aaaaa(aaaaaa),\n" 7114 " aaaaa(aaaaaa) {}", 7115 OnePerLine); 7116 verifyFormat("Constructor() :\n" 7117 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7118 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7119 OnePerLine); 7120 OnePerLine.BinPackParameters = false; 7121 verifyFormat("Constructor() :\n" 7122 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7123 " aaaaaaaaaaa().aaa(),\n" 7124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7125 OnePerLine); 7126 OnePerLine.ColumnLimit = 60; 7127 verifyFormat("Constructor() :\n" 7128 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7129 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7130 OnePerLine); 7131 7132 EXPECT_EQ("Constructor() :\n" 7133 " // Comment forcing unwanted break.\n" 7134 " aaaa(aaaa) {}", 7135 format("Constructor() :\n" 7136 " // Comment forcing unwanted break.\n" 7137 " aaaa(aaaa) {}", 7138 Style)); 7139 7140 Style.ColumnLimit = 0; 7141 verifyFormat("SomeClass::Constructor() :\n" 7142 " a(a) {}", 7143 Style); 7144 verifyFormat("SomeClass::Constructor() noexcept :\n" 7145 " a(a) {}", 7146 Style); 7147 verifyFormat("SomeClass::Constructor() :\n" 7148 " a(a), b(b), c(c) {}", 7149 Style); 7150 verifyFormat("SomeClass::Constructor() :\n" 7151 " a(a) {\n" 7152 " foo();\n" 7153 " bar();\n" 7154 "}", 7155 Style); 7156 7157 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7158 verifyFormat("SomeClass::Constructor() :\n" 7159 " a(a), b(b), c(c) {\n" 7160 "}", 7161 Style); 7162 verifyFormat("SomeClass::Constructor() :\n" 7163 " a(a) {\n" 7164 "}", 7165 Style); 7166 7167 Style.ColumnLimit = 80; 7168 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7169 Style.ConstructorInitializerIndentWidth = 2; 7170 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7171 verifyFormat("SomeClass::Constructor() :\n" 7172 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7173 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7174 Style); 7175 7176 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7177 // well 7178 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7179 verifyFormat( 7180 "class SomeClass\n" 7181 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7182 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7183 Style); 7184 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7185 verifyFormat( 7186 "class SomeClass\n" 7187 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7188 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7189 Style); 7190 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7191 verifyFormat( 7192 "class SomeClass :\n" 7193 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7194 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7195 Style); 7196 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7197 verifyFormat( 7198 "class SomeClass\n" 7199 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7200 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7201 Style); 7202 } 7203 7204 #ifndef EXPENSIVE_CHECKS 7205 // Expensive checks enables libstdc++ checking which includes validating the 7206 // state of ranges used in std::priority_queue - this blows out the 7207 // runtime/scalability of the function and makes this test unacceptably slow. 7208 TEST_F(FormatTest, MemoizationTests) { 7209 // This breaks if the memoization lookup does not take \c Indent and 7210 // \c LastSpace into account. 7211 verifyFormat( 7212 "extern CFRunLoopTimerRef\n" 7213 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7214 " CFTimeInterval interval, CFOptionFlags flags,\n" 7215 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7216 " CFRunLoopTimerContext *context) {}"); 7217 7218 // Deep nesting somewhat works around our memoization. 7219 verifyFormat( 7220 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7221 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7222 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7223 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7224 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7225 getLLVMStyleWithColumns(65)); 7226 verifyFormat( 7227 "aaaaa(\n" 7228 " aaaaa,\n" 7229 " aaaaa(\n" 7230 " aaaaa,\n" 7231 " aaaaa(\n" 7232 " aaaaa,\n" 7233 " aaaaa(\n" 7234 " aaaaa,\n" 7235 " aaaaa(\n" 7236 " aaaaa,\n" 7237 " aaaaa(\n" 7238 " aaaaa,\n" 7239 " aaaaa(\n" 7240 " aaaaa,\n" 7241 " aaaaa(\n" 7242 " aaaaa,\n" 7243 " aaaaa(\n" 7244 " aaaaa,\n" 7245 " aaaaa(\n" 7246 " aaaaa,\n" 7247 " aaaaa(\n" 7248 " aaaaa,\n" 7249 " aaaaa(\n" 7250 " aaaaa,\n" 7251 " aaaaa))))))))))));", 7252 getLLVMStyleWithColumns(65)); 7253 verifyFormat( 7254 "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" 7255 " a),\n" 7256 " a),\n" 7257 " a),\n" 7258 " a),\n" 7259 " a),\n" 7260 " a),\n" 7261 " a),\n" 7262 " a),\n" 7263 " a),\n" 7264 " a),\n" 7265 " a),\n" 7266 " a),\n" 7267 " a),\n" 7268 " a),\n" 7269 " a),\n" 7270 " a),\n" 7271 " a)", 7272 getLLVMStyleWithColumns(65)); 7273 7274 // This test takes VERY long when memoization is broken. 7275 FormatStyle OnePerLine = getLLVMStyle(); 7276 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7277 OnePerLine.BinPackParameters = false; 7278 std::string input = "Constructor()\n" 7279 " : aaaa(a,\n"; 7280 for (unsigned i = 0, e = 80; i != e; ++i) 7281 input += " a,\n"; 7282 input += " a) {}"; 7283 verifyFormat(input, OnePerLine); 7284 } 7285 #endif 7286 7287 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7288 verifyFormat( 7289 "void f() {\n" 7290 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7291 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7292 " f();\n" 7293 "}"); 7294 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7295 " Intervals[i - 1].getRange().getLast()) {\n}"); 7296 } 7297 7298 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7299 // Principially, we break function declarations in a certain order: 7300 // 1) break amongst arguments. 7301 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7302 " Cccccccccccccc cccccccccccccc);"); 7303 verifyFormat("template <class TemplateIt>\n" 7304 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7305 " TemplateIt *stop) {}"); 7306 7307 // 2) break after return type. 7308 verifyFormat( 7309 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7310 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7311 getGoogleStyle()); 7312 7313 // 3) break after (. 7314 verifyFormat( 7315 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7316 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7317 getGoogleStyle()); 7318 7319 // 4) break before after nested name specifiers. 7320 verifyFormat( 7321 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7322 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7323 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7324 getGoogleStyle()); 7325 7326 // However, there are exceptions, if a sufficient amount of lines can be 7327 // saved. 7328 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7329 // more adjusting. 7330 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7331 " Cccccccccccccc cccccccccc,\n" 7332 " Cccccccccccccc cccccccccc,\n" 7333 " Cccccccccccccc cccccccccc,\n" 7334 " Cccccccccccccc cccccccccc);"); 7335 verifyFormat( 7336 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7337 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7338 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7339 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7340 getGoogleStyle()); 7341 verifyFormat( 7342 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7343 " Cccccccccccccc cccccccccc,\n" 7344 " Cccccccccccccc cccccccccc,\n" 7345 " Cccccccccccccc cccccccccc,\n" 7346 " Cccccccccccccc cccccccccc,\n" 7347 " Cccccccccccccc cccccccccc,\n" 7348 " Cccccccccccccc cccccccccc);"); 7349 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7350 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7351 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7352 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7353 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7354 7355 // Break after multi-line parameters. 7356 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7357 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7358 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7359 " bbbb bbbb);"); 7360 verifyFormat("void SomeLoooooooooooongFunction(\n" 7361 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7362 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7363 " int bbbbbbbbbbbbb);"); 7364 7365 // Treat overloaded operators like other functions. 7366 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7367 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7368 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7369 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7370 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7371 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7372 verifyGoogleFormat( 7373 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7374 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7375 verifyGoogleFormat( 7376 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7377 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7378 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7379 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7380 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7381 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7382 verifyGoogleFormat( 7383 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7384 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7385 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7386 verifyGoogleFormat("template <typename T>\n" 7387 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7388 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7389 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7390 7391 FormatStyle Style = getLLVMStyle(); 7392 Style.PointerAlignment = FormatStyle::PAS_Left; 7393 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7394 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7395 Style); 7396 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7397 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7398 Style); 7399 } 7400 7401 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7402 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7403 // Prefer keeping `::` followed by `operator` together. 7404 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7405 "ccccccccc::operator++() {\n" 7406 " stuff();\n" 7407 "}", 7408 format("const aaaa::bbbbbbb\n" 7409 "&ccccccccc::operator++() { stuff(); }", 7410 getLLVMStyleWithColumns(40))); 7411 } 7412 7413 TEST_F(FormatTest, TrailingReturnType) { 7414 verifyFormat("auto foo() -> int;\n"); 7415 // correct trailing return type spacing 7416 verifyFormat("auto operator->() -> int;\n"); 7417 verifyFormat("auto operator++(int) -> int;\n"); 7418 7419 verifyFormat("struct S {\n" 7420 " auto bar() const -> int;\n" 7421 "};"); 7422 verifyFormat("template <size_t Order, typename T>\n" 7423 "auto load_img(const std::string &filename)\n" 7424 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7425 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7426 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7427 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7428 verifyFormat("template <typename T>\n" 7429 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7430 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7431 7432 // Not trailing return types. 7433 verifyFormat("void f() { auto a = b->c(); }"); 7434 verifyFormat("auto a = p->foo();"); 7435 verifyFormat("int a = p->foo();"); 7436 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7437 } 7438 7439 TEST_F(FormatTest, DeductionGuides) { 7440 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7441 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7442 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7443 verifyFormat( 7444 "template <class... T>\n" 7445 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7446 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7447 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7448 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7449 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7450 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7451 verifyFormat("template <class T> x() -> x<1>;"); 7452 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7453 7454 // Ensure not deduction guides. 7455 verifyFormat("c()->f<int>();"); 7456 verifyFormat("x()->foo<1>;"); 7457 verifyFormat("x = p->foo<3>();"); 7458 verifyFormat("x()->x<1>();"); 7459 verifyFormat("x()->x<1>;"); 7460 } 7461 7462 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7463 // Avoid breaking before trailing 'const' or other trailing annotations, if 7464 // they are not function-like. 7465 FormatStyle Style = getGoogleStyleWithColumns(47); 7466 verifyFormat("void someLongFunction(\n" 7467 " int someLoooooooooooooongParameter) const {\n}", 7468 getLLVMStyleWithColumns(47)); 7469 verifyFormat("LoooooongReturnType\n" 7470 "someLoooooooongFunction() const {}", 7471 getLLVMStyleWithColumns(47)); 7472 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7473 " const {}", 7474 Style); 7475 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7476 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7477 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7478 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7479 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7480 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7481 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7482 " aaaaaaaaaaa aaaaa) const override;"); 7483 verifyGoogleFormat( 7484 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7485 " const override;"); 7486 7487 // Even if the first parameter has to be wrapped. 7488 verifyFormat("void someLongFunction(\n" 7489 " int someLongParameter) const {}", 7490 getLLVMStyleWithColumns(46)); 7491 verifyFormat("void someLongFunction(\n" 7492 " int someLongParameter) const {}", 7493 Style); 7494 verifyFormat("void someLongFunction(\n" 7495 " int someLongParameter) override {}", 7496 Style); 7497 verifyFormat("void someLongFunction(\n" 7498 " int someLongParameter) OVERRIDE {}", 7499 Style); 7500 verifyFormat("void someLongFunction(\n" 7501 " int someLongParameter) final {}", 7502 Style); 7503 verifyFormat("void someLongFunction(\n" 7504 " int someLongParameter) FINAL {}", 7505 Style); 7506 verifyFormat("void someLongFunction(\n" 7507 " int parameter) const override {}", 7508 Style); 7509 7510 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7511 verifyFormat("void someLongFunction(\n" 7512 " int someLongParameter) const\n" 7513 "{\n" 7514 "}", 7515 Style); 7516 7517 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7518 verifyFormat("void someLongFunction(\n" 7519 " int someLongParameter) const\n" 7520 " {\n" 7521 " }", 7522 Style); 7523 7524 // Unless these are unknown annotations. 7525 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7526 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7527 " LONG_AND_UGLY_ANNOTATION;"); 7528 7529 // Breaking before function-like trailing annotations is fine to keep them 7530 // close to their arguments. 7531 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7532 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7533 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7534 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7535 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7536 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7537 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7538 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7539 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7540 7541 verifyFormat( 7542 "void aaaaaaaaaaaaaaaaaa()\n" 7543 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7544 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7545 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7546 " __attribute__((unused));"); 7547 verifyGoogleFormat( 7548 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7549 " GUARDED_BY(aaaaaaaaaaaa);"); 7550 verifyGoogleFormat( 7551 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7552 " GUARDED_BY(aaaaaaaaaaaa);"); 7553 verifyGoogleFormat( 7554 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7555 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7556 verifyGoogleFormat( 7557 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7558 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7559 } 7560 7561 TEST_F(FormatTest, FunctionAnnotations) { 7562 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7563 "int OldFunction(const string ¶meter) {}"); 7564 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7565 "string OldFunction(const string ¶meter) {}"); 7566 verifyFormat("template <typename T>\n" 7567 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7568 "string OldFunction(const string ¶meter) {}"); 7569 7570 // Not function annotations. 7571 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7572 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7573 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7574 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7575 verifyFormat("MACRO(abc).function() // wrap\n" 7576 " << abc;"); 7577 verifyFormat("MACRO(abc)->function() // wrap\n" 7578 " << abc;"); 7579 verifyFormat("MACRO(abc)::function() // wrap\n" 7580 " << abc;"); 7581 } 7582 7583 TEST_F(FormatTest, BreaksDesireably) { 7584 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7585 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7586 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7587 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7588 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7589 "}"); 7590 7591 verifyFormat( 7592 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7593 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7594 7595 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7596 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7597 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7598 7599 verifyFormat( 7600 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7601 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7602 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7603 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7604 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7605 7606 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7607 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7608 7609 verifyFormat( 7610 "void f() {\n" 7611 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7612 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7613 "}"); 7614 verifyFormat( 7615 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7616 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7617 verifyFormat( 7618 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7619 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7620 verifyFormat( 7621 "aaaaaa(aaa,\n" 7622 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7623 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7624 " aaaa);"); 7625 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7626 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7627 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7628 7629 // Indent consistently independent of call expression and unary operator. 7630 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7631 " dddddddddddddddddddddddddddddd));"); 7632 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7633 " dddddddddddddddddddddddddddddd));"); 7634 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7635 " dddddddddddddddddddddddddddddd));"); 7636 7637 // This test case breaks on an incorrect memoization, i.e. an optimization not 7638 // taking into account the StopAt value. 7639 verifyFormat( 7640 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7641 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7642 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7643 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7644 7645 verifyFormat("{\n {\n {\n" 7646 " Annotation.SpaceRequiredBefore =\n" 7647 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7648 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7649 " }\n }\n}"); 7650 7651 // Break on an outer level if there was a break on an inner level. 7652 EXPECT_EQ("f(g(h(a, // comment\n" 7653 " b, c),\n" 7654 " d, e),\n" 7655 " x, y);", 7656 format("f(g(h(a, // comment\n" 7657 " b, c), d, e), x, y);")); 7658 7659 // Prefer breaking similar line breaks. 7660 verifyFormat( 7661 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7662 " NSTrackingMouseEnteredAndExited |\n" 7663 " NSTrackingActiveAlways;"); 7664 } 7665 7666 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7667 FormatStyle NoBinPacking = getGoogleStyle(); 7668 NoBinPacking.BinPackParameters = false; 7669 NoBinPacking.BinPackArguments = true; 7670 verifyFormat("void f() {\n" 7671 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7672 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7673 "}", 7674 NoBinPacking); 7675 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7676 " int aaaaaaaaaaaaaaaaaaaa,\n" 7677 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7678 NoBinPacking); 7679 7680 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7681 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7682 " vector<int> bbbbbbbbbbbbbbb);", 7683 NoBinPacking); 7684 // FIXME: This behavior difference is probably not wanted. However, currently 7685 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7686 // template arguments from BreakBeforeParameter being set because of the 7687 // one-per-line formatting. 7688 verifyFormat( 7689 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7690 " aaaaaaaaaa> aaaaaaaaaa);", 7691 NoBinPacking); 7692 verifyFormat( 7693 "void fffffffffff(\n" 7694 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7695 " aaaaaaaaaa);"); 7696 } 7697 7698 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7699 FormatStyle NoBinPacking = getGoogleStyle(); 7700 NoBinPacking.BinPackParameters = false; 7701 NoBinPacking.BinPackArguments = false; 7702 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7703 " aaaaaaaaaaaaaaaaaaaa,\n" 7704 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7705 NoBinPacking); 7706 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7707 " aaaaaaaaaaaaa,\n" 7708 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7709 NoBinPacking); 7710 verifyFormat( 7711 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7712 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7713 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7714 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7715 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7716 NoBinPacking); 7717 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7718 " .aaaaaaaaaaaaaaaaaa();", 7719 NoBinPacking); 7720 verifyFormat("void f() {\n" 7721 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7722 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7723 "}", 7724 NoBinPacking); 7725 7726 verifyFormat( 7727 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7728 " aaaaaaaaaaaa,\n" 7729 " aaaaaaaaaaaa);", 7730 NoBinPacking); 7731 verifyFormat( 7732 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7733 " ddddddddddddddddddddddddddddd),\n" 7734 " test);", 7735 NoBinPacking); 7736 7737 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7738 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7739 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7740 " aaaaaaaaaaaaaaaaaa;", 7741 NoBinPacking); 7742 verifyFormat("a(\"a\"\n" 7743 " \"a\",\n" 7744 " a);"); 7745 7746 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7747 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7748 " aaaaaaaaa,\n" 7749 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7750 NoBinPacking); 7751 verifyFormat( 7752 "void f() {\n" 7753 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7754 " .aaaaaaa();\n" 7755 "}", 7756 NoBinPacking); 7757 verifyFormat( 7758 "template <class SomeType, class SomeOtherType>\n" 7759 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7760 NoBinPacking); 7761 } 7762 7763 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7764 FormatStyle Style = getLLVMStyleWithColumns(15); 7765 Style.ExperimentalAutoDetectBinPacking = true; 7766 EXPECT_EQ("aaa(aaaa,\n" 7767 " aaaa,\n" 7768 " aaaa);\n" 7769 "aaa(aaaa,\n" 7770 " aaaa,\n" 7771 " aaaa);", 7772 format("aaa(aaaa,\n" // one-per-line 7773 " aaaa,\n" 7774 " aaaa );\n" 7775 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7776 Style)); 7777 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7778 " aaaa);\n" 7779 "aaa(aaaa, aaaa,\n" 7780 " aaaa);", 7781 format("aaa(aaaa, aaaa,\n" // bin-packed 7782 " aaaa );\n" 7783 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7784 Style)); 7785 } 7786 7787 TEST_F(FormatTest, FormatsBuilderPattern) { 7788 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7789 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7790 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7791 " .StartsWith(\".init\", ORDER_INIT)\n" 7792 " .StartsWith(\".fini\", ORDER_FINI)\n" 7793 " .StartsWith(\".hash\", ORDER_HASH)\n" 7794 " .Default(ORDER_TEXT);\n"); 7795 7796 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7797 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7798 verifyFormat("aaaaaaa->aaaaaaa\n" 7799 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7800 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7801 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7802 verifyFormat( 7803 "aaaaaaa->aaaaaaa\n" 7804 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7805 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7806 verifyFormat( 7807 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7808 " aaaaaaaaaaaaaa);"); 7809 verifyFormat( 7810 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7811 " aaaaaa->aaaaaaaaaaaa()\n" 7812 " ->aaaaaaaaaaaaaaaa(\n" 7813 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7814 " ->aaaaaaaaaaaaaaaaa();"); 7815 verifyGoogleFormat( 7816 "void f() {\n" 7817 " someo->Add((new util::filetools::Handler(dir))\n" 7818 " ->OnEvent1(NewPermanentCallback(\n" 7819 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7820 " ->OnEvent2(NewPermanentCallback(\n" 7821 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7822 " ->OnEvent3(NewPermanentCallback(\n" 7823 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7824 " ->OnEvent5(NewPermanentCallback(\n" 7825 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7826 " ->OnEvent6(NewPermanentCallback(\n" 7827 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7828 "}"); 7829 7830 verifyFormat( 7831 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7832 verifyFormat("aaaaaaaaaaaaaaa()\n" 7833 " .aaaaaaaaaaaaaaa()\n" 7834 " .aaaaaaaaaaaaaaa()\n" 7835 " .aaaaaaaaaaaaaaa()\n" 7836 " .aaaaaaaaaaaaaaa();"); 7837 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7838 " .aaaaaaaaaaaaaaa()\n" 7839 " .aaaaaaaaaaaaaaa()\n" 7840 " .aaaaaaaaaaaaaaa();"); 7841 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7842 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7843 " .aaaaaaaaaaaaaaa();"); 7844 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7845 " ->aaaaaaaaaaaaaae(0)\n" 7846 " ->aaaaaaaaaaaaaaa();"); 7847 7848 // Don't linewrap after very short segments. 7849 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7850 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7851 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7852 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7853 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7854 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7855 verifyFormat("aaa()\n" 7856 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7857 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7858 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7859 7860 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7861 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7862 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7863 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7864 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7865 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7866 7867 // Prefer not to break after empty parentheses. 7868 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7869 " First->LastNewlineOffset);"); 7870 7871 // Prefer not to create "hanging" indents. 7872 verifyFormat( 7873 "return !soooooooooooooome_map\n" 7874 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7875 " .second;"); 7876 verifyFormat( 7877 "return aaaaaaaaaaaaaaaa\n" 7878 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7879 " .aaaa(aaaaaaaaaaaaaa);"); 7880 // No hanging indent here. 7881 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7882 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7883 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7884 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7885 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7886 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7887 getLLVMStyleWithColumns(60)); 7888 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7889 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7890 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7891 getLLVMStyleWithColumns(59)); 7892 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7893 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7894 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7895 7896 // Dont break if only closing statements before member call 7897 verifyFormat("test() {\n" 7898 " ([]() -> {\n" 7899 " int b = 32;\n" 7900 " return 3;\n" 7901 " }).foo();\n" 7902 "}"); 7903 verifyFormat("test() {\n" 7904 " (\n" 7905 " []() -> {\n" 7906 " int b = 32;\n" 7907 " return 3;\n" 7908 " },\n" 7909 " foo, bar)\n" 7910 " .foo();\n" 7911 "}"); 7912 verifyFormat("test() {\n" 7913 " ([]() -> {\n" 7914 " int b = 32;\n" 7915 " return 3;\n" 7916 " })\n" 7917 " .foo()\n" 7918 " .bar();\n" 7919 "}"); 7920 verifyFormat("test() {\n" 7921 " ([]() -> {\n" 7922 " int b = 32;\n" 7923 " return 3;\n" 7924 " })\n" 7925 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7926 " \"bbbb\");\n" 7927 "}", 7928 getLLVMStyleWithColumns(30)); 7929 } 7930 7931 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7932 verifyFormat( 7933 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7934 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7935 verifyFormat( 7936 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7937 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7938 7939 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7940 " ccccccccccccccccccccccccc) {\n}"); 7941 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7942 " ccccccccccccccccccccccccc) {\n}"); 7943 7944 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7945 " ccccccccccccccccccccccccc) {\n}"); 7946 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7947 " ccccccccccccccccccccccccc) {\n}"); 7948 7949 verifyFormat( 7950 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7951 " ccccccccccccccccccccccccc) {\n}"); 7952 verifyFormat( 7953 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7954 " ccccccccccccccccccccccccc) {\n}"); 7955 7956 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7957 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7958 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7959 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7960 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7961 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7962 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7963 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7964 7965 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7966 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7967 " aaaaaaaaaaaaaaa != aa) {\n}"); 7968 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7969 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7970 " aaaaaaaaaaaaaaa != aa) {\n}"); 7971 } 7972 7973 TEST_F(FormatTest, BreaksAfterAssignments) { 7974 verifyFormat( 7975 "unsigned Cost =\n" 7976 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7977 " SI->getPointerAddressSpaceee());\n"); 7978 verifyFormat( 7979 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7980 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7981 7982 verifyFormat( 7983 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7984 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7985 verifyFormat("unsigned OriginalStartColumn =\n" 7986 " SourceMgr.getSpellingColumnNumber(\n" 7987 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7988 " 1;"); 7989 } 7990 7991 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7992 FormatStyle Style = getLLVMStyle(); 7993 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7994 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7995 Style); 7996 7997 Style.PenaltyBreakAssignment = 20; 7998 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7999 " cccccccccccccccccccccccccc;", 8000 Style); 8001 } 8002 8003 TEST_F(FormatTest, AlignsAfterAssignments) { 8004 verifyFormat( 8005 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8006 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8007 verifyFormat( 8008 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8009 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8010 verifyFormat( 8011 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8012 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8013 verifyFormat( 8014 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8015 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 8016 verifyFormat( 8017 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 8018 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 8019 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 8020 } 8021 8022 TEST_F(FormatTest, AlignsAfterReturn) { 8023 verifyFormat( 8024 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8025 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8026 verifyFormat( 8027 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8028 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 8029 verifyFormat( 8030 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 8031 " aaaaaaaaaaaaaaaaaaaaaa();"); 8032 verifyFormat( 8033 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 8034 " aaaaaaaaaaaaaaaaaaaaaa());"); 8035 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8037 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 8039 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8040 verifyFormat("return\n" 8041 " // true if code is one of a or b.\n" 8042 " code == a || code == b;"); 8043 } 8044 8045 TEST_F(FormatTest, AlignsAfterOpenBracket) { 8046 verifyFormat( 8047 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8048 " aaaaaaaaa aaaaaaa) {}"); 8049 verifyFormat( 8050 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8051 " aaaaaaaaaaa aaaaaaaaa);"); 8052 verifyFormat( 8053 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8054 " aaaaaaaaaaaaaaaaaaaaa));"); 8055 FormatStyle Style = getLLVMStyle(); 8056 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8057 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8058 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8059 Style); 8060 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8061 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8062 Style); 8063 verifyFormat("SomeLongVariableName->someFunction(\n" 8064 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8065 Style); 8066 verifyFormat( 8067 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8068 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8069 Style); 8070 verifyFormat( 8071 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8072 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8073 Style); 8074 verifyFormat( 8075 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8076 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8077 Style); 8078 8079 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8080 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8081 " b));", 8082 Style); 8083 8084 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8085 Style.BinPackArguments = false; 8086 Style.BinPackParameters = false; 8087 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8088 " aaaaaaaaaaa aaaaaaaa,\n" 8089 " aaaaaaaaa aaaaaaa,\n" 8090 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8091 Style); 8092 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8093 " aaaaaaaaaaa aaaaaaaaa,\n" 8094 " aaaaaaaaaaa aaaaaaaaa,\n" 8095 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8096 Style); 8097 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8098 " aaaaaaaaaaaaaaa,\n" 8099 " aaaaaaaaaaaaaaaaaaaaa,\n" 8100 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8101 Style); 8102 verifyFormat( 8103 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8104 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8105 Style); 8106 verifyFormat( 8107 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8108 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8109 Style); 8110 verifyFormat( 8111 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8112 " aaaaaaaaaaaaaaaaaaaaa(\n" 8113 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8114 " aaaaaaaaaaaaaaaa);", 8115 Style); 8116 verifyFormat( 8117 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8118 " aaaaaaaaaaaaaaaaaaaaa(\n" 8119 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8120 " aaaaaaaaaaaaaaaa);", 8121 Style); 8122 } 8123 8124 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8125 FormatStyle Style = getLLVMStyleWithColumns(40); 8126 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8127 " bbbbbbbbbbbbbbbbbbbbbb);", 8128 Style); 8129 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8130 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8131 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8132 " bbbbbbbbbbbbbbbbbbbbbb);", 8133 Style); 8134 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8135 Style.AlignOperands = FormatStyle::OAS_Align; 8136 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8137 " bbbbbbbbbbbbbbbbbbbbbb);", 8138 Style); 8139 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8140 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8141 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8142 " bbbbbbbbbbbbbbbbbbbbbb);", 8143 Style); 8144 } 8145 8146 TEST_F(FormatTest, BreaksConditionalExpressions) { 8147 verifyFormat( 8148 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8149 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8150 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8151 verifyFormat( 8152 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8153 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8154 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8155 verifyFormat( 8156 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8157 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8158 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8159 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8160 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8161 verifyFormat( 8162 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8163 " : aaaaaaaaaaaaa);"); 8164 verifyFormat( 8165 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8166 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8167 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8168 " aaaaaaaaaaaaa);"); 8169 verifyFormat( 8170 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8171 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8172 " aaaaaaaaaaaaa);"); 8173 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8174 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8175 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8176 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8177 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8178 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8179 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8180 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8181 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8182 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8183 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8184 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8185 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8186 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8187 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8188 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8189 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8190 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8191 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8192 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8193 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8194 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8195 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8196 " : aaaaaaaaaaaaaaaa;"); 8197 verifyFormat( 8198 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8199 " ? aaaaaaaaaaaaaaa\n" 8200 " : aaaaaaaaaaaaaaa;"); 8201 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8202 " aaaaaaaaa\n" 8203 " ? b\n" 8204 " : c);"); 8205 verifyFormat("return aaaa == bbbb\n" 8206 " // comment\n" 8207 " ? aaaa\n" 8208 " : bbbb;"); 8209 verifyFormat("unsigned Indent =\n" 8210 " format(TheLine.First,\n" 8211 " IndentForLevel[TheLine.Level] >= 0\n" 8212 " ? IndentForLevel[TheLine.Level]\n" 8213 " : TheLine * 2,\n" 8214 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8215 getLLVMStyleWithColumns(60)); 8216 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8217 " ? aaaaaaaaaaaaaaa\n" 8218 " : bbbbbbbbbbbbbbb //\n" 8219 " ? ccccccccccccccc\n" 8220 " : ddddddddddddddd;"); 8221 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8222 " ? aaaaaaaaaaaaaaa\n" 8223 " : (bbbbbbbbbbbbbbb //\n" 8224 " ? ccccccccccccccc\n" 8225 " : ddddddddddddddd);"); 8226 verifyFormat( 8227 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8228 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8229 " aaaaaaaaaaaaaaaaaaaaa +\n" 8230 " aaaaaaaaaaaaaaaaaaaaa\n" 8231 " : aaaaaaaaaa;"); 8232 verifyFormat( 8233 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8234 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8235 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8236 8237 FormatStyle NoBinPacking = getLLVMStyle(); 8238 NoBinPacking.BinPackArguments = false; 8239 verifyFormat( 8240 "void f() {\n" 8241 " g(aaa,\n" 8242 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8243 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8244 " ? aaaaaaaaaaaaaaa\n" 8245 " : aaaaaaaaaaaaaaa);\n" 8246 "}", 8247 NoBinPacking); 8248 verifyFormat( 8249 "void f() {\n" 8250 " g(aaa,\n" 8251 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8252 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8253 " ?: aaaaaaaaaaaaaaa);\n" 8254 "}", 8255 NoBinPacking); 8256 8257 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8258 " // comment.\n" 8259 " ccccccccccccccccccccccccccccccccccccccc\n" 8260 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8261 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8262 8263 // Assignments in conditional expressions. Apparently not uncommon :-(. 8264 verifyFormat("return a != b\n" 8265 " // comment\n" 8266 " ? a = b\n" 8267 " : a = b;"); 8268 verifyFormat("return a != b\n" 8269 " // comment\n" 8270 " ? a = a != b\n" 8271 " // comment\n" 8272 " ? a = b\n" 8273 " : a\n" 8274 " : a;\n"); 8275 verifyFormat("return a != b\n" 8276 " // comment\n" 8277 " ? a\n" 8278 " : a = a != b\n" 8279 " // comment\n" 8280 " ? a = b\n" 8281 " : a;"); 8282 8283 // Chained conditionals 8284 FormatStyle Style = getLLVMStyleWithColumns(70); 8285 Style.AlignOperands = FormatStyle::OAS_Align; 8286 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8287 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8288 " : 3333333333333333;", 8289 Style); 8290 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8291 " : bbbbbbbbbb ? 2222222222222222\n" 8292 " : 3333333333333333;", 8293 Style); 8294 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8295 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8296 " : 3333333333333333;", 8297 Style); 8298 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8299 " : bbbbbbbbbbbbbb ? 222222\n" 8300 " : 333333;", 8301 Style); 8302 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8303 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8304 " : cccccccccccccc ? 3333333333333333\n" 8305 " : 4444444444444444;", 8306 Style); 8307 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8308 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8309 " : 3333333333333333;", 8310 Style); 8311 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8312 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8313 " : (aaa ? bbb : ccc);", 8314 Style); 8315 verifyFormat( 8316 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8317 " : cccccccccccccccccc)\n" 8318 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8319 " : 3333333333333333;", 8320 Style); 8321 verifyFormat( 8322 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8323 " : cccccccccccccccccc)\n" 8324 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8325 " : 3333333333333333;", 8326 Style); 8327 verifyFormat( 8328 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8329 " : dddddddddddddddddd)\n" 8330 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8331 " : 3333333333333333;", 8332 Style); 8333 verifyFormat( 8334 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8335 " : dddddddddddddddddd)\n" 8336 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8337 " : 3333333333333333;", 8338 Style); 8339 verifyFormat( 8340 "return aaaaaaaaa ? 1111111111111111\n" 8341 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8342 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8343 " : dddddddddddddddddd)\n", 8344 Style); 8345 verifyFormat( 8346 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8347 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8348 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8349 " : cccccccccccccccccc);", 8350 Style); 8351 verifyFormat( 8352 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8353 " : ccccccccccccccc ? dddddddddddddddddd\n" 8354 " : eeeeeeeeeeeeeeeeee)\n" 8355 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8356 " : 3333333333333333;", 8357 Style); 8358 verifyFormat( 8359 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8360 " : ccccccccccccccc ? dddddddddddddddddd\n" 8361 " : eeeeeeeeeeeeeeeeee)\n" 8362 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8363 " : 3333333333333333;", 8364 Style); 8365 verifyFormat( 8366 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8367 " : cccccccccccc ? dddddddddddddddddd\n" 8368 " : eeeeeeeeeeeeeeeeee)\n" 8369 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8370 " : 3333333333333333;", 8371 Style); 8372 verifyFormat( 8373 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8374 " : cccccccccccccccccc\n" 8375 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8376 " : 3333333333333333;", 8377 Style); 8378 verifyFormat( 8379 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8380 " : cccccccccccccccc ? dddddddddddddddddd\n" 8381 " : eeeeeeeeeeeeeeeeee\n" 8382 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8383 " : 3333333333333333;", 8384 Style); 8385 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8386 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8387 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8388 " : eeeeeeeeeeeeeeeeee)\n" 8389 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8390 " : 3333333333333333;", 8391 Style); 8392 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8393 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8394 " : cccccccccccccccc ? dddddddddddddddddd\n" 8395 " : eeeeeeeeeeeeeeeeee\n" 8396 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8397 " : 3333333333333333;", 8398 Style); 8399 8400 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8401 Style.BreakBeforeTernaryOperators = false; 8402 // FIXME: Aligning the question marks is weird given DontAlign. 8403 // Consider disabling this alignment in this case. Also check whether this 8404 // will render the adjustment from https://reviews.llvm.org/D82199 8405 // unnecessary. 8406 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8407 " bbbb ? cccccccccccccccccc :\n" 8408 " ddddd;\n", 8409 Style); 8410 8411 EXPECT_EQ( 8412 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8413 " /*\n" 8414 " */\n" 8415 " function() {\n" 8416 " try {\n" 8417 " return JJJJJJJJJJJJJJ(\n" 8418 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8419 " }\n" 8420 " } :\n" 8421 " function() {};", 8422 format( 8423 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8424 " /*\n" 8425 " */\n" 8426 " function() {\n" 8427 " try {\n" 8428 " return JJJJJJJJJJJJJJ(\n" 8429 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8430 " }\n" 8431 " } :\n" 8432 " function() {};", 8433 getGoogleStyle(FormatStyle::LK_JavaScript))); 8434 } 8435 8436 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8437 FormatStyle Style = getLLVMStyleWithColumns(70); 8438 Style.BreakBeforeTernaryOperators = false; 8439 verifyFormat( 8440 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8441 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8442 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8443 Style); 8444 verifyFormat( 8445 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8446 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8447 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8448 Style); 8449 verifyFormat( 8450 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8451 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8452 Style); 8453 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8454 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8455 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8456 Style); 8457 verifyFormat( 8458 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8459 " aaaaaaaaaaaaa);", 8460 Style); 8461 verifyFormat( 8462 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8463 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8464 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8465 " aaaaaaaaaaaaa);", 8466 Style); 8467 verifyFormat( 8468 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8469 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8470 " aaaaaaaaaaaaa);", 8471 Style); 8472 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8473 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8474 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8475 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8476 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8477 Style); 8478 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8480 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8481 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8482 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8483 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8484 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8485 Style); 8486 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8487 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8488 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8489 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8490 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8491 Style); 8492 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8493 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8494 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8495 Style); 8496 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8497 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8498 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8499 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8500 Style); 8501 verifyFormat( 8502 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8503 " aaaaaaaaaaaaaaa :\n" 8504 " aaaaaaaaaaaaaaa;", 8505 Style); 8506 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8507 " aaaaaaaaa ?\n" 8508 " b :\n" 8509 " c);", 8510 Style); 8511 verifyFormat("unsigned Indent =\n" 8512 " format(TheLine.First,\n" 8513 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8514 " IndentForLevel[TheLine.Level] :\n" 8515 " TheLine * 2,\n" 8516 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8517 Style); 8518 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8519 " aaaaaaaaaaaaaaa :\n" 8520 " bbbbbbbbbbbbbbb ? //\n" 8521 " ccccccccccccccc :\n" 8522 " ddddddddddddddd;", 8523 Style); 8524 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8525 " aaaaaaaaaaaaaaa :\n" 8526 " (bbbbbbbbbbbbbbb ? //\n" 8527 " ccccccccccccccc :\n" 8528 " ddddddddddddddd);", 8529 Style); 8530 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8531 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8532 " ccccccccccccccccccccccccccc;", 8533 Style); 8534 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8535 " aaaaa :\n" 8536 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8537 Style); 8538 8539 // Chained conditionals 8540 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8541 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8542 " 3333333333333333;", 8543 Style); 8544 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8545 " bbbbbbbbbb ? 2222222222222222 :\n" 8546 " 3333333333333333;", 8547 Style); 8548 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8549 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8550 " 3333333333333333;", 8551 Style); 8552 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8553 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8554 " 333333;", 8555 Style); 8556 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8557 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8558 " cccccccccccccccc ? 3333333333333333 :\n" 8559 " 4444444444444444;", 8560 Style); 8561 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8562 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8563 " 3333333333333333;", 8564 Style); 8565 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8566 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8567 " (aaa ? bbb : ccc);", 8568 Style); 8569 verifyFormat( 8570 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8571 " cccccccccccccccccc) :\n" 8572 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8573 " 3333333333333333;", 8574 Style); 8575 verifyFormat( 8576 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8577 " cccccccccccccccccc) :\n" 8578 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8579 " 3333333333333333;", 8580 Style); 8581 verifyFormat( 8582 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8583 " dddddddddddddddddd) :\n" 8584 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8585 " 3333333333333333;", 8586 Style); 8587 verifyFormat( 8588 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8589 " dddddddddddddddddd) :\n" 8590 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8591 " 3333333333333333;", 8592 Style); 8593 verifyFormat( 8594 "return aaaaaaaaa ? 1111111111111111 :\n" 8595 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8596 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8597 " dddddddddddddddddd)\n", 8598 Style); 8599 verifyFormat( 8600 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8601 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8602 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8603 " cccccccccccccccccc);", 8604 Style); 8605 verifyFormat( 8606 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8607 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8608 " eeeeeeeeeeeeeeeeee) :\n" 8609 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8610 " 3333333333333333;", 8611 Style); 8612 verifyFormat( 8613 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8614 " ccccccccccccc ? dddddddddddddddddd :\n" 8615 " eeeeeeeeeeeeeeeeee) :\n" 8616 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8617 " 3333333333333333;", 8618 Style); 8619 verifyFormat( 8620 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8621 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8622 " eeeeeeeeeeeeeeeeee) :\n" 8623 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8624 " 3333333333333333;", 8625 Style); 8626 verifyFormat( 8627 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8628 " cccccccccccccccccc :\n" 8629 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8630 " 3333333333333333;", 8631 Style); 8632 verifyFormat( 8633 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8634 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8635 " eeeeeeeeeeeeeeeeee :\n" 8636 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8637 " 3333333333333333;", 8638 Style); 8639 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8640 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8641 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8642 " eeeeeeeeeeeeeeeeee) :\n" 8643 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8644 " 3333333333333333;", 8645 Style); 8646 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8647 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8648 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8649 " eeeeeeeeeeeeeeeeee :\n" 8650 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8651 " 3333333333333333;", 8652 Style); 8653 } 8654 8655 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8656 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8657 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8658 verifyFormat("bool a = true, b = false;"); 8659 8660 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8661 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8662 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8663 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8664 verifyFormat( 8665 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8666 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8667 " d = e && f;"); 8668 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8669 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8670 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8671 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8672 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8673 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8674 8675 FormatStyle Style = getGoogleStyle(); 8676 Style.PointerAlignment = FormatStyle::PAS_Left; 8677 Style.DerivePointerAlignment = false; 8678 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8679 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8680 " *b = bbbbbbbbbbbbbbbbbbb;", 8681 Style); 8682 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8683 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8684 Style); 8685 verifyFormat("vector<int*> a, b;", Style); 8686 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8687 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8688 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8689 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8690 Style); 8691 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8692 Style); 8693 verifyFormat( 8694 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8695 Style); 8696 8697 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8698 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8699 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8700 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8701 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8702 Style); 8703 } 8704 8705 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8706 verifyFormat("arr[foo ? bar : baz];"); 8707 verifyFormat("f()[foo ? bar : baz];"); 8708 verifyFormat("(a + b)[foo ? bar : baz];"); 8709 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8710 } 8711 8712 TEST_F(FormatTest, AlignsStringLiterals) { 8713 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8714 " \"short literal\");"); 8715 verifyFormat( 8716 "looooooooooooooooooooooooongFunction(\n" 8717 " \"short literal\"\n" 8718 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8719 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8720 " \" string literals\",\n" 8721 " and, other, parameters);"); 8722 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8723 " \"5678\";", 8724 format("fun + \"1243\" /* comment */\n" 8725 " \"5678\";", 8726 getLLVMStyleWithColumns(28))); 8727 EXPECT_EQ( 8728 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8729 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8730 " \"aaaaaaaaaaaaaaaa\";", 8731 format("aaaaaa =" 8732 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8733 "aaaaaaaaaaaaaaaaaaaaa\" " 8734 "\"aaaaaaaaaaaaaaaa\";")); 8735 verifyFormat("a = a + \"a\"\n" 8736 " \"a\"\n" 8737 " \"a\";"); 8738 verifyFormat("f(\"a\", \"b\"\n" 8739 " \"c\");"); 8740 8741 verifyFormat( 8742 "#define LL_FORMAT \"ll\"\n" 8743 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8744 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8745 8746 verifyFormat("#define A(X) \\\n" 8747 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8748 " \"ccccc\"", 8749 getLLVMStyleWithColumns(23)); 8750 verifyFormat("#define A \"def\"\n" 8751 "f(\"abc\" A \"ghi\"\n" 8752 " \"jkl\");"); 8753 8754 verifyFormat("f(L\"a\"\n" 8755 " L\"b\");"); 8756 verifyFormat("#define A(X) \\\n" 8757 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8758 " L\"ccccc\"", 8759 getLLVMStyleWithColumns(25)); 8760 8761 verifyFormat("f(@\"a\"\n" 8762 " @\"b\");"); 8763 verifyFormat("NSString s = @\"a\"\n" 8764 " @\"b\"\n" 8765 " @\"c\";"); 8766 verifyFormat("NSString s = @\"a\"\n" 8767 " \"b\"\n" 8768 " \"c\";"); 8769 } 8770 8771 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8772 FormatStyle Style = getLLVMStyle(); 8773 // No declarations or definitions should be moved to own line. 8774 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8775 verifyFormat("class A {\n" 8776 " int f() { return 1; }\n" 8777 " int g();\n" 8778 "};\n" 8779 "int f() { return 1; }\n" 8780 "int g();\n", 8781 Style); 8782 8783 // All declarations and definitions should have the return type moved to its 8784 // own line. 8785 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8786 Style.TypenameMacros = {"LIST"}; 8787 verifyFormat("SomeType\n" 8788 "funcdecl(LIST(uint64_t));", 8789 Style); 8790 verifyFormat("class E {\n" 8791 " int\n" 8792 " f() {\n" 8793 " return 1;\n" 8794 " }\n" 8795 " int\n" 8796 " g();\n" 8797 "};\n" 8798 "int\n" 8799 "f() {\n" 8800 " return 1;\n" 8801 "}\n" 8802 "int\n" 8803 "g();\n", 8804 Style); 8805 8806 // Top-level definitions, and no kinds of declarations should have the 8807 // return type moved to its own line. 8808 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8809 verifyFormat("class B {\n" 8810 " int f() { return 1; }\n" 8811 " int g();\n" 8812 "};\n" 8813 "int\n" 8814 "f() {\n" 8815 " return 1;\n" 8816 "}\n" 8817 "int g();\n", 8818 Style); 8819 8820 // Top-level definitions and declarations should have the return type moved 8821 // to its own line. 8822 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8823 verifyFormat("class C {\n" 8824 " int f() { return 1; }\n" 8825 " int g();\n" 8826 "};\n" 8827 "int\n" 8828 "f() {\n" 8829 " return 1;\n" 8830 "}\n" 8831 "int\n" 8832 "g();\n", 8833 Style); 8834 8835 // All definitions should have the return type moved to its own line, but no 8836 // kinds of declarations. 8837 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8838 verifyFormat("class D {\n" 8839 " int\n" 8840 " f() {\n" 8841 " return 1;\n" 8842 " }\n" 8843 " int g();\n" 8844 "};\n" 8845 "int\n" 8846 "f() {\n" 8847 " return 1;\n" 8848 "}\n" 8849 "int g();\n", 8850 Style); 8851 verifyFormat("const char *\n" 8852 "f(void) {\n" // Break here. 8853 " return \"\";\n" 8854 "}\n" 8855 "const char *bar(void);\n", // No break here. 8856 Style); 8857 verifyFormat("template <class T>\n" 8858 "T *\n" 8859 "f(T &c) {\n" // Break here. 8860 " return NULL;\n" 8861 "}\n" 8862 "template <class T> T *f(T &c);\n", // No break here. 8863 Style); 8864 verifyFormat("class C {\n" 8865 " int\n" 8866 " operator+() {\n" 8867 " return 1;\n" 8868 " }\n" 8869 " int\n" 8870 " operator()() {\n" 8871 " return 1;\n" 8872 " }\n" 8873 "};\n", 8874 Style); 8875 verifyFormat("void\n" 8876 "A::operator()() {}\n" 8877 "void\n" 8878 "A::operator>>() {}\n" 8879 "void\n" 8880 "A::operator+() {}\n" 8881 "void\n" 8882 "A::operator*() {}\n" 8883 "void\n" 8884 "A::operator->() {}\n" 8885 "void\n" 8886 "A::operator void *() {}\n" 8887 "void\n" 8888 "A::operator void &() {}\n" 8889 "void\n" 8890 "A::operator void &&() {}\n" 8891 "void\n" 8892 "A::operator char *() {}\n" 8893 "void\n" 8894 "A::operator[]() {}\n" 8895 "void\n" 8896 "A::operator!() {}\n" 8897 "void\n" 8898 "A::operator**() {}\n" 8899 "void\n" 8900 "A::operator<Foo> *() {}\n" 8901 "void\n" 8902 "A::operator<Foo> **() {}\n" 8903 "void\n" 8904 "A::operator<Foo> &() {}\n" 8905 "void\n" 8906 "A::operator void **() {}\n", 8907 Style); 8908 verifyFormat("constexpr auto\n" 8909 "operator()() const -> reference {}\n" 8910 "constexpr auto\n" 8911 "operator>>() const -> reference {}\n" 8912 "constexpr auto\n" 8913 "operator+() const -> reference {}\n" 8914 "constexpr auto\n" 8915 "operator*() const -> reference {}\n" 8916 "constexpr auto\n" 8917 "operator->() const -> reference {}\n" 8918 "constexpr auto\n" 8919 "operator++() const -> reference {}\n" 8920 "constexpr auto\n" 8921 "operator void *() const -> reference {}\n" 8922 "constexpr auto\n" 8923 "operator void **() const -> reference {}\n" 8924 "constexpr auto\n" 8925 "operator void *() const -> reference {}\n" 8926 "constexpr auto\n" 8927 "operator void &() const -> reference {}\n" 8928 "constexpr auto\n" 8929 "operator void &&() const -> reference {}\n" 8930 "constexpr auto\n" 8931 "operator char *() const -> reference {}\n" 8932 "constexpr auto\n" 8933 "operator!() const -> reference {}\n" 8934 "constexpr auto\n" 8935 "operator[]() const -> reference {}\n", 8936 Style); 8937 verifyFormat("void *operator new(std::size_t s);", // No break here. 8938 Style); 8939 verifyFormat("void *\n" 8940 "operator new(std::size_t s) {}", 8941 Style); 8942 verifyFormat("void *\n" 8943 "operator delete[](void *ptr) {}", 8944 Style); 8945 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8946 verifyFormat("const char *\n" 8947 "f(void)\n" // Break here. 8948 "{\n" 8949 " return \"\";\n" 8950 "}\n" 8951 "const char *bar(void);\n", // No break here. 8952 Style); 8953 verifyFormat("template <class T>\n" 8954 "T *\n" // Problem here: no line break 8955 "f(T &c)\n" // Break here. 8956 "{\n" 8957 " return NULL;\n" 8958 "}\n" 8959 "template <class T> T *f(T &c);\n", // No break here. 8960 Style); 8961 verifyFormat("int\n" 8962 "foo(A<bool> a)\n" 8963 "{\n" 8964 " return a;\n" 8965 "}\n", 8966 Style); 8967 verifyFormat("int\n" 8968 "foo(A<8> a)\n" 8969 "{\n" 8970 " return a;\n" 8971 "}\n", 8972 Style); 8973 verifyFormat("int\n" 8974 "foo(A<B<bool>, 8> a)\n" 8975 "{\n" 8976 " return a;\n" 8977 "}\n", 8978 Style); 8979 verifyFormat("int\n" 8980 "foo(A<B<8>, bool> a)\n" 8981 "{\n" 8982 " return a;\n" 8983 "}\n", 8984 Style); 8985 verifyFormat("int\n" 8986 "foo(A<B<bool>, bool> a)\n" 8987 "{\n" 8988 " return a;\n" 8989 "}\n", 8990 Style); 8991 verifyFormat("int\n" 8992 "foo(A<B<8>, 8> a)\n" 8993 "{\n" 8994 " return a;\n" 8995 "}\n", 8996 Style); 8997 8998 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8999 Style.BraceWrapping.AfterFunction = true; 9000 verifyFormat("int f(i);\n" // No break here. 9001 "int\n" // Break here. 9002 "f(i)\n" 9003 "{\n" 9004 " return i + 1;\n" 9005 "}\n" 9006 "int\n" // Break here. 9007 "f(i)\n" 9008 "{\n" 9009 " return i + 1;\n" 9010 "};", 9011 Style); 9012 verifyFormat("int f(a, b, c);\n" // No break here. 9013 "int\n" // Break here. 9014 "f(a, b, c)\n" // Break here. 9015 "short a, b;\n" 9016 "float c;\n" 9017 "{\n" 9018 " return a + b < c;\n" 9019 "}\n" 9020 "int\n" // Break here. 9021 "f(a, b, c)\n" // Break here. 9022 "short a, b;\n" 9023 "float c;\n" 9024 "{\n" 9025 " return a + b < c;\n" 9026 "};", 9027 Style); 9028 verifyFormat("byte *\n" // Break here. 9029 "f(a)\n" // Break here. 9030 "byte a[];\n" 9031 "{\n" 9032 " return a;\n" 9033 "}", 9034 Style); 9035 verifyFormat("bool f(int a, int) override;\n" 9036 "Bar g(int a, Bar) final;\n" 9037 "Bar h(a, Bar) final;", 9038 Style); 9039 verifyFormat("int\n" 9040 "f(a)", 9041 Style); 9042 verifyFormat("bool\n" 9043 "f(size_t = 0, bool b = false)\n" 9044 "{\n" 9045 " return !b;\n" 9046 "}", 9047 Style); 9048 9049 // The return breaking style doesn't affect: 9050 // * function and object definitions with attribute-like macros 9051 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9052 " ABSL_GUARDED_BY(mutex) = {};", 9053 getGoogleStyleWithColumns(40)); 9054 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9055 " ABSL_GUARDED_BY(mutex); // comment", 9056 getGoogleStyleWithColumns(40)); 9057 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9058 " ABSL_GUARDED_BY(mutex1)\n" 9059 " ABSL_GUARDED_BY(mutex2);", 9060 getGoogleStyleWithColumns(40)); 9061 verifyFormat("Tttttt f(int a, int b)\n" 9062 " ABSL_GUARDED_BY(mutex1)\n" 9063 " ABSL_GUARDED_BY(mutex2);", 9064 getGoogleStyleWithColumns(40)); 9065 // * typedefs 9066 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9067 9068 Style = getGNUStyle(); 9069 9070 // Test for comments at the end of function declarations. 9071 verifyFormat("void\n" 9072 "foo (int a, /*abc*/ int b) // def\n" 9073 "{\n" 9074 "}\n", 9075 Style); 9076 9077 verifyFormat("void\n" 9078 "foo (int a, /* abc */ int b) /* def */\n" 9079 "{\n" 9080 "}\n", 9081 Style); 9082 9083 // Definitions that should not break after return type 9084 verifyFormat("void foo (int a, int b); // def\n", Style); 9085 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9086 verifyFormat("void foo (int a, int b);\n", Style); 9087 } 9088 9089 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9090 FormatStyle NoBreak = getLLVMStyle(); 9091 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9092 FormatStyle Break = getLLVMStyle(); 9093 Break.AlwaysBreakBeforeMultilineStrings = true; 9094 verifyFormat("aaaa = \"bbbb\"\n" 9095 " \"cccc\";", 9096 NoBreak); 9097 verifyFormat("aaaa =\n" 9098 " \"bbbb\"\n" 9099 " \"cccc\";", 9100 Break); 9101 verifyFormat("aaaa(\"bbbb\"\n" 9102 " \"cccc\");", 9103 NoBreak); 9104 verifyFormat("aaaa(\n" 9105 " \"bbbb\"\n" 9106 " \"cccc\");", 9107 Break); 9108 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9109 " \"cccc\");", 9110 NoBreak); 9111 verifyFormat("aaaa(qqq,\n" 9112 " \"bbbb\"\n" 9113 " \"cccc\");", 9114 Break); 9115 verifyFormat("aaaa(qqq,\n" 9116 " L\"bbbb\"\n" 9117 " L\"cccc\");", 9118 Break); 9119 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9120 " \"bbbb\"));", 9121 Break); 9122 verifyFormat("string s = someFunction(\n" 9123 " \"abc\"\n" 9124 " \"abc\");", 9125 Break); 9126 9127 // As we break before unary operators, breaking right after them is bad. 9128 verifyFormat("string foo = abc ? \"x\"\n" 9129 " \"blah blah blah blah blah blah\"\n" 9130 " : \"y\";", 9131 Break); 9132 9133 // Don't break if there is no column gain. 9134 verifyFormat("f(\"aaaa\"\n" 9135 " \"bbbb\");", 9136 Break); 9137 9138 // Treat literals with escaped newlines like multi-line string literals. 9139 EXPECT_EQ("x = \"a\\\n" 9140 "b\\\n" 9141 "c\";", 9142 format("x = \"a\\\n" 9143 "b\\\n" 9144 "c\";", 9145 NoBreak)); 9146 EXPECT_EQ("xxxx =\n" 9147 " \"a\\\n" 9148 "b\\\n" 9149 "c\";", 9150 format("xxxx = \"a\\\n" 9151 "b\\\n" 9152 "c\";", 9153 Break)); 9154 9155 EXPECT_EQ("NSString *const kString =\n" 9156 " @\"aaaa\"\n" 9157 " @\"bbbb\";", 9158 format("NSString *const kString = @\"aaaa\"\n" 9159 "@\"bbbb\";", 9160 Break)); 9161 9162 Break.ColumnLimit = 0; 9163 verifyFormat("const char *hello = \"hello llvm\";", Break); 9164 } 9165 9166 TEST_F(FormatTest, AlignsPipes) { 9167 verifyFormat( 9168 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9169 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9170 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9171 verifyFormat( 9172 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9173 " << aaaaaaaaaaaaaaaaaaaa;"); 9174 verifyFormat( 9175 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9176 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9177 verifyFormat( 9178 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9179 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9180 verifyFormat( 9181 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9182 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9183 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9184 verifyFormat( 9185 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9186 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9187 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9188 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9189 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9190 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9191 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9192 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9193 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9194 verifyFormat( 9195 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9196 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9197 verifyFormat( 9198 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9199 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9200 9201 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9202 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9203 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9204 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9205 " aaaaaaaaaaaaaaaaaaaaa)\n" 9206 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9207 verifyFormat("LOG_IF(aaa == //\n" 9208 " bbb)\n" 9209 " << a << b;"); 9210 9211 // But sometimes, breaking before the first "<<" is desirable. 9212 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9213 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9214 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9215 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9216 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9217 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9218 " << BEF << IsTemplate << Description << E->getType();"); 9219 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9220 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9222 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9223 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9224 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9225 " << aaa;"); 9226 9227 verifyFormat( 9228 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9229 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9230 9231 // Incomplete string literal. 9232 EXPECT_EQ("llvm::errs() << \"\n" 9233 " << a;", 9234 format("llvm::errs() << \"\n<<a;")); 9235 9236 verifyFormat("void f() {\n" 9237 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9238 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9239 "}"); 9240 9241 // Handle 'endl'. 9242 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9243 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9244 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9245 9246 // Handle '\n'. 9247 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9248 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9249 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9250 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9251 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9252 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9253 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9254 } 9255 9256 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9257 verifyFormat("return out << \"somepacket = {\\n\"\n" 9258 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9259 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9260 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9261 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9262 " << \"}\";"); 9263 9264 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9265 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9266 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9267 verifyFormat( 9268 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9269 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9270 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9271 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9272 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9273 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9274 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9275 verifyFormat( 9276 "void f() {\n" 9277 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9278 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9279 "}"); 9280 9281 // Breaking before the first "<<" is generally not desirable. 9282 verifyFormat( 9283 "llvm::errs()\n" 9284 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9285 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9286 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9287 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9288 getLLVMStyleWithColumns(70)); 9289 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9290 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9291 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9292 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9293 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9294 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9295 getLLVMStyleWithColumns(70)); 9296 9297 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9298 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9299 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9300 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9301 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9302 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9303 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9304 " (aaaa + aaaa);", 9305 getLLVMStyleWithColumns(40)); 9306 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9307 " (aaaaaaa + aaaaa));", 9308 getLLVMStyleWithColumns(40)); 9309 verifyFormat( 9310 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9311 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9312 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9313 } 9314 9315 TEST_F(FormatTest, UnderstandsEquals) { 9316 verifyFormat( 9317 "aaaaaaaaaaaaaaaaa =\n" 9318 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9319 verifyFormat( 9320 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9321 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9322 verifyFormat( 9323 "if (a) {\n" 9324 " f();\n" 9325 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9326 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9327 "}"); 9328 9329 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9330 " 100000000 + 10000000) {\n}"); 9331 } 9332 9333 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9334 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9335 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9336 9337 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9338 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9339 9340 verifyFormat( 9341 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9342 " Parameter2);"); 9343 9344 verifyFormat( 9345 "ShortObject->shortFunction(\n" 9346 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9347 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9348 9349 verifyFormat("loooooooooooooongFunction(\n" 9350 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9351 9352 verifyFormat( 9353 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9354 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9355 9356 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9357 " .WillRepeatedly(Return(SomeValue));"); 9358 verifyFormat("void f() {\n" 9359 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9360 " .Times(2)\n" 9361 " .WillRepeatedly(Return(SomeValue));\n" 9362 "}"); 9363 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9364 " ccccccccccccccccccccccc);"); 9365 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9367 " .aaaaa(aaaaa),\n" 9368 " aaaaaaaaaaaaaaaaaaaaa);"); 9369 verifyFormat("void f() {\n" 9370 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9371 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9372 "}"); 9373 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9374 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9375 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9376 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9377 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9378 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9379 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9380 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9381 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9382 "}"); 9383 9384 // Here, it is not necessary to wrap at "." or "->". 9385 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9386 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9387 verifyFormat( 9388 "aaaaaaaaaaa->aaaaaaaaa(\n" 9389 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9390 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9391 9392 verifyFormat( 9393 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9394 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9395 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9396 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9397 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9398 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9399 9400 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9401 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9402 " .a();"); 9403 9404 FormatStyle NoBinPacking = getLLVMStyle(); 9405 NoBinPacking.BinPackParameters = false; 9406 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9407 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9408 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9409 " aaaaaaaaaaaaaaaaaaa,\n" 9410 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9411 NoBinPacking); 9412 9413 // If there is a subsequent call, change to hanging indentation. 9414 verifyFormat( 9415 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9416 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9417 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9418 verifyFormat( 9419 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9420 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9421 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9422 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9423 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9424 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9425 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9426 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9427 } 9428 9429 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9430 verifyFormat("template <typename T>\n" 9431 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9432 verifyFormat("template <typename T>\n" 9433 "// T should be one of {A, B}.\n" 9434 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9435 verifyFormat( 9436 "template <typename T>\n" 9437 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9438 verifyFormat("template <typename T>\n" 9439 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9440 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9441 verifyFormat( 9442 "template <typename T>\n" 9443 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9444 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9445 verifyFormat( 9446 "template <typename T>\n" 9447 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9448 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9449 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9450 verifyFormat("template <typename T>\n" 9451 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9452 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9453 verifyFormat( 9454 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9455 " typename T4 = char>\n" 9456 "void f();"); 9457 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9458 " template <typename> class cccccccccccccccccccccc,\n" 9459 " typename ddddddddddddd>\n" 9460 "class C {};"); 9461 verifyFormat( 9462 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9464 9465 verifyFormat("void f() {\n" 9466 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9467 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9468 "}"); 9469 9470 verifyFormat("template <typename T> class C {};"); 9471 verifyFormat("template <typename T> void f();"); 9472 verifyFormat("template <typename T> void f() {}"); 9473 verifyFormat( 9474 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9475 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9476 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9477 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9478 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9480 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9481 getLLVMStyleWithColumns(72)); 9482 EXPECT_EQ("static_cast<A< //\n" 9483 " B> *>(\n" 9484 "\n" 9485 ");", 9486 format("static_cast<A<//\n" 9487 " B>*>(\n" 9488 "\n" 9489 " );")); 9490 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9491 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9492 9493 FormatStyle AlwaysBreak = getLLVMStyle(); 9494 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9495 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9496 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9497 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9498 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9499 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9500 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9501 verifyFormat("template <template <typename> class Fooooooo,\n" 9502 " template <typename> class Baaaaaaar>\n" 9503 "struct C {};", 9504 AlwaysBreak); 9505 verifyFormat("template <typename T> // T can be A, B or C.\n" 9506 "struct C {};", 9507 AlwaysBreak); 9508 verifyFormat("template <enum E> class A {\n" 9509 "public:\n" 9510 " E *f();\n" 9511 "};"); 9512 9513 FormatStyle NeverBreak = getLLVMStyle(); 9514 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9515 verifyFormat("template <typename T> class C {};", NeverBreak); 9516 verifyFormat("template <typename T> void f();", NeverBreak); 9517 verifyFormat("template <typename T> void f() {}", NeverBreak); 9518 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9519 "bbbbbbbbbbbbbbbbbbbb) {}", 9520 NeverBreak); 9521 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9522 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9523 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9524 NeverBreak); 9525 verifyFormat("template <template <typename> class Fooooooo,\n" 9526 " template <typename> class Baaaaaaar>\n" 9527 "struct C {};", 9528 NeverBreak); 9529 verifyFormat("template <typename T> // T can be A, B or C.\n" 9530 "struct C {};", 9531 NeverBreak); 9532 verifyFormat("template <enum E> class A {\n" 9533 "public:\n" 9534 " E *f();\n" 9535 "};", 9536 NeverBreak); 9537 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9538 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9539 "bbbbbbbbbbbbbbbbbbbb) {}", 9540 NeverBreak); 9541 } 9542 9543 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9544 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9545 Style.ColumnLimit = 60; 9546 EXPECT_EQ("// Baseline - no comments.\n" 9547 "template <\n" 9548 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9549 "void f() {}", 9550 format("// Baseline - no comments.\n" 9551 "template <\n" 9552 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9553 "void f() {}", 9554 Style)); 9555 9556 EXPECT_EQ("template <\n" 9557 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9558 "void f() {}", 9559 format("template <\n" 9560 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9561 "void f() {}", 9562 Style)); 9563 9564 EXPECT_EQ( 9565 "template <\n" 9566 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9567 "void f() {}", 9568 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9569 "void f() {}", 9570 Style)); 9571 9572 EXPECT_EQ( 9573 "template <\n" 9574 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9575 " // multiline\n" 9576 "void f() {}", 9577 format("template <\n" 9578 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9579 " // multiline\n" 9580 "void f() {}", 9581 Style)); 9582 9583 EXPECT_EQ( 9584 "template <typename aaaaaaaaaa<\n" 9585 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9586 "void f() {}", 9587 format( 9588 "template <\n" 9589 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9590 "void f() {}", 9591 Style)); 9592 } 9593 9594 TEST_F(FormatTest, WrapsTemplateParameters) { 9595 FormatStyle Style = getLLVMStyle(); 9596 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9597 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9598 verifyFormat( 9599 "template <typename... a> struct q {};\n" 9600 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9601 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9602 " y;", 9603 Style); 9604 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9605 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9606 verifyFormat( 9607 "template <typename... a> struct r {};\n" 9608 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9609 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9610 " y;", 9611 Style); 9612 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9613 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9614 verifyFormat("template <typename... a> struct s {};\n" 9615 "extern s<\n" 9616 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9617 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9618 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9619 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9620 " y;", 9621 Style); 9622 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9623 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9624 verifyFormat("template <typename... a> struct t {};\n" 9625 "extern t<\n" 9626 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9627 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9628 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9629 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9630 " y;", 9631 Style); 9632 } 9633 9634 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9635 verifyFormat( 9636 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9637 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9638 verifyFormat( 9639 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9640 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9641 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9642 9643 // FIXME: Should we have the extra indent after the second break? 9644 verifyFormat( 9645 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9646 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9647 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9648 9649 verifyFormat( 9650 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9651 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9652 9653 // Breaking at nested name specifiers is generally not desirable. 9654 verifyFormat( 9655 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9656 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9657 9658 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9659 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9660 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9661 " aaaaaaaaaaaaaaaaaaaaa);", 9662 getLLVMStyleWithColumns(74)); 9663 9664 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9665 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9666 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9667 } 9668 9669 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9670 verifyFormat("A<int> a;"); 9671 verifyFormat("A<A<A<int>>> a;"); 9672 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9673 verifyFormat("bool x = a < 1 || 2 > a;"); 9674 verifyFormat("bool x = 5 < f<int>();"); 9675 verifyFormat("bool x = f<int>() > 5;"); 9676 verifyFormat("bool x = 5 < a<int>::x;"); 9677 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9678 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9679 9680 verifyGoogleFormat("A<A<int>> a;"); 9681 verifyGoogleFormat("A<A<A<int>>> a;"); 9682 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9683 verifyGoogleFormat("A<A<int> > a;"); 9684 verifyGoogleFormat("A<A<A<int> > > a;"); 9685 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9686 verifyGoogleFormat("A<::A<int>> a;"); 9687 verifyGoogleFormat("A<::A> a;"); 9688 verifyGoogleFormat("A< ::A> a;"); 9689 verifyGoogleFormat("A< ::A<int> > a;"); 9690 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9691 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9692 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9693 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9694 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9695 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9696 9697 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9698 9699 // template closer followed by a token that starts with > or = 9700 verifyFormat("bool b = a<1> > 1;"); 9701 verifyFormat("bool b = a<1> >= 1;"); 9702 verifyFormat("int i = a<1> >> 1;"); 9703 FormatStyle Style = getLLVMStyle(); 9704 Style.SpaceBeforeAssignmentOperators = false; 9705 verifyFormat("bool b= a<1> == 1;", Style); 9706 verifyFormat("a<int> = 1;", Style); 9707 verifyFormat("a<int> >>= 1;", Style); 9708 9709 verifyFormat("test < a | b >> c;"); 9710 verifyFormat("test<test<a | b>> c;"); 9711 verifyFormat("test >> a >> b;"); 9712 verifyFormat("test << a >> b;"); 9713 9714 verifyFormat("f<int>();"); 9715 verifyFormat("template <typename T> void f() {}"); 9716 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9717 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9718 "sizeof(char)>::type>;"); 9719 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9720 verifyFormat("f(a.operator()<A>());"); 9721 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9722 " .template operator()<A>());", 9723 getLLVMStyleWithColumns(35)); 9724 verifyFormat("bool_constant<a && noexcept(f())>"); 9725 verifyFormat("bool_constant<a || noexcept(f())>"); 9726 9727 // Not template parameters. 9728 verifyFormat("return a < b && c > d;"); 9729 verifyFormat("void f() {\n" 9730 " while (a < b && c > d) {\n" 9731 " }\n" 9732 "}"); 9733 verifyFormat("template <typename... Types>\n" 9734 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9735 9736 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9737 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9738 getLLVMStyleWithColumns(60)); 9739 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9740 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9741 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9742 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9743 } 9744 9745 TEST_F(FormatTest, UnderstandsShiftOperators) { 9746 verifyFormat("if (i < x >> 1)"); 9747 verifyFormat("while (i < x >> 1)"); 9748 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9749 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9750 verifyFormat( 9751 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9752 verifyFormat("Foo.call<Bar<Function>>()"); 9753 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9754 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9755 "++i, v = v >> 1)"); 9756 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9757 } 9758 9759 TEST_F(FormatTest, BitshiftOperatorWidth) { 9760 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9761 " bar */", 9762 format("int a=1<<2; /* foo\n" 9763 " bar */")); 9764 9765 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9766 " bar */", 9767 format("int b =256>>1 ; /* foo\n" 9768 " bar */")); 9769 } 9770 9771 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9772 verifyFormat("COMPARE(a, ==, b);"); 9773 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9774 } 9775 9776 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9777 verifyFormat("int A::*x;"); 9778 verifyFormat("int (S::*func)(void *);"); 9779 verifyFormat("void f() { int (S::*func)(void *); }"); 9780 verifyFormat("typedef bool *(Class::*Member)() const;"); 9781 verifyFormat("void f() {\n" 9782 " (a->*f)();\n" 9783 " a->*x;\n" 9784 " (a.*f)();\n" 9785 " ((*a).*f)();\n" 9786 " a.*x;\n" 9787 "}"); 9788 verifyFormat("void f() {\n" 9789 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9790 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9791 "}"); 9792 verifyFormat( 9793 "(aaaaaaaaaa->*bbbbbbb)(\n" 9794 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9795 FormatStyle Style = getLLVMStyle(); 9796 Style.PointerAlignment = FormatStyle::PAS_Left; 9797 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9798 } 9799 9800 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9801 verifyFormat("int a = -2;"); 9802 verifyFormat("f(-1, -2, -3);"); 9803 verifyFormat("a[-1] = 5;"); 9804 verifyFormat("int a = 5 + -2;"); 9805 verifyFormat("if (i == -1) {\n}"); 9806 verifyFormat("if (i != -1) {\n}"); 9807 verifyFormat("if (i > -1) {\n}"); 9808 verifyFormat("if (i < -1) {\n}"); 9809 verifyFormat("++(a->f());"); 9810 verifyFormat("--(a->f());"); 9811 verifyFormat("(a->f())++;"); 9812 verifyFormat("a[42]++;"); 9813 verifyFormat("if (!(a->f())) {\n}"); 9814 verifyFormat("if (!+i) {\n}"); 9815 verifyFormat("~&a;"); 9816 verifyFormat("for (x = 0; -10 < x; --x) {\n}"); 9817 verifyFormat("sizeof -x"); 9818 verifyFormat("sizeof +x"); 9819 verifyFormat("sizeof *x"); 9820 verifyFormat("sizeof &x"); 9821 verifyFormat("delete +x;"); 9822 verifyFormat("co_await +x;"); 9823 verifyFormat("case *x:"); 9824 verifyFormat("case &x:"); 9825 9826 verifyFormat("a-- > b;"); 9827 verifyFormat("b ? -a : c;"); 9828 verifyFormat("n * sizeof char16;"); 9829 verifyFormat("n * alignof char16;", getGoogleStyle()); 9830 verifyFormat("sizeof(char);"); 9831 verifyFormat("alignof(char);", getGoogleStyle()); 9832 9833 verifyFormat("return -1;"); 9834 verifyFormat("throw -1;"); 9835 verifyFormat("switch (a) {\n" 9836 "case -1:\n" 9837 " break;\n" 9838 "}"); 9839 verifyFormat("#define X -1"); 9840 verifyFormat("#define X -kConstant"); 9841 9842 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9843 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9844 9845 verifyFormat("int a = /* confusing comment */ -1;"); 9846 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9847 verifyFormat("int a = i /* confusing comment */++;"); 9848 9849 verifyFormat("co_yield -1;"); 9850 verifyFormat("co_return -1;"); 9851 9852 // Check that * is not treated as a binary operator when we set 9853 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9854 FormatStyle PASLeftStyle = getLLVMStyle(); 9855 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9856 verifyFormat("co_return *a;", PASLeftStyle); 9857 verifyFormat("co_await *a;", PASLeftStyle); 9858 verifyFormat("co_yield *a", PASLeftStyle); 9859 verifyFormat("return *a;", PASLeftStyle); 9860 } 9861 9862 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9863 verifyFormat("if (!aaaaaaaaaa( // break\n" 9864 " aaaaa)) {\n" 9865 "}"); 9866 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9867 " aaaaa));"); 9868 verifyFormat("*aaa = aaaaaaa( // break\n" 9869 " bbbbbb);"); 9870 } 9871 9872 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9873 verifyFormat("bool operator<();"); 9874 verifyFormat("bool operator>();"); 9875 verifyFormat("bool operator=();"); 9876 verifyFormat("bool operator==();"); 9877 verifyFormat("bool operator!=();"); 9878 verifyFormat("int operator+();"); 9879 verifyFormat("int operator++();"); 9880 verifyFormat("int operator++(int) volatile noexcept;"); 9881 verifyFormat("bool operator,();"); 9882 verifyFormat("bool operator();"); 9883 verifyFormat("bool operator()();"); 9884 verifyFormat("bool operator[]();"); 9885 verifyFormat("operator bool();"); 9886 verifyFormat("operator int();"); 9887 verifyFormat("operator void *();"); 9888 verifyFormat("operator SomeType<int>();"); 9889 verifyFormat("operator SomeType<int, int>();"); 9890 verifyFormat("operator SomeType<SomeType<int>>();"); 9891 verifyFormat("operator< <>();"); 9892 verifyFormat("operator<< <>();"); 9893 verifyFormat("< <>"); 9894 9895 verifyFormat("void *operator new(std::size_t size);"); 9896 verifyFormat("void *operator new[](std::size_t size);"); 9897 verifyFormat("void operator delete(void *ptr);"); 9898 verifyFormat("void operator delete[](void *ptr);"); 9899 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9900 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9901 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9902 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9903 9904 verifyFormat( 9905 "ostream &operator<<(ostream &OutputStream,\n" 9906 " SomeReallyLongType WithSomeReallyLongValue);"); 9907 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9908 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9909 " return left.group < right.group;\n" 9910 "}"); 9911 verifyFormat("SomeType &operator=(const SomeType &S);"); 9912 verifyFormat("f.template operator()<int>();"); 9913 9914 verifyGoogleFormat("operator void*();"); 9915 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9916 verifyGoogleFormat("operator ::A();"); 9917 9918 verifyFormat("using A::operator+;"); 9919 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9920 "int i;"); 9921 9922 // Calling an operator as a member function. 9923 verifyFormat("void f() { a.operator*(); }"); 9924 verifyFormat("void f() { a.operator*(b & b); }"); 9925 verifyFormat("void f() { a->operator&(a * b); }"); 9926 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9927 // TODO: Calling an operator as a non-member function is hard to distinguish. 9928 // https://llvm.org/PR50629 9929 // verifyFormat("void f() { operator*(a & a); }"); 9930 // verifyFormat("void f() { operator&(a, b * b); }"); 9931 9932 verifyFormat("::operator delete(foo);"); 9933 verifyFormat("::operator new(n * sizeof(foo));"); 9934 verifyFormat("foo() { ::operator delete(foo); }"); 9935 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9936 } 9937 9938 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9939 verifyFormat("void A::b() && {}"); 9940 verifyFormat("void A::b() &&noexcept {}"); 9941 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9942 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9943 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9944 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9945 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9946 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9947 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9948 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9949 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9950 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9951 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9952 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9953 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9954 verifyFormat("void Fn(T const &) const &;"); 9955 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9956 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9957 verifyFormat("template <typename T>\n" 9958 "void F(T) && = delete;", 9959 getGoogleStyle()); 9960 verifyFormat("template <typename T> void operator=(T) &;"); 9961 verifyFormat("template <typename T> void operator=(T) const &;"); 9962 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9963 verifyFormat("template <typename T> void operator=(T) & = default;"); 9964 verifyFormat("template <typename T> void operator=(T) &&;"); 9965 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9966 verifyFormat("template <typename T> void operator=(T) & {}"); 9967 verifyFormat("template <typename T> void operator=(T) && {}"); 9968 9969 FormatStyle AlignLeft = getLLVMStyle(); 9970 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9971 verifyFormat("void A::b() && {}", AlignLeft); 9972 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9973 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9974 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9975 AlignLeft); 9976 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9977 AlignLeft); 9978 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9979 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9980 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9981 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9982 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9983 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9984 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9985 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9986 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9987 AlignLeft); 9988 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 9989 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 9990 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9991 AlignLeft); 9992 verifyFormat("template <typename T> void operator=(T) & = default;", 9993 AlignLeft); 9994 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9995 verifyFormat("template <typename T> void operator=(T) && = delete;", 9996 AlignLeft); 9997 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9998 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9999 10000 FormatStyle AlignMiddle = getLLVMStyle(); 10001 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10002 verifyFormat("void A::b() && {}", AlignMiddle); 10003 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 10004 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 10005 AlignMiddle); 10006 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 10007 AlignMiddle); 10008 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 10009 AlignMiddle); 10010 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 10011 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 10012 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 10013 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 10014 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 10015 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 10016 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 10017 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 10018 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 10019 AlignMiddle); 10020 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 10021 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 10022 verifyFormat("template <typename T> void operator=(T) & noexcept;", 10023 AlignMiddle); 10024 verifyFormat("template <typename T> void operator=(T) & = default;", 10025 AlignMiddle); 10026 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 10027 verifyFormat("template <typename T> void operator=(T) && = delete;", 10028 AlignMiddle); 10029 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 10030 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 10031 10032 FormatStyle Spaces = getLLVMStyle(); 10033 Spaces.SpacesInCStyleCastParentheses = true; 10034 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 10035 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 10036 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 10037 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 10038 10039 Spaces.SpacesInCStyleCastParentheses = false; 10040 Spaces.SpacesInParentheses = true; 10041 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 10042 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 10043 Spaces); 10044 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 10045 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 10046 10047 FormatStyle BreakTemplate = getLLVMStyle(); 10048 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 10049 10050 verifyFormat("struct f {\n" 10051 " template <class T>\n" 10052 " int &foo(const std::string &str) &noexcept {}\n" 10053 "};", 10054 BreakTemplate); 10055 10056 verifyFormat("struct f {\n" 10057 " template <class T>\n" 10058 " int &foo(const std::string &str) &&noexcept {}\n" 10059 "};", 10060 BreakTemplate); 10061 10062 verifyFormat("struct f {\n" 10063 " template <class T>\n" 10064 " int &foo(const std::string &str) const &noexcept {}\n" 10065 "};", 10066 BreakTemplate); 10067 10068 verifyFormat("struct f {\n" 10069 " template <class T>\n" 10070 " int &foo(const std::string &str) const &noexcept {}\n" 10071 "};", 10072 BreakTemplate); 10073 10074 verifyFormat("struct f {\n" 10075 " template <class T>\n" 10076 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10077 "};", 10078 BreakTemplate); 10079 10080 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10081 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10082 FormatStyle::BTDS_Yes; 10083 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10084 10085 verifyFormat("struct f {\n" 10086 " template <class T>\n" 10087 " int& foo(const std::string& str) & noexcept {}\n" 10088 "};", 10089 AlignLeftBreakTemplate); 10090 10091 verifyFormat("struct f {\n" 10092 " template <class T>\n" 10093 " int& foo(const std::string& str) && noexcept {}\n" 10094 "};", 10095 AlignLeftBreakTemplate); 10096 10097 verifyFormat("struct f {\n" 10098 " template <class T>\n" 10099 " int& foo(const std::string& str) const& noexcept {}\n" 10100 "};", 10101 AlignLeftBreakTemplate); 10102 10103 verifyFormat("struct f {\n" 10104 " template <class T>\n" 10105 " int& foo(const std::string& str) const&& noexcept {}\n" 10106 "};", 10107 AlignLeftBreakTemplate); 10108 10109 verifyFormat("struct f {\n" 10110 " template <class T>\n" 10111 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10112 "};", 10113 AlignLeftBreakTemplate); 10114 10115 // The `&` in `Type&` should not be confused with a trailing `&` of 10116 // DEPRECATED(reason) member function. 10117 verifyFormat("struct f {\n" 10118 " template <class T>\n" 10119 " DEPRECATED(reason)\n" 10120 " Type &foo(arguments) {}\n" 10121 "};", 10122 BreakTemplate); 10123 10124 verifyFormat("struct f {\n" 10125 " template <class T>\n" 10126 " DEPRECATED(reason)\n" 10127 " Type& foo(arguments) {}\n" 10128 "};", 10129 AlignLeftBreakTemplate); 10130 10131 verifyFormat("void (*foopt)(int) = &func;"); 10132 10133 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10134 DerivePointerAlignment.DerivePointerAlignment = true; 10135 // There's always a space between the function and its trailing qualifiers. 10136 // This isn't evidence for PAS_Right (or for PAS_Left). 10137 std::string Prefix = "void a() &;\n" 10138 "void b() &;\n"; 10139 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10140 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10141 // Same if the function is an overloaded operator, and with &&. 10142 Prefix = "void operator()() &&;\n" 10143 "void operator()() &&;\n"; 10144 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10145 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10146 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10147 Prefix = "void a() const &;\n" 10148 "void b() const &;\n"; 10149 EXPECT_EQ(Prefix + "int *x;", 10150 format(Prefix + "int* x;", DerivePointerAlignment)); 10151 } 10152 10153 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10154 verifyFormat("void f() {\n" 10155 " A *a = new A;\n" 10156 " A *a = new (placement) A;\n" 10157 " delete a;\n" 10158 " delete (A *)a;\n" 10159 "}"); 10160 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10161 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10162 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10163 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10164 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10165 verifyFormat("delete[] h->p;"); 10166 verifyFormat("delete[] (void *)p;"); 10167 10168 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10169 verifyFormat("void operator new(void *foo) ATTRIB;"); 10170 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10171 verifyFormat("void operator delete(void *ptr) noexcept;"); 10172 10173 EXPECT_EQ("void new(link p);\n" 10174 "void delete(link p);\n", 10175 format("void new (link p);\n" 10176 "void delete (link p);\n")); 10177 } 10178 10179 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10180 verifyFormat("int *f(int *a) {}"); 10181 verifyFormat("int main(int argc, char **argv) {}"); 10182 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10183 verifyIndependentOfContext("f(a, *a);"); 10184 verifyFormat("void g() { f(*a); }"); 10185 verifyIndependentOfContext("int a = b * 10;"); 10186 verifyIndependentOfContext("int a = 10 * b;"); 10187 verifyIndependentOfContext("int a = b * c;"); 10188 verifyIndependentOfContext("int a += b * c;"); 10189 verifyIndependentOfContext("int a -= b * c;"); 10190 verifyIndependentOfContext("int a *= b * c;"); 10191 verifyIndependentOfContext("int a /= b * c;"); 10192 verifyIndependentOfContext("int a = *b;"); 10193 verifyIndependentOfContext("int a = *b * c;"); 10194 verifyIndependentOfContext("int a = b * *c;"); 10195 verifyIndependentOfContext("int a = b * (10);"); 10196 verifyIndependentOfContext("S << b * (10);"); 10197 verifyIndependentOfContext("return 10 * b;"); 10198 verifyIndependentOfContext("return *b * *c;"); 10199 verifyIndependentOfContext("return a & ~b;"); 10200 verifyIndependentOfContext("f(b ? *c : *d);"); 10201 verifyIndependentOfContext("int a = b ? *c : *d;"); 10202 verifyIndependentOfContext("*b = a;"); 10203 verifyIndependentOfContext("a * ~b;"); 10204 verifyIndependentOfContext("a * !b;"); 10205 verifyIndependentOfContext("a * +b;"); 10206 verifyIndependentOfContext("a * -b;"); 10207 verifyIndependentOfContext("a * ++b;"); 10208 verifyIndependentOfContext("a * --b;"); 10209 verifyIndependentOfContext("a[4] * b;"); 10210 verifyIndependentOfContext("a[a * a] = 1;"); 10211 verifyIndependentOfContext("f() * b;"); 10212 verifyIndependentOfContext("a * [self dostuff];"); 10213 verifyIndependentOfContext("int x = a * (a + b);"); 10214 verifyIndependentOfContext("(a *)(a + b);"); 10215 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10216 verifyIndependentOfContext("int *pa = (int *)&a;"); 10217 verifyIndependentOfContext("return sizeof(int **);"); 10218 verifyIndependentOfContext("return sizeof(int ******);"); 10219 verifyIndependentOfContext("return (int **&)a;"); 10220 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10221 verifyFormat("void f(Type (*parameter)[10]) {}"); 10222 verifyFormat("void f(Type (¶meter)[10]) {}"); 10223 verifyGoogleFormat("return sizeof(int**);"); 10224 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10225 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10226 verifyFormat("auto a = [](int **&, int ***) {};"); 10227 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10228 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10229 verifyFormat("[](const decltype(*a) &value) {}"); 10230 verifyFormat("[](const typeof(*a) &value) {}"); 10231 verifyFormat("[](const _Atomic(a *) &value) {}"); 10232 verifyFormat("[](const __underlying_type(a) &value) {}"); 10233 verifyFormat("decltype(a * b) F();"); 10234 verifyFormat("typeof(a * b) F();"); 10235 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10236 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10237 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10238 verifyIndependentOfContext("int i{a * b};"); 10239 verifyIndependentOfContext("aaa && aaa->f();"); 10240 verifyIndependentOfContext("int x = ~*p;"); 10241 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10242 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10243 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10244 verifyFormat("void f() { f(a, c * d); }"); 10245 verifyFormat("void f() { f(new a(), c * d); }"); 10246 verifyFormat("void f(const MyOverride &override);"); 10247 verifyFormat("void f(const MyFinal &final);"); 10248 verifyIndependentOfContext("bool a = f() && override.f();"); 10249 verifyIndependentOfContext("bool a = f() && final.f();"); 10250 10251 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10252 10253 verifyIndependentOfContext("A<int *> a;"); 10254 verifyIndependentOfContext("A<int **> a;"); 10255 verifyIndependentOfContext("A<int *, int *> a;"); 10256 verifyIndependentOfContext("A<int *[]> a;"); 10257 verifyIndependentOfContext( 10258 "const char *const p = reinterpret_cast<const char *const>(q);"); 10259 verifyIndependentOfContext("A<int **, int **> a;"); 10260 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10261 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10262 verifyFormat("for (; a && b;) {\n}"); 10263 verifyFormat("bool foo = true && [] { return false; }();"); 10264 10265 verifyFormat( 10266 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10267 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10268 10269 verifyGoogleFormat("int const* a = &b;"); 10270 verifyGoogleFormat("**outparam = 1;"); 10271 verifyGoogleFormat("*outparam = a * b;"); 10272 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10273 verifyGoogleFormat("A<int*> a;"); 10274 verifyGoogleFormat("A<int**> a;"); 10275 verifyGoogleFormat("A<int*, int*> a;"); 10276 verifyGoogleFormat("A<int**, int**> a;"); 10277 verifyGoogleFormat("f(b ? *c : *d);"); 10278 verifyGoogleFormat("int a = b ? *c : *d;"); 10279 verifyGoogleFormat("Type* t = **x;"); 10280 verifyGoogleFormat("Type* t = *++*x;"); 10281 verifyGoogleFormat("*++*x;"); 10282 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10283 verifyGoogleFormat("Type* t = x++ * y;"); 10284 verifyGoogleFormat( 10285 "const char* const p = reinterpret_cast<const char* const>(q);"); 10286 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10287 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10288 verifyGoogleFormat("template <typename T>\n" 10289 "void f(int i = 0, SomeType** temps = NULL);"); 10290 10291 FormatStyle Left = getLLVMStyle(); 10292 Left.PointerAlignment = FormatStyle::PAS_Left; 10293 verifyFormat("x = *a(x) = *a(y);", Left); 10294 verifyFormat("for (;; *a = b) {\n}", Left); 10295 verifyFormat("return *this += 1;", Left); 10296 verifyFormat("throw *x;", Left); 10297 verifyFormat("delete *x;", Left); 10298 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10299 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10300 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10301 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10302 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10303 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10304 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10305 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10306 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10307 10308 verifyIndependentOfContext("a = *(x + y);"); 10309 verifyIndependentOfContext("a = &(x + y);"); 10310 verifyIndependentOfContext("*(x + y).call();"); 10311 verifyIndependentOfContext("&(x + y)->call();"); 10312 verifyFormat("void f() { &(*I).first; }"); 10313 10314 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10315 verifyFormat("f(* /* confusing comment */ foo);"); 10316 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10317 verifyFormat("void foo(int * // this is the first paramters\n" 10318 " ,\n" 10319 " int second);"); 10320 verifyFormat("double term = a * // first\n" 10321 " b;"); 10322 verifyFormat( 10323 "int *MyValues = {\n" 10324 " *A, // Operator detection might be confused by the '{'\n" 10325 " *BB // Operator detection might be confused by previous comment\n" 10326 "};"); 10327 10328 verifyIndependentOfContext("if (int *a = &b)"); 10329 verifyIndependentOfContext("if (int &a = *b)"); 10330 verifyIndependentOfContext("if (a & b[i])"); 10331 verifyIndependentOfContext("if constexpr (a & b[i])"); 10332 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10333 verifyIndependentOfContext("if (a * (b * c))"); 10334 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10335 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10336 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10337 verifyIndependentOfContext("if (*b[i])"); 10338 verifyIndependentOfContext("if (int *a = (&b))"); 10339 verifyIndependentOfContext("while (int *a = &b)"); 10340 verifyIndependentOfContext("while (a * (b * c))"); 10341 verifyIndependentOfContext("size = sizeof *a;"); 10342 verifyIndependentOfContext("if (a && (b = c))"); 10343 verifyFormat("void f() {\n" 10344 " for (const int &v : Values) {\n" 10345 " }\n" 10346 "}"); 10347 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10348 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10349 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10350 10351 verifyFormat("#define A (!a * b)"); 10352 verifyFormat("#define MACRO \\\n" 10353 " int *i = a * b; \\\n" 10354 " void f(a *b);", 10355 getLLVMStyleWithColumns(19)); 10356 10357 verifyIndependentOfContext("A = new SomeType *[Length];"); 10358 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10359 verifyIndependentOfContext("T **t = new T *;"); 10360 verifyIndependentOfContext("T **t = new T *();"); 10361 verifyGoogleFormat("A = new SomeType*[Length]();"); 10362 verifyGoogleFormat("A = new SomeType*[Length];"); 10363 verifyGoogleFormat("T** t = new T*;"); 10364 verifyGoogleFormat("T** t = new T*();"); 10365 10366 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10367 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10368 verifyFormat("template <bool a, bool b> " 10369 "typename t::if<x && y>::type f() {}"); 10370 verifyFormat("template <int *y> f() {}"); 10371 verifyFormat("vector<int *> v;"); 10372 verifyFormat("vector<int *const> v;"); 10373 verifyFormat("vector<int *const **const *> v;"); 10374 verifyFormat("vector<int *volatile> v;"); 10375 verifyFormat("vector<a *_Nonnull> v;"); 10376 verifyFormat("vector<a *_Nullable> v;"); 10377 verifyFormat("vector<a *_Null_unspecified> v;"); 10378 verifyFormat("vector<a *__ptr32> v;"); 10379 verifyFormat("vector<a *__ptr64> v;"); 10380 verifyFormat("vector<a *__capability> v;"); 10381 FormatStyle TypeMacros = getLLVMStyle(); 10382 TypeMacros.TypenameMacros = {"LIST"}; 10383 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10384 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10385 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10386 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10387 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10388 10389 FormatStyle CustomQualifier = getLLVMStyle(); 10390 // Add identifiers that should not be parsed as a qualifier by default. 10391 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10392 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10393 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10394 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10395 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10396 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10397 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10398 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10399 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10400 verifyFormat("vector<a * _NotAQualifier> v;"); 10401 verifyFormat("vector<a * __not_a_qualifier> v;"); 10402 verifyFormat("vector<a * b> v;"); 10403 verifyFormat("foo<b && false>();"); 10404 verifyFormat("foo<b & 1>();"); 10405 verifyFormat("foo<b & (1)>();"); 10406 verifyFormat("foo<b & (~0)>();"); 10407 verifyFormat("foo<b & (true)>();"); 10408 verifyFormat("foo<b & ((1))>();"); 10409 verifyFormat("foo<b & (/*comment*/ 1)>();"); 10410 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10411 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10412 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10413 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10414 verifyFormat( 10415 "template <class T, class = typename std::enable_if<\n" 10416 " std::is_integral<T>::value &&\n" 10417 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10418 "void F();", 10419 getLLVMStyleWithColumns(70)); 10420 verifyFormat("template <class T,\n" 10421 " class = typename std::enable_if<\n" 10422 " std::is_integral<T>::value &&\n" 10423 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10424 " class U>\n" 10425 "void F();", 10426 getLLVMStyleWithColumns(70)); 10427 verifyFormat( 10428 "template <class T,\n" 10429 " class = typename ::std::enable_if<\n" 10430 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10431 "void F();", 10432 getGoogleStyleWithColumns(68)); 10433 10434 verifyIndependentOfContext("MACRO(int *i);"); 10435 verifyIndependentOfContext("MACRO(auto *a);"); 10436 verifyIndependentOfContext("MACRO(const A *a);"); 10437 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10438 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10439 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10440 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10441 verifyIndependentOfContext("MACRO(A *const a);"); 10442 verifyIndependentOfContext("MACRO(A *restrict a);"); 10443 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10444 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10445 verifyIndependentOfContext("MACRO(A *volatile a);"); 10446 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10447 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10448 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10449 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10450 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10451 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10452 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10453 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10454 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10455 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10456 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10457 verifyIndependentOfContext("MACRO(A *__capability);"); 10458 verifyIndependentOfContext("MACRO(A &__capability);"); 10459 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10460 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10461 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10462 // a type declaration: 10463 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10464 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10465 // Also check that TypenameMacros prevents parsing it as multiplication: 10466 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10467 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10468 10469 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10470 verifyFormat("void f() { f(float{1}, a * a); }"); 10471 verifyFormat("void f() { f(float(1), a * a); }"); 10472 10473 verifyFormat("f((void (*)(int))g);"); 10474 verifyFormat("f((void (&)(int))g);"); 10475 verifyFormat("f((void (^)(int))g);"); 10476 10477 // FIXME: Is there a way to make this work? 10478 // verifyIndependentOfContext("MACRO(A *a);"); 10479 verifyFormat("MACRO(A &B);"); 10480 verifyFormat("MACRO(A *B);"); 10481 verifyFormat("void f() { MACRO(A * B); }"); 10482 verifyFormat("void f() { MACRO(A & B); }"); 10483 10484 // This lambda was mis-formatted after D88956 (treating it as a binop): 10485 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10486 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10487 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10488 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10489 10490 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10491 verifyFormat("return options != nullptr && operator==(*options);"); 10492 10493 EXPECT_EQ("#define OP(x) \\\n" 10494 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10495 " return s << a.DebugString(); \\\n" 10496 " }", 10497 format("#define OP(x) \\\n" 10498 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10499 " return s << a.DebugString(); \\\n" 10500 " }", 10501 getLLVMStyleWithColumns(50))); 10502 10503 // FIXME: We cannot handle this case yet; we might be able to figure out that 10504 // foo<x> d > v; doesn't make sense. 10505 verifyFormat("foo<a<b && c> d> v;"); 10506 10507 FormatStyle PointerMiddle = getLLVMStyle(); 10508 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10509 verifyFormat("delete *x;", PointerMiddle); 10510 verifyFormat("int * x;", PointerMiddle); 10511 verifyFormat("int *[] x;", PointerMiddle); 10512 verifyFormat("template <int * y> f() {}", PointerMiddle); 10513 verifyFormat("int * f(int * a) {}", PointerMiddle); 10514 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10515 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10516 verifyFormat("A<int *> a;", PointerMiddle); 10517 verifyFormat("A<int **> a;", PointerMiddle); 10518 verifyFormat("A<int *, int *> a;", PointerMiddle); 10519 verifyFormat("A<int *[]> a;", PointerMiddle); 10520 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10521 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10522 verifyFormat("T ** t = new T *;", PointerMiddle); 10523 10524 // Member function reference qualifiers aren't binary operators. 10525 verifyFormat("string // break\n" 10526 "operator()() & {}"); 10527 verifyFormat("string // break\n" 10528 "operator()() && {}"); 10529 verifyGoogleFormat("template <typename T>\n" 10530 "auto x() & -> int {}"); 10531 10532 // Should be binary operators when used as an argument expression (overloaded 10533 // operator invoked as a member function). 10534 verifyFormat("void f() { a.operator()(a * a); }"); 10535 verifyFormat("void f() { a->operator()(a & a); }"); 10536 verifyFormat("void f() { a.operator()(*a & *a); }"); 10537 verifyFormat("void f() { a->operator()(*a * *a); }"); 10538 10539 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10540 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10541 } 10542 10543 TEST_F(FormatTest, UnderstandsAttributes) { 10544 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10545 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10546 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10547 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10548 FormatStyle AfterType = getLLVMStyle(); 10549 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10550 verifyFormat("__attribute__((nodebug)) void\n" 10551 "foo() {}\n", 10552 AfterType); 10553 verifyFormat("__unused void\n" 10554 "foo() {}", 10555 AfterType); 10556 10557 FormatStyle CustomAttrs = getLLVMStyle(); 10558 CustomAttrs.AttributeMacros.push_back("__unused"); 10559 CustomAttrs.AttributeMacros.push_back("__attr1"); 10560 CustomAttrs.AttributeMacros.push_back("__attr2"); 10561 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10562 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10563 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10564 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10565 // Check that it is parsed as a multiplication without AttributeMacros and 10566 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10567 verifyFormat("vector<SomeType * __attr1> v;"); 10568 verifyFormat("vector<SomeType __attr1 *> v;"); 10569 verifyFormat("vector<SomeType __attr1 *const> v;"); 10570 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10571 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10572 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10573 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10574 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10575 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10576 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10577 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10578 10579 // Check that these are not parsed as function declarations: 10580 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10581 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10582 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10583 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10584 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10585 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10586 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10587 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10588 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10589 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10590 } 10591 10592 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10593 // Check that qualifiers on pointers don't break parsing of casts. 10594 verifyFormat("x = (foo *const)*v;"); 10595 verifyFormat("x = (foo *volatile)*v;"); 10596 verifyFormat("x = (foo *restrict)*v;"); 10597 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10598 verifyFormat("x = (foo *_Nonnull)*v;"); 10599 verifyFormat("x = (foo *_Nullable)*v;"); 10600 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10601 verifyFormat("x = (foo *_Nonnull)*v;"); 10602 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10603 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10604 verifyFormat("x = (foo *__ptr32)*v;"); 10605 verifyFormat("x = (foo *__ptr64)*v;"); 10606 verifyFormat("x = (foo *__capability)*v;"); 10607 10608 // Check that we handle multiple trailing qualifiers and skip them all to 10609 // determine that the expression is a cast to a pointer type. 10610 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10611 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10612 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10613 StringRef AllQualifiers = 10614 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10615 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10616 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10617 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10618 10619 // Also check that address-of is not parsed as a binary bitwise-and: 10620 verifyFormat("x = (foo *const)&v;"); 10621 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10622 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10623 10624 // Check custom qualifiers: 10625 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10626 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10627 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10628 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10629 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10630 CustomQualifier); 10631 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10632 CustomQualifier); 10633 10634 // Check that unknown identifiers result in binary operator parsing: 10635 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10636 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10637 } 10638 10639 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10640 verifyFormat("SomeType s [[unused]] (InitValue);"); 10641 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10642 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10643 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10644 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10645 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10646 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10647 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10648 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10649 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10650 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10651 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10652 10653 // Make sure we do not mistake attributes for array subscripts. 10654 verifyFormat("int a() {}\n" 10655 "[[unused]] int b() {}\n"); 10656 verifyFormat("NSArray *arr;\n" 10657 "arr[[Foo() bar]];"); 10658 10659 // On the other hand, we still need to correctly find array subscripts. 10660 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10661 10662 // Make sure that we do not mistake Objective-C method inside array literals 10663 // as attributes, even if those method names are also keywords. 10664 verifyFormat("@[ [foo bar] ];"); 10665 verifyFormat("@[ [NSArray class] ];"); 10666 verifyFormat("@[ [foo enum] ];"); 10667 10668 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10669 10670 // Make sure we do not parse attributes as lambda introducers. 10671 FormatStyle MultiLineFunctions = getLLVMStyle(); 10672 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10673 verifyFormat("[[unused]] int b() {\n" 10674 " return 42;\n" 10675 "}\n", 10676 MultiLineFunctions); 10677 } 10678 10679 TEST_F(FormatTest, AttributeClass) { 10680 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10681 verifyFormat("class S {\n" 10682 " S(S&&) = default;\n" 10683 "};", 10684 Style); 10685 verifyFormat("class [[nodiscard]] S {\n" 10686 " S(S&&) = default;\n" 10687 "};", 10688 Style); 10689 verifyFormat("class __attribute((maybeunused)) S {\n" 10690 " S(S&&) = default;\n" 10691 "};", 10692 Style); 10693 verifyFormat("struct S {\n" 10694 " S(S&&) = default;\n" 10695 "};", 10696 Style); 10697 verifyFormat("struct [[nodiscard]] S {\n" 10698 " S(S&&) = default;\n" 10699 "};", 10700 Style); 10701 } 10702 10703 TEST_F(FormatTest, AttributesAfterMacro) { 10704 FormatStyle Style = getLLVMStyle(); 10705 verifyFormat("MACRO;\n" 10706 "__attribute__((maybe_unused)) int foo() {\n" 10707 " //...\n" 10708 "}"); 10709 10710 verifyFormat("MACRO;\n" 10711 "[[nodiscard]] int foo() {\n" 10712 " //...\n" 10713 "}"); 10714 10715 EXPECT_EQ("MACRO\n\n" 10716 "__attribute__((maybe_unused)) int foo() {\n" 10717 " //...\n" 10718 "}", 10719 format("MACRO\n\n" 10720 "__attribute__((maybe_unused)) int foo() {\n" 10721 " //...\n" 10722 "}")); 10723 10724 EXPECT_EQ("MACRO\n\n" 10725 "[[nodiscard]] int foo() {\n" 10726 " //...\n" 10727 "}", 10728 format("MACRO\n\n" 10729 "[[nodiscard]] int foo() {\n" 10730 " //...\n" 10731 "}")); 10732 } 10733 10734 TEST_F(FormatTest, AttributePenaltyBreaking) { 10735 FormatStyle Style = getLLVMStyle(); 10736 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10737 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10738 Style); 10739 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10740 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10741 Style); 10742 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10743 "shared_ptr<ALongTypeName> &C d) {\n}", 10744 Style); 10745 } 10746 10747 TEST_F(FormatTest, UnderstandsEllipsis) { 10748 FormatStyle Style = getLLVMStyle(); 10749 verifyFormat("int printf(const char *fmt, ...);"); 10750 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10751 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10752 10753 verifyFormat("template <int *...PP> a;", Style); 10754 10755 Style.PointerAlignment = FormatStyle::PAS_Left; 10756 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10757 10758 verifyFormat("template <int*... PP> a;", Style); 10759 10760 Style.PointerAlignment = FormatStyle::PAS_Middle; 10761 verifyFormat("template <int *... PP> a;", Style); 10762 } 10763 10764 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10765 EXPECT_EQ("int *a;\n" 10766 "int *a;\n" 10767 "int *a;", 10768 format("int *a;\n" 10769 "int* a;\n" 10770 "int *a;", 10771 getGoogleStyle())); 10772 EXPECT_EQ("int* a;\n" 10773 "int* a;\n" 10774 "int* a;", 10775 format("int* a;\n" 10776 "int* a;\n" 10777 "int *a;", 10778 getGoogleStyle())); 10779 EXPECT_EQ("int *a;\n" 10780 "int *a;\n" 10781 "int *a;", 10782 format("int *a;\n" 10783 "int * a;\n" 10784 "int * a;", 10785 getGoogleStyle())); 10786 EXPECT_EQ("auto x = [] {\n" 10787 " int *a;\n" 10788 " int *a;\n" 10789 " int *a;\n" 10790 "};", 10791 format("auto x=[]{int *a;\n" 10792 "int * a;\n" 10793 "int * a;};", 10794 getGoogleStyle())); 10795 } 10796 10797 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10798 verifyFormat("int f(int &&a) {}"); 10799 verifyFormat("int f(int a, char &&b) {}"); 10800 verifyFormat("void f() { int &&a = b; }"); 10801 verifyGoogleFormat("int f(int a, char&& b) {}"); 10802 verifyGoogleFormat("void f() { int&& a = b; }"); 10803 10804 verifyIndependentOfContext("A<int &&> a;"); 10805 verifyIndependentOfContext("A<int &&, int &&> a;"); 10806 verifyGoogleFormat("A<int&&> a;"); 10807 verifyGoogleFormat("A<int&&, int&&> a;"); 10808 10809 // Not rvalue references: 10810 verifyFormat("template <bool B, bool C> class A {\n" 10811 " static_assert(B && C, \"Something is wrong\");\n" 10812 "};"); 10813 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10814 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10815 verifyFormat("#define A(a, b) (a && b)"); 10816 } 10817 10818 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10819 verifyFormat("void f() {\n" 10820 " x[aaaaaaaaa -\n" 10821 " b] = 23;\n" 10822 "}", 10823 getLLVMStyleWithColumns(15)); 10824 } 10825 10826 TEST_F(FormatTest, FormatsCasts) { 10827 verifyFormat("Type *A = static_cast<Type *>(P);"); 10828 verifyFormat("static_cast<Type *>(P);"); 10829 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10830 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10831 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10832 // Check that static_cast<...>(...) does not require the next token to be on 10833 // the same line. 10834 verifyFormat("some_loooong_output << something_something__ << " 10835 "static_cast<const void *>(R)\n" 10836 " << something;"); 10837 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10838 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10839 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10840 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10841 verifyFormat("Type *A = (Type *)P;"); 10842 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10843 verifyFormat("int a = (int)(2.0f);"); 10844 verifyFormat("int a = (int)2.0f;"); 10845 verifyFormat("x[(int32)y];"); 10846 verifyFormat("x = (int32)y;"); 10847 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10848 verifyFormat("int a = (int)*b;"); 10849 verifyFormat("int a = (int)2.0f;"); 10850 verifyFormat("int a = (int)~0;"); 10851 verifyFormat("int a = (int)++a;"); 10852 verifyFormat("int a = (int)sizeof(int);"); 10853 verifyFormat("int a = (int)+2;"); 10854 verifyFormat("my_int a = (my_int)2.0f;"); 10855 verifyFormat("my_int a = (my_int)sizeof(int);"); 10856 verifyFormat("return (my_int)aaa;"); 10857 verifyFormat("#define x ((int)-1)"); 10858 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10859 verifyFormat("#define p(q) ((int *)&q)"); 10860 verifyFormat("fn(a)(b) + 1;"); 10861 10862 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10863 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10864 verifyFormat("my_int a = (my_int)~0;"); 10865 verifyFormat("my_int a = (my_int)++a;"); 10866 verifyFormat("my_int a = (my_int)-2;"); 10867 verifyFormat("my_int a = (my_int)1;"); 10868 verifyFormat("my_int a = (my_int *)1;"); 10869 verifyFormat("my_int a = (const my_int)-1;"); 10870 verifyFormat("my_int a = (const my_int *)-1;"); 10871 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10872 verifyFormat("my_int a = (ns::my_int)-2;"); 10873 verifyFormat("case (my_int)ONE:"); 10874 verifyFormat("auto x = (X)this;"); 10875 // Casts in Obj-C style calls used to not be recognized as such. 10876 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10877 10878 // FIXME: single value wrapped with paren will be treated as cast. 10879 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10880 10881 verifyFormat("{ (void)F; }"); 10882 10883 // Don't break after a cast's 10884 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10885 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10886 " bbbbbbbbbbbbbbbbbbbbbb);"); 10887 10888 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10889 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10890 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10891 verifyFormat("bool *y = (bool *)(void *)(x);"); 10892 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10893 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10894 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10895 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10896 10897 // These are not casts. 10898 verifyFormat("void f(int *) {}"); 10899 verifyFormat("f(foo)->b;"); 10900 verifyFormat("f(foo).b;"); 10901 verifyFormat("f(foo)(b);"); 10902 verifyFormat("f(foo)[b];"); 10903 verifyFormat("[](foo) { return 4; }(bar);"); 10904 verifyFormat("(*funptr)(foo)[4];"); 10905 verifyFormat("funptrs[4](foo)[4];"); 10906 verifyFormat("void f(int *);"); 10907 verifyFormat("void f(int *) = 0;"); 10908 verifyFormat("void f(SmallVector<int>) {}"); 10909 verifyFormat("void f(SmallVector<int>);"); 10910 verifyFormat("void f(SmallVector<int>) = 0;"); 10911 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10912 verifyFormat("int a = sizeof(int) * b;"); 10913 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10914 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10915 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10916 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10917 10918 // These are not casts, but at some point were confused with casts. 10919 verifyFormat("virtual void foo(int *) override;"); 10920 verifyFormat("virtual void foo(char &) const;"); 10921 verifyFormat("virtual void foo(int *a, char *) const;"); 10922 verifyFormat("int a = sizeof(int *) + b;"); 10923 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10924 verifyFormat("bool b = f(g<int>) && c;"); 10925 verifyFormat("typedef void (*f)(int i) func;"); 10926 verifyFormat("void operator++(int) noexcept;"); 10927 verifyFormat("void operator++(int &) noexcept;"); 10928 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10929 "&) noexcept;"); 10930 verifyFormat( 10931 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10932 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10933 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10934 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10935 verifyFormat("void operator delete(foo &) noexcept;"); 10936 verifyFormat("void operator delete(foo) noexcept;"); 10937 verifyFormat("void operator delete(int) noexcept;"); 10938 verifyFormat("void operator delete(int &) noexcept;"); 10939 verifyFormat("void operator delete(int &) volatile noexcept;"); 10940 verifyFormat("void operator delete(int &) const"); 10941 verifyFormat("void operator delete(int &) = default"); 10942 verifyFormat("void operator delete(int &) = delete"); 10943 verifyFormat("void operator delete(int &) [[noreturn]]"); 10944 verifyFormat("void operator delete(int &) throw();"); 10945 verifyFormat("void operator delete(int &) throw(int);"); 10946 verifyFormat("auto operator delete(int &) -> int;"); 10947 verifyFormat("auto operator delete(int &) override"); 10948 verifyFormat("auto operator delete(int &) final"); 10949 10950 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10951 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10952 // FIXME: The indentation here is not ideal. 10953 verifyFormat( 10954 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10955 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10956 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10957 } 10958 10959 TEST_F(FormatTest, FormatsFunctionTypes) { 10960 verifyFormat("A<bool()> a;"); 10961 verifyFormat("A<SomeType()> a;"); 10962 verifyFormat("A<void (*)(int, std::string)> a;"); 10963 verifyFormat("A<void *(int)>;"); 10964 verifyFormat("void *(*a)(int *, SomeType *);"); 10965 verifyFormat("int (*func)(void *);"); 10966 verifyFormat("void f() { int (*func)(void *); }"); 10967 verifyFormat("template <class CallbackClass>\n" 10968 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10969 10970 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10971 verifyGoogleFormat("void* (*a)(int);"); 10972 verifyGoogleFormat( 10973 "template <class CallbackClass>\n" 10974 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10975 10976 // Other constructs can look somewhat like function types: 10977 verifyFormat("A<sizeof(*x)> a;"); 10978 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10979 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10980 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10981 verifyFormat("int x = f(&h)();"); 10982 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10983 verifyFormat("std::function<\n" 10984 " LooooooooooongTemplatedType<\n" 10985 " SomeType>*(\n" 10986 " LooooooooooooooooongType type)>\n" 10987 " function;", 10988 getGoogleStyleWithColumns(40)); 10989 } 10990 10991 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10992 verifyFormat("A (*foo_)[6];"); 10993 verifyFormat("vector<int> (*foo_)[6];"); 10994 } 10995 10996 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10997 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10998 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10999 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 11000 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11001 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11002 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11003 11004 // Different ways of ()-initializiation. 11005 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11006 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 11007 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11008 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 11009 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11010 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 11011 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11012 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 11013 11014 // Lambdas should not confuse the variable declaration heuristic. 11015 verifyFormat("LooooooooooooooooongType\n" 11016 " variable(nullptr, [](A *a) {});", 11017 getLLVMStyleWithColumns(40)); 11018 } 11019 11020 TEST_F(FormatTest, BreaksLongDeclarations) { 11021 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 11022 " AnotherNameForTheLongType;"); 11023 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 11024 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 11025 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11026 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 11027 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 11028 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 11029 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11030 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11031 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 11032 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11033 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11034 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11035 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11036 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11037 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 11038 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11039 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 11040 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11041 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 11042 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11043 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11044 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 11045 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11046 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 11047 FormatStyle Indented = getLLVMStyle(); 11048 Indented.IndentWrappedFunctionNames = true; 11049 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11050 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 11051 Indented); 11052 verifyFormat( 11053 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11054 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11055 Indented); 11056 verifyFormat( 11057 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11058 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11059 Indented); 11060 verifyFormat( 11061 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11062 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11063 Indented); 11064 11065 // FIXME: Without the comment, this breaks after "(". 11066 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 11067 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 11068 getGoogleStyle()); 11069 11070 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 11071 " int LoooooooooooooooooooongParam2) {}"); 11072 verifyFormat( 11073 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 11074 " SourceLocation L, IdentifierIn *II,\n" 11075 " Type *T) {}"); 11076 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 11077 "ReallyReaaallyLongFunctionName(\n" 11078 " const std::string &SomeParameter,\n" 11079 " const SomeType<string, SomeOtherTemplateParameter>\n" 11080 " &ReallyReallyLongParameterName,\n" 11081 " const SomeType<string, SomeOtherTemplateParameter>\n" 11082 " &AnotherLongParameterName) {}"); 11083 verifyFormat("template <typename A>\n" 11084 "SomeLoooooooooooooooooooooongType<\n" 11085 " typename some_namespace::SomeOtherType<A>::Type>\n" 11086 "Function() {}"); 11087 11088 verifyGoogleFormat( 11089 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11090 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11091 verifyGoogleFormat( 11092 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11093 " SourceLocation L) {}"); 11094 verifyGoogleFormat( 11095 "some_namespace::LongReturnType\n" 11096 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11097 " int first_long_parameter, int second_parameter) {}"); 11098 11099 verifyGoogleFormat("template <typename T>\n" 11100 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11101 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11102 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11103 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11104 11105 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11106 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11107 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11108 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11109 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11110 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11111 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11112 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11113 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11115 11116 verifyFormat("template <typename T> // Templates on own line.\n" 11117 "static int // Some comment.\n" 11118 "MyFunction(int a);", 11119 getLLVMStyle()); 11120 } 11121 11122 TEST_F(FormatTest, FormatsAccessModifiers) { 11123 FormatStyle Style = getLLVMStyle(); 11124 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11125 FormatStyle::ELBAMS_LogicalBlock); 11126 verifyFormat("struct foo {\n" 11127 "private:\n" 11128 " void f() {}\n" 11129 "\n" 11130 "private:\n" 11131 " int i;\n" 11132 "\n" 11133 "protected:\n" 11134 " int j;\n" 11135 "};\n", 11136 Style); 11137 verifyFormat("struct foo {\n" 11138 "private:\n" 11139 " void f() {}\n" 11140 "\n" 11141 "private:\n" 11142 " int i;\n" 11143 "\n" 11144 "protected:\n" 11145 " int j;\n" 11146 "};\n", 11147 "struct foo {\n" 11148 "private:\n" 11149 " void f() {}\n" 11150 "private:\n" 11151 " int i;\n" 11152 "protected:\n" 11153 " int j;\n" 11154 "};\n", 11155 Style); 11156 verifyFormat("struct foo { /* comment */\n" 11157 "private:\n" 11158 " int i;\n" 11159 " // comment\n" 11160 "private:\n" 11161 " int j;\n" 11162 "};\n", 11163 Style); 11164 verifyFormat("struct foo {\n" 11165 "#ifdef FOO\n" 11166 "#endif\n" 11167 "private:\n" 11168 " int i;\n" 11169 "#ifdef FOO\n" 11170 "private:\n" 11171 "#endif\n" 11172 " int j;\n" 11173 "};\n", 11174 Style); 11175 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11176 verifyFormat("struct foo {\n" 11177 "private:\n" 11178 " void f() {}\n" 11179 "private:\n" 11180 " int i;\n" 11181 "protected:\n" 11182 " int j;\n" 11183 "};\n", 11184 Style); 11185 verifyFormat("struct foo {\n" 11186 "private:\n" 11187 " void f() {}\n" 11188 "private:\n" 11189 " int i;\n" 11190 "protected:\n" 11191 " int j;\n" 11192 "};\n", 11193 "struct foo {\n" 11194 "\n" 11195 "private:\n" 11196 " void f() {}\n" 11197 "\n" 11198 "private:\n" 11199 " int i;\n" 11200 "\n" 11201 "protected:\n" 11202 " int j;\n" 11203 "};\n", 11204 Style); 11205 verifyFormat("struct foo { /* comment */\n" 11206 "private:\n" 11207 " int i;\n" 11208 " // comment\n" 11209 "private:\n" 11210 " int j;\n" 11211 "};\n", 11212 "struct foo { /* comment */\n" 11213 "\n" 11214 "private:\n" 11215 " int i;\n" 11216 " // comment\n" 11217 "\n" 11218 "private:\n" 11219 " int j;\n" 11220 "};\n", 11221 Style); 11222 verifyFormat("struct foo {\n" 11223 "#ifdef FOO\n" 11224 "#endif\n" 11225 "private:\n" 11226 " int i;\n" 11227 "#ifdef FOO\n" 11228 "private:\n" 11229 "#endif\n" 11230 " int j;\n" 11231 "};\n", 11232 "struct foo {\n" 11233 "#ifdef FOO\n" 11234 "#endif\n" 11235 "\n" 11236 "private:\n" 11237 " int i;\n" 11238 "#ifdef FOO\n" 11239 "\n" 11240 "private:\n" 11241 "#endif\n" 11242 " int j;\n" 11243 "};\n", 11244 Style); 11245 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11246 verifyFormat("struct foo {\n" 11247 "private:\n" 11248 " void f() {}\n" 11249 "\n" 11250 "private:\n" 11251 " int i;\n" 11252 "\n" 11253 "protected:\n" 11254 " int j;\n" 11255 "};\n", 11256 Style); 11257 verifyFormat("struct foo {\n" 11258 "private:\n" 11259 " void f() {}\n" 11260 "\n" 11261 "private:\n" 11262 " int i;\n" 11263 "\n" 11264 "protected:\n" 11265 " int j;\n" 11266 "};\n", 11267 "struct foo {\n" 11268 "private:\n" 11269 " void f() {}\n" 11270 "private:\n" 11271 " int i;\n" 11272 "protected:\n" 11273 " int j;\n" 11274 "};\n", 11275 Style); 11276 verifyFormat("struct foo { /* comment */\n" 11277 "private:\n" 11278 " int i;\n" 11279 " // comment\n" 11280 "\n" 11281 "private:\n" 11282 " int j;\n" 11283 "};\n", 11284 "struct foo { /* comment */\n" 11285 "private:\n" 11286 " int i;\n" 11287 " // comment\n" 11288 "\n" 11289 "private:\n" 11290 " int j;\n" 11291 "};\n", 11292 Style); 11293 verifyFormat("struct foo {\n" 11294 "#ifdef FOO\n" 11295 "#endif\n" 11296 "\n" 11297 "private:\n" 11298 " int i;\n" 11299 "#ifdef FOO\n" 11300 "\n" 11301 "private:\n" 11302 "#endif\n" 11303 " int j;\n" 11304 "};\n", 11305 "struct foo {\n" 11306 "#ifdef FOO\n" 11307 "#endif\n" 11308 "private:\n" 11309 " int i;\n" 11310 "#ifdef FOO\n" 11311 "private:\n" 11312 "#endif\n" 11313 " int j;\n" 11314 "};\n", 11315 Style); 11316 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11317 EXPECT_EQ("struct foo {\n" 11318 "\n" 11319 "private:\n" 11320 " void f() {}\n" 11321 "\n" 11322 "private:\n" 11323 " int i;\n" 11324 "\n" 11325 "protected:\n" 11326 " int j;\n" 11327 "};\n", 11328 format("struct foo {\n" 11329 "\n" 11330 "private:\n" 11331 " void f() {}\n" 11332 "\n" 11333 "private:\n" 11334 " int i;\n" 11335 "\n" 11336 "protected:\n" 11337 " int j;\n" 11338 "};\n", 11339 Style)); 11340 verifyFormat("struct foo {\n" 11341 "private:\n" 11342 " void f() {}\n" 11343 "private:\n" 11344 " int i;\n" 11345 "protected:\n" 11346 " int j;\n" 11347 "};\n", 11348 Style); 11349 EXPECT_EQ("struct foo { /* comment */\n" 11350 "\n" 11351 "private:\n" 11352 " int i;\n" 11353 " // comment\n" 11354 "\n" 11355 "private:\n" 11356 " int j;\n" 11357 "};\n", 11358 format("struct foo { /* comment */\n" 11359 "\n" 11360 "private:\n" 11361 " int i;\n" 11362 " // comment\n" 11363 "\n" 11364 "private:\n" 11365 " int j;\n" 11366 "};\n", 11367 Style)); 11368 verifyFormat("struct foo { /* comment */\n" 11369 "private:\n" 11370 " int i;\n" 11371 " // comment\n" 11372 "private:\n" 11373 " int j;\n" 11374 "};\n", 11375 Style); 11376 EXPECT_EQ("struct foo {\n" 11377 "#ifdef FOO\n" 11378 "#endif\n" 11379 "\n" 11380 "private:\n" 11381 " int i;\n" 11382 "#ifdef FOO\n" 11383 "\n" 11384 "private:\n" 11385 "#endif\n" 11386 " int j;\n" 11387 "};\n", 11388 format("struct foo {\n" 11389 "#ifdef FOO\n" 11390 "#endif\n" 11391 "\n" 11392 "private:\n" 11393 " int i;\n" 11394 "#ifdef FOO\n" 11395 "\n" 11396 "private:\n" 11397 "#endif\n" 11398 " int j;\n" 11399 "};\n", 11400 Style)); 11401 verifyFormat("struct foo {\n" 11402 "#ifdef FOO\n" 11403 "#endif\n" 11404 "private:\n" 11405 " int i;\n" 11406 "#ifdef FOO\n" 11407 "private:\n" 11408 "#endif\n" 11409 " int j;\n" 11410 "};\n", 11411 Style); 11412 11413 FormatStyle NoEmptyLines = getLLVMStyle(); 11414 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11415 verifyFormat("struct foo {\n" 11416 "private:\n" 11417 " void f() {}\n" 11418 "\n" 11419 "private:\n" 11420 " int i;\n" 11421 "\n" 11422 "public:\n" 11423 "protected:\n" 11424 " int j;\n" 11425 "};\n", 11426 NoEmptyLines); 11427 11428 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11429 verifyFormat("struct foo {\n" 11430 "private:\n" 11431 " void f() {}\n" 11432 "private:\n" 11433 " int i;\n" 11434 "public:\n" 11435 "protected:\n" 11436 " int j;\n" 11437 "};\n", 11438 NoEmptyLines); 11439 11440 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11441 verifyFormat("struct foo {\n" 11442 "private:\n" 11443 " void f() {}\n" 11444 "\n" 11445 "private:\n" 11446 " int i;\n" 11447 "\n" 11448 "public:\n" 11449 "\n" 11450 "protected:\n" 11451 " int j;\n" 11452 "};\n", 11453 NoEmptyLines); 11454 } 11455 11456 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11457 11458 FormatStyle Style = getLLVMStyle(); 11459 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11460 verifyFormat("struct foo {\n" 11461 "private:\n" 11462 " void f() {}\n" 11463 "\n" 11464 "private:\n" 11465 " int i;\n" 11466 "\n" 11467 "protected:\n" 11468 " int j;\n" 11469 "};\n", 11470 Style); 11471 11472 // Check if lines are removed. 11473 verifyFormat("struct foo {\n" 11474 "private:\n" 11475 " void f() {}\n" 11476 "\n" 11477 "private:\n" 11478 " int i;\n" 11479 "\n" 11480 "protected:\n" 11481 " int j;\n" 11482 "};\n", 11483 "struct foo {\n" 11484 "private:\n" 11485 "\n" 11486 " void f() {}\n" 11487 "\n" 11488 "private:\n" 11489 "\n" 11490 " int i;\n" 11491 "\n" 11492 "protected:\n" 11493 "\n" 11494 " int j;\n" 11495 "};\n", 11496 Style); 11497 11498 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11499 verifyFormat("struct foo {\n" 11500 "private:\n" 11501 "\n" 11502 " void f() {}\n" 11503 "\n" 11504 "private:\n" 11505 "\n" 11506 " int i;\n" 11507 "\n" 11508 "protected:\n" 11509 "\n" 11510 " int j;\n" 11511 "};\n", 11512 Style); 11513 11514 // Check if lines are added. 11515 verifyFormat("struct foo {\n" 11516 "private:\n" 11517 "\n" 11518 " void f() {}\n" 11519 "\n" 11520 "private:\n" 11521 "\n" 11522 " int i;\n" 11523 "\n" 11524 "protected:\n" 11525 "\n" 11526 " int j;\n" 11527 "};\n", 11528 "struct foo {\n" 11529 "private:\n" 11530 " void f() {}\n" 11531 "\n" 11532 "private:\n" 11533 " int i;\n" 11534 "\n" 11535 "protected:\n" 11536 " int j;\n" 11537 "};\n", 11538 Style); 11539 11540 // Leave tests rely on the code layout, test::messUp can not be used. 11541 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11542 Style.MaxEmptyLinesToKeep = 0u; 11543 verifyFormat("struct foo {\n" 11544 "private:\n" 11545 " void f() {}\n" 11546 "\n" 11547 "private:\n" 11548 " int i;\n" 11549 "\n" 11550 "protected:\n" 11551 " int j;\n" 11552 "};\n", 11553 Style); 11554 11555 // Check if MaxEmptyLinesToKeep is respected. 11556 EXPECT_EQ("struct foo {\n" 11557 "private:\n" 11558 " void f() {}\n" 11559 "\n" 11560 "private:\n" 11561 " int i;\n" 11562 "\n" 11563 "protected:\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 = 1u; 11582 EXPECT_EQ("struct foo {\n" 11583 "private:\n" 11584 "\n" 11585 " void f() {}\n" 11586 "\n" 11587 "private:\n" 11588 "\n" 11589 " int i;\n" 11590 "\n" 11591 "protected:\n" 11592 "\n" 11593 " int j;\n" 11594 "};\n", 11595 format("struct foo {\n" 11596 "private:\n" 11597 "\n" 11598 " void f() {}\n" 11599 "\n" 11600 "private:\n" 11601 "\n" 11602 " int i;\n" 11603 "\n" 11604 "protected:\n" 11605 "\n" 11606 " int j;\n" 11607 "};\n", 11608 Style)); 11609 // Check if no lines are kept. 11610 EXPECT_EQ("struct foo {\n" 11611 "private:\n" 11612 " void f() {}\n" 11613 "\n" 11614 "private:\n" 11615 " int i;\n" 11616 "\n" 11617 "protected:\n" 11618 " int j;\n" 11619 "};\n", 11620 format("struct foo {\n" 11621 "private:\n" 11622 " void f() {}\n" 11623 "\n" 11624 "private:\n" 11625 " int i;\n" 11626 "\n" 11627 "protected:\n" 11628 " int j;\n" 11629 "};\n", 11630 Style)); 11631 // Check if MaxEmptyLinesToKeep is respected. 11632 EXPECT_EQ("struct foo {\n" 11633 "private:\n" 11634 "\n" 11635 " void f() {}\n" 11636 "\n" 11637 "private:\n" 11638 "\n" 11639 " int i;\n" 11640 "\n" 11641 "protected:\n" 11642 "\n" 11643 " int j;\n" 11644 "};\n", 11645 format("struct foo {\n" 11646 "private:\n" 11647 "\n\n\n" 11648 " void f() {}\n" 11649 "\n" 11650 "private:\n" 11651 "\n\n\n" 11652 " int i;\n" 11653 "\n" 11654 "protected:\n" 11655 "\n\n\n" 11656 " int j;\n" 11657 "};\n", 11658 Style)); 11659 11660 Style.MaxEmptyLinesToKeep = 10u; 11661 EXPECT_EQ("struct foo {\n" 11662 "private:\n" 11663 "\n\n\n" 11664 " void f() {}\n" 11665 "\n" 11666 "private:\n" 11667 "\n\n\n" 11668 " int i;\n" 11669 "\n" 11670 "protected:\n" 11671 "\n\n\n" 11672 " int j;\n" 11673 "};\n", 11674 format("struct foo {\n" 11675 "private:\n" 11676 "\n\n\n" 11677 " void f() {}\n" 11678 "\n" 11679 "private:\n" 11680 "\n\n\n" 11681 " int i;\n" 11682 "\n" 11683 "protected:\n" 11684 "\n\n\n" 11685 " int j;\n" 11686 "};\n", 11687 Style)); 11688 11689 // Test with comments. 11690 Style = getLLVMStyle(); 11691 verifyFormat("struct foo {\n" 11692 "private:\n" 11693 " // comment\n" 11694 " void f() {}\n" 11695 "\n" 11696 "private: /* comment */\n" 11697 " int i;\n" 11698 "};\n", 11699 Style); 11700 verifyFormat("struct foo {\n" 11701 "private:\n" 11702 " // comment\n" 11703 " void f() {}\n" 11704 "\n" 11705 "private: /* comment */\n" 11706 " int i;\n" 11707 "};\n", 11708 "struct foo {\n" 11709 "private:\n" 11710 "\n" 11711 " // comment\n" 11712 " void f() {}\n" 11713 "\n" 11714 "private: /* comment */\n" 11715 "\n" 11716 " int i;\n" 11717 "};\n", 11718 Style); 11719 11720 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11721 verifyFormat("struct foo {\n" 11722 "private:\n" 11723 "\n" 11724 " // comment\n" 11725 " void f() {}\n" 11726 "\n" 11727 "private: /* comment */\n" 11728 "\n" 11729 " int i;\n" 11730 "};\n", 11731 "struct foo {\n" 11732 "private:\n" 11733 " // comment\n" 11734 " void f() {}\n" 11735 "\n" 11736 "private: /* comment */\n" 11737 " int i;\n" 11738 "};\n", 11739 Style); 11740 verifyFormat("struct foo {\n" 11741 "private:\n" 11742 "\n" 11743 " // comment\n" 11744 " void f() {}\n" 11745 "\n" 11746 "private: /* comment */\n" 11747 "\n" 11748 " int i;\n" 11749 "};\n", 11750 Style); 11751 11752 // Test with preprocessor defines. 11753 Style = getLLVMStyle(); 11754 verifyFormat("struct foo {\n" 11755 "private:\n" 11756 "#ifdef FOO\n" 11757 "#endif\n" 11758 " void f() {}\n" 11759 "};\n", 11760 Style); 11761 verifyFormat("struct foo {\n" 11762 "private:\n" 11763 "#ifdef FOO\n" 11764 "#endif\n" 11765 " void f() {}\n" 11766 "};\n", 11767 "struct foo {\n" 11768 "private:\n" 11769 "\n" 11770 "#ifdef FOO\n" 11771 "#endif\n" 11772 " void f() {}\n" 11773 "};\n", 11774 Style); 11775 11776 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11777 verifyFormat("struct foo {\n" 11778 "private:\n" 11779 "\n" 11780 "#ifdef FOO\n" 11781 "#endif\n" 11782 " void f() {}\n" 11783 "};\n", 11784 "struct foo {\n" 11785 "private:\n" 11786 "#ifdef FOO\n" 11787 "#endif\n" 11788 " void f() {}\n" 11789 "};\n", 11790 Style); 11791 verifyFormat("struct foo {\n" 11792 "private:\n" 11793 "\n" 11794 "#ifdef FOO\n" 11795 "#endif\n" 11796 " void f() {}\n" 11797 "};\n", 11798 Style); 11799 } 11800 11801 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11802 // Combined tests of EmptyLineAfterAccessModifier and 11803 // EmptyLineBeforeAccessModifier. 11804 FormatStyle Style = getLLVMStyle(); 11805 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11806 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11807 verifyFormat("struct foo {\n" 11808 "private:\n" 11809 "\n" 11810 "protected:\n" 11811 "};\n", 11812 Style); 11813 11814 Style.MaxEmptyLinesToKeep = 10u; 11815 // Both remove all new lines. 11816 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11817 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11818 verifyFormat("struct foo {\n" 11819 "private:\n" 11820 "protected:\n" 11821 "};\n", 11822 "struct foo {\n" 11823 "private:\n" 11824 "\n\n\n" 11825 "protected:\n" 11826 "};\n", 11827 Style); 11828 11829 // Leave tests rely on the code layout, test::messUp can not be used. 11830 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11831 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11832 Style.MaxEmptyLinesToKeep = 10u; 11833 EXPECT_EQ("struct foo {\n" 11834 "private:\n" 11835 "\n\n\n" 11836 "protected:\n" 11837 "};\n", 11838 format("struct foo {\n" 11839 "private:\n" 11840 "\n\n\n" 11841 "protected:\n" 11842 "};\n", 11843 Style)); 11844 Style.MaxEmptyLinesToKeep = 3u; 11845 EXPECT_EQ("struct foo {\n" 11846 "private:\n" 11847 "\n\n\n" 11848 "protected:\n" 11849 "};\n", 11850 format("struct foo {\n" 11851 "private:\n" 11852 "\n\n\n" 11853 "protected:\n" 11854 "};\n", 11855 Style)); 11856 Style.MaxEmptyLinesToKeep = 1u; 11857 EXPECT_EQ("struct foo {\n" 11858 "private:\n" 11859 "\n\n\n" 11860 "protected:\n" 11861 "};\n", 11862 format("struct foo {\n" 11863 "private:\n" 11864 "\n\n\n" 11865 "protected:\n" 11866 "};\n", 11867 Style)); // Based on new lines in original document and not 11868 // on the setting. 11869 11870 Style.MaxEmptyLinesToKeep = 10u; 11871 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11872 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11873 // Newlines are kept if they are greater than zero, 11874 // test::messUp removes all new lines which changes the logic 11875 EXPECT_EQ("struct foo {\n" 11876 "private:\n" 11877 "\n\n\n" 11878 "protected:\n" 11879 "};\n", 11880 format("struct foo {\n" 11881 "private:\n" 11882 "\n\n\n" 11883 "protected:\n" 11884 "};\n", 11885 Style)); 11886 11887 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11888 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11889 // test::messUp removes all new lines which changes the logic 11890 EXPECT_EQ("struct foo {\n" 11891 "private:\n" 11892 "\n\n\n" 11893 "protected:\n" 11894 "};\n", 11895 format("struct foo {\n" 11896 "private:\n" 11897 "\n\n\n" 11898 "protected:\n" 11899 "};\n", 11900 Style)); 11901 11902 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11903 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11904 EXPECT_EQ("struct foo {\n" 11905 "private:\n" 11906 "\n\n\n" 11907 "protected:\n" 11908 "};\n", 11909 format("struct foo {\n" 11910 "private:\n" 11911 "\n\n\n" 11912 "protected:\n" 11913 "};\n", 11914 Style)); // test::messUp removes all new lines which changes 11915 // the logic. 11916 11917 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11918 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11919 verifyFormat("struct foo {\n" 11920 "private:\n" 11921 "protected:\n" 11922 "};\n", 11923 "struct foo {\n" 11924 "private:\n" 11925 "\n\n\n" 11926 "protected:\n" 11927 "};\n", 11928 Style); 11929 11930 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11931 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11932 EXPECT_EQ("struct foo {\n" 11933 "private:\n" 11934 "\n\n\n" 11935 "protected:\n" 11936 "};\n", 11937 format("struct foo {\n" 11938 "private:\n" 11939 "\n\n\n" 11940 "protected:\n" 11941 "};\n", 11942 Style)); // test::messUp removes all new lines which changes 11943 // the logic. 11944 11945 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11946 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11947 verifyFormat("struct foo {\n" 11948 "private:\n" 11949 "protected:\n" 11950 "};\n", 11951 "struct foo {\n" 11952 "private:\n" 11953 "\n\n\n" 11954 "protected:\n" 11955 "};\n", 11956 Style); 11957 11958 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11959 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11960 verifyFormat("struct foo {\n" 11961 "private:\n" 11962 "protected:\n" 11963 "};\n", 11964 "struct foo {\n" 11965 "private:\n" 11966 "\n\n\n" 11967 "protected:\n" 11968 "};\n", 11969 Style); 11970 11971 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11972 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11973 verifyFormat("struct foo {\n" 11974 "private:\n" 11975 "protected:\n" 11976 "};\n", 11977 "struct foo {\n" 11978 "private:\n" 11979 "\n\n\n" 11980 "protected:\n" 11981 "};\n", 11982 Style); 11983 11984 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11985 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11986 verifyFormat("struct foo {\n" 11987 "private:\n" 11988 "protected:\n" 11989 "};\n", 11990 "struct foo {\n" 11991 "private:\n" 11992 "\n\n\n" 11993 "protected:\n" 11994 "};\n", 11995 Style); 11996 } 11997 11998 TEST_F(FormatTest, FormatsArrays) { 11999 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12000 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 12001 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 12002 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 12003 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 12004 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 12005 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12006 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 12007 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12008 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 12009 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12010 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12011 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 12012 verifyFormat( 12013 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 12014 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12015 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 12016 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 12017 " .aaaaaaaaaaaaaaaaaaaaaa();"); 12018 12019 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 12020 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 12021 verifyFormat( 12022 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 12023 " .aaaaaaa[0]\n" 12024 " .aaaaaaaaaaaaaaaaaaaaaa();"); 12025 verifyFormat("a[::b::c];"); 12026 12027 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 12028 12029 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12030 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 12031 } 12032 12033 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 12034 verifyFormat("(a)->b();"); 12035 verifyFormat("--a;"); 12036 } 12037 12038 TEST_F(FormatTest, HandlesIncludeDirectives) { 12039 verifyFormat("#include <string>\n" 12040 "#include <a/b/c.h>\n" 12041 "#include \"a/b/string\"\n" 12042 "#include \"string.h\"\n" 12043 "#include \"string.h\"\n" 12044 "#include <a-a>\n" 12045 "#include < path with space >\n" 12046 "#include_next <test.h>" 12047 "#include \"abc.h\" // this is included for ABC\n" 12048 "#include \"some long include\" // with a comment\n" 12049 "#include \"some very long include path\"\n" 12050 "#include <some/very/long/include/path>\n", 12051 getLLVMStyleWithColumns(35)); 12052 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 12053 EXPECT_EQ("#include <a>", format("#include<a>")); 12054 12055 verifyFormat("#import <string>"); 12056 verifyFormat("#import <a/b/c.h>"); 12057 verifyFormat("#import \"a/b/string\""); 12058 verifyFormat("#import \"string.h\""); 12059 verifyFormat("#import \"string.h\""); 12060 verifyFormat("#if __has_include(<strstream>)\n" 12061 "#include <strstream>\n" 12062 "#endif"); 12063 12064 verifyFormat("#define MY_IMPORT <a/b>"); 12065 12066 verifyFormat("#if __has_include(<a/b>)"); 12067 verifyFormat("#if __has_include_next(<a/b>)"); 12068 verifyFormat("#define F __has_include(<a/b>)"); 12069 verifyFormat("#define F __has_include_next(<a/b>)"); 12070 12071 // Protocol buffer definition or missing "#". 12072 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 12073 getLLVMStyleWithColumns(30)); 12074 12075 FormatStyle Style = getLLVMStyle(); 12076 Style.AlwaysBreakBeforeMultilineStrings = true; 12077 Style.ColumnLimit = 0; 12078 verifyFormat("#import \"abc.h\"", Style); 12079 12080 // But 'import' might also be a regular C++ namespace. 12081 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12082 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12083 } 12084 12085 //===----------------------------------------------------------------------===// 12086 // Error recovery tests. 12087 //===----------------------------------------------------------------------===// 12088 12089 TEST_F(FormatTest, IncompleteParameterLists) { 12090 FormatStyle NoBinPacking = getLLVMStyle(); 12091 NoBinPacking.BinPackParameters = false; 12092 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12093 " double *min_x,\n" 12094 " double *max_x,\n" 12095 " double *min_y,\n" 12096 " double *max_y,\n" 12097 " double *min_z,\n" 12098 " double *max_z, ) {}", 12099 NoBinPacking); 12100 } 12101 12102 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12103 verifyFormat("void f() { return; }\n42"); 12104 verifyFormat("void f() {\n" 12105 " if (0)\n" 12106 " return;\n" 12107 "}\n" 12108 "42"); 12109 verifyFormat("void f() { return }\n42"); 12110 verifyFormat("void f() {\n" 12111 " if (0)\n" 12112 " return\n" 12113 "}\n" 12114 "42"); 12115 } 12116 12117 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12118 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12119 EXPECT_EQ("void f() {\n" 12120 " if (a)\n" 12121 " return\n" 12122 "}", 12123 format("void f ( ) { if ( a ) return }")); 12124 EXPECT_EQ("namespace N {\n" 12125 "void f()\n" 12126 "}", 12127 format("namespace N { void f() }")); 12128 EXPECT_EQ("namespace N {\n" 12129 "void f() {}\n" 12130 "void g()\n" 12131 "} // namespace N", 12132 format("namespace N { void f( ) { } void g( ) }")); 12133 } 12134 12135 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12136 verifyFormat("int aaaaaaaa =\n" 12137 " // Overlylongcomment\n" 12138 " b;", 12139 getLLVMStyleWithColumns(20)); 12140 verifyFormat("function(\n" 12141 " ShortArgument,\n" 12142 " LoooooooooooongArgument);\n", 12143 getLLVMStyleWithColumns(20)); 12144 } 12145 12146 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12147 verifyFormat("public:"); 12148 verifyFormat("class A {\n" 12149 "public\n" 12150 " void f() {}\n" 12151 "};"); 12152 verifyFormat("public\n" 12153 "int qwerty;"); 12154 verifyFormat("public\n" 12155 "B {}"); 12156 verifyFormat("public\n" 12157 "{}"); 12158 verifyFormat("public\n" 12159 "B { int x; }"); 12160 } 12161 12162 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12163 verifyFormat("{"); 12164 verifyFormat("#})"); 12165 verifyNoCrash("(/**/[:!] ?[)."); 12166 } 12167 12168 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12169 // Found by oss-fuzz: 12170 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12171 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12172 Style.ColumnLimit = 60; 12173 verifyNoCrash( 12174 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12175 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12176 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12177 Style); 12178 } 12179 12180 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12181 verifyFormat("do {\n}"); 12182 verifyFormat("do {\n}\n" 12183 "f();"); 12184 verifyFormat("do {\n}\n" 12185 "wheeee(fun);"); 12186 verifyFormat("do {\n" 12187 " f();\n" 12188 "}"); 12189 } 12190 12191 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12192 verifyFormat("if {\n foo;\n foo();\n}"); 12193 verifyFormat("switch {\n foo;\n foo();\n}"); 12194 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12195 verifyIncompleteFormat("ERROR: for target;"); 12196 verifyFormat("while {\n foo;\n foo();\n}"); 12197 verifyFormat("do {\n foo;\n foo();\n} while;"); 12198 } 12199 12200 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12201 verifyIncompleteFormat("namespace {\n" 12202 "class Foo { Foo (\n" 12203 "};\n" 12204 "} // namespace"); 12205 } 12206 12207 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12208 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12209 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12210 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12211 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12212 12213 EXPECT_EQ("{\n" 12214 " {\n" 12215 " breakme(\n" 12216 " qwe);\n" 12217 " }\n", 12218 format("{\n" 12219 " {\n" 12220 " breakme(qwe);\n" 12221 "}\n", 12222 getLLVMStyleWithColumns(10))); 12223 } 12224 12225 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12226 verifyFormat("int x = {\n" 12227 " avariable,\n" 12228 " b(alongervariable)};", 12229 getLLVMStyleWithColumns(25)); 12230 } 12231 12232 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12233 verifyFormat("return (a)(b){1, 2, 3};"); 12234 } 12235 12236 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12237 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12238 verifyFormat("vector<int> x{\n" 12239 " 1,\n" 12240 " 2,\n" 12241 " 3,\n" 12242 " 4,\n" 12243 "};"); 12244 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12245 verifyFormat("f({1, 2});"); 12246 verifyFormat("auto v = Foo{-1};"); 12247 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12248 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12249 verifyFormat("new vector<int>{1, 2, 3};"); 12250 verifyFormat("new int[3]{1, 2, 3};"); 12251 verifyFormat("new int{1};"); 12252 verifyFormat("return {arg1, arg2};"); 12253 verifyFormat("return {arg1, SomeType{parameter}};"); 12254 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12255 verifyFormat("new T{arg1, arg2};"); 12256 verifyFormat("f(MyMap[{composite, key}]);"); 12257 verifyFormat("class Class {\n" 12258 " T member = {arg1, arg2};\n" 12259 "};"); 12260 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12261 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12262 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12263 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12264 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12265 12266 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12267 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12268 verifyFormat("auto i = decltype(x){};"); 12269 verifyFormat("auto i = typeof(x){};"); 12270 verifyFormat("auto i = _Atomic(x){};"); 12271 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12272 verifyFormat("Node n{1, Node{1000}, //\n" 12273 " 2};"); 12274 verifyFormat("Aaaa aaaaaaa{\n" 12275 " {\n" 12276 " aaaa,\n" 12277 " },\n" 12278 "};"); 12279 verifyFormat("class C : public D {\n" 12280 " SomeClass SC{2};\n" 12281 "};"); 12282 verifyFormat("class C : public A {\n" 12283 " class D : public B {\n" 12284 " void f() { int i{2}; }\n" 12285 " };\n" 12286 "};"); 12287 verifyFormat("#define A {a, a},"); 12288 // Don't confuse braced list initializers with compound statements. 12289 verifyFormat( 12290 "class A {\n" 12291 " A() : a{} {}\n" 12292 " A(int b) : b(b) {}\n" 12293 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12294 " int a, b;\n" 12295 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12296 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12297 "{}\n" 12298 "};"); 12299 12300 // Avoid breaking between equal sign and opening brace 12301 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12302 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12303 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12304 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12305 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12306 " {\"ccccccccccccccccccccc\", 2}};", 12307 AvoidBreakingFirstArgument); 12308 12309 // Binpacking only if there is no trailing comma 12310 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12311 " cccccccccc, dddddddddd};", 12312 getLLVMStyleWithColumns(50)); 12313 verifyFormat("const Aaaaaa aaaaa = {\n" 12314 " aaaaaaaaaaa,\n" 12315 " bbbbbbbbbbb,\n" 12316 " ccccccccccc,\n" 12317 " ddddddddddd,\n" 12318 "};", 12319 getLLVMStyleWithColumns(50)); 12320 12321 // Cases where distinguising braced lists and blocks is hard. 12322 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12323 verifyFormat("void f() {\n" 12324 " return; // comment\n" 12325 "}\n" 12326 "SomeType t;"); 12327 verifyFormat("void f() {\n" 12328 " if (a) {\n" 12329 " f();\n" 12330 " }\n" 12331 "}\n" 12332 "SomeType t;"); 12333 12334 // In combination with BinPackArguments = false. 12335 FormatStyle NoBinPacking = getLLVMStyle(); 12336 NoBinPacking.BinPackArguments = false; 12337 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12338 " bbbbb,\n" 12339 " ccccc,\n" 12340 " ddddd,\n" 12341 " eeeee,\n" 12342 " ffffff,\n" 12343 " ggggg,\n" 12344 " hhhhhh,\n" 12345 " iiiiii,\n" 12346 " jjjjjj,\n" 12347 " kkkkkk};", 12348 NoBinPacking); 12349 verifyFormat("const Aaaaaa aaaaa = {\n" 12350 " aaaaa,\n" 12351 " bbbbb,\n" 12352 " ccccc,\n" 12353 " ddddd,\n" 12354 " eeeee,\n" 12355 " ffffff,\n" 12356 " ggggg,\n" 12357 " hhhhhh,\n" 12358 " iiiiii,\n" 12359 " jjjjjj,\n" 12360 " kkkkkk,\n" 12361 "};", 12362 NoBinPacking); 12363 verifyFormat( 12364 "const Aaaaaa aaaaa = {\n" 12365 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12366 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12367 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12368 "};", 12369 NoBinPacking); 12370 12371 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12372 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12373 " CDDDP83848_BMCR_REGISTER,\n" 12374 " CDDDP83848_BMSR_REGISTER,\n" 12375 " CDDDP83848_RBR_REGISTER};", 12376 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12377 " CDDDP83848_BMSR_REGISTER,\n" 12378 " CDDDP83848_RBR_REGISTER};", 12379 NoBinPacking)); 12380 12381 // FIXME: The alignment of these trailing comments might be bad. Then again, 12382 // this might be utterly useless in real code. 12383 verifyFormat("Constructor::Constructor()\n" 12384 " : some_value{ //\n" 12385 " aaaaaaa, //\n" 12386 " bbbbbbb} {}"); 12387 12388 // In braced lists, the first comment is always assumed to belong to the 12389 // first element. Thus, it can be moved to the next or previous line as 12390 // appropriate. 12391 EXPECT_EQ("function({// First element:\n" 12392 " 1,\n" 12393 " // Second element:\n" 12394 " 2});", 12395 format("function({\n" 12396 " // First element:\n" 12397 " 1,\n" 12398 " // Second element:\n" 12399 " 2});")); 12400 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12401 " // First element:\n" 12402 " 1,\n" 12403 " // Second element:\n" 12404 " 2};", 12405 format("std::vector<int> MyNumbers{// First element:\n" 12406 " 1,\n" 12407 " // Second element:\n" 12408 " 2};", 12409 getLLVMStyleWithColumns(30))); 12410 // A trailing comma should still lead to an enforced line break and no 12411 // binpacking. 12412 EXPECT_EQ("vector<int> SomeVector = {\n" 12413 " // aaa\n" 12414 " 1,\n" 12415 " 2,\n" 12416 "};", 12417 format("vector<int> SomeVector = { // aaa\n" 12418 " 1, 2, };")); 12419 12420 // C++11 brace initializer list l-braces should not be treated any differently 12421 // when breaking before lambda bodies is enabled 12422 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12423 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12424 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12425 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12426 verifyFormat( 12427 "std::runtime_error{\n" 12428 " \"Long string which will force a break onto the next line...\"};", 12429 BreakBeforeLambdaBody); 12430 12431 FormatStyle ExtraSpaces = getLLVMStyle(); 12432 ExtraSpaces.Cpp11BracedListStyle = false; 12433 ExtraSpaces.ColumnLimit = 75; 12434 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12435 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12436 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12437 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12438 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12439 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12440 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12441 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12442 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12443 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12444 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12445 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12446 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12447 verifyFormat("class Class {\n" 12448 " T member = { arg1, arg2 };\n" 12449 "};", 12450 ExtraSpaces); 12451 verifyFormat( 12452 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12453 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12454 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12455 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12456 ExtraSpaces); 12457 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12458 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12459 ExtraSpaces); 12460 verifyFormat( 12461 "someFunction(OtherParam,\n" 12462 " BracedList{ // comment 1 (Forcing interesting break)\n" 12463 " param1, param2,\n" 12464 " // comment 2\n" 12465 " param3, param4 });", 12466 ExtraSpaces); 12467 verifyFormat( 12468 "std::this_thread::sleep_for(\n" 12469 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12470 ExtraSpaces); 12471 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12472 " aaaaaaa,\n" 12473 " aaaaaaaaaa,\n" 12474 " aaaaa,\n" 12475 " aaaaaaaaaaaaaaa,\n" 12476 " aaa,\n" 12477 " aaaaaaaaaa,\n" 12478 " a,\n" 12479 " aaaaaaaaaaaaaaaaaaaaa,\n" 12480 " aaaaaaaaaaaa,\n" 12481 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12482 " aaaaaaa,\n" 12483 " a};"); 12484 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12485 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12486 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12487 12488 // Avoid breaking between initializer/equal sign and opening brace 12489 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12490 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12491 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12492 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12493 " { \"ccccccccccccccccccccc\", 2 }\n" 12494 "};", 12495 ExtraSpaces); 12496 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12497 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12498 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12499 " { \"ccccccccccccccccccccc\", 2 }\n" 12500 "};", 12501 ExtraSpaces); 12502 12503 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12504 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12505 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12506 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12507 12508 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12509 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12510 SpaceBetweenBraces.SpacesInParentheses = true; 12511 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12512 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12513 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12514 verifyFormat("vector< int > x{ // comment 1\n" 12515 " 1, 2, 3, 4 };", 12516 SpaceBetweenBraces); 12517 SpaceBetweenBraces.ColumnLimit = 20; 12518 EXPECT_EQ("vector< int > x{\n" 12519 " 1, 2, 3, 4 };", 12520 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12521 SpaceBetweenBraces.ColumnLimit = 24; 12522 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12523 " 3, 4 };", 12524 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12525 EXPECT_EQ("vector< int > x{\n" 12526 " 1,\n" 12527 " 2,\n" 12528 " 3,\n" 12529 " 4,\n" 12530 "};", 12531 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12532 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12533 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12534 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12535 } 12536 12537 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12538 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12539 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12540 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12541 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12542 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12543 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12544 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12545 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12546 " 1, 22, 333, 4444, 55555, //\n" 12547 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12548 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12549 verifyFormat( 12550 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12551 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12552 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12553 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12554 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12555 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12556 " 7777777};"); 12557 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12558 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12559 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12560 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12561 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12562 " // Separating comment.\n" 12563 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12564 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12565 " // Leading comment\n" 12566 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12567 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12568 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12569 " 1, 1, 1, 1};", 12570 getLLVMStyleWithColumns(39)); 12571 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12572 " 1, 1, 1, 1};", 12573 getLLVMStyleWithColumns(38)); 12574 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12575 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12576 getLLVMStyleWithColumns(43)); 12577 verifyFormat( 12578 "static unsigned SomeValues[10][3] = {\n" 12579 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12580 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12581 verifyFormat("static auto fields = new vector<string>{\n" 12582 " \"aaaaaaaaaaaaa\",\n" 12583 " \"aaaaaaaaaaaaa\",\n" 12584 " \"aaaaaaaaaaaa\",\n" 12585 " \"aaaaaaaaaaaaaa\",\n" 12586 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12587 " \"aaaaaaaaaaaa\",\n" 12588 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12589 "};"); 12590 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12591 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12592 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12593 " 3, cccccccccccccccccccccc};", 12594 getLLVMStyleWithColumns(60)); 12595 12596 // Trailing commas. 12597 verifyFormat("vector<int> x = {\n" 12598 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12599 "};", 12600 getLLVMStyleWithColumns(39)); 12601 verifyFormat("vector<int> x = {\n" 12602 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12603 "};", 12604 getLLVMStyleWithColumns(39)); 12605 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12606 " 1, 1, 1, 1,\n" 12607 " /**/ /**/};", 12608 getLLVMStyleWithColumns(39)); 12609 12610 // Trailing comment in the first line. 12611 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12612 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12613 " 111111111, 222222222, 3333333333, 444444444, //\n" 12614 " 11111111, 22222222, 333333333, 44444444};"); 12615 // Trailing comment in the last line. 12616 verifyFormat("int aaaaa[] = {\n" 12617 " 1, 2, 3, // comment\n" 12618 " 4, 5, 6 // comment\n" 12619 "};"); 12620 12621 // With nested lists, we should either format one item per line or all nested 12622 // lists one on line. 12623 // FIXME: For some nested lists, we can do better. 12624 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12625 " {aaaaaaaaaaaaaaaaaaa},\n" 12626 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12627 " {aaaaaaaaaaaaaaaaa}};", 12628 getLLVMStyleWithColumns(60)); 12629 verifyFormat( 12630 "SomeStruct my_struct_array = {\n" 12631 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12632 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12633 " {aaa, aaa},\n" 12634 " {aaa, aaa},\n" 12635 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12636 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12637 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12638 12639 // No column layout should be used here. 12640 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12641 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12642 12643 verifyNoCrash("a<,"); 12644 12645 // No braced initializer here. 12646 verifyFormat("void f() {\n" 12647 " struct Dummy {};\n" 12648 " f(v);\n" 12649 "}"); 12650 12651 // Long lists should be formatted in columns even if they are nested. 12652 verifyFormat( 12653 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12654 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12655 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12656 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12657 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12658 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12659 12660 // Allow "single-column" layout even if that violates the column limit. There 12661 // isn't going to be a better way. 12662 verifyFormat("std::vector<int> a = {\n" 12663 " aaaaaaaa,\n" 12664 " aaaaaaaa,\n" 12665 " aaaaaaaa,\n" 12666 " aaaaaaaa,\n" 12667 " aaaaaaaaaa,\n" 12668 " aaaaaaaa,\n" 12669 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12670 getLLVMStyleWithColumns(30)); 12671 verifyFormat("vector<int> aaaa = {\n" 12672 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12673 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12674 " aaaaaa.aaaaaaa,\n" 12675 " aaaaaa.aaaaaaa,\n" 12676 " aaaaaa.aaaaaaa,\n" 12677 " aaaaaa.aaaaaaa,\n" 12678 "};"); 12679 12680 // Don't create hanging lists. 12681 verifyFormat("someFunction(Param, {List1, List2,\n" 12682 " List3});", 12683 getLLVMStyleWithColumns(35)); 12684 verifyFormat("someFunction(Param, Param,\n" 12685 " {List1, List2,\n" 12686 " List3});", 12687 getLLVMStyleWithColumns(35)); 12688 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12689 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12690 } 12691 12692 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12693 FormatStyle DoNotMerge = getLLVMStyle(); 12694 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12695 12696 verifyFormat("void f() { return 42; }"); 12697 verifyFormat("void f() {\n" 12698 " return 42;\n" 12699 "}", 12700 DoNotMerge); 12701 verifyFormat("void f() {\n" 12702 " // Comment\n" 12703 "}"); 12704 verifyFormat("{\n" 12705 "#error {\n" 12706 " int a;\n" 12707 "}"); 12708 verifyFormat("{\n" 12709 " int a;\n" 12710 "#error {\n" 12711 "}"); 12712 verifyFormat("void f() {} // comment"); 12713 verifyFormat("void f() { int a; } // comment"); 12714 verifyFormat("void f() {\n" 12715 "} // comment", 12716 DoNotMerge); 12717 verifyFormat("void f() {\n" 12718 " int a;\n" 12719 "} // comment", 12720 DoNotMerge); 12721 verifyFormat("void f() {\n" 12722 "} // comment", 12723 getLLVMStyleWithColumns(15)); 12724 12725 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12726 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12727 12728 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12729 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12730 verifyFormat("class C {\n" 12731 " C()\n" 12732 " : iiiiiiii(nullptr),\n" 12733 " kkkkkkk(nullptr),\n" 12734 " mmmmmmm(nullptr),\n" 12735 " nnnnnnn(nullptr) {}\n" 12736 "};", 12737 getGoogleStyle()); 12738 12739 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12740 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12741 EXPECT_EQ("class C {\n" 12742 " A() : b(0) {}\n" 12743 "};", 12744 format("class C{A():b(0){}};", NoColumnLimit)); 12745 EXPECT_EQ("A()\n" 12746 " : b(0) {\n" 12747 "}", 12748 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12749 12750 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12751 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12752 FormatStyle::SFS_None; 12753 EXPECT_EQ("A()\n" 12754 " : b(0) {\n" 12755 "}", 12756 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12757 EXPECT_EQ("A()\n" 12758 " : b(0) {\n" 12759 "}", 12760 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12761 12762 verifyFormat("#define A \\\n" 12763 " void f() { \\\n" 12764 " int i; \\\n" 12765 " }", 12766 getLLVMStyleWithColumns(20)); 12767 verifyFormat("#define A \\\n" 12768 " void f() { int i; }", 12769 getLLVMStyleWithColumns(21)); 12770 verifyFormat("#define A \\\n" 12771 " void f() { \\\n" 12772 " int i; \\\n" 12773 " } \\\n" 12774 " int j;", 12775 getLLVMStyleWithColumns(22)); 12776 verifyFormat("#define A \\\n" 12777 " void f() { int i; } \\\n" 12778 " int j;", 12779 getLLVMStyleWithColumns(23)); 12780 } 12781 12782 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12783 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12784 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12785 verifyFormat("class C {\n" 12786 " int f() {}\n" 12787 "};", 12788 MergeEmptyOnly); 12789 verifyFormat("class C {\n" 12790 " int f() {\n" 12791 " return 42;\n" 12792 " }\n" 12793 "};", 12794 MergeEmptyOnly); 12795 verifyFormat("int f() {}", MergeEmptyOnly); 12796 verifyFormat("int f() {\n" 12797 " return 42;\n" 12798 "}", 12799 MergeEmptyOnly); 12800 12801 // Also verify behavior when BraceWrapping.AfterFunction = true 12802 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12803 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12804 verifyFormat("int f() {}", MergeEmptyOnly); 12805 verifyFormat("class C {\n" 12806 " int f() {}\n" 12807 "};", 12808 MergeEmptyOnly); 12809 } 12810 12811 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12812 FormatStyle MergeInlineOnly = getLLVMStyle(); 12813 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12814 verifyFormat("class C {\n" 12815 " int f() { return 42; }\n" 12816 "};", 12817 MergeInlineOnly); 12818 verifyFormat("int f() {\n" 12819 " return 42;\n" 12820 "}", 12821 MergeInlineOnly); 12822 12823 // SFS_Inline implies SFS_Empty 12824 verifyFormat("class C {\n" 12825 " int f() {}\n" 12826 "};", 12827 MergeInlineOnly); 12828 verifyFormat("int f() {}", MergeInlineOnly); 12829 // https://llvm.org/PR54147 12830 verifyFormat("auto lambda = []() {\n" 12831 " // comment\n" 12832 " f();\n" 12833 " g();\n" 12834 "};", 12835 MergeInlineOnly); 12836 12837 verifyFormat("class C {\n" 12838 "#ifdef A\n" 12839 " int f() { return 42; }\n" 12840 "#endif\n" 12841 "};", 12842 MergeInlineOnly); 12843 12844 verifyFormat("struct S {\n" 12845 "// comment\n" 12846 "#ifdef FOO\n" 12847 " int foo() { bar(); }\n" 12848 "#endif\n" 12849 "};", 12850 MergeInlineOnly); 12851 12852 // Also verify behavior when BraceWrapping.AfterFunction = true 12853 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12854 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12855 verifyFormat("class C {\n" 12856 " int f() { return 42; }\n" 12857 "};", 12858 MergeInlineOnly); 12859 verifyFormat("int f()\n" 12860 "{\n" 12861 " return 42;\n" 12862 "}", 12863 MergeInlineOnly); 12864 12865 // SFS_Inline implies SFS_Empty 12866 verifyFormat("int f() {}", MergeInlineOnly); 12867 verifyFormat("class C {\n" 12868 " int f() {}\n" 12869 "};", 12870 MergeInlineOnly); 12871 12872 MergeInlineOnly.BraceWrapping.AfterClass = true; 12873 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12874 verifyFormat("class C\n" 12875 "{\n" 12876 " int f() { return 42; }\n" 12877 "};", 12878 MergeInlineOnly); 12879 verifyFormat("struct C\n" 12880 "{\n" 12881 " int f() { return 42; }\n" 12882 "};", 12883 MergeInlineOnly); 12884 verifyFormat("int f()\n" 12885 "{\n" 12886 " return 42;\n" 12887 "}", 12888 MergeInlineOnly); 12889 verifyFormat("int f() {}", MergeInlineOnly); 12890 verifyFormat("class C\n" 12891 "{\n" 12892 " int f() { return 42; }\n" 12893 "};", 12894 MergeInlineOnly); 12895 verifyFormat("struct C\n" 12896 "{\n" 12897 " int f() { return 42; }\n" 12898 "};", 12899 MergeInlineOnly); 12900 verifyFormat("struct C\n" 12901 "// comment\n" 12902 "/* comment */\n" 12903 "// comment\n" 12904 "{\n" 12905 " int f() { return 42; }\n" 12906 "};", 12907 MergeInlineOnly); 12908 verifyFormat("/* comment */ struct C\n" 12909 "{\n" 12910 " int f() { return 42; }\n" 12911 "};", 12912 MergeInlineOnly); 12913 } 12914 12915 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12916 FormatStyle MergeInlineOnly = getLLVMStyle(); 12917 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12918 FormatStyle::SFS_InlineOnly; 12919 verifyFormat("class C {\n" 12920 " int f() { return 42; }\n" 12921 "};", 12922 MergeInlineOnly); 12923 verifyFormat("int f() {\n" 12924 " return 42;\n" 12925 "}", 12926 MergeInlineOnly); 12927 12928 // SFS_InlineOnly does not imply SFS_Empty 12929 verifyFormat("class C {\n" 12930 " int f() {}\n" 12931 "};", 12932 MergeInlineOnly); 12933 verifyFormat("int f() {\n" 12934 "}", 12935 MergeInlineOnly); 12936 12937 // Also verify behavior when BraceWrapping.AfterFunction = true 12938 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12939 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12940 verifyFormat("class C {\n" 12941 " int f() { return 42; }\n" 12942 "};", 12943 MergeInlineOnly); 12944 verifyFormat("int f()\n" 12945 "{\n" 12946 " return 42;\n" 12947 "}", 12948 MergeInlineOnly); 12949 12950 // SFS_InlineOnly does not imply SFS_Empty 12951 verifyFormat("int f()\n" 12952 "{\n" 12953 "}", 12954 MergeInlineOnly); 12955 verifyFormat("class C {\n" 12956 " int f() {}\n" 12957 "};", 12958 MergeInlineOnly); 12959 } 12960 12961 TEST_F(FormatTest, SplitEmptyFunction) { 12962 FormatStyle Style = getLLVMStyleWithColumns(40); 12963 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12964 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12965 Style.BraceWrapping.AfterFunction = true; 12966 Style.BraceWrapping.SplitEmptyFunction = false; 12967 12968 verifyFormat("int f()\n" 12969 "{}", 12970 Style); 12971 verifyFormat("int f()\n" 12972 "{\n" 12973 " return 42;\n" 12974 "}", 12975 Style); 12976 verifyFormat("int f()\n" 12977 "{\n" 12978 " // some comment\n" 12979 "}", 12980 Style); 12981 12982 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12983 verifyFormat("int f() {}", Style); 12984 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12985 "{}", 12986 Style); 12987 verifyFormat("int f()\n" 12988 "{\n" 12989 " return 0;\n" 12990 "}", 12991 Style); 12992 12993 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12994 verifyFormat("class Foo {\n" 12995 " int f() {}\n" 12996 "};\n", 12997 Style); 12998 verifyFormat("class Foo {\n" 12999 " int f() { return 0; }\n" 13000 "};\n", 13001 Style); 13002 verifyFormat("class Foo {\n" 13003 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13004 " {}\n" 13005 "};\n", 13006 Style); 13007 verifyFormat("class Foo {\n" 13008 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13009 " {\n" 13010 " return 0;\n" 13011 " }\n" 13012 "};\n", 13013 Style); 13014 13015 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13016 verifyFormat("int f() {}", Style); 13017 verifyFormat("int f() { return 0; }", Style); 13018 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13019 "{}", 13020 Style); 13021 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13022 "{\n" 13023 " return 0;\n" 13024 "}", 13025 Style); 13026 } 13027 13028 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 13029 FormatStyle Style = getLLVMStyleWithColumns(40); 13030 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 13031 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13032 Style.BraceWrapping.AfterFunction = true; 13033 Style.BraceWrapping.SplitEmptyFunction = true; 13034 Style.BraceWrapping.SplitEmptyRecord = false; 13035 13036 verifyFormat("class C {};", Style); 13037 verifyFormat("struct C {};", Style); 13038 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13039 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13040 "{\n" 13041 "}", 13042 Style); 13043 verifyFormat("class C {\n" 13044 " C()\n" 13045 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 13046 " bbbbbbbbbbbbbbbbbbb()\n" 13047 " {\n" 13048 " }\n" 13049 " void\n" 13050 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13051 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13052 " {\n" 13053 " }\n" 13054 "};", 13055 Style); 13056 } 13057 13058 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 13059 FormatStyle Style = getLLVMStyle(); 13060 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13061 verifyFormat("#ifdef A\n" 13062 "int f() {}\n" 13063 "#else\n" 13064 "int g() {}\n" 13065 "#endif", 13066 Style); 13067 } 13068 13069 TEST_F(FormatTest, SplitEmptyClass) { 13070 FormatStyle Style = getLLVMStyle(); 13071 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13072 Style.BraceWrapping.AfterClass = true; 13073 Style.BraceWrapping.SplitEmptyRecord = false; 13074 13075 verifyFormat("class Foo\n" 13076 "{};", 13077 Style); 13078 verifyFormat("/* something */ class Foo\n" 13079 "{};", 13080 Style); 13081 verifyFormat("template <typename X> class Foo\n" 13082 "{};", 13083 Style); 13084 verifyFormat("class Foo\n" 13085 "{\n" 13086 " Foo();\n" 13087 "};", 13088 Style); 13089 verifyFormat("typedef class Foo\n" 13090 "{\n" 13091 "} Foo_t;", 13092 Style); 13093 13094 Style.BraceWrapping.SplitEmptyRecord = true; 13095 Style.BraceWrapping.AfterStruct = true; 13096 verifyFormat("class rep\n" 13097 "{\n" 13098 "};", 13099 Style); 13100 verifyFormat("struct rep\n" 13101 "{\n" 13102 "};", 13103 Style); 13104 verifyFormat("template <typename T> class rep\n" 13105 "{\n" 13106 "};", 13107 Style); 13108 verifyFormat("template <typename T> struct rep\n" 13109 "{\n" 13110 "};", 13111 Style); 13112 verifyFormat("class rep\n" 13113 "{\n" 13114 " int x;\n" 13115 "};", 13116 Style); 13117 verifyFormat("struct rep\n" 13118 "{\n" 13119 " int x;\n" 13120 "};", 13121 Style); 13122 verifyFormat("template <typename T> class rep\n" 13123 "{\n" 13124 " int x;\n" 13125 "};", 13126 Style); 13127 verifyFormat("template <typename T> struct rep\n" 13128 "{\n" 13129 " int x;\n" 13130 "};", 13131 Style); 13132 verifyFormat("template <typename T> class rep // Foo\n" 13133 "{\n" 13134 " int x;\n" 13135 "};", 13136 Style); 13137 verifyFormat("template <typename T> struct rep // Bar\n" 13138 "{\n" 13139 " int x;\n" 13140 "};", 13141 Style); 13142 13143 verifyFormat("template <typename T> class rep<T>\n" 13144 "{\n" 13145 " int x;\n" 13146 "};", 13147 Style); 13148 13149 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13150 "{\n" 13151 " int x;\n" 13152 "};", 13153 Style); 13154 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13155 "{\n" 13156 "};", 13157 Style); 13158 13159 verifyFormat("#include \"stdint.h\"\n" 13160 "namespace rep {}", 13161 Style); 13162 verifyFormat("#include <stdint.h>\n" 13163 "namespace rep {}", 13164 Style); 13165 verifyFormat("#include <stdint.h>\n" 13166 "namespace rep {}", 13167 "#include <stdint.h>\n" 13168 "namespace rep {\n" 13169 "\n" 13170 "\n" 13171 "}", 13172 Style); 13173 } 13174 13175 TEST_F(FormatTest, SplitEmptyStruct) { 13176 FormatStyle Style = getLLVMStyle(); 13177 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13178 Style.BraceWrapping.AfterStruct = true; 13179 Style.BraceWrapping.SplitEmptyRecord = false; 13180 13181 verifyFormat("struct Foo\n" 13182 "{};", 13183 Style); 13184 verifyFormat("/* something */ struct Foo\n" 13185 "{};", 13186 Style); 13187 verifyFormat("template <typename X> struct Foo\n" 13188 "{};", 13189 Style); 13190 verifyFormat("struct Foo\n" 13191 "{\n" 13192 " Foo();\n" 13193 "};", 13194 Style); 13195 verifyFormat("typedef struct Foo\n" 13196 "{\n" 13197 "} Foo_t;", 13198 Style); 13199 // typedef struct Bar {} Bar_t; 13200 } 13201 13202 TEST_F(FormatTest, SplitEmptyUnion) { 13203 FormatStyle Style = getLLVMStyle(); 13204 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13205 Style.BraceWrapping.AfterUnion = true; 13206 Style.BraceWrapping.SplitEmptyRecord = false; 13207 13208 verifyFormat("union Foo\n" 13209 "{};", 13210 Style); 13211 verifyFormat("/* something */ union Foo\n" 13212 "{};", 13213 Style); 13214 verifyFormat("union Foo\n" 13215 "{\n" 13216 " A,\n" 13217 "};", 13218 Style); 13219 verifyFormat("typedef union Foo\n" 13220 "{\n" 13221 "} Foo_t;", 13222 Style); 13223 } 13224 13225 TEST_F(FormatTest, SplitEmptyNamespace) { 13226 FormatStyle Style = getLLVMStyle(); 13227 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13228 Style.BraceWrapping.AfterNamespace = true; 13229 Style.BraceWrapping.SplitEmptyNamespace = false; 13230 13231 verifyFormat("namespace Foo\n" 13232 "{};", 13233 Style); 13234 verifyFormat("/* something */ namespace Foo\n" 13235 "{};", 13236 Style); 13237 verifyFormat("inline namespace Foo\n" 13238 "{};", 13239 Style); 13240 verifyFormat("/* something */ inline namespace Foo\n" 13241 "{};", 13242 Style); 13243 verifyFormat("export namespace Foo\n" 13244 "{};", 13245 Style); 13246 verifyFormat("namespace Foo\n" 13247 "{\n" 13248 "void Bar();\n" 13249 "};", 13250 Style); 13251 } 13252 13253 TEST_F(FormatTest, NeverMergeShortRecords) { 13254 FormatStyle Style = getLLVMStyle(); 13255 13256 verifyFormat("class Foo {\n" 13257 " Foo();\n" 13258 "};", 13259 Style); 13260 verifyFormat("typedef class Foo {\n" 13261 " Foo();\n" 13262 "} Foo_t;", 13263 Style); 13264 verifyFormat("struct Foo {\n" 13265 " Foo();\n" 13266 "};", 13267 Style); 13268 verifyFormat("typedef struct Foo {\n" 13269 " Foo();\n" 13270 "} Foo_t;", 13271 Style); 13272 verifyFormat("union Foo {\n" 13273 " A,\n" 13274 "};", 13275 Style); 13276 verifyFormat("typedef union Foo {\n" 13277 " A,\n" 13278 "} Foo_t;", 13279 Style); 13280 verifyFormat("namespace Foo {\n" 13281 "void Bar();\n" 13282 "};", 13283 Style); 13284 13285 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13286 Style.BraceWrapping.AfterClass = true; 13287 Style.BraceWrapping.AfterStruct = true; 13288 Style.BraceWrapping.AfterUnion = true; 13289 Style.BraceWrapping.AfterNamespace = true; 13290 verifyFormat("class Foo\n" 13291 "{\n" 13292 " Foo();\n" 13293 "};", 13294 Style); 13295 verifyFormat("typedef class Foo\n" 13296 "{\n" 13297 " Foo();\n" 13298 "} Foo_t;", 13299 Style); 13300 verifyFormat("struct Foo\n" 13301 "{\n" 13302 " Foo();\n" 13303 "};", 13304 Style); 13305 verifyFormat("typedef struct Foo\n" 13306 "{\n" 13307 " Foo();\n" 13308 "} Foo_t;", 13309 Style); 13310 verifyFormat("union Foo\n" 13311 "{\n" 13312 " A,\n" 13313 "};", 13314 Style); 13315 verifyFormat("typedef union Foo\n" 13316 "{\n" 13317 " A,\n" 13318 "} Foo_t;", 13319 Style); 13320 verifyFormat("namespace Foo\n" 13321 "{\n" 13322 "void Bar();\n" 13323 "};", 13324 Style); 13325 } 13326 13327 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13328 // Elaborate type variable declarations. 13329 verifyFormat("struct foo a = {bar};\nint n;"); 13330 verifyFormat("class foo a = {bar};\nint n;"); 13331 verifyFormat("union foo a = {bar};\nint n;"); 13332 13333 // Elaborate types inside function definitions. 13334 verifyFormat("struct foo f() {}\nint n;"); 13335 verifyFormat("class foo f() {}\nint n;"); 13336 verifyFormat("union foo f() {}\nint n;"); 13337 13338 // Templates. 13339 verifyFormat("template <class X> void f() {}\nint n;"); 13340 verifyFormat("template <struct X> void f() {}\nint n;"); 13341 verifyFormat("template <union X> void f() {}\nint n;"); 13342 13343 // Actual definitions... 13344 verifyFormat("struct {\n} n;"); 13345 verifyFormat( 13346 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13347 verifyFormat("union Z {\n int n;\n} x;"); 13348 verifyFormat("class MACRO Z {\n} n;"); 13349 verifyFormat("class MACRO(X) Z {\n} n;"); 13350 verifyFormat("class __attribute__(X) Z {\n} n;"); 13351 verifyFormat("class __declspec(X) Z {\n} n;"); 13352 verifyFormat("class A##B##C {\n} n;"); 13353 verifyFormat("class alignas(16) Z {\n} n;"); 13354 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13355 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13356 13357 // Redefinition from nested context: 13358 verifyFormat("class A::B::C {\n} n;"); 13359 13360 // Template definitions. 13361 verifyFormat( 13362 "template <typename F>\n" 13363 "Matcher(const Matcher<F> &Other,\n" 13364 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13365 " !is_same<F, T>::value>::type * = 0)\n" 13366 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13367 13368 // FIXME: This is still incorrectly handled at the formatter side. 13369 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13370 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13371 13372 // FIXME: 13373 // This now gets parsed incorrectly as class definition. 13374 // verifyFormat("class A<int> f() {\n}\nint n;"); 13375 13376 // Elaborate types where incorrectly parsing the structural element would 13377 // break the indent. 13378 verifyFormat("if (true)\n" 13379 " class X x;\n" 13380 "else\n" 13381 " f();\n"); 13382 13383 // This is simply incomplete. Formatting is not important, but must not crash. 13384 verifyFormat("class A:"); 13385 } 13386 13387 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13388 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13389 format("#error Leave all white!!!!! space* alone!\n")); 13390 EXPECT_EQ( 13391 "#warning Leave all white!!!!! space* alone!\n", 13392 format("#warning Leave all white!!!!! space* alone!\n")); 13393 EXPECT_EQ("#error 1", format(" # error 1")); 13394 EXPECT_EQ("#warning 1", format(" # warning 1")); 13395 } 13396 13397 TEST_F(FormatTest, FormatHashIfExpressions) { 13398 verifyFormat("#if AAAA && BBBB"); 13399 verifyFormat("#if (AAAA && BBBB)"); 13400 verifyFormat("#elif (AAAA && BBBB)"); 13401 // FIXME: Come up with a better indentation for #elif. 13402 verifyFormat( 13403 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13404 " defined(BBBBBBBB)\n" 13405 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13406 " defined(BBBBBBBB)\n" 13407 "#endif", 13408 getLLVMStyleWithColumns(65)); 13409 } 13410 13411 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13412 FormatStyle AllowsMergedIf = getGoogleStyle(); 13413 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13414 FormatStyle::SIS_WithoutElse; 13415 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13416 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13417 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13418 EXPECT_EQ("if (true) return 42;", 13419 format("if (true)\nreturn 42;", AllowsMergedIf)); 13420 FormatStyle ShortMergedIf = AllowsMergedIf; 13421 ShortMergedIf.ColumnLimit = 25; 13422 verifyFormat("#define A \\\n" 13423 " if (true) return 42;", 13424 ShortMergedIf); 13425 verifyFormat("#define A \\\n" 13426 " f(); \\\n" 13427 " if (true)\n" 13428 "#define B", 13429 ShortMergedIf); 13430 verifyFormat("#define A \\\n" 13431 " f(); \\\n" 13432 " if (true)\n" 13433 "g();", 13434 ShortMergedIf); 13435 verifyFormat("{\n" 13436 "#ifdef A\n" 13437 " // Comment\n" 13438 " if (true) continue;\n" 13439 "#endif\n" 13440 " // Comment\n" 13441 " if (true) continue;\n" 13442 "}", 13443 ShortMergedIf); 13444 ShortMergedIf.ColumnLimit = 33; 13445 verifyFormat("#define A \\\n" 13446 " if constexpr (true) return 42;", 13447 ShortMergedIf); 13448 verifyFormat("#define A \\\n" 13449 " if CONSTEXPR (true) return 42;", 13450 ShortMergedIf); 13451 ShortMergedIf.ColumnLimit = 29; 13452 verifyFormat("#define A \\\n" 13453 " if (aaaaaaaaaa) return 1; \\\n" 13454 " return 2;", 13455 ShortMergedIf); 13456 ShortMergedIf.ColumnLimit = 28; 13457 verifyFormat("#define A \\\n" 13458 " if (aaaaaaaaaa) \\\n" 13459 " return 1; \\\n" 13460 " return 2;", 13461 ShortMergedIf); 13462 verifyFormat("#define A \\\n" 13463 " if constexpr (aaaaaaa) \\\n" 13464 " return 1; \\\n" 13465 " return 2;", 13466 ShortMergedIf); 13467 verifyFormat("#define A \\\n" 13468 " if CONSTEXPR (aaaaaaa) \\\n" 13469 " return 1; \\\n" 13470 " return 2;", 13471 ShortMergedIf); 13472 13473 verifyFormat("//\n" 13474 "#define a \\\n" 13475 " if \\\n" 13476 " 0", 13477 getChromiumStyle(FormatStyle::LK_Cpp)); 13478 } 13479 13480 TEST_F(FormatTest, FormatStarDependingOnContext) { 13481 verifyFormat("void f(int *a);"); 13482 verifyFormat("void f() { f(fint * b); }"); 13483 verifyFormat("class A {\n void f(int *a);\n};"); 13484 verifyFormat("class A {\n int *a;\n};"); 13485 verifyFormat("namespace a {\n" 13486 "namespace b {\n" 13487 "class A {\n" 13488 " void f() {}\n" 13489 " int *a;\n" 13490 "};\n" 13491 "} // namespace b\n" 13492 "} // namespace a"); 13493 } 13494 13495 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13496 verifyFormat("while"); 13497 verifyFormat("operator"); 13498 } 13499 13500 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13501 // This code would be painfully slow to format if we didn't skip it. 13502 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 13503 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13504 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13505 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13506 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13507 "A(1, 1)\n" 13508 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13509 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13510 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13511 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13512 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13513 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13514 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13515 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13516 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13517 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13518 // Deeply nested part is untouched, rest is formatted. 13519 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13520 format(std::string("int i;\n") + Code + "int j;\n", 13521 getLLVMStyle(), SC_ExpectIncomplete)); 13522 } 13523 13524 //===----------------------------------------------------------------------===// 13525 // Objective-C tests. 13526 //===----------------------------------------------------------------------===// 13527 13528 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13529 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13530 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13531 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13532 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13533 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13534 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13535 format("-(NSInteger)Method3:(id)anObject;")); 13536 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13537 format("-(NSInteger)Method4:(id)anObject;")); 13538 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13539 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13540 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13541 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13542 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13543 "forAllCells:(BOOL)flag;", 13544 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13545 "forAllCells:(BOOL)flag;")); 13546 13547 // Very long objectiveC method declaration. 13548 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13549 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13550 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13551 " inRange:(NSRange)range\n" 13552 " outRange:(NSRange)out_range\n" 13553 " outRange1:(NSRange)out_range1\n" 13554 " outRange2:(NSRange)out_range2\n" 13555 " outRange3:(NSRange)out_range3\n" 13556 " outRange4:(NSRange)out_range4\n" 13557 " outRange5:(NSRange)out_range5\n" 13558 " outRange6:(NSRange)out_range6\n" 13559 " outRange7:(NSRange)out_range7\n" 13560 " outRange8:(NSRange)out_range8\n" 13561 " outRange9:(NSRange)out_range9;"); 13562 13563 // When the function name has to be wrapped. 13564 FormatStyle Style = getLLVMStyle(); 13565 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13566 // and always indents instead. 13567 Style.IndentWrappedFunctionNames = false; 13568 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13569 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13570 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13571 "}", 13572 Style); 13573 Style.IndentWrappedFunctionNames = true; 13574 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13575 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13576 " anotherName:(NSString)dddddddddddddd {\n" 13577 "}", 13578 Style); 13579 13580 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13581 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13582 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13583 // protocol lists (but not for template classes): 13584 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13585 13586 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13587 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13588 13589 // If there's no return type (very rare in practice!), LLVM and Google style 13590 // agree. 13591 verifyFormat("- foo;"); 13592 verifyFormat("- foo:(int)f;"); 13593 verifyGoogleFormat("- foo:(int)foo;"); 13594 } 13595 13596 TEST_F(FormatTest, BreaksStringLiterals) { 13597 EXPECT_EQ("\"some text \"\n" 13598 "\"other\";", 13599 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13600 EXPECT_EQ("\"some text \"\n" 13601 "\"other\";", 13602 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13603 EXPECT_EQ( 13604 "#define A \\\n" 13605 " \"some \" \\\n" 13606 " \"text \" \\\n" 13607 " \"other\";", 13608 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13609 EXPECT_EQ( 13610 "#define A \\\n" 13611 " \"so \" \\\n" 13612 " \"text \" \\\n" 13613 " \"other\";", 13614 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13615 13616 EXPECT_EQ("\"some text\"", 13617 format("\"some text\"", getLLVMStyleWithColumns(1))); 13618 EXPECT_EQ("\"some text\"", 13619 format("\"some text\"", getLLVMStyleWithColumns(11))); 13620 EXPECT_EQ("\"some \"\n" 13621 "\"text\"", 13622 format("\"some text\"", getLLVMStyleWithColumns(10))); 13623 EXPECT_EQ("\"some \"\n" 13624 "\"text\"", 13625 format("\"some text\"", getLLVMStyleWithColumns(7))); 13626 EXPECT_EQ("\"some\"\n" 13627 "\" tex\"\n" 13628 "\"t\"", 13629 format("\"some text\"", getLLVMStyleWithColumns(6))); 13630 EXPECT_EQ("\"some\"\n" 13631 "\" tex\"\n" 13632 "\" and\"", 13633 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13634 EXPECT_EQ("\"some\"\n" 13635 "\"/tex\"\n" 13636 "\"/and\"", 13637 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13638 13639 EXPECT_EQ("variable =\n" 13640 " \"long string \"\n" 13641 " \"literal\";", 13642 format("variable = \"long string literal\";", 13643 getLLVMStyleWithColumns(20))); 13644 13645 EXPECT_EQ("variable = f(\n" 13646 " \"long string \"\n" 13647 " \"literal\",\n" 13648 " short,\n" 13649 " loooooooooooooooooooong);", 13650 format("variable = f(\"long string literal\", short, " 13651 "loooooooooooooooooooong);", 13652 getLLVMStyleWithColumns(20))); 13653 13654 EXPECT_EQ( 13655 "f(g(\"long string \"\n" 13656 " \"literal\"),\n" 13657 " b);", 13658 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13659 EXPECT_EQ("f(g(\"long string \"\n" 13660 " \"literal\",\n" 13661 " a),\n" 13662 " b);", 13663 format("f(g(\"long string literal\", a), b);", 13664 getLLVMStyleWithColumns(20))); 13665 EXPECT_EQ( 13666 "f(\"one two\".split(\n" 13667 " variable));", 13668 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13669 EXPECT_EQ("f(\"one two three four five six \"\n" 13670 " \"seven\".split(\n" 13671 " really_looooong_variable));", 13672 format("f(\"one two three four five six seven\"." 13673 "split(really_looooong_variable));", 13674 getLLVMStyleWithColumns(33))); 13675 13676 EXPECT_EQ("f(\"some \"\n" 13677 " \"text\",\n" 13678 " other);", 13679 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13680 13681 // Only break as a last resort. 13682 verifyFormat( 13683 "aaaaaaaaaaaaaaaaaaaa(\n" 13684 " aaaaaaaaaaaaaaaaaaaa,\n" 13685 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13686 13687 EXPECT_EQ("\"splitmea\"\n" 13688 "\"trandomp\"\n" 13689 "\"oint\"", 13690 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13691 13692 EXPECT_EQ("\"split/\"\n" 13693 "\"pathat/\"\n" 13694 "\"slashes\"", 13695 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13696 13697 EXPECT_EQ("\"split/\"\n" 13698 "\"pathat/\"\n" 13699 "\"slashes\"", 13700 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13701 EXPECT_EQ("\"split at \"\n" 13702 "\"spaces/at/\"\n" 13703 "\"slashes.at.any$\"\n" 13704 "\"non-alphanumeric%\"\n" 13705 "\"1111111111characte\"\n" 13706 "\"rs\"", 13707 format("\"split at " 13708 "spaces/at/" 13709 "slashes.at." 13710 "any$non-" 13711 "alphanumeric%" 13712 "1111111111characte" 13713 "rs\"", 13714 getLLVMStyleWithColumns(20))); 13715 13716 // Verify that splitting the strings understands 13717 // Style::AlwaysBreakBeforeMultilineStrings. 13718 EXPECT_EQ("aaaaaaaaaaaa(\n" 13719 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13720 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13721 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13722 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13723 "aaaaaaaaaaaaaaaaaaaaaa\");", 13724 getGoogleStyle())); 13725 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13726 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13727 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13728 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13729 "aaaaaaaaaaaaaaaaaaaaaa\";", 13730 getGoogleStyle())); 13731 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13732 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13733 format("llvm::outs() << " 13734 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13735 "aaaaaaaaaaaaaaaaaaa\";")); 13736 EXPECT_EQ("ffff(\n" 13737 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13738 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13739 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13740 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13741 getGoogleStyle())); 13742 13743 FormatStyle Style = getLLVMStyleWithColumns(12); 13744 Style.BreakStringLiterals = false; 13745 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13746 13747 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13748 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13749 EXPECT_EQ("#define A \\\n" 13750 " \"some \" \\\n" 13751 " \"text \" \\\n" 13752 " \"other\";", 13753 format("#define A \"some text other\";", AlignLeft)); 13754 } 13755 13756 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13757 EXPECT_EQ("C a = \"some more \"\n" 13758 " \"text\";", 13759 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13760 } 13761 13762 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13763 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13764 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13765 EXPECT_EQ("int i = a(b());", 13766 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13767 } 13768 13769 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13770 EXPECT_EQ( 13771 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13772 "(\n" 13773 " \"x\t\");", 13774 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13775 "aaaaaaa(" 13776 "\"x\t\");")); 13777 } 13778 13779 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13780 EXPECT_EQ( 13781 "u8\"utf8 string \"\n" 13782 "u8\"literal\";", 13783 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13784 EXPECT_EQ( 13785 "u\"utf16 string \"\n" 13786 "u\"literal\";", 13787 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13788 EXPECT_EQ( 13789 "U\"utf32 string \"\n" 13790 "U\"literal\";", 13791 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13792 EXPECT_EQ("L\"wide string \"\n" 13793 "L\"literal\";", 13794 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13795 EXPECT_EQ("@\"NSString \"\n" 13796 "@\"literal\";", 13797 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13798 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13799 13800 // This input makes clang-format try to split the incomplete unicode escape 13801 // sequence, which used to lead to a crasher. 13802 verifyNoCrash( 13803 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13804 getLLVMStyleWithColumns(60)); 13805 } 13806 13807 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13808 FormatStyle Style = getGoogleStyleWithColumns(15); 13809 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13810 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13811 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13812 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13813 EXPECT_EQ("u8R\"x(raw literal)x\";", 13814 format("u8R\"x(raw literal)x\";", Style)); 13815 } 13816 13817 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13818 FormatStyle Style = getLLVMStyleWithColumns(20); 13819 EXPECT_EQ( 13820 "_T(\"aaaaaaaaaaaaaa\")\n" 13821 "_T(\"aaaaaaaaaaaaaa\")\n" 13822 "_T(\"aaaaaaaaaaaa\")", 13823 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13824 EXPECT_EQ("f(x,\n" 13825 " _T(\"aaaaaaaaaaaa\")\n" 13826 " _T(\"aaa\"),\n" 13827 " z);", 13828 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13829 13830 // FIXME: Handle embedded spaces in one iteration. 13831 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13832 // "_T(\"aaaaaaaaaaaaa\")\n" 13833 // "_T(\"aaaaaaaaaaaaa\")\n" 13834 // "_T(\"a\")", 13835 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13836 // getLLVMStyleWithColumns(20))); 13837 EXPECT_EQ( 13838 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13839 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13840 EXPECT_EQ("f(\n" 13841 "#if !TEST\n" 13842 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13843 "#endif\n" 13844 ");", 13845 format("f(\n" 13846 "#if !TEST\n" 13847 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13848 "#endif\n" 13849 ");")); 13850 EXPECT_EQ("f(\n" 13851 "\n" 13852 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13853 format("f(\n" 13854 "\n" 13855 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13856 // Regression test for accessing tokens past the end of a vector in the 13857 // TokenLexer. 13858 verifyNoCrash(R"(_T( 13859 " 13860 ) 13861 )"); 13862 } 13863 13864 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13865 // In a function call with two operands, the second can be broken with no line 13866 // break before it. 13867 EXPECT_EQ( 13868 "func(a, \"long long \"\n" 13869 " \"long long\");", 13870 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13871 // In a function call with three operands, the second must be broken with a 13872 // line break before it. 13873 EXPECT_EQ("func(a,\n" 13874 " \"long long long \"\n" 13875 " \"long\",\n" 13876 " c);", 13877 format("func(a, \"long long long long\", c);", 13878 getLLVMStyleWithColumns(24))); 13879 // In a function call with three operands, the third must be broken with a 13880 // line break before it. 13881 EXPECT_EQ("func(a, b,\n" 13882 " \"long long long \"\n" 13883 " \"long\");", 13884 format("func(a, b, \"long long long long\");", 13885 getLLVMStyleWithColumns(24))); 13886 // In a function call with three operands, both the second and the third must 13887 // be broken with a line break before them. 13888 EXPECT_EQ("func(a,\n" 13889 " \"long long long \"\n" 13890 " \"long\",\n" 13891 " \"long long long \"\n" 13892 " \"long\");", 13893 format("func(a, \"long long long long\", \"long long long long\");", 13894 getLLVMStyleWithColumns(24))); 13895 // In a chain of << with two operands, the second can be broken with no line 13896 // break before it. 13897 EXPECT_EQ("a << \"line line \"\n" 13898 " \"line\";", 13899 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13900 // In a chain of << with three operands, the second can be broken with no line 13901 // break before it. 13902 EXPECT_EQ( 13903 "abcde << \"line \"\n" 13904 " \"line line\"\n" 13905 " << c;", 13906 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13907 // In a chain of << with three operands, the third must be broken with a line 13908 // break before it. 13909 EXPECT_EQ( 13910 "a << b\n" 13911 " << \"line line \"\n" 13912 " \"line\";", 13913 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13914 // In a chain of << with three operands, the second can be broken with no line 13915 // break before it and the third must be broken with a line break before it. 13916 EXPECT_EQ("abcd << \"line line \"\n" 13917 " \"line\"\n" 13918 " << \"line line \"\n" 13919 " \"line\";", 13920 format("abcd << \"line line line\" << \"line line line\";", 13921 getLLVMStyleWithColumns(20))); 13922 // In a chain of binary operators with two operands, the second can be broken 13923 // with no line break before it. 13924 EXPECT_EQ( 13925 "abcd + \"line line \"\n" 13926 " \"line line\";", 13927 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13928 // In a chain of binary operators with three operands, the second must be 13929 // broken with a line break before it. 13930 EXPECT_EQ("abcd +\n" 13931 " \"line line \"\n" 13932 " \"line line\" +\n" 13933 " e;", 13934 format("abcd + \"line line line line\" + e;", 13935 getLLVMStyleWithColumns(20))); 13936 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13937 // the first must be broken with a line break before it. 13938 FormatStyle Style = getLLVMStyleWithColumns(25); 13939 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13940 EXPECT_EQ("someFunction(\n" 13941 " \"long long long \"\n" 13942 " \"long\",\n" 13943 " a);", 13944 format("someFunction(\"long long long long\", a);", Style)); 13945 } 13946 13947 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13948 EXPECT_EQ( 13949 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13950 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13951 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13952 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13953 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13954 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13955 } 13956 13957 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13958 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13959 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13960 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13961 "multiline raw string literal xxxxxxxxxxxxxx\n" 13962 ")x\",\n" 13963 " a),\n" 13964 " b);", 13965 format("fffffffffff(g(R\"x(\n" 13966 "multiline raw string literal xxxxxxxxxxxxxx\n" 13967 ")x\", a), b);", 13968 getGoogleStyleWithColumns(20))); 13969 EXPECT_EQ("fffffffffff(\n" 13970 " g(R\"x(qqq\n" 13971 "multiline raw string literal xxxxxxxxxxxxxx\n" 13972 ")x\",\n" 13973 " a),\n" 13974 " b);", 13975 format("fffffffffff(g(R\"x(qqq\n" 13976 "multiline raw string literal xxxxxxxxxxxxxx\n" 13977 ")x\", a), b);", 13978 getGoogleStyleWithColumns(20))); 13979 13980 EXPECT_EQ("fffffffffff(R\"x(\n" 13981 "multiline raw string literal xxxxxxxxxxxxxx\n" 13982 ")x\");", 13983 format("fffffffffff(R\"x(\n" 13984 "multiline raw string literal xxxxxxxxxxxxxx\n" 13985 ")x\");", 13986 getGoogleStyleWithColumns(20))); 13987 EXPECT_EQ("fffffffffff(R\"x(\n" 13988 "multiline raw string literal xxxxxxxxxxxxxx\n" 13989 ")x\" + bbbbbb);", 13990 format("fffffffffff(R\"x(\n" 13991 "multiline raw string literal xxxxxxxxxxxxxx\n" 13992 ")x\" + bbbbbb);", 13993 getGoogleStyleWithColumns(20))); 13994 EXPECT_EQ("fffffffffff(\n" 13995 " R\"x(\n" 13996 "multiline raw string literal xxxxxxxxxxxxxx\n" 13997 ")x\" +\n" 13998 " bbbbbb);", 13999 format("fffffffffff(\n" 14000 " R\"x(\n" 14001 "multiline raw string literal xxxxxxxxxxxxxx\n" 14002 ")x\" + bbbbbb);", 14003 getGoogleStyleWithColumns(20))); 14004 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 14005 format("fffffffffff(\n" 14006 " R\"(single line raw string)\" + bbbbbb);")); 14007 } 14008 14009 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 14010 verifyFormat("string a = \"unterminated;"); 14011 EXPECT_EQ("function(\"unterminated,\n" 14012 " OtherParameter);", 14013 format("function( \"unterminated,\n" 14014 " OtherParameter);")); 14015 } 14016 14017 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 14018 FormatStyle Style = getLLVMStyle(); 14019 Style.Standard = FormatStyle::LS_Cpp03; 14020 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 14021 format("#define x(_a) printf(\"foo\"_a);", Style)); 14022 } 14023 14024 TEST_F(FormatTest, CppLexVersion) { 14025 FormatStyle Style = getLLVMStyle(); 14026 // Formatting of x * y differs if x is a type. 14027 verifyFormat("void foo() { MACRO(a * b); }", Style); 14028 verifyFormat("void foo() { MACRO(int *b); }", Style); 14029 14030 // LLVM style uses latest lexer. 14031 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 14032 Style.Standard = FormatStyle::LS_Cpp17; 14033 // But in c++17, char8_t isn't a keyword. 14034 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 14035 } 14036 14037 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 14038 14039 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 14040 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 14041 " \"ddeeefff\");", 14042 format("someFunction(\"aaabbbcccdddeeefff\");", 14043 getLLVMStyleWithColumns(25))); 14044 EXPECT_EQ("someFunction1234567890(\n" 14045 " \"aaabbbcccdddeeefff\");", 14046 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14047 getLLVMStyleWithColumns(26))); 14048 EXPECT_EQ("someFunction1234567890(\n" 14049 " \"aaabbbcccdddeeeff\"\n" 14050 " \"f\");", 14051 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14052 getLLVMStyleWithColumns(25))); 14053 EXPECT_EQ("someFunction1234567890(\n" 14054 " \"aaabbbcccdddeeeff\"\n" 14055 " \"f\");", 14056 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14057 getLLVMStyleWithColumns(24))); 14058 EXPECT_EQ("someFunction(\n" 14059 " \"aaabbbcc ddde \"\n" 14060 " \"efff\");", 14061 format("someFunction(\"aaabbbcc ddde efff\");", 14062 getLLVMStyleWithColumns(25))); 14063 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 14064 " \"ddeeefff\");", 14065 format("someFunction(\"aaabbbccc ddeeefff\");", 14066 getLLVMStyleWithColumns(25))); 14067 EXPECT_EQ("someFunction1234567890(\n" 14068 " \"aaabb \"\n" 14069 " \"cccdddeeefff\");", 14070 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 14071 getLLVMStyleWithColumns(25))); 14072 EXPECT_EQ("#define A \\\n" 14073 " string s = \\\n" 14074 " \"123456789\" \\\n" 14075 " \"0\"; \\\n" 14076 " int i;", 14077 format("#define A string s = \"1234567890\"; int i;", 14078 getLLVMStyleWithColumns(20))); 14079 EXPECT_EQ("someFunction(\n" 14080 " \"aaabbbcc \"\n" 14081 " \"dddeeefff\");", 14082 format("someFunction(\"aaabbbcc dddeeefff\");", 14083 getLLVMStyleWithColumns(25))); 14084 } 14085 14086 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 14087 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 14088 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 14089 EXPECT_EQ("\"test\"\n" 14090 "\"\\n\"", 14091 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 14092 EXPECT_EQ("\"tes\\\\\"\n" 14093 "\"n\"", 14094 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 14095 EXPECT_EQ("\"\\\\\\\\\"\n" 14096 "\"\\n\"", 14097 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 14098 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 14099 EXPECT_EQ("\"\\uff01\"\n" 14100 "\"test\"", 14101 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14102 EXPECT_EQ("\"\\Uff01ff02\"", 14103 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14104 EXPECT_EQ("\"\\x000000000001\"\n" 14105 "\"next\"", 14106 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14107 EXPECT_EQ("\"\\x000000000001next\"", 14108 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14109 EXPECT_EQ("\"\\x000000000001\"", 14110 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14111 EXPECT_EQ("\"test\"\n" 14112 "\"\\000000\"\n" 14113 "\"000001\"", 14114 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14115 EXPECT_EQ("\"test\\000\"\n" 14116 "\"00000000\"\n" 14117 "\"1\"", 14118 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14119 } 14120 14121 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14122 verifyFormat("void f() {\n" 14123 " return g() {}\n" 14124 " void h() {}"); 14125 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14126 "g();\n" 14127 "}"); 14128 } 14129 14130 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14131 verifyFormat( 14132 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14133 } 14134 14135 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14136 verifyFormat("class X {\n" 14137 " void f() {\n" 14138 " }\n" 14139 "};", 14140 getLLVMStyleWithColumns(12)); 14141 } 14142 14143 TEST_F(FormatTest, ConfigurableIndentWidth) { 14144 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14145 EightIndent.IndentWidth = 8; 14146 EightIndent.ContinuationIndentWidth = 8; 14147 verifyFormat("void f() {\n" 14148 " someFunction();\n" 14149 " if (true) {\n" 14150 " f();\n" 14151 " }\n" 14152 "}", 14153 EightIndent); 14154 verifyFormat("class X {\n" 14155 " void f() {\n" 14156 " }\n" 14157 "};", 14158 EightIndent); 14159 verifyFormat("int x[] = {\n" 14160 " call(),\n" 14161 " call()};", 14162 EightIndent); 14163 } 14164 14165 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14166 verifyFormat("double\n" 14167 "f();", 14168 getLLVMStyleWithColumns(8)); 14169 } 14170 14171 TEST_F(FormatTest, ConfigurableUseOfTab) { 14172 FormatStyle Tab = getLLVMStyleWithColumns(42); 14173 Tab.IndentWidth = 8; 14174 Tab.UseTab = FormatStyle::UT_Always; 14175 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14176 14177 EXPECT_EQ("if (aaaaaaaa && // q\n" 14178 " bb)\t\t// w\n" 14179 "\t;", 14180 format("if (aaaaaaaa &&// q\n" 14181 "bb)// w\n" 14182 ";", 14183 Tab)); 14184 EXPECT_EQ("if (aaa && bbb) // w\n" 14185 "\t;", 14186 format("if(aaa&&bbb)// w\n" 14187 ";", 14188 Tab)); 14189 14190 verifyFormat("class X {\n" 14191 "\tvoid f() {\n" 14192 "\t\tsomeFunction(parameter1,\n" 14193 "\t\t\t parameter2);\n" 14194 "\t}\n" 14195 "};", 14196 Tab); 14197 verifyFormat("#define A \\\n" 14198 "\tvoid f() { \\\n" 14199 "\t\tsomeFunction( \\\n" 14200 "\t\t parameter1, \\\n" 14201 "\t\t parameter2); \\\n" 14202 "\t}", 14203 Tab); 14204 verifyFormat("int a;\t // x\n" 14205 "int bbbbbbbb; // x\n", 14206 Tab); 14207 14208 FormatStyle TabAlignment = Tab; 14209 TabAlignment.AlignConsecutiveDeclarations.Enabled = true; 14210 TabAlignment.PointerAlignment = FormatStyle::PAS_Left; 14211 verifyFormat("unsigned long long big;\n" 14212 "char*\t\t ptr;", 14213 TabAlignment); 14214 TabAlignment.PointerAlignment = FormatStyle::PAS_Middle; 14215 verifyFormat("unsigned long long big;\n" 14216 "char *\t\t ptr;", 14217 TabAlignment); 14218 TabAlignment.PointerAlignment = FormatStyle::PAS_Right; 14219 verifyFormat("unsigned long long big;\n" 14220 "char\t\t *ptr;", 14221 TabAlignment); 14222 14223 Tab.TabWidth = 4; 14224 Tab.IndentWidth = 8; 14225 verifyFormat("class TabWidth4Indent8 {\n" 14226 "\t\tvoid f() {\n" 14227 "\t\t\t\tsomeFunction(parameter1,\n" 14228 "\t\t\t\t\t\t\t parameter2);\n" 14229 "\t\t}\n" 14230 "};", 14231 Tab); 14232 14233 Tab.TabWidth = 4; 14234 Tab.IndentWidth = 4; 14235 verifyFormat("class TabWidth4Indent4 {\n" 14236 "\tvoid f() {\n" 14237 "\t\tsomeFunction(parameter1,\n" 14238 "\t\t\t\t\t parameter2);\n" 14239 "\t}\n" 14240 "};", 14241 Tab); 14242 14243 Tab.TabWidth = 8; 14244 Tab.IndentWidth = 4; 14245 verifyFormat("class TabWidth8Indent4 {\n" 14246 " void f() {\n" 14247 "\tsomeFunction(parameter1,\n" 14248 "\t\t parameter2);\n" 14249 " }\n" 14250 "};", 14251 Tab); 14252 14253 Tab.TabWidth = 8; 14254 Tab.IndentWidth = 8; 14255 EXPECT_EQ("/*\n" 14256 "\t a\t\tcomment\n" 14257 "\t in multiple lines\n" 14258 " */", 14259 format(" /*\t \t \n" 14260 " \t \t a\t\tcomment\t \t\n" 14261 " \t \t in multiple lines\t\n" 14262 " \t */", 14263 Tab)); 14264 14265 TabAlignment.UseTab = FormatStyle::UT_ForIndentation; 14266 TabAlignment.PointerAlignment = FormatStyle::PAS_Left; 14267 verifyFormat("void f() {\n" 14268 "\tunsigned long long big;\n" 14269 "\tchar* ptr;\n" 14270 "}", 14271 TabAlignment); 14272 TabAlignment.PointerAlignment = FormatStyle::PAS_Middle; 14273 verifyFormat("void f() {\n" 14274 "\tunsigned long long big;\n" 14275 "\tchar * ptr;\n" 14276 "}", 14277 TabAlignment); 14278 TabAlignment.PointerAlignment = FormatStyle::PAS_Right; 14279 verifyFormat("void f() {\n" 14280 "\tunsigned long long big;\n" 14281 "\tchar *ptr;\n" 14282 "}", 14283 TabAlignment); 14284 14285 Tab.UseTab = FormatStyle::UT_ForIndentation; 14286 verifyFormat("{\n" 14287 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14288 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14289 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14290 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14291 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14292 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14293 "};", 14294 Tab); 14295 verifyFormat("enum AA {\n" 14296 "\ta1, // Force multiple lines\n" 14297 "\ta2,\n" 14298 "\ta3\n" 14299 "};", 14300 Tab); 14301 EXPECT_EQ("if (aaaaaaaa && // q\n" 14302 " bb) // w\n" 14303 "\t;", 14304 format("if (aaaaaaaa &&// q\n" 14305 "bb)// w\n" 14306 ";", 14307 Tab)); 14308 verifyFormat("class X {\n" 14309 "\tvoid f() {\n" 14310 "\t\tsomeFunction(parameter1,\n" 14311 "\t\t parameter2);\n" 14312 "\t}\n" 14313 "};", 14314 Tab); 14315 verifyFormat("{\n" 14316 "\tQ(\n" 14317 "\t {\n" 14318 "\t\t int a;\n" 14319 "\t\t someFunction(aaaaaaaa,\n" 14320 "\t\t bbbbbbb);\n" 14321 "\t },\n" 14322 "\t p);\n" 14323 "}", 14324 Tab); 14325 EXPECT_EQ("{\n" 14326 "\t/* aaaa\n" 14327 "\t bbbb */\n" 14328 "}", 14329 format("{\n" 14330 "/* aaaa\n" 14331 " bbbb */\n" 14332 "}", 14333 Tab)); 14334 EXPECT_EQ("{\n" 14335 "\t/*\n" 14336 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14337 "\t bbbbbbbbbbbbb\n" 14338 "\t*/\n" 14339 "}", 14340 format("{\n" 14341 "/*\n" 14342 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14343 "*/\n" 14344 "}", 14345 Tab)); 14346 EXPECT_EQ("{\n" 14347 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14348 "\t// bbbbbbbbbbbbb\n" 14349 "}", 14350 format("{\n" 14351 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14352 "}", 14353 Tab)); 14354 EXPECT_EQ("{\n" 14355 "\t/*\n" 14356 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14357 "\t bbbbbbbbbbbbb\n" 14358 "\t*/\n" 14359 "}", 14360 format("{\n" 14361 "\t/*\n" 14362 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14363 "\t*/\n" 14364 "}", 14365 Tab)); 14366 EXPECT_EQ("{\n" 14367 "\t/*\n" 14368 "\n" 14369 "\t*/\n" 14370 "}", 14371 format("{\n" 14372 "\t/*\n" 14373 "\n" 14374 "\t*/\n" 14375 "}", 14376 Tab)); 14377 EXPECT_EQ("{\n" 14378 "\t/*\n" 14379 " asdf\n" 14380 "\t*/\n" 14381 "}", 14382 format("{\n" 14383 "\t/*\n" 14384 " asdf\n" 14385 "\t*/\n" 14386 "}", 14387 Tab)); 14388 14389 verifyFormat("void f() {\n" 14390 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14391 "\t : bbbbbbbbbbbbbbbbbb\n" 14392 "}", 14393 Tab); 14394 FormatStyle TabNoBreak = Tab; 14395 TabNoBreak.BreakBeforeTernaryOperators = false; 14396 verifyFormat("void f() {\n" 14397 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14398 "\t bbbbbbbbbbbbbbbbbb\n" 14399 "}", 14400 TabNoBreak); 14401 verifyFormat("void f() {\n" 14402 "\treturn true ?\n" 14403 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14404 "\t bbbbbbbbbbbbbbbbbbbb\n" 14405 "}", 14406 TabNoBreak); 14407 14408 Tab.UseTab = FormatStyle::UT_Never; 14409 EXPECT_EQ("/*\n" 14410 " a\t\tcomment\n" 14411 " in multiple lines\n" 14412 " */", 14413 format(" /*\t \t \n" 14414 " \t \t a\t\tcomment\t \t\n" 14415 " \t \t in multiple lines\t\n" 14416 " \t */", 14417 Tab)); 14418 EXPECT_EQ("/* some\n" 14419 " comment */", 14420 format(" \t \t /* some\n" 14421 " \t \t comment */", 14422 Tab)); 14423 EXPECT_EQ("int a; /* some\n" 14424 " comment */", 14425 format(" \t \t int a; /* some\n" 14426 " \t \t comment */", 14427 Tab)); 14428 14429 EXPECT_EQ("int a; /* some\n" 14430 "comment */", 14431 format(" \t \t int\ta; /* some\n" 14432 " \t \t comment */", 14433 Tab)); 14434 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14435 " comment */", 14436 format(" \t \t f(\"\t\t\"); /* some\n" 14437 " \t \t comment */", 14438 Tab)); 14439 EXPECT_EQ("{\n" 14440 " /*\n" 14441 " * Comment\n" 14442 " */\n" 14443 " int i;\n" 14444 "}", 14445 format("{\n" 14446 "\t/*\n" 14447 "\t * Comment\n" 14448 "\t */\n" 14449 "\t int i;\n" 14450 "}", 14451 Tab)); 14452 14453 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14454 Tab.TabWidth = 8; 14455 Tab.IndentWidth = 8; 14456 EXPECT_EQ("if (aaaaaaaa && // q\n" 14457 " bb) // w\n" 14458 "\t;", 14459 format("if (aaaaaaaa &&// q\n" 14460 "bb)// w\n" 14461 ";", 14462 Tab)); 14463 EXPECT_EQ("if (aaa && bbb) // w\n" 14464 "\t;", 14465 format("if(aaa&&bbb)// w\n" 14466 ";", 14467 Tab)); 14468 verifyFormat("class X {\n" 14469 "\tvoid f() {\n" 14470 "\t\tsomeFunction(parameter1,\n" 14471 "\t\t\t parameter2);\n" 14472 "\t}\n" 14473 "};", 14474 Tab); 14475 verifyFormat("#define A \\\n" 14476 "\tvoid f() { \\\n" 14477 "\t\tsomeFunction( \\\n" 14478 "\t\t parameter1, \\\n" 14479 "\t\t parameter2); \\\n" 14480 "\t}", 14481 Tab); 14482 Tab.TabWidth = 4; 14483 Tab.IndentWidth = 8; 14484 verifyFormat("class TabWidth4Indent8 {\n" 14485 "\t\tvoid f() {\n" 14486 "\t\t\t\tsomeFunction(parameter1,\n" 14487 "\t\t\t\t\t\t\t parameter2);\n" 14488 "\t\t}\n" 14489 "};", 14490 Tab); 14491 Tab.TabWidth = 4; 14492 Tab.IndentWidth = 4; 14493 verifyFormat("class TabWidth4Indent4 {\n" 14494 "\tvoid f() {\n" 14495 "\t\tsomeFunction(parameter1,\n" 14496 "\t\t\t\t\t parameter2);\n" 14497 "\t}\n" 14498 "};", 14499 Tab); 14500 Tab.TabWidth = 8; 14501 Tab.IndentWidth = 4; 14502 verifyFormat("class TabWidth8Indent4 {\n" 14503 " void f() {\n" 14504 "\tsomeFunction(parameter1,\n" 14505 "\t\t parameter2);\n" 14506 " }\n" 14507 "};", 14508 Tab); 14509 Tab.TabWidth = 8; 14510 Tab.IndentWidth = 8; 14511 EXPECT_EQ("/*\n" 14512 "\t a\t\tcomment\n" 14513 "\t in multiple lines\n" 14514 " */", 14515 format(" /*\t \t \n" 14516 " \t \t a\t\tcomment\t \t\n" 14517 " \t \t in multiple lines\t\n" 14518 " \t */", 14519 Tab)); 14520 verifyFormat("{\n" 14521 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14522 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14523 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14524 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14525 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14526 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14527 "};", 14528 Tab); 14529 verifyFormat("enum AA {\n" 14530 "\ta1, // Force multiple lines\n" 14531 "\ta2,\n" 14532 "\ta3\n" 14533 "};", 14534 Tab); 14535 EXPECT_EQ("if (aaaaaaaa && // q\n" 14536 " bb) // w\n" 14537 "\t;", 14538 format("if (aaaaaaaa &&// q\n" 14539 "bb)// w\n" 14540 ";", 14541 Tab)); 14542 verifyFormat("class X {\n" 14543 "\tvoid f() {\n" 14544 "\t\tsomeFunction(parameter1,\n" 14545 "\t\t\t parameter2);\n" 14546 "\t}\n" 14547 "};", 14548 Tab); 14549 verifyFormat("{\n" 14550 "\tQ(\n" 14551 "\t {\n" 14552 "\t\t int a;\n" 14553 "\t\t someFunction(aaaaaaaa,\n" 14554 "\t\t\t\t bbbbbbb);\n" 14555 "\t },\n" 14556 "\t p);\n" 14557 "}", 14558 Tab); 14559 EXPECT_EQ("{\n" 14560 "\t/* aaaa\n" 14561 "\t bbbb */\n" 14562 "}", 14563 format("{\n" 14564 "/* aaaa\n" 14565 " bbbb */\n" 14566 "}", 14567 Tab)); 14568 EXPECT_EQ("{\n" 14569 "\t/*\n" 14570 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14571 "\t bbbbbbbbbbbbb\n" 14572 "\t*/\n" 14573 "}", 14574 format("{\n" 14575 "/*\n" 14576 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14577 "*/\n" 14578 "}", 14579 Tab)); 14580 EXPECT_EQ("{\n" 14581 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14582 "\t// bbbbbbbbbbbbb\n" 14583 "}", 14584 format("{\n" 14585 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14586 "}", 14587 Tab)); 14588 EXPECT_EQ("{\n" 14589 "\t/*\n" 14590 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14591 "\t bbbbbbbbbbbbb\n" 14592 "\t*/\n" 14593 "}", 14594 format("{\n" 14595 "\t/*\n" 14596 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14597 "\t*/\n" 14598 "}", 14599 Tab)); 14600 EXPECT_EQ("{\n" 14601 "\t/*\n" 14602 "\n" 14603 "\t*/\n" 14604 "}", 14605 format("{\n" 14606 "\t/*\n" 14607 "\n" 14608 "\t*/\n" 14609 "}", 14610 Tab)); 14611 EXPECT_EQ("{\n" 14612 "\t/*\n" 14613 " asdf\n" 14614 "\t*/\n" 14615 "}", 14616 format("{\n" 14617 "\t/*\n" 14618 " asdf\n" 14619 "\t*/\n" 14620 "}", 14621 Tab)); 14622 EXPECT_EQ("/* some\n" 14623 " comment */", 14624 format(" \t \t /* some\n" 14625 " \t \t comment */", 14626 Tab)); 14627 EXPECT_EQ("int a; /* some\n" 14628 " comment */", 14629 format(" \t \t int a; /* some\n" 14630 " \t \t comment */", 14631 Tab)); 14632 EXPECT_EQ("int a; /* some\n" 14633 "comment */", 14634 format(" \t \t int\ta; /* some\n" 14635 " \t \t comment */", 14636 Tab)); 14637 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14638 " comment */", 14639 format(" \t \t f(\"\t\t\"); /* some\n" 14640 " \t \t comment */", 14641 Tab)); 14642 EXPECT_EQ("{\n" 14643 "\t/*\n" 14644 "\t * Comment\n" 14645 "\t */\n" 14646 "\tint i;\n" 14647 "}", 14648 format("{\n" 14649 "\t/*\n" 14650 "\t * Comment\n" 14651 "\t */\n" 14652 "\t int i;\n" 14653 "}", 14654 Tab)); 14655 Tab.TabWidth = 2; 14656 Tab.IndentWidth = 2; 14657 EXPECT_EQ("{\n" 14658 "\t/* aaaa\n" 14659 "\t\t bbbb */\n" 14660 "}", 14661 format("{\n" 14662 "/* aaaa\n" 14663 "\t bbbb */\n" 14664 "}", 14665 Tab)); 14666 EXPECT_EQ("{\n" 14667 "\t/*\n" 14668 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14669 "\t\tbbbbbbbbbbbbb\n" 14670 "\t*/\n" 14671 "}", 14672 format("{\n" 14673 "/*\n" 14674 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14675 "*/\n" 14676 "}", 14677 Tab)); 14678 Tab.AlignConsecutiveAssignments.Enabled = true; 14679 Tab.AlignConsecutiveDeclarations.Enabled = true; 14680 Tab.TabWidth = 4; 14681 Tab.IndentWidth = 4; 14682 verifyFormat("class Assign {\n" 14683 "\tvoid f() {\n" 14684 "\t\tint x = 123;\n" 14685 "\t\tint random = 4;\n" 14686 "\t\tstd::string alphabet =\n" 14687 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14688 "\t}\n" 14689 "};", 14690 Tab); 14691 14692 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14693 Tab.TabWidth = 8; 14694 Tab.IndentWidth = 8; 14695 EXPECT_EQ("if (aaaaaaaa && // q\n" 14696 " bb) // w\n" 14697 "\t;", 14698 format("if (aaaaaaaa &&// q\n" 14699 "bb)// w\n" 14700 ";", 14701 Tab)); 14702 EXPECT_EQ("if (aaa && bbb) // w\n" 14703 "\t;", 14704 format("if(aaa&&bbb)// w\n" 14705 ";", 14706 Tab)); 14707 verifyFormat("class X {\n" 14708 "\tvoid f() {\n" 14709 "\t\tsomeFunction(parameter1,\n" 14710 "\t\t parameter2);\n" 14711 "\t}\n" 14712 "};", 14713 Tab); 14714 verifyFormat("#define A \\\n" 14715 "\tvoid f() { \\\n" 14716 "\t\tsomeFunction( \\\n" 14717 "\t\t parameter1, \\\n" 14718 "\t\t parameter2); \\\n" 14719 "\t}", 14720 Tab); 14721 Tab.TabWidth = 4; 14722 Tab.IndentWidth = 8; 14723 verifyFormat("class TabWidth4Indent8 {\n" 14724 "\t\tvoid f() {\n" 14725 "\t\t\t\tsomeFunction(parameter1,\n" 14726 "\t\t\t\t parameter2);\n" 14727 "\t\t}\n" 14728 "};", 14729 Tab); 14730 Tab.TabWidth = 4; 14731 Tab.IndentWidth = 4; 14732 verifyFormat("class TabWidth4Indent4 {\n" 14733 "\tvoid f() {\n" 14734 "\t\tsomeFunction(parameter1,\n" 14735 "\t\t parameter2);\n" 14736 "\t}\n" 14737 "};", 14738 Tab); 14739 Tab.TabWidth = 8; 14740 Tab.IndentWidth = 4; 14741 verifyFormat("class TabWidth8Indent4 {\n" 14742 " void f() {\n" 14743 "\tsomeFunction(parameter1,\n" 14744 "\t parameter2);\n" 14745 " }\n" 14746 "};", 14747 Tab); 14748 Tab.TabWidth = 8; 14749 Tab.IndentWidth = 8; 14750 EXPECT_EQ("/*\n" 14751 " a\t\tcomment\n" 14752 " in multiple lines\n" 14753 " */", 14754 format(" /*\t \t \n" 14755 " \t \t a\t\tcomment\t \t\n" 14756 " \t \t in multiple lines\t\n" 14757 " \t */", 14758 Tab)); 14759 verifyFormat("{\n" 14760 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14761 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14762 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14763 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14764 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14765 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14766 "};", 14767 Tab); 14768 verifyFormat("enum AA {\n" 14769 "\ta1, // Force multiple lines\n" 14770 "\ta2,\n" 14771 "\ta3\n" 14772 "};", 14773 Tab); 14774 EXPECT_EQ("if (aaaaaaaa && // q\n" 14775 " bb) // w\n" 14776 "\t;", 14777 format("if (aaaaaaaa &&// q\n" 14778 "bb)// w\n" 14779 ";", 14780 Tab)); 14781 verifyFormat("class X {\n" 14782 "\tvoid f() {\n" 14783 "\t\tsomeFunction(parameter1,\n" 14784 "\t\t parameter2);\n" 14785 "\t}\n" 14786 "};", 14787 Tab); 14788 verifyFormat("{\n" 14789 "\tQ(\n" 14790 "\t {\n" 14791 "\t\t int a;\n" 14792 "\t\t someFunction(aaaaaaaa,\n" 14793 "\t\t bbbbbbb);\n" 14794 "\t },\n" 14795 "\t p);\n" 14796 "}", 14797 Tab); 14798 EXPECT_EQ("{\n" 14799 "\t/* aaaa\n" 14800 "\t bbbb */\n" 14801 "}", 14802 format("{\n" 14803 "/* aaaa\n" 14804 " bbbb */\n" 14805 "}", 14806 Tab)); 14807 EXPECT_EQ("{\n" 14808 "\t/*\n" 14809 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14810 "\t bbbbbbbbbbbbb\n" 14811 "\t*/\n" 14812 "}", 14813 format("{\n" 14814 "/*\n" 14815 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14816 "*/\n" 14817 "}", 14818 Tab)); 14819 EXPECT_EQ("{\n" 14820 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14821 "\t// bbbbbbbbbbbbb\n" 14822 "}", 14823 format("{\n" 14824 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14825 "}", 14826 Tab)); 14827 EXPECT_EQ("{\n" 14828 "\t/*\n" 14829 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14830 "\t bbbbbbbbbbbbb\n" 14831 "\t*/\n" 14832 "}", 14833 format("{\n" 14834 "\t/*\n" 14835 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14836 "\t*/\n" 14837 "}", 14838 Tab)); 14839 EXPECT_EQ("{\n" 14840 "\t/*\n" 14841 "\n" 14842 "\t*/\n" 14843 "}", 14844 format("{\n" 14845 "\t/*\n" 14846 "\n" 14847 "\t*/\n" 14848 "}", 14849 Tab)); 14850 EXPECT_EQ("{\n" 14851 "\t/*\n" 14852 " asdf\n" 14853 "\t*/\n" 14854 "}", 14855 format("{\n" 14856 "\t/*\n" 14857 " asdf\n" 14858 "\t*/\n" 14859 "}", 14860 Tab)); 14861 EXPECT_EQ("/* some\n" 14862 " comment */", 14863 format(" \t \t /* some\n" 14864 " \t \t comment */", 14865 Tab)); 14866 EXPECT_EQ("int a; /* some\n" 14867 " comment */", 14868 format(" \t \t int a; /* some\n" 14869 " \t \t comment */", 14870 Tab)); 14871 EXPECT_EQ("int a; /* some\n" 14872 "comment */", 14873 format(" \t \t int\ta; /* some\n" 14874 " \t \t comment */", 14875 Tab)); 14876 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14877 " comment */", 14878 format(" \t \t f(\"\t\t\"); /* some\n" 14879 " \t \t comment */", 14880 Tab)); 14881 EXPECT_EQ("{\n" 14882 "\t/*\n" 14883 "\t * Comment\n" 14884 "\t */\n" 14885 "\tint i;\n" 14886 "}", 14887 format("{\n" 14888 "\t/*\n" 14889 "\t * Comment\n" 14890 "\t */\n" 14891 "\t int i;\n" 14892 "}", 14893 Tab)); 14894 Tab.TabWidth = 2; 14895 Tab.IndentWidth = 2; 14896 EXPECT_EQ("{\n" 14897 "\t/* aaaa\n" 14898 "\t bbbb */\n" 14899 "}", 14900 format("{\n" 14901 "/* aaaa\n" 14902 " bbbb */\n" 14903 "}", 14904 Tab)); 14905 EXPECT_EQ("{\n" 14906 "\t/*\n" 14907 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14908 "\t bbbbbbbbbbbbb\n" 14909 "\t*/\n" 14910 "}", 14911 format("{\n" 14912 "/*\n" 14913 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14914 "*/\n" 14915 "}", 14916 Tab)); 14917 Tab.AlignConsecutiveAssignments.Enabled = true; 14918 Tab.AlignConsecutiveDeclarations.Enabled = true; 14919 Tab.TabWidth = 4; 14920 Tab.IndentWidth = 4; 14921 verifyFormat("class Assign {\n" 14922 "\tvoid f() {\n" 14923 "\t\tint x = 123;\n" 14924 "\t\tint random = 4;\n" 14925 "\t\tstd::string alphabet =\n" 14926 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14927 "\t}\n" 14928 "};", 14929 Tab); 14930 Tab.AlignOperands = FormatStyle::OAS_Align; 14931 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14932 " cccccccccccccccccccc;", 14933 Tab); 14934 // no alignment 14935 verifyFormat("int aaaaaaaaaa =\n" 14936 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14937 Tab); 14938 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14939 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14940 " : 333333333333333;", 14941 Tab); 14942 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14943 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14944 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14945 " + cccccccccccccccccccc;", 14946 Tab); 14947 } 14948 14949 TEST_F(FormatTest, ZeroTabWidth) { 14950 FormatStyle Tab = getLLVMStyleWithColumns(42); 14951 Tab.IndentWidth = 8; 14952 Tab.UseTab = FormatStyle::UT_Never; 14953 Tab.TabWidth = 0; 14954 EXPECT_EQ("void a(){\n" 14955 " // line starts with '\t'\n" 14956 "};", 14957 format("void a(){\n" 14958 "\t// line starts with '\t'\n" 14959 "};", 14960 Tab)); 14961 14962 EXPECT_EQ("void a(){\n" 14963 " // line starts with '\t'\n" 14964 "};", 14965 format("void a(){\n" 14966 "\t\t// line starts with '\t'\n" 14967 "};", 14968 Tab)); 14969 14970 Tab.UseTab = FormatStyle::UT_ForIndentation; 14971 EXPECT_EQ("void a(){\n" 14972 " // line starts with '\t'\n" 14973 "};", 14974 format("void a(){\n" 14975 "\t// line starts with '\t'\n" 14976 "};", 14977 Tab)); 14978 14979 EXPECT_EQ("void a(){\n" 14980 " // line starts with '\t'\n" 14981 "};", 14982 format("void a(){\n" 14983 "\t\t// line starts with '\t'\n" 14984 "};", 14985 Tab)); 14986 14987 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14988 EXPECT_EQ("void a(){\n" 14989 " // line starts with '\t'\n" 14990 "};", 14991 format("void a(){\n" 14992 "\t// line starts with '\t'\n" 14993 "};", 14994 Tab)); 14995 14996 EXPECT_EQ("void a(){\n" 14997 " // line starts with '\t'\n" 14998 "};", 14999 format("void a(){\n" 15000 "\t\t// line starts with '\t'\n" 15001 "};", 15002 Tab)); 15003 15004 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 15005 EXPECT_EQ("void a(){\n" 15006 " // line starts with '\t'\n" 15007 "};", 15008 format("void a(){\n" 15009 "\t// line starts with '\t'\n" 15010 "};", 15011 Tab)); 15012 15013 EXPECT_EQ("void a(){\n" 15014 " // line starts with '\t'\n" 15015 "};", 15016 format("void a(){\n" 15017 "\t\t// line starts with '\t'\n" 15018 "};", 15019 Tab)); 15020 15021 Tab.UseTab = FormatStyle::UT_Always; 15022 EXPECT_EQ("void a(){\n" 15023 "// line starts with '\t'\n" 15024 "};", 15025 format("void a(){\n" 15026 "\t// line starts with '\t'\n" 15027 "};", 15028 Tab)); 15029 15030 EXPECT_EQ("void a(){\n" 15031 "// line starts with '\t'\n" 15032 "};", 15033 format("void a(){\n" 15034 "\t\t// line starts with '\t'\n" 15035 "};", 15036 Tab)); 15037 } 15038 15039 TEST_F(FormatTest, CalculatesOriginalColumn) { 15040 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15041 "q\"; /* some\n" 15042 " comment */", 15043 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15044 "q\"; /* some\n" 15045 " comment */", 15046 getLLVMStyle())); 15047 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 15048 "/* some\n" 15049 " comment */", 15050 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 15051 " /* some\n" 15052 " comment */", 15053 getLLVMStyle())); 15054 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15055 "qqq\n" 15056 "/* some\n" 15057 " comment */", 15058 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15059 "qqq\n" 15060 " /* some\n" 15061 " comment */", 15062 getLLVMStyle())); 15063 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15064 "wwww; /* some\n" 15065 " comment */", 15066 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15067 "wwww; /* some\n" 15068 " comment */", 15069 getLLVMStyle())); 15070 } 15071 15072 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 15073 FormatStyle NoSpace = getLLVMStyle(); 15074 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 15075 15076 verifyFormat("while(true)\n" 15077 " continue;", 15078 NoSpace); 15079 verifyFormat("for(;;)\n" 15080 " continue;", 15081 NoSpace); 15082 verifyFormat("if(true)\n" 15083 " f();\n" 15084 "else if(true)\n" 15085 " f();", 15086 NoSpace); 15087 verifyFormat("do {\n" 15088 " do_something();\n" 15089 "} while(something());", 15090 NoSpace); 15091 verifyFormat("switch(x) {\n" 15092 "default:\n" 15093 " break;\n" 15094 "}", 15095 NoSpace); 15096 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 15097 verifyFormat("size_t x = sizeof(x);", NoSpace); 15098 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 15099 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 15100 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 15101 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 15102 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 15103 verifyFormat("alignas(128) char a[128];", NoSpace); 15104 verifyFormat("size_t x = alignof(MyType);", NoSpace); 15105 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 15106 verifyFormat("int f() throw(Deprecated);", NoSpace); 15107 verifyFormat("typedef void (*cb)(int);", NoSpace); 15108 verifyFormat("T A::operator()();", NoSpace); 15109 verifyFormat("X A::operator++(T);", NoSpace); 15110 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 15111 15112 FormatStyle Space = getLLVMStyle(); 15113 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 15114 15115 verifyFormat("int f ();", Space); 15116 verifyFormat("void f (int a, T b) {\n" 15117 " while (true)\n" 15118 " continue;\n" 15119 "}", 15120 Space); 15121 verifyFormat("if (true)\n" 15122 " f ();\n" 15123 "else if (true)\n" 15124 " f ();", 15125 Space); 15126 verifyFormat("do {\n" 15127 " do_something ();\n" 15128 "} while (something ());", 15129 Space); 15130 verifyFormat("switch (x) {\n" 15131 "default:\n" 15132 " break;\n" 15133 "}", 15134 Space); 15135 verifyFormat("A::A () : a (1) {}", Space); 15136 verifyFormat("void f () __attribute__ ((asdf));", Space); 15137 verifyFormat("*(&a + 1);\n" 15138 "&((&a)[1]);\n" 15139 "a[(b + c) * d];\n" 15140 "(((a + 1) * 2) + 3) * 4;", 15141 Space); 15142 verifyFormat("#define A(x) x", Space); 15143 verifyFormat("#define A (x) x", Space); 15144 verifyFormat("#if defined(x)\n" 15145 "#endif", 15146 Space); 15147 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15148 verifyFormat("size_t x = sizeof (x);", Space); 15149 verifyFormat("auto f (int x) -> decltype (x);", Space); 15150 verifyFormat("auto f (int x) -> typeof (x);", Space); 15151 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15152 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15153 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15154 verifyFormat("alignas (128) char a[128];", Space); 15155 verifyFormat("size_t x = alignof (MyType);", Space); 15156 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15157 verifyFormat("int f () throw (Deprecated);", Space); 15158 verifyFormat("typedef void (*cb) (int);", Space); 15159 // FIXME these tests regressed behaviour. 15160 // verifyFormat("T A::operator() ();", Space); 15161 // verifyFormat("X A::operator++ (T);", Space); 15162 verifyFormat("auto lambda = [] () { return 0; };", Space); 15163 verifyFormat("int x = int (y);", Space); 15164 verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space); 15165 verifyFormat("__builtin_LINE ()", Space); 15166 verifyFormat("__builtin_UNKNOWN ()", Space); 15167 15168 FormatStyle SomeSpace = getLLVMStyle(); 15169 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15170 15171 verifyFormat("[]() -> float {}", SomeSpace); 15172 verifyFormat("[] (auto foo) {}", SomeSpace); 15173 verifyFormat("[foo]() -> int {}", SomeSpace); 15174 verifyFormat("int f();", SomeSpace); 15175 verifyFormat("void f (int a, T b) {\n" 15176 " while (true)\n" 15177 " continue;\n" 15178 "}", 15179 SomeSpace); 15180 verifyFormat("if (true)\n" 15181 " f();\n" 15182 "else if (true)\n" 15183 " f();", 15184 SomeSpace); 15185 verifyFormat("do {\n" 15186 " do_something();\n" 15187 "} while (something());", 15188 SomeSpace); 15189 verifyFormat("switch (x) {\n" 15190 "default:\n" 15191 " break;\n" 15192 "}", 15193 SomeSpace); 15194 verifyFormat("A::A() : a (1) {}", SomeSpace); 15195 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15196 verifyFormat("*(&a + 1);\n" 15197 "&((&a)[1]);\n" 15198 "a[(b + c) * d];\n" 15199 "(((a + 1) * 2) + 3) * 4;", 15200 SomeSpace); 15201 verifyFormat("#define A(x) x", SomeSpace); 15202 verifyFormat("#define A (x) x", SomeSpace); 15203 verifyFormat("#if defined(x)\n" 15204 "#endif", 15205 SomeSpace); 15206 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15207 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15208 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15209 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15210 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15211 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15212 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15213 verifyFormat("alignas (128) char a[128];", SomeSpace); 15214 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15215 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15216 SomeSpace); 15217 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15218 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15219 verifyFormat("T A::operator()();", SomeSpace); 15220 // FIXME these tests regressed behaviour. 15221 // verifyFormat("X A::operator++ (T);", SomeSpace); 15222 verifyFormat("int x = int (y);", SomeSpace); 15223 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15224 15225 FormatStyle SpaceControlStatements = getLLVMStyle(); 15226 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15227 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15228 15229 verifyFormat("while (true)\n" 15230 " continue;", 15231 SpaceControlStatements); 15232 verifyFormat("if (true)\n" 15233 " f();\n" 15234 "else if (true)\n" 15235 " f();", 15236 SpaceControlStatements); 15237 verifyFormat("for (;;) {\n" 15238 " do_something();\n" 15239 "}", 15240 SpaceControlStatements); 15241 verifyFormat("do {\n" 15242 " do_something();\n" 15243 "} while (something());", 15244 SpaceControlStatements); 15245 verifyFormat("switch (x) {\n" 15246 "default:\n" 15247 " break;\n" 15248 "}", 15249 SpaceControlStatements); 15250 15251 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15252 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15253 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15254 15255 verifyFormat("int f ();", SpaceFuncDecl); 15256 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15257 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15258 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15259 verifyFormat("#define A(x) x", SpaceFuncDecl); 15260 verifyFormat("#define A (x) x", SpaceFuncDecl); 15261 verifyFormat("#if defined(x)\n" 15262 "#endif", 15263 SpaceFuncDecl); 15264 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15265 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15266 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15267 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15268 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15269 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15270 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15271 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15272 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15273 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15274 SpaceFuncDecl); 15275 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15276 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15277 // FIXME these tests regressed behaviour. 15278 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15279 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15280 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15281 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15282 verifyFormat("int x = int(y);", SpaceFuncDecl); 15283 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15284 SpaceFuncDecl); 15285 15286 FormatStyle SpaceFuncDef = getLLVMStyle(); 15287 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15288 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15289 15290 verifyFormat("int f();", SpaceFuncDef); 15291 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15292 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15293 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15294 verifyFormat("#define A(x) x", SpaceFuncDef); 15295 verifyFormat("#define A (x) x", SpaceFuncDef); 15296 verifyFormat("#if defined(x)\n" 15297 "#endif", 15298 SpaceFuncDef); 15299 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15300 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15301 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15302 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15303 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15304 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15305 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15306 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15307 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15308 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15309 SpaceFuncDef); 15310 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15311 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15312 verifyFormat("T A::operator()();", SpaceFuncDef); 15313 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15314 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15315 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15316 verifyFormat("int x = int(y);", SpaceFuncDef); 15317 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15318 SpaceFuncDef); 15319 15320 FormatStyle SpaceIfMacros = getLLVMStyle(); 15321 SpaceIfMacros.IfMacros.clear(); 15322 SpaceIfMacros.IfMacros.push_back("MYIF"); 15323 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15324 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15325 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15326 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15327 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15328 15329 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15330 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15331 FormatStyle::SBS_Never); 15332 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15333 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15334 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15335 verifyFormat("for (;;) {\n" 15336 "}", 15337 SpaceForeachMacros); 15338 verifyFormat("foreach (Item *item, itemlist) {\n" 15339 "}", 15340 SpaceForeachMacros); 15341 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15342 "}", 15343 SpaceForeachMacros); 15344 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15345 "}", 15346 SpaceForeachMacros); 15347 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15348 15349 FormatStyle SomeSpace2 = getLLVMStyle(); 15350 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15351 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15352 verifyFormat("[]() -> float {}", SomeSpace2); 15353 verifyFormat("[] (auto foo) {}", SomeSpace2); 15354 verifyFormat("[foo]() -> int {}", SomeSpace2); 15355 verifyFormat("int f();", SomeSpace2); 15356 verifyFormat("void f (int a, T b) {\n" 15357 " while (true)\n" 15358 " continue;\n" 15359 "}", 15360 SomeSpace2); 15361 verifyFormat("if (true)\n" 15362 " f();\n" 15363 "else if (true)\n" 15364 " f();", 15365 SomeSpace2); 15366 verifyFormat("do {\n" 15367 " do_something();\n" 15368 "} while (something());", 15369 SomeSpace2); 15370 verifyFormat("switch (x) {\n" 15371 "default:\n" 15372 " break;\n" 15373 "}", 15374 SomeSpace2); 15375 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15376 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15377 verifyFormat("*(&a + 1);\n" 15378 "&((&a)[1]);\n" 15379 "a[(b + c) * d];\n" 15380 "(((a + 1) * 2) + 3) * 4;", 15381 SomeSpace2); 15382 verifyFormat("#define A(x) x", SomeSpace2); 15383 verifyFormat("#define A (x) x", SomeSpace2); 15384 verifyFormat("#if defined(x)\n" 15385 "#endif", 15386 SomeSpace2); 15387 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15388 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15389 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15390 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15391 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15392 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15393 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15394 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15395 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15396 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15397 SomeSpace2); 15398 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15399 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15400 verifyFormat("T A::operator()();", SomeSpace2); 15401 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15402 verifyFormat("int x = int (y);", SomeSpace2); 15403 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15404 15405 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15406 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15407 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15408 .AfterOverloadedOperator = true; 15409 15410 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15411 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15412 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15413 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15414 15415 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15416 .AfterOverloadedOperator = false; 15417 15418 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15419 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15420 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15421 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15422 15423 auto SpaceAfterRequires = getLLVMStyle(); 15424 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15425 EXPECT_FALSE( 15426 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15427 EXPECT_FALSE( 15428 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15429 verifyFormat("void f(auto x)\n" 15430 " requires requires(int i) { x + i; }\n" 15431 "{}", 15432 SpaceAfterRequires); 15433 verifyFormat("void f(auto x)\n" 15434 " requires(requires(int i) { x + i; })\n" 15435 "{}", 15436 SpaceAfterRequires); 15437 verifyFormat("if (requires(int i) { x + i; })\n" 15438 " return;", 15439 SpaceAfterRequires); 15440 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15441 verifyFormat("template <typename T>\n" 15442 " requires(Foo<T>)\n" 15443 "class Bar;", 15444 SpaceAfterRequires); 15445 15446 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15447 verifyFormat("void f(auto x)\n" 15448 " requires requires(int i) { x + i; }\n" 15449 "{}", 15450 SpaceAfterRequires); 15451 verifyFormat("void f(auto x)\n" 15452 " requires (requires(int i) { x + i; })\n" 15453 "{}", 15454 SpaceAfterRequires); 15455 verifyFormat("if (requires(int i) { x + i; })\n" 15456 " return;", 15457 SpaceAfterRequires); 15458 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15459 verifyFormat("template <typename T>\n" 15460 " requires (Foo<T>)\n" 15461 "class Bar;", 15462 SpaceAfterRequires); 15463 15464 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15465 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15466 verifyFormat("void f(auto x)\n" 15467 " requires requires (int i) { x + i; }\n" 15468 "{}", 15469 SpaceAfterRequires); 15470 verifyFormat("void f(auto x)\n" 15471 " requires(requires (int i) { x + i; })\n" 15472 "{}", 15473 SpaceAfterRequires); 15474 verifyFormat("if (requires (int i) { x + i; })\n" 15475 " return;", 15476 SpaceAfterRequires); 15477 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15478 verifyFormat("template <typename T>\n" 15479 " requires(Foo<T>)\n" 15480 "class Bar;", 15481 SpaceAfterRequires); 15482 15483 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15484 verifyFormat("void f(auto x)\n" 15485 " requires requires (int i) { x + i; }\n" 15486 "{}", 15487 SpaceAfterRequires); 15488 verifyFormat("void f(auto x)\n" 15489 " requires (requires (int i) { x + i; })\n" 15490 "{}", 15491 SpaceAfterRequires); 15492 verifyFormat("if (requires (int i) { x + i; })\n" 15493 " return;", 15494 SpaceAfterRequires); 15495 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15496 verifyFormat("template <typename T>\n" 15497 " requires (Foo<T>)\n" 15498 "class Bar;", 15499 SpaceAfterRequires); 15500 } 15501 15502 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15503 FormatStyle Spaces = getLLVMStyle(); 15504 Spaces.SpaceAfterLogicalNot = true; 15505 15506 verifyFormat("bool x = ! y", Spaces); 15507 verifyFormat("if (! isFailure())", Spaces); 15508 verifyFormat("if (! (a && b))", Spaces); 15509 verifyFormat("\"Error!\"", Spaces); 15510 verifyFormat("! ! x", Spaces); 15511 } 15512 15513 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15514 FormatStyle Spaces = getLLVMStyle(); 15515 15516 Spaces.SpacesInParentheses = true; 15517 verifyFormat("do_something( ::globalVar );", Spaces); 15518 verifyFormat("call( x, y, z );", Spaces); 15519 verifyFormat("call();", Spaces); 15520 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15521 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15522 Spaces); 15523 verifyFormat("while ( (bool)1 )\n" 15524 " continue;", 15525 Spaces); 15526 verifyFormat("for ( ;; )\n" 15527 " continue;", 15528 Spaces); 15529 verifyFormat("if ( true )\n" 15530 " f();\n" 15531 "else if ( true )\n" 15532 " f();", 15533 Spaces); 15534 verifyFormat("do {\n" 15535 " do_something( (int)i );\n" 15536 "} while ( something() );", 15537 Spaces); 15538 verifyFormat("switch ( x ) {\n" 15539 "default:\n" 15540 " break;\n" 15541 "}", 15542 Spaces); 15543 15544 Spaces.SpacesInParentheses = false; 15545 Spaces.SpacesInCStyleCastParentheses = true; 15546 verifyFormat("Type *A = ( Type * )P;", Spaces); 15547 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15548 verifyFormat("x = ( int32 )y;", Spaces); 15549 verifyFormat("int a = ( int )(2.0f);", Spaces); 15550 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15551 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15552 verifyFormat("#define x (( int )-1)", Spaces); 15553 15554 // Run the first set of tests again with: 15555 Spaces.SpacesInParentheses = false; 15556 Spaces.SpaceInEmptyParentheses = true; 15557 Spaces.SpacesInCStyleCastParentheses = true; 15558 verifyFormat("call(x, y, z);", Spaces); 15559 verifyFormat("call( );", Spaces); 15560 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15561 verifyFormat("while (( bool )1)\n" 15562 " continue;", 15563 Spaces); 15564 verifyFormat("for (;;)\n" 15565 " continue;", 15566 Spaces); 15567 verifyFormat("if (true)\n" 15568 " f( );\n" 15569 "else if (true)\n" 15570 " f( );", 15571 Spaces); 15572 verifyFormat("do {\n" 15573 " do_something(( int )i);\n" 15574 "} while (something( ));", 15575 Spaces); 15576 verifyFormat("switch (x) {\n" 15577 "default:\n" 15578 " break;\n" 15579 "}", 15580 Spaces); 15581 15582 // Run the first set of tests again with: 15583 Spaces.SpaceAfterCStyleCast = true; 15584 verifyFormat("call(x, y, z);", Spaces); 15585 verifyFormat("call( );", Spaces); 15586 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15587 verifyFormat("while (( bool ) 1)\n" 15588 " continue;", 15589 Spaces); 15590 verifyFormat("for (;;)\n" 15591 " continue;", 15592 Spaces); 15593 verifyFormat("if (true)\n" 15594 " f( );\n" 15595 "else if (true)\n" 15596 " f( );", 15597 Spaces); 15598 verifyFormat("do {\n" 15599 " do_something(( int ) i);\n" 15600 "} while (something( ));", 15601 Spaces); 15602 verifyFormat("switch (x) {\n" 15603 "default:\n" 15604 " break;\n" 15605 "}", 15606 Spaces); 15607 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15608 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15609 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15610 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15611 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15612 15613 // Run subset of tests again with: 15614 Spaces.SpacesInCStyleCastParentheses = false; 15615 Spaces.SpaceAfterCStyleCast = true; 15616 verifyFormat("while ((bool) 1)\n" 15617 " continue;", 15618 Spaces); 15619 verifyFormat("do {\n" 15620 " do_something((int) i);\n" 15621 "} while (something( ));", 15622 Spaces); 15623 15624 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15625 verifyFormat("size_t idx = (size_t) a;", Spaces); 15626 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15627 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15628 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15629 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15630 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15631 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15632 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15633 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15634 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15635 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15636 Spaces.ColumnLimit = 80; 15637 Spaces.IndentWidth = 4; 15638 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15639 verifyFormat("void foo( ) {\n" 15640 " size_t foo = (*(function))(\n" 15641 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15642 "BarrrrrrrrrrrrLong,\n" 15643 " FoooooooooLooooong);\n" 15644 "}", 15645 Spaces); 15646 Spaces.SpaceAfterCStyleCast = false; 15647 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15648 verifyFormat("size_t idx = (size_t)a;", Spaces); 15649 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15650 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15651 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15652 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15653 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15654 15655 verifyFormat("void foo( ) {\n" 15656 " size_t foo = (*(function))(\n" 15657 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15658 "BarrrrrrrrrrrrLong,\n" 15659 " FoooooooooLooooong);\n" 15660 "}", 15661 Spaces); 15662 } 15663 15664 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15665 verifyFormat("int a[5];"); 15666 verifyFormat("a[3] += 42;"); 15667 15668 FormatStyle Spaces = getLLVMStyle(); 15669 Spaces.SpacesInSquareBrackets = true; 15670 // Not lambdas. 15671 verifyFormat("int a[ 5 ];", Spaces); 15672 verifyFormat("a[ 3 ] += 42;", Spaces); 15673 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15674 verifyFormat("double &operator[](int i) { return 0; }\n" 15675 "int i;", 15676 Spaces); 15677 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15678 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15679 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15680 // Lambdas. 15681 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15682 verifyFormat("return [ i, args... ] {};", Spaces); 15683 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15684 verifyFormat("int foo = [ = ]() {};", Spaces); 15685 verifyFormat("int foo = [ & ]() {};", Spaces); 15686 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15687 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15688 } 15689 15690 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15691 FormatStyle NoSpaceStyle = getLLVMStyle(); 15692 verifyFormat("int a[5];", NoSpaceStyle); 15693 verifyFormat("a[3] += 42;", NoSpaceStyle); 15694 15695 verifyFormat("int a[1];", NoSpaceStyle); 15696 verifyFormat("int 1 [a];", NoSpaceStyle); 15697 verifyFormat("int a[1][2];", NoSpaceStyle); 15698 verifyFormat("a[7] = 5;", NoSpaceStyle); 15699 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15700 verifyFormat("f([] {})", NoSpaceStyle); 15701 15702 FormatStyle Space = getLLVMStyle(); 15703 Space.SpaceBeforeSquareBrackets = true; 15704 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15705 verifyFormat("return [i, args...] {};", Space); 15706 15707 verifyFormat("int a [5];", Space); 15708 verifyFormat("a [3] += 42;", Space); 15709 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15710 verifyFormat("double &operator[](int i) { return 0; }\n" 15711 "int i;", 15712 Space); 15713 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15714 verifyFormat("int i = a [a][a]->f();", Space); 15715 verifyFormat("int i = (*b) [a]->f();", Space); 15716 15717 verifyFormat("int a [1];", Space); 15718 verifyFormat("int 1 [a];", Space); 15719 verifyFormat("int a [1][2];", Space); 15720 verifyFormat("a [7] = 5;", Space); 15721 verifyFormat("int a = (f()) [23];", Space); 15722 verifyFormat("f([] {})", Space); 15723 } 15724 15725 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15726 verifyFormat("int a = 5;"); 15727 verifyFormat("a += 42;"); 15728 verifyFormat("a or_eq 8;"); 15729 15730 FormatStyle Spaces = getLLVMStyle(); 15731 Spaces.SpaceBeforeAssignmentOperators = false; 15732 verifyFormat("int a= 5;", Spaces); 15733 verifyFormat("a+= 42;", Spaces); 15734 verifyFormat("a or_eq 8;", Spaces); 15735 } 15736 15737 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15738 verifyFormat("class Foo : public Bar {};"); 15739 verifyFormat("Foo::Foo() : foo(1) {}"); 15740 verifyFormat("for (auto a : b) {\n}"); 15741 verifyFormat("int x = a ? b : c;"); 15742 verifyFormat("{\n" 15743 "label0:\n" 15744 " int x = 0;\n" 15745 "}"); 15746 verifyFormat("switch (x) {\n" 15747 "case 1:\n" 15748 "default:\n" 15749 "}"); 15750 verifyFormat("switch (allBraces) {\n" 15751 "case 1: {\n" 15752 " break;\n" 15753 "}\n" 15754 "case 2: {\n" 15755 " [[fallthrough]];\n" 15756 "}\n" 15757 "default: {\n" 15758 " break;\n" 15759 "}\n" 15760 "}"); 15761 15762 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15763 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15764 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15765 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15766 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15767 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15768 verifyFormat("{\n" 15769 "label1:\n" 15770 " int x = 0;\n" 15771 "}", 15772 CtorInitializerStyle); 15773 verifyFormat("switch (x) {\n" 15774 "case 1:\n" 15775 "default:\n" 15776 "}", 15777 CtorInitializerStyle); 15778 verifyFormat("switch (allBraces) {\n" 15779 "case 1: {\n" 15780 " break;\n" 15781 "}\n" 15782 "case 2: {\n" 15783 " [[fallthrough]];\n" 15784 "}\n" 15785 "default: {\n" 15786 " break;\n" 15787 "}\n" 15788 "}", 15789 CtorInitializerStyle); 15790 CtorInitializerStyle.BreakConstructorInitializers = 15791 FormatStyle::BCIS_AfterColon; 15792 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15793 " aaaaaaaaaaaaaaaa(1),\n" 15794 " bbbbbbbbbbbbbbbb(2) {}", 15795 CtorInitializerStyle); 15796 CtorInitializerStyle.BreakConstructorInitializers = 15797 FormatStyle::BCIS_BeforeComma; 15798 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15799 " : aaaaaaaaaaaaaaaa(1)\n" 15800 " , bbbbbbbbbbbbbbbb(2) {}", 15801 CtorInitializerStyle); 15802 CtorInitializerStyle.BreakConstructorInitializers = 15803 FormatStyle::BCIS_BeforeColon; 15804 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15805 " : aaaaaaaaaaaaaaaa(1),\n" 15806 " bbbbbbbbbbbbbbbb(2) {}", 15807 CtorInitializerStyle); 15808 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15809 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15810 ": aaaaaaaaaaaaaaaa(1),\n" 15811 " bbbbbbbbbbbbbbbb(2) {}", 15812 CtorInitializerStyle); 15813 15814 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15815 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15816 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15817 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15818 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15819 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15820 verifyFormat("{\n" 15821 "label2:\n" 15822 " int x = 0;\n" 15823 "}", 15824 InheritanceStyle); 15825 verifyFormat("switch (x) {\n" 15826 "case 1:\n" 15827 "default:\n" 15828 "}", 15829 InheritanceStyle); 15830 verifyFormat("switch (allBraces) {\n" 15831 "case 1: {\n" 15832 " break;\n" 15833 "}\n" 15834 "case 2: {\n" 15835 " [[fallthrough]];\n" 15836 "}\n" 15837 "default: {\n" 15838 " break;\n" 15839 "}\n" 15840 "}", 15841 InheritanceStyle); 15842 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15843 verifyFormat("class Foooooooooooooooooooooo\n" 15844 " : public aaaaaaaaaaaaaaaaaa,\n" 15845 " public bbbbbbbbbbbbbbbbbb {\n" 15846 "}", 15847 InheritanceStyle); 15848 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15849 verifyFormat("class Foooooooooooooooooooooo:\n" 15850 " public aaaaaaaaaaaaaaaaaa,\n" 15851 " public bbbbbbbbbbbbbbbbbb {\n" 15852 "}", 15853 InheritanceStyle); 15854 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15855 verifyFormat("class Foooooooooooooooooooooo\n" 15856 " : public aaaaaaaaaaaaaaaaaa\n" 15857 " , public bbbbbbbbbbbbbbbbbb {\n" 15858 "}", 15859 InheritanceStyle); 15860 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15861 verifyFormat("class Foooooooooooooooooooooo\n" 15862 " : public aaaaaaaaaaaaaaaaaa,\n" 15863 " public bbbbbbbbbbbbbbbbbb {\n" 15864 "}", 15865 InheritanceStyle); 15866 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15867 verifyFormat("class Foooooooooooooooooooooo\n" 15868 ": public aaaaaaaaaaaaaaaaaa,\n" 15869 " public bbbbbbbbbbbbbbbbbb {}", 15870 InheritanceStyle); 15871 15872 FormatStyle ForLoopStyle = getLLVMStyle(); 15873 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15874 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15875 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15876 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15877 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15878 verifyFormat("{\n" 15879 "label2:\n" 15880 " int x = 0;\n" 15881 "}", 15882 ForLoopStyle); 15883 verifyFormat("switch (x) {\n" 15884 "case 1:\n" 15885 "default:\n" 15886 "}", 15887 ForLoopStyle); 15888 verifyFormat("switch (allBraces) {\n" 15889 "case 1: {\n" 15890 " break;\n" 15891 "}\n" 15892 "case 2: {\n" 15893 " [[fallthrough]];\n" 15894 "}\n" 15895 "default: {\n" 15896 " break;\n" 15897 "}\n" 15898 "}", 15899 ForLoopStyle); 15900 15901 FormatStyle CaseStyle = getLLVMStyle(); 15902 CaseStyle.SpaceBeforeCaseColon = true; 15903 verifyFormat("class Foo : public Bar {};", CaseStyle); 15904 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15905 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15906 verifyFormat("int x = a ? b : c;", CaseStyle); 15907 verifyFormat("switch (x) {\n" 15908 "case 1 :\n" 15909 "default :\n" 15910 "}", 15911 CaseStyle); 15912 verifyFormat("switch (allBraces) {\n" 15913 "case 1 : {\n" 15914 " break;\n" 15915 "}\n" 15916 "case 2 : {\n" 15917 " [[fallthrough]];\n" 15918 "}\n" 15919 "default : {\n" 15920 " break;\n" 15921 "}\n" 15922 "}", 15923 CaseStyle); 15924 15925 FormatStyle NoSpaceStyle = getLLVMStyle(); 15926 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15927 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15928 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15929 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15930 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15931 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15932 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15933 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15934 verifyFormat("{\n" 15935 "label3:\n" 15936 " int x = 0;\n" 15937 "}", 15938 NoSpaceStyle); 15939 verifyFormat("switch (x) {\n" 15940 "case 1:\n" 15941 "default:\n" 15942 "}", 15943 NoSpaceStyle); 15944 verifyFormat("switch (allBraces) {\n" 15945 "case 1: {\n" 15946 " break;\n" 15947 "}\n" 15948 "case 2: {\n" 15949 " [[fallthrough]];\n" 15950 "}\n" 15951 "default: {\n" 15952 " break;\n" 15953 "}\n" 15954 "}", 15955 NoSpaceStyle); 15956 15957 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15958 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15959 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15960 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15961 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15962 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15963 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15964 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15965 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15966 verifyFormat("{\n" 15967 "label3:\n" 15968 " int x = 0;\n" 15969 "}", 15970 InvertedSpaceStyle); 15971 verifyFormat("switch (x) {\n" 15972 "case 1 :\n" 15973 "case 2 : {\n" 15974 " break;\n" 15975 "}\n" 15976 "default :\n" 15977 " break;\n" 15978 "}", 15979 InvertedSpaceStyle); 15980 verifyFormat("switch (allBraces) {\n" 15981 "case 1 : {\n" 15982 " break;\n" 15983 "}\n" 15984 "case 2 : {\n" 15985 " [[fallthrough]];\n" 15986 "}\n" 15987 "default : {\n" 15988 " break;\n" 15989 "}\n" 15990 "}", 15991 InvertedSpaceStyle); 15992 } 15993 15994 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15995 FormatStyle Style = getLLVMStyle(); 15996 15997 Style.PointerAlignment = FormatStyle::PAS_Left; 15998 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15999 verifyFormat("void* const* x = NULL;", Style); 16000 16001 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 16002 do { \ 16003 Style.PointerAlignment = FormatStyle::Pointers; \ 16004 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 16005 verifyFormat(Code, Style); \ 16006 } while (false) 16007 16008 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 16009 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 16010 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 16011 16012 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 16013 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 16014 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 16015 16016 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 16017 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 16018 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 16019 16020 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 16021 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 16022 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 16023 16024 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 16025 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 16026 SAPQ_Default); 16027 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16028 SAPQ_Default); 16029 16030 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 16031 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 16032 SAPQ_Before); 16033 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16034 SAPQ_Before); 16035 16036 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 16037 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 16038 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16039 SAPQ_After); 16040 16041 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 16042 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 16043 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 16044 16045 #undef verifyQualifierSpaces 16046 16047 FormatStyle Spaces = getLLVMStyle(); 16048 Spaces.AttributeMacros.push_back("qualified"); 16049 Spaces.PointerAlignment = FormatStyle::PAS_Right; 16050 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 16051 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 16052 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 16053 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 16054 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 16055 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16056 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 16057 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 16058 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 16059 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 16060 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 16061 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16062 16063 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 16064 Spaces.PointerAlignment = FormatStyle::PAS_Left; 16065 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 16066 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 16067 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 16068 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 16069 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 16070 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16071 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 16072 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 16073 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 16074 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 16075 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 16076 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 16077 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16078 16079 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 16080 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 16081 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 16082 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 16083 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 16084 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 16085 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 16086 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16087 } 16088 16089 TEST_F(FormatTest, AlignConsecutiveMacros) { 16090 FormatStyle Style = getLLVMStyle(); 16091 Style.AlignConsecutiveAssignments.Enabled = true; 16092 Style.AlignConsecutiveDeclarations.Enabled = true; 16093 16094 verifyFormat("#define a 3\n" 16095 "#define bbbb 4\n" 16096 "#define ccc (5)", 16097 Style); 16098 16099 verifyFormat("#define f(x) (x * x)\n" 16100 "#define fff(x, y, z) (x * y + z)\n" 16101 "#define ffff(x, y) (x - y)", 16102 Style); 16103 16104 verifyFormat("#define foo(x, y) (x + y)\n" 16105 "#define bar (5, 6)(2 + 2)", 16106 Style); 16107 16108 verifyFormat("#define a 3\n" 16109 "#define bbbb 4\n" 16110 "#define ccc (5)\n" 16111 "#define f(x) (x * x)\n" 16112 "#define fff(x, y, z) (x * y + z)\n" 16113 "#define ffff(x, y) (x - y)", 16114 Style); 16115 16116 Style.AlignConsecutiveMacros.Enabled = true; 16117 verifyFormat("#define a 3\n" 16118 "#define bbbb 4\n" 16119 "#define ccc (5)", 16120 Style); 16121 16122 verifyFormat("#define true 1\n" 16123 "#define false 0", 16124 Style); 16125 16126 verifyFormat("#define f(x) (x * x)\n" 16127 "#define fff(x, y, z) (x * y + z)\n" 16128 "#define ffff(x, y) (x - y)", 16129 Style); 16130 16131 verifyFormat("#define foo(x, y) (x + y)\n" 16132 "#define bar (5, 6)(2 + 2)", 16133 Style); 16134 16135 verifyFormat("#define a 3\n" 16136 "#define bbbb 4\n" 16137 "#define ccc (5)\n" 16138 "#define f(x) (x * x)\n" 16139 "#define fff(x, y, z) (x * y + z)\n" 16140 "#define ffff(x, y) (x - y)", 16141 Style); 16142 16143 verifyFormat("#define a 5\n" 16144 "#define foo(x, y) (x + y)\n" 16145 "#define CCC (6)\n" 16146 "auto lambda = []() {\n" 16147 " auto ii = 0;\n" 16148 " float j = 0;\n" 16149 " return 0;\n" 16150 "};\n" 16151 "int i = 0;\n" 16152 "float i2 = 0;\n" 16153 "auto v = type{\n" 16154 " i = 1, //\n" 16155 " (i = 2), //\n" 16156 " i = 3 //\n" 16157 "};", 16158 Style); 16159 16160 Style.AlignConsecutiveMacros.Enabled = false; 16161 Style.ColumnLimit = 20; 16162 16163 verifyFormat("#define a \\\n" 16164 " \"aabbbbbbbbbbbb\"\n" 16165 "#define D \\\n" 16166 " \"aabbbbbbbbbbbb\" \\\n" 16167 " \"ccddeeeeeeeee\"\n" 16168 "#define B \\\n" 16169 " \"QQQQQQQQQQQQQ\" \\\n" 16170 " \"FFFFFFFFFFFFF\" \\\n" 16171 " \"LLLLLLLL\"\n", 16172 Style); 16173 16174 Style.AlignConsecutiveMacros.Enabled = true; 16175 verifyFormat("#define a \\\n" 16176 " \"aabbbbbbbbbbbb\"\n" 16177 "#define D \\\n" 16178 " \"aabbbbbbbbbbbb\" \\\n" 16179 " \"ccddeeeeeeeee\"\n" 16180 "#define B \\\n" 16181 " \"QQQQQQQQQQQQQ\" \\\n" 16182 " \"FFFFFFFFFFFFF\" \\\n" 16183 " \"LLLLLLLL\"\n", 16184 Style); 16185 16186 // Test across comments 16187 Style.MaxEmptyLinesToKeep = 10; 16188 Style.ReflowComments = false; 16189 Style.AlignConsecutiveMacros.AcrossComments = true; 16190 EXPECT_EQ("#define a 3\n" 16191 "// line comment\n" 16192 "#define bbbb 4\n" 16193 "#define ccc (5)", 16194 format("#define a 3\n" 16195 "// line comment\n" 16196 "#define bbbb 4\n" 16197 "#define ccc (5)", 16198 Style)); 16199 16200 EXPECT_EQ("#define a 3\n" 16201 "/* block comment */\n" 16202 "#define bbbb 4\n" 16203 "#define ccc (5)", 16204 format("#define a 3\n" 16205 "/* block comment */\n" 16206 "#define bbbb 4\n" 16207 "#define ccc (5)", 16208 Style)); 16209 16210 EXPECT_EQ("#define a 3\n" 16211 "/* multi-line *\n" 16212 " * block comment */\n" 16213 "#define bbbb 4\n" 16214 "#define ccc (5)", 16215 format("#define a 3\n" 16216 "/* multi-line *\n" 16217 " * block comment */\n" 16218 "#define bbbb 4\n" 16219 "#define ccc (5)", 16220 Style)); 16221 16222 EXPECT_EQ("#define a 3\n" 16223 "// multi-line line comment\n" 16224 "//\n" 16225 "#define bbbb 4\n" 16226 "#define ccc (5)", 16227 format("#define a 3\n" 16228 "// multi-line line comment\n" 16229 "//\n" 16230 "#define bbbb 4\n" 16231 "#define ccc (5)", 16232 Style)); 16233 16234 EXPECT_EQ("#define a 3\n" 16235 "// empty lines still break.\n" 16236 "\n" 16237 "#define bbbb 4\n" 16238 "#define ccc (5)", 16239 format("#define a 3\n" 16240 "// empty lines still break.\n" 16241 "\n" 16242 "#define bbbb 4\n" 16243 "#define ccc (5)", 16244 Style)); 16245 16246 // Test across empty lines 16247 Style.AlignConsecutiveMacros.AcrossComments = false; 16248 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16249 EXPECT_EQ("#define a 3\n" 16250 "\n" 16251 "#define bbbb 4\n" 16252 "#define ccc (5)", 16253 format("#define a 3\n" 16254 "\n" 16255 "#define bbbb 4\n" 16256 "#define ccc (5)", 16257 Style)); 16258 16259 EXPECT_EQ("#define a 3\n" 16260 "\n" 16261 "\n" 16262 "\n" 16263 "#define bbbb 4\n" 16264 "#define ccc (5)", 16265 format("#define a 3\n" 16266 "\n" 16267 "\n" 16268 "\n" 16269 "#define bbbb 4\n" 16270 "#define ccc (5)", 16271 Style)); 16272 16273 EXPECT_EQ("#define a 3\n" 16274 "// comments should break alignment\n" 16275 "//\n" 16276 "#define bbbb 4\n" 16277 "#define ccc (5)", 16278 format("#define a 3\n" 16279 "// comments should break alignment\n" 16280 "//\n" 16281 "#define bbbb 4\n" 16282 "#define ccc (5)", 16283 Style)); 16284 16285 // Test across empty lines and comments 16286 Style.AlignConsecutiveMacros.AcrossComments = true; 16287 verifyFormat("#define a 3\n" 16288 "\n" 16289 "// line comment\n" 16290 "#define bbbb 4\n" 16291 "#define ccc (5)", 16292 Style); 16293 16294 EXPECT_EQ("#define a 3\n" 16295 "\n" 16296 "\n" 16297 "/* multi-line *\n" 16298 " * block comment */\n" 16299 "\n" 16300 "\n" 16301 "#define bbbb 4\n" 16302 "#define ccc (5)", 16303 format("#define a 3\n" 16304 "\n" 16305 "\n" 16306 "/* multi-line *\n" 16307 " * block comment */\n" 16308 "\n" 16309 "\n" 16310 "#define bbbb 4\n" 16311 "#define ccc (5)", 16312 Style)); 16313 16314 EXPECT_EQ("#define a 3\n" 16315 "\n" 16316 "\n" 16317 "/* multi-line *\n" 16318 " * block comment */\n" 16319 "\n" 16320 "\n" 16321 "#define bbbb 4\n" 16322 "#define ccc (5)", 16323 format("#define a 3\n" 16324 "\n" 16325 "\n" 16326 "/* multi-line *\n" 16327 " * block comment */\n" 16328 "\n" 16329 "\n" 16330 "#define bbbb 4\n" 16331 "#define ccc (5)", 16332 Style)); 16333 } 16334 16335 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16336 FormatStyle Alignment = getLLVMStyle(); 16337 Alignment.AlignConsecutiveMacros.Enabled = true; 16338 Alignment.AlignConsecutiveAssignments.Enabled = true; 16339 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16340 16341 Alignment.MaxEmptyLinesToKeep = 10; 16342 /* Test alignment across empty lines */ 16343 EXPECT_EQ("int a = 5;\n" 16344 "\n" 16345 "int oneTwoThree = 123;", 16346 format("int a = 5;\n" 16347 "\n" 16348 "int oneTwoThree= 123;", 16349 Alignment)); 16350 EXPECT_EQ("int a = 5;\n" 16351 "int one = 1;\n" 16352 "\n" 16353 "int oneTwoThree = 123;", 16354 format("int a = 5;\n" 16355 "int one = 1;\n" 16356 "\n" 16357 "int oneTwoThree = 123;", 16358 Alignment)); 16359 EXPECT_EQ("int a = 5;\n" 16360 "int one = 1;\n" 16361 "\n" 16362 "int oneTwoThree = 123;\n" 16363 "int oneTwo = 12;", 16364 format("int a = 5;\n" 16365 "int one = 1;\n" 16366 "\n" 16367 "int oneTwoThree = 123;\n" 16368 "int oneTwo = 12;", 16369 Alignment)); 16370 16371 /* Test across comments */ 16372 EXPECT_EQ("int a = 5;\n" 16373 "/* block comment */\n" 16374 "int oneTwoThree = 123;", 16375 format("int a = 5;\n" 16376 "/* block comment */\n" 16377 "int oneTwoThree=123;", 16378 Alignment)); 16379 16380 EXPECT_EQ("int a = 5;\n" 16381 "// line comment\n" 16382 "int oneTwoThree = 123;", 16383 format("int a = 5;\n" 16384 "// line comment\n" 16385 "int oneTwoThree=123;", 16386 Alignment)); 16387 16388 /* Test across comments and newlines */ 16389 EXPECT_EQ("int a = 5;\n" 16390 "\n" 16391 "/* block comment */\n" 16392 "int oneTwoThree = 123;", 16393 format("int a = 5;\n" 16394 "\n" 16395 "/* block comment */\n" 16396 "int oneTwoThree=123;", 16397 Alignment)); 16398 16399 EXPECT_EQ("int a = 5;\n" 16400 "\n" 16401 "// line comment\n" 16402 "int oneTwoThree = 123;", 16403 format("int a = 5;\n" 16404 "\n" 16405 "// line comment\n" 16406 "int oneTwoThree=123;", 16407 Alignment)); 16408 } 16409 16410 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16411 FormatStyle Alignment = getLLVMStyle(); 16412 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16413 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16414 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16415 16416 Alignment.MaxEmptyLinesToKeep = 10; 16417 /* Test alignment across empty lines */ 16418 EXPECT_EQ("int a = 5;\n" 16419 "\n" 16420 "float const oneTwoThree = 123;", 16421 format("int a = 5;\n" 16422 "\n" 16423 "float const oneTwoThree = 123;", 16424 Alignment)); 16425 EXPECT_EQ("int a = 5;\n" 16426 "float const one = 1;\n" 16427 "\n" 16428 "int oneTwoThree = 123;", 16429 format("int a = 5;\n" 16430 "float const one = 1;\n" 16431 "\n" 16432 "int oneTwoThree = 123;", 16433 Alignment)); 16434 16435 /* Test across comments */ 16436 EXPECT_EQ("float const a = 5;\n" 16437 "/* block comment */\n" 16438 "int oneTwoThree = 123;", 16439 format("float const a = 5;\n" 16440 "/* block comment */\n" 16441 "int oneTwoThree=123;", 16442 Alignment)); 16443 16444 EXPECT_EQ("float const a = 5;\n" 16445 "// line comment\n" 16446 "int oneTwoThree = 123;", 16447 format("float const a = 5;\n" 16448 "// line comment\n" 16449 "int oneTwoThree=123;", 16450 Alignment)); 16451 16452 /* Test across comments and newlines */ 16453 EXPECT_EQ("float const a = 5;\n" 16454 "\n" 16455 "/* block comment */\n" 16456 "int oneTwoThree = 123;", 16457 format("float const a = 5;\n" 16458 "\n" 16459 "/* block comment */\n" 16460 "int oneTwoThree=123;", 16461 Alignment)); 16462 16463 EXPECT_EQ("float const a = 5;\n" 16464 "\n" 16465 "// line comment\n" 16466 "int oneTwoThree = 123;", 16467 format("float const a = 5;\n" 16468 "\n" 16469 "// line comment\n" 16470 "int oneTwoThree=123;", 16471 Alignment)); 16472 } 16473 16474 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16475 FormatStyle Alignment = getLLVMStyle(); 16476 Alignment.AlignConsecutiveBitFields.Enabled = true; 16477 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16478 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16479 16480 Alignment.MaxEmptyLinesToKeep = 10; 16481 /* Test alignment across empty lines */ 16482 EXPECT_EQ("int a : 5;\n" 16483 "\n" 16484 "int longbitfield : 6;", 16485 format("int a : 5;\n" 16486 "\n" 16487 "int longbitfield : 6;", 16488 Alignment)); 16489 EXPECT_EQ("int a : 5;\n" 16490 "int one : 1;\n" 16491 "\n" 16492 "int longbitfield : 6;", 16493 format("int a : 5;\n" 16494 "int one : 1;\n" 16495 "\n" 16496 "int longbitfield : 6;", 16497 Alignment)); 16498 16499 /* Test across comments */ 16500 EXPECT_EQ("int a : 5;\n" 16501 "/* block comment */\n" 16502 "int longbitfield : 6;", 16503 format("int a : 5;\n" 16504 "/* block comment */\n" 16505 "int longbitfield : 6;", 16506 Alignment)); 16507 EXPECT_EQ("int a : 5;\n" 16508 "int one : 1;\n" 16509 "// line comment\n" 16510 "int longbitfield : 6;", 16511 format("int a : 5;\n" 16512 "int one : 1;\n" 16513 "// line comment\n" 16514 "int longbitfield : 6;", 16515 Alignment)); 16516 16517 /* Test across comments and newlines */ 16518 EXPECT_EQ("int a : 5;\n" 16519 "/* block comment */\n" 16520 "\n" 16521 "int longbitfield : 6;", 16522 format("int a : 5;\n" 16523 "/* block comment */\n" 16524 "\n" 16525 "int longbitfield : 6;", 16526 Alignment)); 16527 EXPECT_EQ("int a : 5;\n" 16528 "int one : 1;\n" 16529 "\n" 16530 "// line comment\n" 16531 "\n" 16532 "int longbitfield : 6;", 16533 format("int a : 5;\n" 16534 "int one : 1;\n" 16535 "\n" 16536 "// line comment \n" 16537 "\n" 16538 "int longbitfield : 6;", 16539 Alignment)); 16540 } 16541 16542 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16543 FormatStyle Alignment = getLLVMStyle(); 16544 Alignment.AlignConsecutiveMacros.Enabled = true; 16545 Alignment.AlignConsecutiveAssignments.Enabled = true; 16546 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16547 16548 Alignment.MaxEmptyLinesToKeep = 10; 16549 /* Test alignment across empty lines */ 16550 EXPECT_EQ("int a = 5;\n" 16551 "\n" 16552 "int oneTwoThree = 123;", 16553 format("int a = 5;\n" 16554 "\n" 16555 "int oneTwoThree= 123;", 16556 Alignment)); 16557 EXPECT_EQ("int a = 5;\n" 16558 "int one = 1;\n" 16559 "\n" 16560 "int oneTwoThree = 123;", 16561 format("int a = 5;\n" 16562 "int one = 1;\n" 16563 "\n" 16564 "int oneTwoThree = 123;", 16565 Alignment)); 16566 16567 /* Test across comments */ 16568 EXPECT_EQ("int a = 5;\n" 16569 "/* block comment */\n" 16570 "int oneTwoThree = 123;", 16571 format("int a = 5;\n" 16572 "/* block comment */\n" 16573 "int oneTwoThree=123;", 16574 Alignment)); 16575 16576 EXPECT_EQ("int a = 5;\n" 16577 "// line comment\n" 16578 "int oneTwoThree = 123;", 16579 format("int a = 5;\n" 16580 "// line comment\n" 16581 "int oneTwoThree=123;", 16582 Alignment)); 16583 16584 EXPECT_EQ("int a = 5;\n" 16585 "/*\n" 16586 " * multi-line block comment\n" 16587 " */\n" 16588 "int oneTwoThree = 123;", 16589 format("int a = 5;\n" 16590 "/*\n" 16591 " * multi-line block comment\n" 16592 " */\n" 16593 "int oneTwoThree=123;", 16594 Alignment)); 16595 16596 EXPECT_EQ("int a = 5;\n" 16597 "//\n" 16598 "// multi-line line comment\n" 16599 "//\n" 16600 "int oneTwoThree = 123;", 16601 format("int a = 5;\n" 16602 "//\n" 16603 "// multi-line line comment\n" 16604 "//\n" 16605 "int oneTwoThree=123;", 16606 Alignment)); 16607 16608 /* Test across comments and newlines */ 16609 EXPECT_EQ("int a = 5;\n" 16610 "\n" 16611 "/* block comment */\n" 16612 "int oneTwoThree = 123;", 16613 format("int a = 5;\n" 16614 "\n" 16615 "/* block comment */\n" 16616 "int oneTwoThree=123;", 16617 Alignment)); 16618 16619 EXPECT_EQ("int a = 5;\n" 16620 "\n" 16621 "// line comment\n" 16622 "int oneTwoThree = 123;", 16623 format("int a = 5;\n" 16624 "\n" 16625 "// line comment\n" 16626 "int oneTwoThree=123;", 16627 Alignment)); 16628 } 16629 16630 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16631 FormatStyle Alignment = getLLVMStyle(); 16632 Alignment.AlignConsecutiveMacros.Enabled = true; 16633 Alignment.AlignConsecutiveAssignments.Enabled = true; 16634 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16635 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16636 verifyFormat("int a = 5;\n" 16637 "int oneTwoThree = 123;", 16638 Alignment); 16639 verifyFormat("int a = method();\n" 16640 "int oneTwoThree = 133;", 16641 Alignment); 16642 verifyFormat("a &= 5;\n" 16643 "bcd *= 5;\n" 16644 "ghtyf += 5;\n" 16645 "dvfvdb -= 5;\n" 16646 "a /= 5;\n" 16647 "vdsvsv %= 5;\n" 16648 "sfdbddfbdfbb ^= 5;\n" 16649 "dvsdsv |= 5;\n" 16650 "int dsvvdvsdvvv = 123;", 16651 Alignment); 16652 verifyFormat("int i = 1, j = 10;\n" 16653 "something = 2000;", 16654 Alignment); 16655 verifyFormat("something = 2000;\n" 16656 "int i = 1, j = 10;\n", 16657 Alignment); 16658 verifyFormat("something = 2000;\n" 16659 "another = 911;\n" 16660 "int i = 1, j = 10;\n" 16661 "oneMore = 1;\n" 16662 "i = 2;", 16663 Alignment); 16664 verifyFormat("int a = 5;\n" 16665 "int one = 1;\n" 16666 "method();\n" 16667 "int oneTwoThree = 123;\n" 16668 "int oneTwo = 12;", 16669 Alignment); 16670 verifyFormat("int oneTwoThree = 123;\n" 16671 "int oneTwo = 12;\n" 16672 "method();\n", 16673 Alignment); 16674 verifyFormat("int oneTwoThree = 123; // comment\n" 16675 "int oneTwo = 12; // comment", 16676 Alignment); 16677 16678 // Bug 25167 16679 /* Uncomment when fixed 16680 verifyFormat("#if A\n" 16681 "#else\n" 16682 "int aaaaaaaa = 12;\n" 16683 "#endif\n" 16684 "#if B\n" 16685 "#else\n" 16686 "int a = 12;\n" 16687 "#endif\n", 16688 Alignment); 16689 verifyFormat("enum foo {\n" 16690 "#if A\n" 16691 "#else\n" 16692 " aaaaaaaa = 12;\n" 16693 "#endif\n" 16694 "#if B\n" 16695 "#else\n" 16696 " a = 12;\n" 16697 "#endif\n" 16698 "};\n", 16699 Alignment); 16700 */ 16701 16702 Alignment.MaxEmptyLinesToKeep = 10; 16703 /* Test alignment across empty lines */ 16704 EXPECT_EQ("int a = 5;\n" 16705 "\n" 16706 "int oneTwoThree = 123;", 16707 format("int a = 5;\n" 16708 "\n" 16709 "int oneTwoThree= 123;", 16710 Alignment)); 16711 EXPECT_EQ("int a = 5;\n" 16712 "int one = 1;\n" 16713 "\n" 16714 "int oneTwoThree = 123;", 16715 format("int a = 5;\n" 16716 "int one = 1;\n" 16717 "\n" 16718 "int oneTwoThree = 123;", 16719 Alignment)); 16720 EXPECT_EQ("int a = 5;\n" 16721 "int one = 1;\n" 16722 "\n" 16723 "int oneTwoThree = 123;\n" 16724 "int oneTwo = 12;", 16725 format("int a = 5;\n" 16726 "int one = 1;\n" 16727 "\n" 16728 "int oneTwoThree = 123;\n" 16729 "int oneTwo = 12;", 16730 Alignment)); 16731 16732 /* Test across comments */ 16733 EXPECT_EQ("int a = 5;\n" 16734 "/* block comment */\n" 16735 "int oneTwoThree = 123;", 16736 format("int a = 5;\n" 16737 "/* block comment */\n" 16738 "int oneTwoThree=123;", 16739 Alignment)); 16740 16741 EXPECT_EQ("int a = 5;\n" 16742 "// line comment\n" 16743 "int oneTwoThree = 123;", 16744 format("int a = 5;\n" 16745 "// line comment\n" 16746 "int oneTwoThree=123;", 16747 Alignment)); 16748 16749 /* Test across comments and newlines */ 16750 EXPECT_EQ("int a = 5;\n" 16751 "\n" 16752 "/* block comment */\n" 16753 "int oneTwoThree = 123;", 16754 format("int a = 5;\n" 16755 "\n" 16756 "/* block comment */\n" 16757 "int oneTwoThree=123;", 16758 Alignment)); 16759 16760 EXPECT_EQ("int a = 5;\n" 16761 "\n" 16762 "// line comment\n" 16763 "int oneTwoThree = 123;", 16764 format("int a = 5;\n" 16765 "\n" 16766 "// line comment\n" 16767 "int oneTwoThree=123;", 16768 Alignment)); 16769 16770 EXPECT_EQ("int a = 5;\n" 16771 "//\n" 16772 "// multi-line line comment\n" 16773 "//\n" 16774 "int oneTwoThree = 123;", 16775 format("int a = 5;\n" 16776 "//\n" 16777 "// multi-line line comment\n" 16778 "//\n" 16779 "int oneTwoThree=123;", 16780 Alignment)); 16781 16782 EXPECT_EQ("int a = 5;\n" 16783 "/*\n" 16784 " * multi-line block comment\n" 16785 " */\n" 16786 "int oneTwoThree = 123;", 16787 format("int a = 5;\n" 16788 "/*\n" 16789 " * multi-line block comment\n" 16790 " */\n" 16791 "int oneTwoThree=123;", 16792 Alignment)); 16793 16794 EXPECT_EQ("int a = 5;\n" 16795 "\n" 16796 "/* block comment */\n" 16797 "\n" 16798 "\n" 16799 "\n" 16800 "int oneTwoThree = 123;", 16801 format("int a = 5;\n" 16802 "\n" 16803 "/* block comment */\n" 16804 "\n" 16805 "\n" 16806 "\n" 16807 "int oneTwoThree=123;", 16808 Alignment)); 16809 16810 EXPECT_EQ("int a = 5;\n" 16811 "\n" 16812 "// line comment\n" 16813 "\n" 16814 "\n" 16815 "\n" 16816 "int oneTwoThree = 123;", 16817 format("int a = 5;\n" 16818 "\n" 16819 "// line comment\n" 16820 "\n" 16821 "\n" 16822 "\n" 16823 "int oneTwoThree=123;", 16824 Alignment)); 16825 16826 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16827 verifyFormat("#define A \\\n" 16828 " int aaaa = 12; \\\n" 16829 " int b = 23; \\\n" 16830 " int ccc = 234; \\\n" 16831 " int dddddddddd = 2345;", 16832 Alignment); 16833 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16834 verifyFormat("#define A \\\n" 16835 " int aaaa = 12; \\\n" 16836 " int b = 23; \\\n" 16837 " int ccc = 234; \\\n" 16838 " int dddddddddd = 2345;", 16839 Alignment); 16840 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16841 verifyFormat("#define A " 16842 " \\\n" 16843 " int aaaa = 12; " 16844 " \\\n" 16845 " int b = 23; " 16846 " \\\n" 16847 " int ccc = 234; " 16848 " \\\n" 16849 " int dddddddddd = 2345;", 16850 Alignment); 16851 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16852 "k = 4, int l = 5,\n" 16853 " int m = 6) {\n" 16854 " int j = 10;\n" 16855 " otherThing = 1;\n" 16856 "}", 16857 Alignment); 16858 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16859 " int i = 1;\n" 16860 " int j = 2;\n" 16861 " int big = 10000;\n" 16862 "}", 16863 Alignment); 16864 verifyFormat("class C {\n" 16865 "public:\n" 16866 " int i = 1;\n" 16867 " virtual void f() = 0;\n" 16868 "};", 16869 Alignment); 16870 verifyFormat("int i = 1;\n" 16871 "if (SomeType t = getSomething()) {\n" 16872 "}\n" 16873 "int j = 2;\n" 16874 "int big = 10000;", 16875 Alignment); 16876 verifyFormat("int j = 7;\n" 16877 "for (int k = 0; k < N; ++k) {\n" 16878 "}\n" 16879 "int j = 2;\n" 16880 "int big = 10000;\n" 16881 "}", 16882 Alignment); 16883 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16884 verifyFormat("int i = 1;\n" 16885 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16886 " = someLooooooooooooooooongFunction();\n" 16887 "int j = 2;", 16888 Alignment); 16889 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16890 verifyFormat("int i = 1;\n" 16891 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16892 " someLooooooooooooooooongFunction();\n" 16893 "int j = 2;", 16894 Alignment); 16895 16896 verifyFormat("auto lambda = []() {\n" 16897 " auto i = 0;\n" 16898 " return 0;\n" 16899 "};\n" 16900 "int i = 0;\n" 16901 "auto v = type{\n" 16902 " i = 1, //\n" 16903 " (i = 2), //\n" 16904 " i = 3 //\n" 16905 "};", 16906 Alignment); 16907 16908 verifyFormat( 16909 "int i = 1;\n" 16910 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16911 " loooooooooooooooooooooongParameterB);\n" 16912 "int j = 2;", 16913 Alignment); 16914 16915 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16916 " typename B = very_long_type_name_1,\n" 16917 " typename T_2 = very_long_type_name_2>\n" 16918 "auto foo() {}\n", 16919 Alignment); 16920 verifyFormat("int a, b = 1;\n" 16921 "int c = 2;\n" 16922 "int dd = 3;\n", 16923 Alignment); 16924 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16925 "float b[1][] = {{3.f}};\n", 16926 Alignment); 16927 verifyFormat("for (int i = 0; i < 1; i++)\n" 16928 " int x = 1;\n", 16929 Alignment); 16930 verifyFormat("for (i = 0; i < 1; i++)\n" 16931 " x = 1;\n" 16932 "y = 1;\n", 16933 Alignment); 16934 16935 Alignment.ReflowComments = true; 16936 Alignment.ColumnLimit = 50; 16937 EXPECT_EQ("int x = 0;\n" 16938 "int yy = 1; /// specificlennospace\n" 16939 "int zzz = 2;\n", 16940 format("int x = 0;\n" 16941 "int yy = 1; ///specificlennospace\n" 16942 "int zzz = 2;\n", 16943 Alignment)); 16944 } 16945 16946 TEST_F(FormatTest, AlignCompoundAssignments) { 16947 FormatStyle Alignment = getLLVMStyle(); 16948 Alignment.AlignConsecutiveAssignments.Enabled = true; 16949 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 16950 Alignment.AlignConsecutiveAssignments.PadOperators = false; 16951 verifyFormat("sfdbddfbdfbb = 5;\n" 16952 "dvsdsv = 5;\n" 16953 "int dsvvdvsdvvv = 123;", 16954 Alignment); 16955 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16956 "dvsdsv |= 5;\n" 16957 "int dsvvdvsdvvv = 123;", 16958 Alignment); 16959 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16960 "dvsdsv <<= 5;\n" 16961 "int dsvvdvsdvvv = 123;", 16962 Alignment); 16963 // Test that `<=` is not treated as a compound assignment. 16964 verifyFormat("aa &= 5;\n" 16965 "b <= 10;\n" 16966 "c = 15;", 16967 Alignment); 16968 Alignment.AlignConsecutiveAssignments.PadOperators = true; 16969 verifyFormat("sfdbddfbdfbb = 5;\n" 16970 "dvsdsv = 5;\n" 16971 "int dsvvdvsdvvv = 123;", 16972 Alignment); 16973 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16974 "dvsdsv |= 5;\n" 16975 "int dsvvdvsdvvv = 123;", 16976 Alignment); 16977 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16978 "dvsdsv <<= 5;\n" 16979 "int dsvvdvsdvvv = 123;", 16980 Alignment); 16981 EXPECT_EQ("a += 5;\n" 16982 "one = 1;\n" 16983 "\n" 16984 "oneTwoThree = 123;\n", 16985 format("a += 5;\n" 16986 "one = 1;\n" 16987 "\n" 16988 "oneTwoThree = 123;\n", 16989 Alignment)); 16990 EXPECT_EQ("a += 5;\n" 16991 "one = 1;\n" 16992 "//\n" 16993 "oneTwoThree = 123;\n", 16994 format("a += 5;\n" 16995 "one = 1;\n" 16996 "//\n" 16997 "oneTwoThree = 123;\n", 16998 Alignment)); 16999 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 17000 EXPECT_EQ("a += 5;\n" 17001 "one = 1;\n" 17002 "\n" 17003 "oneTwoThree = 123;\n", 17004 format("a += 5;\n" 17005 "one = 1;\n" 17006 "\n" 17007 "oneTwoThree = 123;\n", 17008 Alignment)); 17009 EXPECT_EQ("a += 5;\n" 17010 "one = 1;\n" 17011 "//\n" 17012 "oneTwoThree = 123;\n", 17013 format("a += 5;\n" 17014 "one = 1;\n" 17015 "//\n" 17016 "oneTwoThree = 123;\n", 17017 Alignment)); 17018 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 17019 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 17020 EXPECT_EQ("a += 5;\n" 17021 "one = 1;\n" 17022 "\n" 17023 "oneTwoThree = 123;\n", 17024 format("a += 5;\n" 17025 "one = 1;\n" 17026 "\n" 17027 "oneTwoThree = 123;\n", 17028 Alignment)); 17029 EXPECT_EQ("a += 5;\n" 17030 "one = 1;\n" 17031 "//\n" 17032 "oneTwoThree = 123;\n", 17033 format("a += 5;\n" 17034 "one = 1;\n" 17035 "//\n" 17036 "oneTwoThree = 123;\n", 17037 Alignment)); 17038 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 17039 EXPECT_EQ("a += 5;\n" 17040 "one >>= 1;\n" 17041 "\n" 17042 "oneTwoThree = 123;\n", 17043 format("a += 5;\n" 17044 "one >>= 1;\n" 17045 "\n" 17046 "oneTwoThree = 123;\n", 17047 Alignment)); 17048 EXPECT_EQ("a += 5;\n" 17049 "one = 1;\n" 17050 "//\n" 17051 "oneTwoThree <<= 123;\n", 17052 format("a += 5;\n" 17053 "one = 1;\n" 17054 "//\n" 17055 "oneTwoThree <<= 123;\n", 17056 Alignment)); 17057 } 17058 17059 TEST_F(FormatTest, AlignConsecutiveAssignments) { 17060 FormatStyle Alignment = getLLVMStyle(); 17061 Alignment.AlignConsecutiveMacros.Enabled = true; 17062 verifyFormat("int a = 5;\n" 17063 "int oneTwoThree = 123;", 17064 Alignment); 17065 verifyFormat("int a = 5;\n" 17066 "int oneTwoThree = 123;", 17067 Alignment); 17068 17069 Alignment.AlignConsecutiveAssignments.Enabled = true; 17070 verifyFormat("int a = 5;\n" 17071 "int oneTwoThree = 123;", 17072 Alignment); 17073 verifyFormat("int a = method();\n" 17074 "int oneTwoThree = 133;", 17075 Alignment); 17076 verifyFormat("aa <= 5;\n" 17077 "a &= 5;\n" 17078 "bcd *= 5;\n" 17079 "ghtyf += 5;\n" 17080 "dvfvdb -= 5;\n" 17081 "a /= 5;\n" 17082 "vdsvsv %= 5;\n" 17083 "sfdbddfbdfbb ^= 5;\n" 17084 "dvsdsv |= 5;\n" 17085 "int dsvvdvsdvvv = 123;", 17086 Alignment); 17087 verifyFormat("int i = 1, j = 10;\n" 17088 "something = 2000;", 17089 Alignment); 17090 verifyFormat("something = 2000;\n" 17091 "int i = 1, j = 10;\n", 17092 Alignment); 17093 verifyFormat("something = 2000;\n" 17094 "another = 911;\n" 17095 "int i = 1, j = 10;\n" 17096 "oneMore = 1;\n" 17097 "i = 2;", 17098 Alignment); 17099 verifyFormat("int a = 5;\n" 17100 "int one = 1;\n" 17101 "method();\n" 17102 "int oneTwoThree = 123;\n" 17103 "int oneTwo = 12;", 17104 Alignment); 17105 verifyFormat("int oneTwoThree = 123;\n" 17106 "int oneTwo = 12;\n" 17107 "method();\n", 17108 Alignment); 17109 verifyFormat("int oneTwoThree = 123; // comment\n" 17110 "int oneTwo = 12; // comment", 17111 Alignment); 17112 verifyFormat("int f() = default;\n" 17113 "int &operator() = default;\n" 17114 "int &operator=() {", 17115 Alignment); 17116 verifyFormat("int f() = delete;\n" 17117 "int &operator() = delete;\n" 17118 "int &operator=() {", 17119 Alignment); 17120 verifyFormat("int f() = default; // comment\n" 17121 "int &operator() = default; // comment\n" 17122 "int &operator=() {", 17123 Alignment); 17124 verifyFormat("int f() = default;\n" 17125 "int &operator() = default;\n" 17126 "int &operator==() {", 17127 Alignment); 17128 verifyFormat("int f() = default;\n" 17129 "int &operator() = default;\n" 17130 "int &operator<=() {", 17131 Alignment); 17132 verifyFormat("int f() = default;\n" 17133 "int &operator() = default;\n" 17134 "int &operator!=() {", 17135 Alignment); 17136 verifyFormat("int f() = default;\n" 17137 "int &operator() = default;\n" 17138 "int &operator=();", 17139 Alignment); 17140 verifyFormat("int f() = delete;\n" 17141 "int &operator() = delete;\n" 17142 "int &operator=();", 17143 Alignment); 17144 verifyFormat("/* long long padding */ int f() = default;\n" 17145 "int &operator() = default;\n" 17146 "int &operator/**/ =();", 17147 Alignment); 17148 // https://llvm.org/PR33697 17149 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17150 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17151 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17152 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17153 " void f() = delete;\n" 17154 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17155 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17156 "};\n", 17157 AlignmentWithPenalty); 17158 17159 // Bug 25167 17160 /* Uncomment when fixed 17161 verifyFormat("#if A\n" 17162 "#else\n" 17163 "int aaaaaaaa = 12;\n" 17164 "#endif\n" 17165 "#if B\n" 17166 "#else\n" 17167 "int a = 12;\n" 17168 "#endif\n", 17169 Alignment); 17170 verifyFormat("enum foo {\n" 17171 "#if A\n" 17172 "#else\n" 17173 " aaaaaaaa = 12;\n" 17174 "#endif\n" 17175 "#if B\n" 17176 "#else\n" 17177 " a = 12;\n" 17178 "#endif\n" 17179 "};\n", 17180 Alignment); 17181 */ 17182 17183 EXPECT_EQ("int a = 5;\n" 17184 "\n" 17185 "int oneTwoThree = 123;", 17186 format("int a = 5;\n" 17187 "\n" 17188 "int oneTwoThree= 123;", 17189 Alignment)); 17190 EXPECT_EQ("int a = 5;\n" 17191 "int one = 1;\n" 17192 "\n" 17193 "int oneTwoThree = 123;", 17194 format("int a = 5;\n" 17195 "int one = 1;\n" 17196 "\n" 17197 "int oneTwoThree = 123;", 17198 Alignment)); 17199 EXPECT_EQ("int a = 5;\n" 17200 "int one = 1;\n" 17201 "\n" 17202 "int oneTwoThree = 123;\n" 17203 "int oneTwo = 12;", 17204 format("int a = 5;\n" 17205 "int one = 1;\n" 17206 "\n" 17207 "int oneTwoThree = 123;\n" 17208 "int oneTwo = 12;", 17209 Alignment)); 17210 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17211 verifyFormat("#define A \\\n" 17212 " int aaaa = 12; \\\n" 17213 " int b = 23; \\\n" 17214 " int ccc = 234; \\\n" 17215 " int dddddddddd = 2345;", 17216 Alignment); 17217 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17218 verifyFormat("#define A \\\n" 17219 " int aaaa = 12; \\\n" 17220 " int b = 23; \\\n" 17221 " int ccc = 234; \\\n" 17222 " int dddddddddd = 2345;", 17223 Alignment); 17224 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17225 verifyFormat("#define A " 17226 " \\\n" 17227 " int aaaa = 12; " 17228 " \\\n" 17229 " int b = 23; " 17230 " \\\n" 17231 " int ccc = 234; " 17232 " \\\n" 17233 " int dddddddddd = 2345;", 17234 Alignment); 17235 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17236 "k = 4, int l = 5,\n" 17237 " int m = 6) {\n" 17238 " int j = 10;\n" 17239 " otherThing = 1;\n" 17240 "}", 17241 Alignment); 17242 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17243 " int i = 1;\n" 17244 " int j = 2;\n" 17245 " int big = 10000;\n" 17246 "}", 17247 Alignment); 17248 verifyFormat("class C {\n" 17249 "public:\n" 17250 " int i = 1;\n" 17251 " virtual void f() = 0;\n" 17252 "};", 17253 Alignment); 17254 verifyFormat("int i = 1;\n" 17255 "if (SomeType t = getSomething()) {\n" 17256 "}\n" 17257 "int j = 2;\n" 17258 "int big = 10000;", 17259 Alignment); 17260 verifyFormat("int j = 7;\n" 17261 "for (int k = 0; k < N; ++k) {\n" 17262 "}\n" 17263 "int j = 2;\n" 17264 "int big = 10000;\n" 17265 "}", 17266 Alignment); 17267 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17268 verifyFormat("int i = 1;\n" 17269 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17270 " = someLooooooooooooooooongFunction();\n" 17271 "int j = 2;", 17272 Alignment); 17273 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17274 verifyFormat("int i = 1;\n" 17275 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17276 " someLooooooooooooooooongFunction();\n" 17277 "int j = 2;", 17278 Alignment); 17279 17280 verifyFormat("auto lambda = []() {\n" 17281 " auto i = 0;\n" 17282 " return 0;\n" 17283 "};\n" 17284 "int i = 0;\n" 17285 "auto v = type{\n" 17286 " i = 1, //\n" 17287 " (i = 2), //\n" 17288 " i = 3 //\n" 17289 "};", 17290 Alignment); 17291 17292 verifyFormat( 17293 "int i = 1;\n" 17294 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17295 " loooooooooooooooooooooongParameterB);\n" 17296 "int j = 2;", 17297 Alignment); 17298 17299 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17300 " typename B = very_long_type_name_1,\n" 17301 " typename T_2 = very_long_type_name_2>\n" 17302 "auto foo() {}\n", 17303 Alignment); 17304 verifyFormat("int a, b = 1;\n" 17305 "int c = 2;\n" 17306 "int dd = 3;\n", 17307 Alignment); 17308 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17309 "float b[1][] = {{3.f}};\n", 17310 Alignment); 17311 verifyFormat("for (int i = 0; i < 1; i++)\n" 17312 " int x = 1;\n", 17313 Alignment); 17314 verifyFormat("for (i = 0; i < 1; i++)\n" 17315 " x = 1;\n" 17316 "y = 1;\n", 17317 Alignment); 17318 17319 EXPECT_EQ(Alignment.ReflowComments, true); 17320 Alignment.ColumnLimit = 50; 17321 EXPECT_EQ("int x = 0;\n" 17322 "int yy = 1; /// specificlennospace\n" 17323 "int zzz = 2;\n", 17324 format("int x = 0;\n" 17325 "int yy = 1; ///specificlennospace\n" 17326 "int zzz = 2;\n", 17327 Alignment)); 17328 17329 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17330 "auto b = [] {\n" 17331 " f();\n" 17332 " return;\n" 17333 "};", 17334 Alignment); 17335 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17336 "auto b = g([] {\n" 17337 " f();\n" 17338 " return;\n" 17339 "});", 17340 Alignment); 17341 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17342 "auto b = g(param, [] {\n" 17343 " f();\n" 17344 " return;\n" 17345 "});", 17346 Alignment); 17347 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17348 "auto b = [] {\n" 17349 " if (condition) {\n" 17350 " return;\n" 17351 " }\n" 17352 "};", 17353 Alignment); 17354 17355 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17356 " ccc ? aaaaa : bbbbb,\n" 17357 " dddddddddddddddddddddddddd);", 17358 Alignment); 17359 // FIXME: https://llvm.org/PR53497 17360 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17361 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17362 // " ccc ? aaaaa : bbbbb,\n" 17363 // " dddddddddddddddddddddddddd);", 17364 // Alignment); 17365 17366 // Confirm proper handling of AlignConsecutiveAssignments with 17367 // BinPackArguments. 17368 // See https://llvm.org/PR55360 17369 Alignment = getLLVMStyleWithColumns(50); 17370 Alignment.AlignConsecutiveAssignments.Enabled = true; 17371 Alignment.BinPackArguments = false; 17372 verifyFormat("int a_long_name = 1;\n" 17373 "auto b = B({a_long_name, a_long_name},\n" 17374 " {a_longer_name_for_wrap,\n" 17375 " a_longer_name_for_wrap});", 17376 Alignment); 17377 verifyFormat("int a_long_name = 1;\n" 17378 "auto b = B{{a_long_name, a_long_name},\n" 17379 " {a_longer_name_for_wrap,\n" 17380 " a_longer_name_for_wrap}};", 17381 Alignment); 17382 } 17383 17384 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17385 FormatStyle Alignment = getLLVMStyle(); 17386 Alignment.AlignConsecutiveBitFields.Enabled = true; 17387 verifyFormat("int const a : 5;\n" 17388 "int oneTwoThree : 23;", 17389 Alignment); 17390 17391 // Initializers are allowed starting with c++2a 17392 verifyFormat("int const a : 5 = 1;\n" 17393 "int oneTwoThree : 23 = 0;", 17394 Alignment); 17395 17396 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17397 verifyFormat("int const a : 5;\n" 17398 "int oneTwoThree : 23;", 17399 Alignment); 17400 17401 verifyFormat("int const a : 5; // comment\n" 17402 "int oneTwoThree : 23; // comment", 17403 Alignment); 17404 17405 verifyFormat("int const a : 5 = 1;\n" 17406 "int oneTwoThree : 23 = 0;", 17407 Alignment); 17408 17409 Alignment.AlignConsecutiveAssignments.Enabled = true; 17410 verifyFormat("int const a : 5 = 1;\n" 17411 "int oneTwoThree : 23 = 0;", 17412 Alignment); 17413 verifyFormat("int const a : 5 = {1};\n" 17414 "int oneTwoThree : 23 = 0;", 17415 Alignment); 17416 17417 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17418 verifyFormat("int const a :5;\n" 17419 "int oneTwoThree:23;", 17420 Alignment); 17421 17422 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17423 verifyFormat("int const a :5;\n" 17424 "int oneTwoThree :23;", 17425 Alignment); 17426 17427 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17428 verifyFormat("int const a : 5;\n" 17429 "int oneTwoThree: 23;", 17430 Alignment); 17431 17432 // Known limitations: ':' is only recognized as a bitfield colon when 17433 // followed by a number. 17434 /* 17435 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17436 "int a : 5;", 17437 Alignment); 17438 */ 17439 } 17440 17441 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17442 FormatStyle Alignment = getLLVMStyle(); 17443 Alignment.AlignConsecutiveMacros.Enabled = true; 17444 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17445 verifyFormat("float const a = 5;\n" 17446 "int oneTwoThree = 123;", 17447 Alignment); 17448 verifyFormat("int a = 5;\n" 17449 "float const oneTwoThree = 123;", 17450 Alignment); 17451 17452 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17453 verifyFormat("float const a = 5;\n" 17454 "int oneTwoThree = 123;", 17455 Alignment); 17456 verifyFormat("int a = method();\n" 17457 "float const oneTwoThree = 133;", 17458 Alignment); 17459 verifyFormat("int i = 1, j = 10;\n" 17460 "something = 2000;", 17461 Alignment); 17462 verifyFormat("something = 2000;\n" 17463 "int i = 1, j = 10;\n", 17464 Alignment); 17465 verifyFormat("float something = 2000;\n" 17466 "double another = 911;\n" 17467 "int i = 1, j = 10;\n" 17468 "const int *oneMore = 1;\n" 17469 "unsigned i = 2;", 17470 Alignment); 17471 verifyFormat("float a = 5;\n" 17472 "int one = 1;\n" 17473 "method();\n" 17474 "const double oneTwoThree = 123;\n" 17475 "const unsigned int oneTwo = 12;", 17476 Alignment); 17477 verifyFormat("int oneTwoThree{0}; // comment\n" 17478 "unsigned oneTwo; // comment", 17479 Alignment); 17480 verifyFormat("unsigned int *a;\n" 17481 "int *b;\n" 17482 "unsigned int Const *c;\n" 17483 "unsigned int const *d;\n" 17484 "unsigned int Const &e;\n" 17485 "unsigned int const &f;", 17486 Alignment); 17487 verifyFormat("Const unsigned int *c;\n" 17488 "const unsigned int *d;\n" 17489 "Const unsigned int &e;\n" 17490 "const unsigned int &f;\n" 17491 "const unsigned g;\n" 17492 "Const unsigned h;", 17493 Alignment); 17494 EXPECT_EQ("float const a = 5;\n" 17495 "\n" 17496 "int oneTwoThree = 123;", 17497 format("float const a = 5;\n" 17498 "\n" 17499 "int oneTwoThree= 123;", 17500 Alignment)); 17501 EXPECT_EQ("float a = 5;\n" 17502 "int one = 1;\n" 17503 "\n" 17504 "unsigned oneTwoThree = 123;", 17505 format("float a = 5;\n" 17506 "int one = 1;\n" 17507 "\n" 17508 "unsigned oneTwoThree = 123;", 17509 Alignment)); 17510 EXPECT_EQ("float a = 5;\n" 17511 "int one = 1;\n" 17512 "\n" 17513 "unsigned oneTwoThree = 123;\n" 17514 "int oneTwo = 12;", 17515 format("float a = 5;\n" 17516 "int one = 1;\n" 17517 "\n" 17518 "unsigned oneTwoThree = 123;\n" 17519 "int oneTwo = 12;", 17520 Alignment)); 17521 // Function prototype alignment 17522 verifyFormat("int a();\n" 17523 "double b();", 17524 Alignment); 17525 verifyFormat("int a(int x);\n" 17526 "double b();", 17527 Alignment); 17528 unsigned OldColumnLimit = Alignment.ColumnLimit; 17529 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17530 // otherwise the function parameters will be re-flowed onto a single line. 17531 Alignment.ColumnLimit = 0; 17532 EXPECT_EQ("int a(int x,\n" 17533 " float y);\n" 17534 "double b(int x,\n" 17535 " double y);", 17536 format("int a(int x,\n" 17537 " float y);\n" 17538 "double b(int x,\n" 17539 " double y);", 17540 Alignment)); 17541 // This ensures that function parameters of function declarations are 17542 // correctly indented when their owning functions are indented. 17543 // The failure case here is for 'double y' to not be indented enough. 17544 EXPECT_EQ("double a(int x);\n" 17545 "int b(int y,\n" 17546 " double z);", 17547 format("double a(int x);\n" 17548 "int b(int y,\n" 17549 " double z);", 17550 Alignment)); 17551 // Set ColumnLimit low so that we induce wrapping immediately after 17552 // the function name and opening paren. 17553 Alignment.ColumnLimit = 13; 17554 verifyFormat("int function(\n" 17555 " int x,\n" 17556 " bool y);", 17557 Alignment); 17558 Alignment.ColumnLimit = OldColumnLimit; 17559 // Ensure function pointers don't screw up recursive alignment 17560 verifyFormat("int a(int x, void (*fp)(int y));\n" 17561 "double b();", 17562 Alignment); 17563 Alignment.AlignConsecutiveAssignments.Enabled = true; 17564 // Ensure recursive alignment is broken by function braces, so that the 17565 // "a = 1" does not align with subsequent assignments inside the function 17566 // body. 17567 verifyFormat("int func(int a = 1) {\n" 17568 " int b = 2;\n" 17569 " int cc = 3;\n" 17570 "}", 17571 Alignment); 17572 verifyFormat("float something = 2000;\n" 17573 "double another = 911;\n" 17574 "int i = 1, j = 10;\n" 17575 "const int *oneMore = 1;\n" 17576 "unsigned i = 2;", 17577 Alignment); 17578 verifyFormat("int oneTwoThree = {0}; // comment\n" 17579 "unsigned oneTwo = 0; // comment", 17580 Alignment); 17581 // Make sure that scope is correctly tracked, in the absence of braces 17582 verifyFormat("for (int i = 0; i < n; i++)\n" 17583 " j = i;\n" 17584 "double x = 1;\n", 17585 Alignment); 17586 verifyFormat("if (int i = 0)\n" 17587 " j = i;\n" 17588 "double x = 1;\n", 17589 Alignment); 17590 // Ensure operator[] and operator() are comprehended 17591 verifyFormat("struct test {\n" 17592 " long long int foo();\n" 17593 " int operator[](int a);\n" 17594 " double bar();\n" 17595 "};\n", 17596 Alignment); 17597 verifyFormat("struct test {\n" 17598 " long long int foo();\n" 17599 " int operator()(int a);\n" 17600 " double bar();\n" 17601 "};\n", 17602 Alignment); 17603 // http://llvm.org/PR52914 17604 verifyFormat("char *a[] = {\"a\", // comment\n" 17605 " \"bb\"};\n" 17606 "int bbbbbbb = 0;", 17607 Alignment); 17608 17609 // PAS_Right 17610 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17611 " int const i = 1;\n" 17612 " int *j = 2;\n" 17613 " int big = 10000;\n" 17614 "\n" 17615 " unsigned oneTwoThree = 123;\n" 17616 " int oneTwo = 12;\n" 17617 " method();\n" 17618 " float k = 2;\n" 17619 " int ll = 10000;\n" 17620 "}", 17621 format("void SomeFunction(int parameter= 0) {\n" 17622 " int const i= 1;\n" 17623 " int *j=2;\n" 17624 " int big = 10000;\n" 17625 "\n" 17626 "unsigned oneTwoThree =123;\n" 17627 "int oneTwo = 12;\n" 17628 " method();\n" 17629 "float k= 2;\n" 17630 "int ll=10000;\n" 17631 "}", 17632 Alignment)); 17633 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17634 " int const i = 1;\n" 17635 " int **j = 2, ***k;\n" 17636 " int &k = i;\n" 17637 " int &&l = i + j;\n" 17638 " int big = 10000;\n" 17639 "\n" 17640 " unsigned oneTwoThree = 123;\n" 17641 " int oneTwo = 12;\n" 17642 " method();\n" 17643 " float k = 2;\n" 17644 " int ll = 10000;\n" 17645 "}", 17646 format("void SomeFunction(int parameter= 0) {\n" 17647 " int const i= 1;\n" 17648 " int **j=2,***k;\n" 17649 "int &k=i;\n" 17650 "int &&l=i+j;\n" 17651 " int big = 10000;\n" 17652 "\n" 17653 "unsigned oneTwoThree =123;\n" 17654 "int oneTwo = 12;\n" 17655 " method();\n" 17656 "float k= 2;\n" 17657 "int ll=10000;\n" 17658 "}", 17659 Alignment)); 17660 // variables are aligned at their name, pointers are at the right most 17661 // position 17662 verifyFormat("int *a;\n" 17663 "int **b;\n" 17664 "int ***c;\n" 17665 "int foobar;\n", 17666 Alignment); 17667 17668 // PAS_Left 17669 FormatStyle AlignmentLeft = Alignment; 17670 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17671 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17672 " int const i = 1;\n" 17673 " int* j = 2;\n" 17674 " int big = 10000;\n" 17675 "\n" 17676 " unsigned oneTwoThree = 123;\n" 17677 " int oneTwo = 12;\n" 17678 " method();\n" 17679 " float k = 2;\n" 17680 " int ll = 10000;\n" 17681 "}", 17682 format("void SomeFunction(int parameter= 0) {\n" 17683 " int const i= 1;\n" 17684 " int *j=2;\n" 17685 " int big = 10000;\n" 17686 "\n" 17687 "unsigned oneTwoThree =123;\n" 17688 "int oneTwo = 12;\n" 17689 " method();\n" 17690 "float k= 2;\n" 17691 "int ll=10000;\n" 17692 "}", 17693 AlignmentLeft)); 17694 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17695 " int const i = 1;\n" 17696 " int** j = 2;\n" 17697 " int& k = i;\n" 17698 " int&& l = i + j;\n" 17699 " int big = 10000;\n" 17700 "\n" 17701 " unsigned oneTwoThree = 123;\n" 17702 " int oneTwo = 12;\n" 17703 " method();\n" 17704 " float k = 2;\n" 17705 " int ll = 10000;\n" 17706 "}", 17707 format("void SomeFunction(int parameter= 0) {\n" 17708 " int const i= 1;\n" 17709 " int **j=2;\n" 17710 "int &k=i;\n" 17711 "int &&l=i+j;\n" 17712 " int big = 10000;\n" 17713 "\n" 17714 "unsigned oneTwoThree =123;\n" 17715 "int oneTwo = 12;\n" 17716 " method();\n" 17717 "float k= 2;\n" 17718 "int ll=10000;\n" 17719 "}", 17720 AlignmentLeft)); 17721 // variables are aligned at their name, pointers are at the left most position 17722 verifyFormat("int* a;\n" 17723 "int** b;\n" 17724 "int*** c;\n" 17725 "int foobar;\n", 17726 AlignmentLeft); 17727 17728 // PAS_Middle 17729 FormatStyle AlignmentMiddle = Alignment; 17730 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17731 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17732 " int const i = 1;\n" 17733 " int * j = 2;\n" 17734 " int big = 10000;\n" 17735 "\n" 17736 " unsigned oneTwoThree = 123;\n" 17737 " int oneTwo = 12;\n" 17738 " method();\n" 17739 " float k = 2;\n" 17740 " int ll = 10000;\n" 17741 "}", 17742 format("void SomeFunction(int parameter= 0) {\n" 17743 " int const i= 1;\n" 17744 " int *j=2;\n" 17745 " int big = 10000;\n" 17746 "\n" 17747 "unsigned oneTwoThree =123;\n" 17748 "int oneTwo = 12;\n" 17749 " method();\n" 17750 "float k= 2;\n" 17751 "int ll=10000;\n" 17752 "}", 17753 AlignmentMiddle)); 17754 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17755 " int const i = 1;\n" 17756 " int ** j = 2, ***k;\n" 17757 " int & k = i;\n" 17758 " int && l = i + j;\n" 17759 " int big = 10000;\n" 17760 "\n" 17761 " unsigned oneTwoThree = 123;\n" 17762 " int oneTwo = 12;\n" 17763 " method();\n" 17764 " float k = 2;\n" 17765 " int ll = 10000;\n" 17766 "}", 17767 format("void SomeFunction(int parameter= 0) {\n" 17768 " int const i= 1;\n" 17769 " int **j=2,***k;\n" 17770 "int &k=i;\n" 17771 "int &&l=i+j;\n" 17772 " int big = 10000;\n" 17773 "\n" 17774 "unsigned oneTwoThree =123;\n" 17775 "int oneTwo = 12;\n" 17776 " method();\n" 17777 "float k= 2;\n" 17778 "int ll=10000;\n" 17779 "}", 17780 AlignmentMiddle)); 17781 // variables are aligned at their name, pointers are in the middle 17782 verifyFormat("int * a;\n" 17783 "int * b;\n" 17784 "int *** c;\n" 17785 "int foobar;\n", 17786 AlignmentMiddle); 17787 17788 Alignment.AlignConsecutiveAssignments.Enabled = false; 17789 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17790 verifyFormat("#define A \\\n" 17791 " int aaaa = 12; \\\n" 17792 " float b = 23; \\\n" 17793 " const int ccc = 234; \\\n" 17794 " unsigned dddddddddd = 2345;", 17795 Alignment); 17796 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17797 verifyFormat("#define A \\\n" 17798 " int aaaa = 12; \\\n" 17799 " float b = 23; \\\n" 17800 " const int ccc = 234; \\\n" 17801 " unsigned dddddddddd = 2345;", 17802 Alignment); 17803 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17804 Alignment.ColumnLimit = 30; 17805 verifyFormat("#define A \\\n" 17806 " int aaaa = 12; \\\n" 17807 " float b = 23; \\\n" 17808 " const int ccc = 234; \\\n" 17809 " int dddddddddd = 2345;", 17810 Alignment); 17811 Alignment.ColumnLimit = 80; 17812 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17813 "k = 4, int l = 5,\n" 17814 " int m = 6) {\n" 17815 " const int j = 10;\n" 17816 " otherThing = 1;\n" 17817 "}", 17818 Alignment); 17819 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17820 " int const i = 1;\n" 17821 " int *j = 2;\n" 17822 " int big = 10000;\n" 17823 "}", 17824 Alignment); 17825 verifyFormat("class C {\n" 17826 "public:\n" 17827 " int i = 1;\n" 17828 " virtual void f() = 0;\n" 17829 "};", 17830 Alignment); 17831 verifyFormat("float i = 1;\n" 17832 "if (SomeType t = getSomething()) {\n" 17833 "}\n" 17834 "const unsigned j = 2;\n" 17835 "int big = 10000;", 17836 Alignment); 17837 verifyFormat("float j = 7;\n" 17838 "for (int k = 0; k < N; ++k) {\n" 17839 "}\n" 17840 "unsigned j = 2;\n" 17841 "int big = 10000;\n" 17842 "}", 17843 Alignment); 17844 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17845 verifyFormat("float i = 1;\n" 17846 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17847 " = someLooooooooooooooooongFunction();\n" 17848 "int j = 2;", 17849 Alignment); 17850 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17851 verifyFormat("int i = 1;\n" 17852 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17853 " someLooooooooooooooooongFunction();\n" 17854 "int j = 2;", 17855 Alignment); 17856 17857 Alignment.AlignConsecutiveAssignments.Enabled = true; 17858 verifyFormat("auto lambda = []() {\n" 17859 " auto ii = 0;\n" 17860 " float j = 0;\n" 17861 " return 0;\n" 17862 "};\n" 17863 "int i = 0;\n" 17864 "float i2 = 0;\n" 17865 "auto v = type{\n" 17866 " i = 1, //\n" 17867 " (i = 2), //\n" 17868 " i = 3 //\n" 17869 "};", 17870 Alignment); 17871 Alignment.AlignConsecutiveAssignments.Enabled = false; 17872 17873 verifyFormat( 17874 "int i = 1;\n" 17875 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17876 " loooooooooooooooooooooongParameterB);\n" 17877 "int j = 2;", 17878 Alignment); 17879 17880 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17881 // We expect declarations and assignments to align, as long as it doesn't 17882 // exceed the column limit, starting a new alignment sequence whenever it 17883 // happens. 17884 Alignment.AlignConsecutiveAssignments.Enabled = true; 17885 Alignment.ColumnLimit = 30; 17886 verifyFormat("float ii = 1;\n" 17887 "unsigned j = 2;\n" 17888 "int someVerylongVariable = 1;\n" 17889 "AnotherLongType ll = 123456;\n" 17890 "VeryVeryLongType k = 2;\n" 17891 "int myvar = 1;", 17892 Alignment); 17893 Alignment.ColumnLimit = 80; 17894 Alignment.AlignConsecutiveAssignments.Enabled = false; 17895 17896 verifyFormat( 17897 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17898 " typename LongType, typename B>\n" 17899 "auto foo() {}\n", 17900 Alignment); 17901 verifyFormat("float a, b = 1;\n" 17902 "int c = 2;\n" 17903 "int dd = 3;\n", 17904 Alignment); 17905 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17906 "float b[1][] = {{3.f}};\n", 17907 Alignment); 17908 Alignment.AlignConsecutiveAssignments.Enabled = true; 17909 verifyFormat("float a, b = 1;\n" 17910 "int c = 2;\n" 17911 "int dd = 3;\n", 17912 Alignment); 17913 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17914 "float b[1][] = {{3.f}};\n", 17915 Alignment); 17916 Alignment.AlignConsecutiveAssignments.Enabled = false; 17917 17918 Alignment.ColumnLimit = 30; 17919 Alignment.BinPackParameters = false; 17920 verifyFormat("void foo(float a,\n" 17921 " float b,\n" 17922 " int c,\n" 17923 " uint32_t *d) {\n" 17924 " int *e = 0;\n" 17925 " float f = 0;\n" 17926 " double g = 0;\n" 17927 "}\n" 17928 "void bar(ino_t a,\n" 17929 " int b,\n" 17930 " uint32_t *c,\n" 17931 " bool d) {}\n", 17932 Alignment); 17933 Alignment.BinPackParameters = true; 17934 Alignment.ColumnLimit = 80; 17935 17936 // Bug 33507 17937 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17938 verifyFormat( 17939 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17940 " static const Version verVs2017;\n" 17941 " return true;\n" 17942 "});\n", 17943 Alignment); 17944 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17945 17946 // See llvm.org/PR35641 17947 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17948 verifyFormat("int func() { //\n" 17949 " int b;\n" 17950 " unsigned c;\n" 17951 "}", 17952 Alignment); 17953 17954 // See PR37175 17955 FormatStyle Style = getMozillaStyle(); 17956 Style.AlignConsecutiveDeclarations.Enabled = true; 17957 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17958 "foo(int a);", 17959 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17960 17961 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17962 verifyFormat("unsigned int* a;\n" 17963 "int* b;\n" 17964 "unsigned int Const* c;\n" 17965 "unsigned int const* d;\n" 17966 "unsigned int Const& e;\n" 17967 "unsigned int const& f;", 17968 Alignment); 17969 verifyFormat("Const unsigned int* c;\n" 17970 "const unsigned int* d;\n" 17971 "Const unsigned int& e;\n" 17972 "const unsigned int& f;\n" 17973 "const unsigned g;\n" 17974 "Const unsigned h;", 17975 Alignment); 17976 17977 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17978 verifyFormat("unsigned int * a;\n" 17979 "int * b;\n" 17980 "unsigned int Const * c;\n" 17981 "unsigned int const * d;\n" 17982 "unsigned int Const & e;\n" 17983 "unsigned int const & f;", 17984 Alignment); 17985 verifyFormat("Const unsigned int * c;\n" 17986 "const unsigned int * d;\n" 17987 "Const unsigned int & e;\n" 17988 "const unsigned int & f;\n" 17989 "const unsigned g;\n" 17990 "Const unsigned h;", 17991 Alignment); 17992 17993 // See PR46529 17994 FormatStyle BracedAlign = getLLVMStyle(); 17995 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 17996 verifyFormat("const auto result{[]() {\n" 17997 " const auto something = 1;\n" 17998 " return 2;\n" 17999 "}};", 18000 BracedAlign); 18001 verifyFormat("int foo{[]() {\n" 18002 " int bar{0};\n" 18003 " return 0;\n" 18004 "}()};", 18005 BracedAlign); 18006 BracedAlign.Cpp11BracedListStyle = false; 18007 verifyFormat("const auto result{ []() {\n" 18008 " const auto something = 1;\n" 18009 " return 2;\n" 18010 "} };", 18011 BracedAlign); 18012 verifyFormat("int foo{ []() {\n" 18013 " int bar{ 0 };\n" 18014 " return 0;\n" 18015 "}() };", 18016 BracedAlign); 18017 } 18018 18019 TEST_F(FormatTest, AlignWithLineBreaks) { 18020 auto Style = getLLVMStyleWithColumns(120); 18021 18022 EXPECT_EQ(Style.AlignConsecutiveAssignments, 18023 FormatStyle::AlignConsecutiveStyle( 18024 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 18025 /*AcrossComments=*/false, /*AlignCompound=*/false, 18026 /*PadOperators=*/true})); 18027 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 18028 FormatStyle::AlignConsecutiveStyle({})); 18029 verifyFormat("void foo() {\n" 18030 " int myVar = 5;\n" 18031 " double x = 3.14;\n" 18032 " auto str = \"Hello \"\n" 18033 " \"World\";\n" 18034 " auto s = \"Hello \"\n" 18035 " \"Again\";\n" 18036 "}", 18037 Style); 18038 18039 // clang-format off 18040 verifyFormat("void foo() {\n" 18041 " const int capacityBefore = Entries.capacity();\n" 18042 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18043 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18044 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18045 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18046 "}", 18047 Style); 18048 // clang-format on 18049 18050 Style.AlignConsecutiveAssignments.Enabled = true; 18051 verifyFormat("void foo() {\n" 18052 " int myVar = 5;\n" 18053 " double x = 3.14;\n" 18054 " auto str = \"Hello \"\n" 18055 " \"World\";\n" 18056 " auto s = \"Hello \"\n" 18057 " \"Again\";\n" 18058 "}", 18059 Style); 18060 18061 // clang-format off 18062 verifyFormat("void foo() {\n" 18063 " const int capacityBefore = Entries.capacity();\n" 18064 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18065 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18066 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18067 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18068 "}", 18069 Style); 18070 // clang-format on 18071 18072 Style.AlignConsecutiveAssignments.Enabled = false; 18073 Style.AlignConsecutiveDeclarations.Enabled = true; 18074 verifyFormat("void foo() {\n" 18075 " int myVar = 5;\n" 18076 " double x = 3.14;\n" 18077 " auto str = \"Hello \"\n" 18078 " \"World\";\n" 18079 " auto s = \"Hello \"\n" 18080 " \"Again\";\n" 18081 "}", 18082 Style); 18083 18084 // clang-format off 18085 verifyFormat("void foo() {\n" 18086 " const int capacityBefore = Entries.capacity();\n" 18087 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18088 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18089 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18090 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18091 "}", 18092 Style); 18093 // clang-format on 18094 18095 Style.AlignConsecutiveAssignments.Enabled = true; 18096 Style.AlignConsecutiveDeclarations.Enabled = true; 18097 18098 verifyFormat("void foo() {\n" 18099 " int myVar = 5;\n" 18100 " double x = 3.14;\n" 18101 " auto str = \"Hello \"\n" 18102 " \"World\";\n" 18103 " auto s = \"Hello \"\n" 18104 " \"Again\";\n" 18105 "}", 18106 Style); 18107 18108 // clang-format off 18109 verifyFormat("void foo() {\n" 18110 " const int capacityBefore = Entries.capacity();\n" 18111 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18112 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18113 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18114 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18115 "}", 18116 Style); 18117 // clang-format on 18118 18119 Style = getLLVMStyleWithColumns(20); 18120 Style.AlignConsecutiveAssignments.Enabled = true; 18121 Style.IndentWidth = 4; 18122 18123 verifyFormat("void foo() {\n" 18124 " int i1 = 1;\n" 18125 " int j = 0;\n" 18126 " int k = bar(\n" 18127 " argument1,\n" 18128 " argument2);\n" 18129 "}", 18130 Style); 18131 18132 verifyFormat("unsigned i = 0;\n" 18133 "int a[] = {\n" 18134 " 1234567890,\n" 18135 " -1234567890};", 18136 Style); 18137 18138 Style.ColumnLimit = 120; 18139 18140 // clang-format off 18141 verifyFormat("void SomeFunc() {\n" 18142 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18143 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18144 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18145 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18146 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18147 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18148 "}", 18149 Style); 18150 // clang-format on 18151 18152 Style.BinPackArguments = false; 18153 18154 // clang-format off 18155 verifyFormat("void SomeFunc() {\n" 18156 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 18157 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18158 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 18159 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18160 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 18161 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18162 "}", 18163 Style); 18164 // clang-format on 18165 } 18166 18167 TEST_F(FormatTest, AlignWithInitializerPeriods) { 18168 auto Style = getLLVMStyleWithColumns(60); 18169 18170 verifyFormat("void foo1(void) {\n" 18171 " BYTE p[1] = 1;\n" 18172 " A B = {.one_foooooooooooooooo = 2,\n" 18173 " .two_fooooooooooooo = 3,\n" 18174 " .three_fooooooooooooo = 4};\n" 18175 " BYTE payload = 2;\n" 18176 "}", 18177 Style); 18178 18179 Style.AlignConsecutiveAssignments.Enabled = true; 18180 Style.AlignConsecutiveDeclarations.Enabled = false; 18181 verifyFormat("void foo2(void) {\n" 18182 " BYTE p[1] = 1;\n" 18183 " A B = {.one_foooooooooooooooo = 2,\n" 18184 " .two_fooooooooooooo = 3,\n" 18185 " .three_fooooooooooooo = 4};\n" 18186 " BYTE payload = 2;\n" 18187 "}", 18188 Style); 18189 18190 Style.AlignConsecutiveAssignments.Enabled = false; 18191 Style.AlignConsecutiveDeclarations.Enabled = true; 18192 verifyFormat("void foo3(void) {\n" 18193 " BYTE p[1] = 1;\n" 18194 " A B = {.one_foooooooooooooooo = 2,\n" 18195 " .two_fooooooooooooo = 3,\n" 18196 " .three_fooooooooooooo = 4};\n" 18197 " BYTE payload = 2;\n" 18198 "}", 18199 Style); 18200 18201 Style.AlignConsecutiveAssignments.Enabled = true; 18202 Style.AlignConsecutiveDeclarations.Enabled = true; 18203 verifyFormat("void foo4(void) {\n" 18204 " BYTE p[1] = 1;\n" 18205 " A B = {.one_foooooooooooooooo = 2,\n" 18206 " .two_fooooooooooooo = 3,\n" 18207 " .three_fooooooooooooo = 4};\n" 18208 " BYTE payload = 2;\n" 18209 "}", 18210 Style); 18211 } 18212 18213 TEST_F(FormatTest, LinuxBraceBreaking) { 18214 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18215 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18216 verifyFormat("namespace a\n" 18217 "{\n" 18218 "class A\n" 18219 "{\n" 18220 " void f()\n" 18221 " {\n" 18222 " if (true) {\n" 18223 " a();\n" 18224 " b();\n" 18225 " } else {\n" 18226 " a();\n" 18227 " }\n" 18228 " }\n" 18229 " void g() { return; }\n" 18230 "};\n" 18231 "struct B {\n" 18232 " int x;\n" 18233 "};\n" 18234 "} // namespace a\n", 18235 LinuxBraceStyle); 18236 verifyFormat("enum X {\n" 18237 " Y = 0,\n" 18238 "}\n", 18239 LinuxBraceStyle); 18240 verifyFormat("struct S {\n" 18241 " int Type;\n" 18242 " union {\n" 18243 " int x;\n" 18244 " double y;\n" 18245 " } Value;\n" 18246 " class C\n" 18247 " {\n" 18248 " MyFavoriteType Value;\n" 18249 " } Class;\n" 18250 "}\n", 18251 LinuxBraceStyle); 18252 } 18253 18254 TEST_F(FormatTest, MozillaBraceBreaking) { 18255 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18256 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18257 MozillaBraceStyle.FixNamespaceComments = false; 18258 verifyFormat("namespace a {\n" 18259 "class A\n" 18260 "{\n" 18261 " void f()\n" 18262 " {\n" 18263 " if (true) {\n" 18264 " a();\n" 18265 " b();\n" 18266 " }\n" 18267 " }\n" 18268 " void g() { return; }\n" 18269 "};\n" 18270 "enum E\n" 18271 "{\n" 18272 " A,\n" 18273 " // foo\n" 18274 " B,\n" 18275 " C\n" 18276 "};\n" 18277 "struct B\n" 18278 "{\n" 18279 " int x;\n" 18280 "};\n" 18281 "}\n", 18282 MozillaBraceStyle); 18283 verifyFormat("struct S\n" 18284 "{\n" 18285 " int Type;\n" 18286 " union\n" 18287 " {\n" 18288 " int x;\n" 18289 " double y;\n" 18290 " } Value;\n" 18291 " class C\n" 18292 " {\n" 18293 " MyFavoriteType Value;\n" 18294 " } Class;\n" 18295 "}\n", 18296 MozillaBraceStyle); 18297 } 18298 18299 TEST_F(FormatTest, StroustrupBraceBreaking) { 18300 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18301 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18302 verifyFormat("namespace a {\n" 18303 "class A {\n" 18304 " void f()\n" 18305 " {\n" 18306 " if (true) {\n" 18307 " a();\n" 18308 " b();\n" 18309 " }\n" 18310 " }\n" 18311 " void g() { return; }\n" 18312 "};\n" 18313 "struct B {\n" 18314 " int x;\n" 18315 "};\n" 18316 "} // namespace a\n", 18317 StroustrupBraceStyle); 18318 18319 verifyFormat("void foo()\n" 18320 "{\n" 18321 " if (a) {\n" 18322 " a();\n" 18323 " }\n" 18324 " else {\n" 18325 " b();\n" 18326 " }\n" 18327 "}\n", 18328 StroustrupBraceStyle); 18329 18330 verifyFormat("#ifdef _DEBUG\n" 18331 "int foo(int i = 0)\n" 18332 "#else\n" 18333 "int foo(int i = 5)\n" 18334 "#endif\n" 18335 "{\n" 18336 " return i;\n" 18337 "}", 18338 StroustrupBraceStyle); 18339 18340 verifyFormat("void foo() {}\n" 18341 "void bar()\n" 18342 "#ifdef _DEBUG\n" 18343 "{\n" 18344 " foo();\n" 18345 "}\n" 18346 "#else\n" 18347 "{\n" 18348 "}\n" 18349 "#endif", 18350 StroustrupBraceStyle); 18351 18352 verifyFormat("void foobar() { int i = 5; }\n" 18353 "#ifdef _DEBUG\n" 18354 "void bar() {}\n" 18355 "#else\n" 18356 "void bar() { foobar(); }\n" 18357 "#endif", 18358 StroustrupBraceStyle); 18359 } 18360 18361 TEST_F(FormatTest, AllmanBraceBreaking) { 18362 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18363 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18364 18365 EXPECT_EQ("namespace a\n" 18366 "{\n" 18367 "void f();\n" 18368 "void g();\n" 18369 "} // namespace a\n", 18370 format("namespace a\n" 18371 "{\n" 18372 "void f();\n" 18373 "void g();\n" 18374 "}\n", 18375 AllmanBraceStyle)); 18376 18377 verifyFormat("namespace a\n" 18378 "{\n" 18379 "class A\n" 18380 "{\n" 18381 " void f()\n" 18382 " {\n" 18383 " if (true)\n" 18384 " {\n" 18385 " a();\n" 18386 " b();\n" 18387 " }\n" 18388 " }\n" 18389 " void g() { return; }\n" 18390 "};\n" 18391 "struct B\n" 18392 "{\n" 18393 " int x;\n" 18394 "};\n" 18395 "union C\n" 18396 "{\n" 18397 "};\n" 18398 "} // namespace a", 18399 AllmanBraceStyle); 18400 18401 verifyFormat("void f()\n" 18402 "{\n" 18403 " if (true)\n" 18404 " {\n" 18405 " a();\n" 18406 " }\n" 18407 " else if (false)\n" 18408 " {\n" 18409 " b();\n" 18410 " }\n" 18411 " else\n" 18412 " {\n" 18413 " c();\n" 18414 " }\n" 18415 "}\n", 18416 AllmanBraceStyle); 18417 18418 verifyFormat("void f()\n" 18419 "{\n" 18420 " for (int i = 0; i < 10; ++i)\n" 18421 " {\n" 18422 " a();\n" 18423 " }\n" 18424 " while (false)\n" 18425 " {\n" 18426 " b();\n" 18427 " }\n" 18428 " do\n" 18429 " {\n" 18430 " c();\n" 18431 " } while (false)\n" 18432 "}\n", 18433 AllmanBraceStyle); 18434 18435 verifyFormat("void f(int a)\n" 18436 "{\n" 18437 " switch (a)\n" 18438 " {\n" 18439 " case 0:\n" 18440 " break;\n" 18441 " case 1:\n" 18442 " {\n" 18443 " break;\n" 18444 " }\n" 18445 " case 2:\n" 18446 " {\n" 18447 " }\n" 18448 " break;\n" 18449 " default:\n" 18450 " break;\n" 18451 " }\n" 18452 "}\n", 18453 AllmanBraceStyle); 18454 18455 verifyFormat("enum X\n" 18456 "{\n" 18457 " Y = 0,\n" 18458 "}\n", 18459 AllmanBraceStyle); 18460 verifyFormat("enum X\n" 18461 "{\n" 18462 " Y = 0\n" 18463 "}\n", 18464 AllmanBraceStyle); 18465 18466 verifyFormat("@interface BSApplicationController ()\n" 18467 "{\n" 18468 "@private\n" 18469 " id _extraIvar;\n" 18470 "}\n" 18471 "@end\n", 18472 AllmanBraceStyle); 18473 18474 verifyFormat("#ifdef _DEBUG\n" 18475 "int foo(int i = 0)\n" 18476 "#else\n" 18477 "int foo(int i = 5)\n" 18478 "#endif\n" 18479 "{\n" 18480 " return i;\n" 18481 "}", 18482 AllmanBraceStyle); 18483 18484 verifyFormat("void foo() {}\n" 18485 "void bar()\n" 18486 "#ifdef _DEBUG\n" 18487 "{\n" 18488 " foo();\n" 18489 "}\n" 18490 "#else\n" 18491 "{\n" 18492 "}\n" 18493 "#endif", 18494 AllmanBraceStyle); 18495 18496 verifyFormat("void foobar() { int i = 5; }\n" 18497 "#ifdef _DEBUG\n" 18498 "void bar() {}\n" 18499 "#else\n" 18500 "void bar() { foobar(); }\n" 18501 "#endif", 18502 AllmanBraceStyle); 18503 18504 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18505 FormatStyle::SLS_All); 18506 18507 verifyFormat("[](int i) { return i + 2; };\n" 18508 "[](int i, int j)\n" 18509 "{\n" 18510 " auto x = i + j;\n" 18511 " auto y = i * j;\n" 18512 " return x ^ y;\n" 18513 "};\n" 18514 "void foo()\n" 18515 "{\n" 18516 " auto shortLambda = [](int i) { return i + 2; };\n" 18517 " auto longLambda = [](int i, int j)\n" 18518 " {\n" 18519 " auto x = i + j;\n" 18520 " auto y = i * j;\n" 18521 " return x ^ y;\n" 18522 " };\n" 18523 "}", 18524 AllmanBraceStyle); 18525 18526 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18527 18528 verifyFormat("[](int i)\n" 18529 "{\n" 18530 " return i + 2;\n" 18531 "};\n" 18532 "[](int i, int j)\n" 18533 "{\n" 18534 " auto x = i + j;\n" 18535 " auto y = i * j;\n" 18536 " return x ^ y;\n" 18537 "};\n" 18538 "void foo()\n" 18539 "{\n" 18540 " auto shortLambda = [](int i)\n" 18541 " {\n" 18542 " return i + 2;\n" 18543 " };\n" 18544 " auto longLambda = [](int i, int j)\n" 18545 " {\n" 18546 " auto x = i + j;\n" 18547 " auto y = i * j;\n" 18548 " return x ^ y;\n" 18549 " };\n" 18550 "}", 18551 AllmanBraceStyle); 18552 18553 // Reset 18554 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18555 18556 // This shouldn't affect ObjC blocks.. 18557 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18558 " // ...\n" 18559 " int i;\n" 18560 "}];", 18561 AllmanBraceStyle); 18562 verifyFormat("void (^block)(void) = ^{\n" 18563 " // ...\n" 18564 " int i;\n" 18565 "};", 18566 AllmanBraceStyle); 18567 // .. or dict literals. 18568 verifyFormat("void f()\n" 18569 "{\n" 18570 " // ...\n" 18571 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18572 "}", 18573 AllmanBraceStyle); 18574 verifyFormat("void f()\n" 18575 "{\n" 18576 " // ...\n" 18577 " [object someMethod:@{a : @\"b\"}];\n" 18578 "}", 18579 AllmanBraceStyle); 18580 verifyFormat("int f()\n" 18581 "{ // comment\n" 18582 " return 42;\n" 18583 "}", 18584 AllmanBraceStyle); 18585 18586 AllmanBraceStyle.ColumnLimit = 19; 18587 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18588 AllmanBraceStyle.ColumnLimit = 18; 18589 verifyFormat("void f()\n" 18590 "{\n" 18591 " int i;\n" 18592 "}", 18593 AllmanBraceStyle); 18594 AllmanBraceStyle.ColumnLimit = 80; 18595 18596 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18597 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18598 FormatStyle::SIS_WithoutElse; 18599 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18600 verifyFormat("void f(bool b)\n" 18601 "{\n" 18602 " if (b)\n" 18603 " {\n" 18604 " return;\n" 18605 " }\n" 18606 "}\n", 18607 BreakBeforeBraceShortIfs); 18608 verifyFormat("void f(bool b)\n" 18609 "{\n" 18610 " if constexpr (b)\n" 18611 " {\n" 18612 " return;\n" 18613 " }\n" 18614 "}\n", 18615 BreakBeforeBraceShortIfs); 18616 verifyFormat("void f(bool b)\n" 18617 "{\n" 18618 " if CONSTEXPR (b)\n" 18619 " {\n" 18620 " return;\n" 18621 " }\n" 18622 "}\n", 18623 BreakBeforeBraceShortIfs); 18624 verifyFormat("void f(bool b)\n" 18625 "{\n" 18626 " if (b) return;\n" 18627 "}\n", 18628 BreakBeforeBraceShortIfs); 18629 verifyFormat("void f(bool b)\n" 18630 "{\n" 18631 " if constexpr (b) return;\n" 18632 "}\n", 18633 BreakBeforeBraceShortIfs); 18634 verifyFormat("void f(bool b)\n" 18635 "{\n" 18636 " if CONSTEXPR (b) return;\n" 18637 "}\n", 18638 BreakBeforeBraceShortIfs); 18639 verifyFormat("void f(bool b)\n" 18640 "{\n" 18641 " while (b)\n" 18642 " {\n" 18643 " return;\n" 18644 " }\n" 18645 "}\n", 18646 BreakBeforeBraceShortIfs); 18647 } 18648 18649 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18650 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18651 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18652 18653 // Make a few changes to the style for testing purposes 18654 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18655 FormatStyle::SFS_Empty; 18656 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18657 18658 // FIXME: this test case can't decide whether there should be a blank line 18659 // after the ~D() line or not. It adds one if one doesn't exist in the test 18660 // and it removes the line if one exists. 18661 /* 18662 verifyFormat("class A;\n" 18663 "namespace B\n" 18664 " {\n" 18665 "class C;\n" 18666 "// Comment\n" 18667 "class D\n" 18668 " {\n" 18669 "public:\n" 18670 " D();\n" 18671 " ~D() {}\n" 18672 "private:\n" 18673 " enum E\n" 18674 " {\n" 18675 " F\n" 18676 " }\n" 18677 " };\n" 18678 " } // namespace B\n", 18679 WhitesmithsBraceStyle); 18680 */ 18681 18682 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18683 verifyFormat("namespace a\n" 18684 " {\n" 18685 "class A\n" 18686 " {\n" 18687 " void f()\n" 18688 " {\n" 18689 " if (true)\n" 18690 " {\n" 18691 " a();\n" 18692 " b();\n" 18693 " }\n" 18694 " }\n" 18695 " void g()\n" 18696 " {\n" 18697 " return;\n" 18698 " }\n" 18699 " };\n" 18700 "struct B\n" 18701 " {\n" 18702 " int x;\n" 18703 " };\n" 18704 " } // namespace a", 18705 WhitesmithsBraceStyle); 18706 18707 verifyFormat("namespace a\n" 18708 " {\n" 18709 "namespace b\n" 18710 " {\n" 18711 "class A\n" 18712 " {\n" 18713 " void f()\n" 18714 " {\n" 18715 " if (true)\n" 18716 " {\n" 18717 " a();\n" 18718 " b();\n" 18719 " }\n" 18720 " }\n" 18721 " void g()\n" 18722 " {\n" 18723 " return;\n" 18724 " }\n" 18725 " };\n" 18726 "struct B\n" 18727 " {\n" 18728 " int x;\n" 18729 " };\n" 18730 " } // namespace b\n" 18731 " } // namespace a", 18732 WhitesmithsBraceStyle); 18733 18734 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18735 verifyFormat("namespace a\n" 18736 " {\n" 18737 "namespace b\n" 18738 " {\n" 18739 " class A\n" 18740 " {\n" 18741 " void f()\n" 18742 " {\n" 18743 " if (true)\n" 18744 " {\n" 18745 " a();\n" 18746 " b();\n" 18747 " }\n" 18748 " }\n" 18749 " void g()\n" 18750 " {\n" 18751 " return;\n" 18752 " }\n" 18753 " };\n" 18754 " struct B\n" 18755 " {\n" 18756 " int x;\n" 18757 " };\n" 18758 " } // namespace b\n" 18759 " } // namespace a", 18760 WhitesmithsBraceStyle); 18761 18762 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18763 verifyFormat("namespace a\n" 18764 " {\n" 18765 " namespace b\n" 18766 " {\n" 18767 " class A\n" 18768 " {\n" 18769 " void f()\n" 18770 " {\n" 18771 " if (true)\n" 18772 " {\n" 18773 " a();\n" 18774 " b();\n" 18775 " }\n" 18776 " }\n" 18777 " void g()\n" 18778 " {\n" 18779 " return;\n" 18780 " }\n" 18781 " };\n" 18782 " struct B\n" 18783 " {\n" 18784 " int x;\n" 18785 " };\n" 18786 " } // namespace b\n" 18787 " } // namespace a", 18788 WhitesmithsBraceStyle); 18789 18790 verifyFormat("void f()\n" 18791 " {\n" 18792 " if (true)\n" 18793 " {\n" 18794 " a();\n" 18795 " }\n" 18796 " else if (false)\n" 18797 " {\n" 18798 " b();\n" 18799 " }\n" 18800 " else\n" 18801 " {\n" 18802 " c();\n" 18803 " }\n" 18804 " }\n", 18805 WhitesmithsBraceStyle); 18806 18807 verifyFormat("void f()\n" 18808 " {\n" 18809 " for (int i = 0; i < 10; ++i)\n" 18810 " {\n" 18811 " a();\n" 18812 " }\n" 18813 " while (false)\n" 18814 " {\n" 18815 " b();\n" 18816 " }\n" 18817 " do\n" 18818 " {\n" 18819 " c();\n" 18820 " } while (false)\n" 18821 " }\n", 18822 WhitesmithsBraceStyle); 18823 18824 WhitesmithsBraceStyle.IndentCaseLabels = true; 18825 verifyFormat("void switchTest1(int a)\n" 18826 " {\n" 18827 " switch (a)\n" 18828 " {\n" 18829 " case 2:\n" 18830 " {\n" 18831 " }\n" 18832 " break;\n" 18833 " }\n" 18834 " }\n", 18835 WhitesmithsBraceStyle); 18836 18837 verifyFormat("void switchTest2(int a)\n" 18838 " {\n" 18839 " switch (a)\n" 18840 " {\n" 18841 " case 0:\n" 18842 " break;\n" 18843 " case 1:\n" 18844 " {\n" 18845 " break;\n" 18846 " }\n" 18847 " case 2:\n" 18848 " {\n" 18849 " }\n" 18850 " break;\n" 18851 " default:\n" 18852 " break;\n" 18853 " }\n" 18854 " }\n", 18855 WhitesmithsBraceStyle); 18856 18857 verifyFormat("void switchTest3(int a)\n" 18858 " {\n" 18859 " switch (a)\n" 18860 " {\n" 18861 " case 0:\n" 18862 " {\n" 18863 " foo(x);\n" 18864 " }\n" 18865 " break;\n" 18866 " default:\n" 18867 " {\n" 18868 " foo(1);\n" 18869 " }\n" 18870 " break;\n" 18871 " }\n" 18872 " }\n", 18873 WhitesmithsBraceStyle); 18874 18875 WhitesmithsBraceStyle.IndentCaseLabels = false; 18876 18877 verifyFormat("void switchTest4(int a)\n" 18878 " {\n" 18879 " switch (a)\n" 18880 " {\n" 18881 " case 2:\n" 18882 " {\n" 18883 " }\n" 18884 " break;\n" 18885 " }\n" 18886 " }\n", 18887 WhitesmithsBraceStyle); 18888 18889 verifyFormat("void switchTest5(int a)\n" 18890 " {\n" 18891 " switch (a)\n" 18892 " {\n" 18893 " case 0:\n" 18894 " break;\n" 18895 " case 1:\n" 18896 " {\n" 18897 " foo();\n" 18898 " break;\n" 18899 " }\n" 18900 " case 2:\n" 18901 " {\n" 18902 " }\n" 18903 " break;\n" 18904 " default:\n" 18905 " break;\n" 18906 " }\n" 18907 " }\n", 18908 WhitesmithsBraceStyle); 18909 18910 verifyFormat("void switchTest6(int a)\n" 18911 " {\n" 18912 " switch (a)\n" 18913 " {\n" 18914 " case 0:\n" 18915 " {\n" 18916 " foo(x);\n" 18917 " }\n" 18918 " break;\n" 18919 " default:\n" 18920 " {\n" 18921 " foo(1);\n" 18922 " }\n" 18923 " break;\n" 18924 " }\n" 18925 " }\n", 18926 WhitesmithsBraceStyle); 18927 18928 verifyFormat("enum X\n" 18929 " {\n" 18930 " Y = 0, // testing\n" 18931 " }\n", 18932 WhitesmithsBraceStyle); 18933 18934 verifyFormat("enum X\n" 18935 " {\n" 18936 " Y = 0\n" 18937 " }\n", 18938 WhitesmithsBraceStyle); 18939 verifyFormat("enum X\n" 18940 " {\n" 18941 " Y = 0,\n" 18942 " Z = 1\n" 18943 " };\n", 18944 WhitesmithsBraceStyle); 18945 18946 verifyFormat("@interface BSApplicationController ()\n" 18947 " {\n" 18948 "@private\n" 18949 " id _extraIvar;\n" 18950 " }\n" 18951 "@end\n", 18952 WhitesmithsBraceStyle); 18953 18954 verifyFormat("#ifdef _DEBUG\n" 18955 "int foo(int i = 0)\n" 18956 "#else\n" 18957 "int foo(int i = 5)\n" 18958 "#endif\n" 18959 " {\n" 18960 " return i;\n" 18961 " }", 18962 WhitesmithsBraceStyle); 18963 18964 verifyFormat("void foo() {}\n" 18965 "void bar()\n" 18966 "#ifdef _DEBUG\n" 18967 " {\n" 18968 " foo();\n" 18969 " }\n" 18970 "#else\n" 18971 " {\n" 18972 " }\n" 18973 "#endif", 18974 WhitesmithsBraceStyle); 18975 18976 verifyFormat("void foobar()\n" 18977 " {\n" 18978 " int i = 5;\n" 18979 " }\n" 18980 "#ifdef _DEBUG\n" 18981 "void bar()\n" 18982 " {\n" 18983 " }\n" 18984 "#else\n" 18985 "void bar()\n" 18986 " {\n" 18987 " foobar();\n" 18988 " }\n" 18989 "#endif", 18990 WhitesmithsBraceStyle); 18991 18992 // This shouldn't affect ObjC blocks.. 18993 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18994 " // ...\n" 18995 " int i;\n" 18996 "}];", 18997 WhitesmithsBraceStyle); 18998 verifyFormat("void (^block)(void) = ^{\n" 18999 " // ...\n" 19000 " int i;\n" 19001 "};", 19002 WhitesmithsBraceStyle); 19003 // .. or dict literals. 19004 verifyFormat("void f()\n" 19005 " {\n" 19006 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 19007 " }", 19008 WhitesmithsBraceStyle); 19009 19010 verifyFormat("int f()\n" 19011 " { // comment\n" 19012 " return 42;\n" 19013 " }", 19014 WhitesmithsBraceStyle); 19015 19016 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 19017 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 19018 FormatStyle::SIS_OnlyFirstIf; 19019 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 19020 verifyFormat("void f(bool b)\n" 19021 " {\n" 19022 " if (b)\n" 19023 " {\n" 19024 " return;\n" 19025 " }\n" 19026 " }\n", 19027 BreakBeforeBraceShortIfs); 19028 verifyFormat("void f(bool b)\n" 19029 " {\n" 19030 " if (b) return;\n" 19031 " }\n", 19032 BreakBeforeBraceShortIfs); 19033 verifyFormat("void f(bool b)\n" 19034 " {\n" 19035 " while (b)\n" 19036 " {\n" 19037 " return;\n" 19038 " }\n" 19039 " }\n", 19040 BreakBeforeBraceShortIfs); 19041 } 19042 19043 TEST_F(FormatTest, GNUBraceBreaking) { 19044 FormatStyle GNUBraceStyle = getLLVMStyle(); 19045 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 19046 verifyFormat("namespace a\n" 19047 "{\n" 19048 "class A\n" 19049 "{\n" 19050 " void f()\n" 19051 " {\n" 19052 " int a;\n" 19053 " {\n" 19054 " int b;\n" 19055 " }\n" 19056 " if (true)\n" 19057 " {\n" 19058 " a();\n" 19059 " b();\n" 19060 " }\n" 19061 " }\n" 19062 " void g() { return; }\n" 19063 "}\n" 19064 "} // namespace a", 19065 GNUBraceStyle); 19066 19067 verifyFormat("void f()\n" 19068 "{\n" 19069 " if (true)\n" 19070 " {\n" 19071 " a();\n" 19072 " }\n" 19073 " else if (false)\n" 19074 " {\n" 19075 " b();\n" 19076 " }\n" 19077 " else\n" 19078 " {\n" 19079 " c();\n" 19080 " }\n" 19081 "}\n", 19082 GNUBraceStyle); 19083 19084 verifyFormat("void f()\n" 19085 "{\n" 19086 " for (int i = 0; i < 10; ++i)\n" 19087 " {\n" 19088 " a();\n" 19089 " }\n" 19090 " while (false)\n" 19091 " {\n" 19092 " b();\n" 19093 " }\n" 19094 " do\n" 19095 " {\n" 19096 " c();\n" 19097 " }\n" 19098 " while (false);\n" 19099 "}\n", 19100 GNUBraceStyle); 19101 19102 verifyFormat("void f(int a)\n" 19103 "{\n" 19104 " switch (a)\n" 19105 " {\n" 19106 " case 0:\n" 19107 " break;\n" 19108 " case 1:\n" 19109 " {\n" 19110 " break;\n" 19111 " }\n" 19112 " case 2:\n" 19113 " {\n" 19114 " }\n" 19115 " break;\n" 19116 " default:\n" 19117 " break;\n" 19118 " }\n" 19119 "}\n", 19120 GNUBraceStyle); 19121 19122 verifyFormat("enum X\n" 19123 "{\n" 19124 " Y = 0,\n" 19125 "}\n", 19126 GNUBraceStyle); 19127 19128 verifyFormat("@interface BSApplicationController ()\n" 19129 "{\n" 19130 "@private\n" 19131 " id _extraIvar;\n" 19132 "}\n" 19133 "@end\n", 19134 GNUBraceStyle); 19135 19136 verifyFormat("#ifdef _DEBUG\n" 19137 "int foo(int i = 0)\n" 19138 "#else\n" 19139 "int foo(int i = 5)\n" 19140 "#endif\n" 19141 "{\n" 19142 " return i;\n" 19143 "}", 19144 GNUBraceStyle); 19145 19146 verifyFormat("void foo() {}\n" 19147 "void bar()\n" 19148 "#ifdef _DEBUG\n" 19149 "{\n" 19150 " foo();\n" 19151 "}\n" 19152 "#else\n" 19153 "{\n" 19154 "}\n" 19155 "#endif", 19156 GNUBraceStyle); 19157 19158 verifyFormat("void foobar() { int i = 5; }\n" 19159 "#ifdef _DEBUG\n" 19160 "void bar() {}\n" 19161 "#else\n" 19162 "void bar() { foobar(); }\n" 19163 "#endif", 19164 GNUBraceStyle); 19165 } 19166 19167 TEST_F(FormatTest, WebKitBraceBreaking) { 19168 FormatStyle WebKitBraceStyle = getLLVMStyle(); 19169 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 19170 WebKitBraceStyle.FixNamespaceComments = false; 19171 verifyFormat("namespace a {\n" 19172 "class A {\n" 19173 " void f()\n" 19174 " {\n" 19175 " if (true) {\n" 19176 " a();\n" 19177 " b();\n" 19178 " }\n" 19179 " }\n" 19180 " void g() { return; }\n" 19181 "};\n" 19182 "enum E {\n" 19183 " A,\n" 19184 " // foo\n" 19185 " B,\n" 19186 " C\n" 19187 "};\n" 19188 "struct B {\n" 19189 " int x;\n" 19190 "};\n" 19191 "}\n", 19192 WebKitBraceStyle); 19193 verifyFormat("struct S {\n" 19194 " int Type;\n" 19195 " union {\n" 19196 " int x;\n" 19197 " double y;\n" 19198 " } Value;\n" 19199 " class C {\n" 19200 " MyFavoriteType Value;\n" 19201 " } Class;\n" 19202 "};\n", 19203 WebKitBraceStyle); 19204 } 19205 19206 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19207 verifyFormat("void f() {\n" 19208 " try {\n" 19209 " } catch (const Exception &e) {\n" 19210 " }\n" 19211 "}\n", 19212 getLLVMStyle()); 19213 } 19214 19215 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19216 auto Style = getLLVMStyle(); 19217 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19218 Style.AlignConsecutiveAssignments.Enabled = true; 19219 Style.AlignConsecutiveDeclarations.Enabled = true; 19220 verifyFormat("struct test demo[] = {\n" 19221 " {56, 23, \"hello\"},\n" 19222 " {-1, 93463, \"world\"},\n" 19223 " { 7, 5, \"!!\"}\n" 19224 "};\n", 19225 Style); 19226 19227 verifyFormat("struct test demo[] = {\n" 19228 " {56, 23, \"hello\"}, // first line\n" 19229 " {-1, 93463, \"world\"}, // second line\n" 19230 " { 7, 5, \"!!\"} // third line\n" 19231 "};\n", 19232 Style); 19233 19234 verifyFormat("struct test demo[4] = {\n" 19235 " { 56, 23, 21, \"oh\"}, // first line\n" 19236 " { -1, 93463, 22, \"my\"}, // second line\n" 19237 " { 7, 5, 1, \"goodness\"} // third line\n" 19238 " {234, 5, 1, \"gracious\"} // fourth line\n" 19239 "};\n", 19240 Style); 19241 19242 verifyFormat("struct test demo[3] = {\n" 19243 " {56, 23, \"hello\"},\n" 19244 " {-1, 93463, \"world\"},\n" 19245 " { 7, 5, \"!!\"}\n" 19246 "};\n", 19247 Style); 19248 19249 verifyFormat("struct test demo[3] = {\n" 19250 " {int{56}, 23, \"hello\"},\n" 19251 " {int{-1}, 93463, \"world\"},\n" 19252 " { int{7}, 5, \"!!\"}\n" 19253 "};\n", 19254 Style); 19255 19256 verifyFormat("struct test demo[] = {\n" 19257 " {56, 23, \"hello\"},\n" 19258 " {-1, 93463, \"world\"},\n" 19259 " { 7, 5, \"!!\"},\n" 19260 "};\n", 19261 Style); 19262 19263 verifyFormat("test demo[] = {\n" 19264 " {56, 23, \"hello\"},\n" 19265 " {-1, 93463, \"world\"},\n" 19266 " { 7, 5, \"!!\"},\n" 19267 "};\n", 19268 Style); 19269 19270 verifyFormat("demo = std::array<struct test, 3>{\n" 19271 " test{56, 23, \"hello\"},\n" 19272 " test{-1, 93463, \"world\"},\n" 19273 " test{ 7, 5, \"!!\"},\n" 19274 "};\n", 19275 Style); 19276 19277 verifyFormat("test demo[] = {\n" 19278 " {56, 23, \"hello\"},\n" 19279 "#if X\n" 19280 " {-1, 93463, \"world\"},\n" 19281 "#endif\n" 19282 " { 7, 5, \"!!\"}\n" 19283 "};\n", 19284 Style); 19285 19286 verifyFormat( 19287 "test demo[] = {\n" 19288 " { 7, 23,\n" 19289 " \"hello world i am a very long line that really, in any\"\n" 19290 " \"just world, ought to be split over multiple lines\"},\n" 19291 " {-1, 93463, \"world\"},\n" 19292 " {56, 5, \"!!\"}\n" 19293 "};\n", 19294 Style); 19295 19296 verifyFormat("return GradForUnaryCwise(g, {\n" 19297 " {{\"sign\"}, \"Sign\", " 19298 " {\"x\", \"dy\"}},\n" 19299 " { {\"dx\"}, \"Mul\", {\"dy\"" 19300 ", \"sign\"}},\n" 19301 "});\n", 19302 Style); 19303 19304 Style.ColumnLimit = 0; 19305 EXPECT_EQ( 19306 "test demo[] = {\n" 19307 " {56, 23, \"hello world i am a very long line that really, " 19308 "in any just world, ought to be split over multiple lines\"},\n" 19309 " {-1, 93463, " 19310 " \"world\"},\n" 19311 " { 7, 5, " 19312 " \"!!\"},\n" 19313 "};", 19314 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19315 "that really, in any just world, ought to be split over multiple " 19316 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19317 Style)); 19318 19319 Style.ColumnLimit = 80; 19320 verifyFormat("test demo[] = {\n" 19321 " {56, 23, /* a comment */ \"hello\"},\n" 19322 " {-1, 93463, \"world\"},\n" 19323 " { 7, 5, \"!!\"}\n" 19324 "};\n", 19325 Style); 19326 19327 verifyFormat("test demo[] = {\n" 19328 " {56, 23, \"hello\"},\n" 19329 " {-1, 93463, \"world\" /* comment here */},\n" 19330 " { 7, 5, \"!!\"}\n" 19331 "};\n", 19332 Style); 19333 19334 verifyFormat("test demo[] = {\n" 19335 " {56, /* a comment */ 23, \"hello\"},\n" 19336 " {-1, 93463, \"world\"},\n" 19337 " { 7, 5, \"!!\"}\n" 19338 "};\n", 19339 Style); 19340 19341 Style.ColumnLimit = 20; 19342 EXPECT_EQ( 19343 "demo = std::array<\n" 19344 " struct test, 3>{\n" 19345 " test{\n" 19346 " 56, 23,\n" 19347 " \"hello \"\n" 19348 " \"world i \"\n" 19349 " \"am a very \"\n" 19350 " \"long line \"\n" 19351 " \"that \"\n" 19352 " \"really, \"\n" 19353 " \"in any \"\n" 19354 " \"just \"\n" 19355 " \"world, \"\n" 19356 " \"ought to \"\n" 19357 " \"be split \"\n" 19358 " \"over \"\n" 19359 " \"multiple \"\n" 19360 " \"lines\"},\n" 19361 " test{-1, 93463,\n" 19362 " \"world\"},\n" 19363 " test{ 7, 5,\n" 19364 " \"!!\" },\n" 19365 "};", 19366 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19367 "i am a very long line that really, in any just world, ought " 19368 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19369 "test{7, 5, \"!!\"},};", 19370 Style)); 19371 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19372 Style = getLLVMStyleWithColumns(50); 19373 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19374 verifyFormat("static A x = {\n" 19375 " {{init1, init2, init3, init4},\n" 19376 " {init1, init2, init3, init4}}\n" 19377 "};", 19378 Style); 19379 // TODO: Fix the indentations below when this option is fully functional. 19380 verifyFormat("int a[][] = {\n" 19381 " {\n" 19382 " {0, 2}, //\n" 19383 " {1, 2} //\n" 19384 " }\n" 19385 "};", 19386 Style); 19387 Style.ColumnLimit = 100; 19388 EXPECT_EQ( 19389 "test demo[] = {\n" 19390 " {56, 23,\n" 19391 " \"hello world i am a very long line that really, in any just world" 19392 ", ought to be split over \"\n" 19393 " \"multiple lines\" },\n" 19394 " {-1, 93463, \"world\"},\n" 19395 " { 7, 5, \"!!\"},\n" 19396 "};", 19397 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19398 "that really, in any just world, ought to be split over multiple " 19399 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19400 Style)); 19401 19402 Style = getLLVMStyleWithColumns(50); 19403 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19404 verifyFormat("struct test demo[] = {\n" 19405 " {56, 23, \"hello\"},\n" 19406 " {-1, 93463, \"world\"},\n" 19407 " { 7, 5, \"!!\"}\n" 19408 "};\n" 19409 "static A x = {\n" 19410 " {{init1, init2, init3, init4},\n" 19411 " {init1, init2, init3, init4}}\n" 19412 "};", 19413 Style); 19414 Style.ColumnLimit = 100; 19415 Style.AlignConsecutiveAssignments.AcrossComments = true; 19416 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19417 verifyFormat("struct test demo[] = {\n" 19418 " {56, 23, \"hello\"},\n" 19419 " {-1, 93463, \"world\"},\n" 19420 " { 7, 5, \"!!\"}\n" 19421 "};\n" 19422 "struct test demo[4] = {\n" 19423 " { 56, 23, 21, \"oh\"}, // first line\n" 19424 " { -1, 93463, 22, \"my\"}, // second line\n" 19425 " { 7, 5, 1, \"goodness\"} // third line\n" 19426 " {234, 5, 1, \"gracious\"} // fourth line\n" 19427 "};\n", 19428 Style); 19429 EXPECT_EQ( 19430 "test demo[] = {\n" 19431 " {56,\n" 19432 " \"hello world i am a very long line that really, in any just world" 19433 ", ought to be split over \"\n" 19434 " \"multiple lines\", 23},\n" 19435 " {-1, \"world\", 93463},\n" 19436 " { 7, \"!!\", 5},\n" 19437 "};", 19438 format("test demo[] = {{56, \"hello world i am a very long line " 19439 "that really, in any just world, ought to be split over multiple " 19440 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19441 Style)); 19442 } 19443 19444 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19445 auto Style = getLLVMStyle(); 19446 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19447 /* FIXME: This case gets misformatted. 19448 verifyFormat("auto foo = Items{\n" 19449 " Section{0, bar(), },\n" 19450 " Section{1, boo() }\n" 19451 "};\n", 19452 Style); 19453 */ 19454 verifyFormat("auto foo = Items{\n" 19455 " Section{\n" 19456 " 0, bar(),\n" 19457 " }\n" 19458 "};\n", 19459 Style); 19460 verifyFormat("struct test demo[] = {\n" 19461 " {56, 23, \"hello\"},\n" 19462 " {-1, 93463, \"world\"},\n" 19463 " {7, 5, \"!!\" }\n" 19464 "};\n", 19465 Style); 19466 verifyFormat("struct test demo[] = {\n" 19467 " {56, 23, \"hello\"}, // first line\n" 19468 " {-1, 93463, \"world\"}, // second line\n" 19469 " {7, 5, \"!!\" } // third line\n" 19470 "};\n", 19471 Style); 19472 verifyFormat("struct test demo[4] = {\n" 19473 " {56, 23, 21, \"oh\" }, // first line\n" 19474 " {-1, 93463, 22, \"my\" }, // second line\n" 19475 " {7, 5, 1, \"goodness\"} // third line\n" 19476 " {234, 5, 1, \"gracious\"} // fourth line\n" 19477 "};\n", 19478 Style); 19479 verifyFormat("struct test demo[3] = {\n" 19480 " {56, 23, \"hello\"},\n" 19481 " {-1, 93463, \"world\"},\n" 19482 " {7, 5, \"!!\" }\n" 19483 "};\n", 19484 Style); 19485 19486 verifyFormat("struct test demo[3] = {\n" 19487 " {int{56}, 23, \"hello\"},\n" 19488 " {int{-1}, 93463, \"world\"},\n" 19489 " {int{7}, 5, \"!!\" }\n" 19490 "};\n", 19491 Style); 19492 verifyFormat("struct test demo[] = {\n" 19493 " {56, 23, \"hello\"},\n" 19494 " {-1, 93463, \"world\"},\n" 19495 " {7, 5, \"!!\" },\n" 19496 "};\n", 19497 Style); 19498 verifyFormat("test demo[] = {\n" 19499 " {56, 23, \"hello\"},\n" 19500 " {-1, 93463, \"world\"},\n" 19501 " {7, 5, \"!!\" },\n" 19502 "};\n", 19503 Style); 19504 verifyFormat("demo = std::array<struct test, 3>{\n" 19505 " test{56, 23, \"hello\"},\n" 19506 " test{-1, 93463, \"world\"},\n" 19507 " test{7, 5, \"!!\" },\n" 19508 "};\n", 19509 Style); 19510 verifyFormat("test demo[] = {\n" 19511 " {56, 23, \"hello\"},\n" 19512 "#if X\n" 19513 " {-1, 93463, \"world\"},\n" 19514 "#endif\n" 19515 " {7, 5, \"!!\" }\n" 19516 "};\n", 19517 Style); 19518 verifyFormat( 19519 "test demo[] = {\n" 19520 " {7, 23,\n" 19521 " \"hello world i am a very long line that really, in any\"\n" 19522 " \"just world, ought to be split over multiple lines\"},\n" 19523 " {-1, 93463, \"world\" },\n" 19524 " {56, 5, \"!!\" }\n" 19525 "};\n", 19526 Style); 19527 19528 verifyFormat("return GradForUnaryCwise(g, {\n" 19529 " {{\"sign\"}, \"Sign\", {\"x\", " 19530 "\"dy\"} },\n" 19531 " {{\"dx\"}, \"Mul\", " 19532 "{\"dy\", \"sign\"}},\n" 19533 "});\n", 19534 Style); 19535 19536 Style.ColumnLimit = 0; 19537 EXPECT_EQ( 19538 "test demo[] = {\n" 19539 " {56, 23, \"hello world i am a very long line that really, in any " 19540 "just world, ought to be split over multiple lines\"},\n" 19541 " {-1, 93463, \"world\" " 19542 " },\n" 19543 " {7, 5, \"!!\" " 19544 " },\n" 19545 "};", 19546 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19547 "that really, in any just world, ought to be split over multiple " 19548 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19549 Style)); 19550 19551 Style.ColumnLimit = 80; 19552 verifyFormat("test demo[] = {\n" 19553 " {56, 23, /* a comment */ \"hello\"},\n" 19554 " {-1, 93463, \"world\" },\n" 19555 " {7, 5, \"!!\" }\n" 19556 "};\n", 19557 Style); 19558 19559 verifyFormat("test demo[] = {\n" 19560 " {56, 23, \"hello\" },\n" 19561 " {-1, 93463, \"world\" /* comment here */},\n" 19562 " {7, 5, \"!!\" }\n" 19563 "};\n", 19564 Style); 19565 19566 verifyFormat("test demo[] = {\n" 19567 " {56, /* a comment */ 23, \"hello\"},\n" 19568 " {-1, 93463, \"world\"},\n" 19569 " {7, 5, \"!!\" }\n" 19570 "};\n", 19571 Style); 19572 19573 Style.ColumnLimit = 20; 19574 EXPECT_EQ( 19575 "demo = std::array<\n" 19576 " struct test, 3>{\n" 19577 " test{\n" 19578 " 56, 23,\n" 19579 " \"hello \"\n" 19580 " \"world i \"\n" 19581 " \"am a very \"\n" 19582 " \"long line \"\n" 19583 " \"that \"\n" 19584 " \"really, \"\n" 19585 " \"in any \"\n" 19586 " \"just \"\n" 19587 " \"world, \"\n" 19588 " \"ought to \"\n" 19589 " \"be split \"\n" 19590 " \"over \"\n" 19591 " \"multiple \"\n" 19592 " \"lines\"},\n" 19593 " test{-1, 93463,\n" 19594 " \"world\"},\n" 19595 " test{7, 5,\n" 19596 " \"!!\" },\n" 19597 "};", 19598 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19599 "i am a very long line that really, in any just world, ought " 19600 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19601 "test{7, 5, \"!!\"},};", 19602 Style)); 19603 19604 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19605 Style = getLLVMStyleWithColumns(50); 19606 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19607 verifyFormat("static A x = {\n" 19608 " {{init1, init2, init3, init4},\n" 19609 " {init1, init2, init3, init4}}\n" 19610 "};", 19611 Style); 19612 Style.ColumnLimit = 100; 19613 EXPECT_EQ( 19614 "test demo[] = {\n" 19615 " {56, 23,\n" 19616 " \"hello world i am a very long line that really, in any just world" 19617 ", ought to be split over \"\n" 19618 " \"multiple lines\" },\n" 19619 " {-1, 93463, \"world\"},\n" 19620 " {7, 5, \"!!\" },\n" 19621 "};", 19622 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19623 "that really, in any just world, ought to be split over multiple " 19624 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19625 Style)); 19626 } 19627 19628 TEST_F(FormatTest, UnderstandsPragmas) { 19629 verifyFormat("#pragma omp reduction(| : var)"); 19630 verifyFormat("#pragma omp reduction(+ : var)"); 19631 19632 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19633 "(including parentheses).", 19634 format("#pragma mark Any non-hyphenated or hyphenated string " 19635 "(including parentheses).")); 19636 } 19637 19638 TEST_F(FormatTest, UnderstandPragmaOption) { 19639 verifyFormat("#pragma option -C -A"); 19640 19641 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19642 } 19643 19644 TEST_F(FormatTest, UnderstandPragmaRegion) { 19645 auto Style = getLLVMStyleWithColumns(0); 19646 verifyFormat("#pragma region TEST(FOO : BAR)", Style); 19647 19648 EXPECT_EQ("#pragma region TEST(FOO : BAR)", 19649 format("#pragma region TEST(FOO : BAR)", Style)); 19650 } 19651 19652 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19653 FormatStyle Style = getLLVMStyleWithColumns(20); 19654 19655 // See PR41213 19656 EXPECT_EQ("/*\n" 19657 " *\t9012345\n" 19658 " * /8901\n" 19659 " */", 19660 format("/*\n" 19661 " *\t9012345 /8901\n" 19662 " */", 19663 Style)); 19664 EXPECT_EQ("/*\n" 19665 " *345678\n" 19666 " *\t/8901\n" 19667 " */", 19668 format("/*\n" 19669 " *345678\t/8901\n" 19670 " */", 19671 Style)); 19672 19673 verifyFormat("int a; // the\n" 19674 " // comment", 19675 Style); 19676 EXPECT_EQ("int a; /* first line\n" 19677 " * second\n" 19678 " * line third\n" 19679 " * line\n" 19680 " */", 19681 format("int a; /* first line\n" 19682 " * second\n" 19683 " * line third\n" 19684 " * line\n" 19685 " */", 19686 Style)); 19687 EXPECT_EQ("int a; // first line\n" 19688 " // second\n" 19689 " // line third\n" 19690 " // line", 19691 format("int a; // first line\n" 19692 " // second line\n" 19693 " // third line", 19694 Style)); 19695 19696 Style.PenaltyExcessCharacter = 90; 19697 verifyFormat("int a; // the comment", Style); 19698 EXPECT_EQ("int a; // the comment\n" 19699 " // aaa", 19700 format("int a; // the comment aaa", Style)); 19701 EXPECT_EQ("int a; /* first line\n" 19702 " * second line\n" 19703 " * third line\n" 19704 " */", 19705 format("int a; /* first line\n" 19706 " * second line\n" 19707 " * third line\n" 19708 " */", 19709 Style)); 19710 EXPECT_EQ("int a; // first line\n" 19711 " // second line\n" 19712 " // third line", 19713 format("int a; // first line\n" 19714 " // second line\n" 19715 " // third line", 19716 Style)); 19717 // FIXME: Investigate why this is not getting the same layout as the test 19718 // above. 19719 EXPECT_EQ("int a; /* first line\n" 19720 " * second line\n" 19721 " * third line\n" 19722 " */", 19723 format("int a; /* first line second line third line" 19724 "\n*/", 19725 Style)); 19726 19727 EXPECT_EQ("// foo bar baz bazfoo\n" 19728 "// foo bar foo bar\n", 19729 format("// foo bar baz bazfoo\n" 19730 "// foo bar foo bar\n", 19731 Style)); 19732 EXPECT_EQ("// foo bar baz bazfoo\n" 19733 "// foo bar foo bar\n", 19734 format("// foo bar baz bazfoo\n" 19735 "// foo bar foo bar\n", 19736 Style)); 19737 19738 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19739 // next one. 19740 EXPECT_EQ("// foo bar baz bazfoo\n" 19741 "// bar foo bar\n", 19742 format("// foo bar baz bazfoo bar\n" 19743 "// foo bar\n", 19744 Style)); 19745 19746 EXPECT_EQ("// foo bar baz bazfoo\n" 19747 "// foo bar baz bazfoo\n" 19748 "// bar foo bar\n", 19749 format("// foo bar baz bazfoo\n" 19750 "// foo bar baz bazfoo bar\n" 19751 "// foo bar\n", 19752 Style)); 19753 19754 EXPECT_EQ("// foo bar baz bazfoo\n" 19755 "// foo bar baz bazfoo\n" 19756 "// bar foo bar\n", 19757 format("// foo bar baz bazfoo\n" 19758 "// foo bar baz bazfoo bar\n" 19759 "// foo bar\n", 19760 Style)); 19761 19762 // Make sure we do not keep protruding characters if strict mode reflow is 19763 // cheaper than keeping protruding characters. 19764 Style.ColumnLimit = 21; 19765 EXPECT_EQ( 19766 "// foo foo foo foo\n" 19767 "// foo foo foo foo\n" 19768 "// foo foo foo foo\n", 19769 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19770 19771 EXPECT_EQ("int a = /* long block\n" 19772 " comment */\n" 19773 " 42;", 19774 format("int a = /* long block comment */ 42;", Style)); 19775 } 19776 19777 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19778 FormatStyle Style = getLLVMStyle(); 19779 Style.ColumnLimit = 8; 19780 Style.PenaltyExcessCharacter = 15; 19781 verifyFormat("int foo(\n" 19782 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19783 Style); 19784 Style.PenaltyBreakOpenParenthesis = 200; 19785 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19786 format("int foo(\n" 19787 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19788 Style)); 19789 } 19790 19791 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19792 FormatStyle Style = getLLVMStyle(); 19793 Style.ColumnLimit = 5; 19794 Style.PenaltyExcessCharacter = 150; 19795 verifyFormat("foo((\n" 19796 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19797 19798 Style); 19799 Style.PenaltyBreakOpenParenthesis = 100000; 19800 EXPECT_EQ("foo((int)\n" 19801 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19802 format("foo((\n" 19803 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19804 Style)); 19805 } 19806 19807 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19808 FormatStyle Style = getLLVMStyle(); 19809 Style.ColumnLimit = 4; 19810 Style.PenaltyExcessCharacter = 100; 19811 verifyFormat("for (\n" 19812 " int iiiiiiiiiiiiiiiii =\n" 19813 " 0;\n" 19814 " iiiiiiiiiiiiiiiii <\n" 19815 " 2;\n" 19816 " iiiiiiiiiiiiiiiii++) {\n" 19817 "}", 19818 19819 Style); 19820 Style.PenaltyBreakOpenParenthesis = 1250; 19821 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19822 " 0;\n" 19823 " iiiiiiiiiiiiiiiii <\n" 19824 " 2;\n" 19825 " iiiiiiiiiiiiiiiii++) {\n" 19826 "}", 19827 format("for (\n" 19828 " int iiiiiiiiiiiiiiiii =\n" 19829 " 0;\n" 19830 " iiiiiiiiiiiiiiiii <\n" 19831 " 2;\n" 19832 " iiiiiiiiiiiiiiiii++) {\n" 19833 "}", 19834 Style)); 19835 } 19836 19837 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19838 for (size_t i = 1; i < Styles.size(); ++i) \ 19839 EXPECT_EQ(Styles[0], Styles[i]) \ 19840 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19841 19842 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19843 SmallVector<FormatStyle, 3> Styles; 19844 Styles.resize(3); 19845 19846 Styles[0] = getLLVMStyle(); 19847 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19848 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19849 EXPECT_ALL_STYLES_EQUAL(Styles); 19850 19851 Styles[0] = getGoogleStyle(); 19852 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19853 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19854 EXPECT_ALL_STYLES_EQUAL(Styles); 19855 19856 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19857 EXPECT_TRUE( 19858 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19859 EXPECT_TRUE( 19860 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19861 EXPECT_ALL_STYLES_EQUAL(Styles); 19862 19863 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19864 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19865 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19866 EXPECT_ALL_STYLES_EQUAL(Styles); 19867 19868 Styles[0] = getMozillaStyle(); 19869 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19870 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19871 EXPECT_ALL_STYLES_EQUAL(Styles); 19872 19873 Styles[0] = getWebKitStyle(); 19874 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19875 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19876 EXPECT_ALL_STYLES_EQUAL(Styles); 19877 19878 Styles[0] = getGNUStyle(); 19879 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19880 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19881 EXPECT_ALL_STYLES_EQUAL(Styles); 19882 19883 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19884 } 19885 19886 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19887 SmallVector<FormatStyle, 8> Styles; 19888 Styles.resize(2); 19889 19890 Styles[0] = getGoogleStyle(); 19891 Styles[1] = getLLVMStyle(); 19892 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19893 EXPECT_ALL_STYLES_EQUAL(Styles); 19894 19895 Styles.resize(5); 19896 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19897 Styles[1] = getLLVMStyle(); 19898 Styles[1].Language = FormatStyle::LK_JavaScript; 19899 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19900 19901 Styles[2] = getLLVMStyle(); 19902 Styles[2].Language = FormatStyle::LK_JavaScript; 19903 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19904 "BasedOnStyle: Google", 19905 &Styles[2]) 19906 .value()); 19907 19908 Styles[3] = getLLVMStyle(); 19909 Styles[3].Language = FormatStyle::LK_JavaScript; 19910 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19911 "Language: JavaScript", 19912 &Styles[3]) 19913 .value()); 19914 19915 Styles[4] = getLLVMStyle(); 19916 Styles[4].Language = FormatStyle::LK_JavaScript; 19917 EXPECT_EQ(0, parseConfiguration("---\n" 19918 "BasedOnStyle: LLVM\n" 19919 "IndentWidth: 123\n" 19920 "---\n" 19921 "BasedOnStyle: Google\n" 19922 "Language: JavaScript", 19923 &Styles[4]) 19924 .value()); 19925 EXPECT_ALL_STYLES_EQUAL(Styles); 19926 } 19927 19928 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19929 Style.FIELD = false; \ 19930 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19931 EXPECT_TRUE(Style.FIELD); \ 19932 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19933 EXPECT_FALSE(Style.FIELD); 19934 19935 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19936 19937 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19938 Style.STRUCT.FIELD = false; \ 19939 EXPECT_EQ(0, \ 19940 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19941 .value()); \ 19942 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19943 EXPECT_EQ(0, \ 19944 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19945 .value()); \ 19946 EXPECT_FALSE(Style.STRUCT.FIELD); 19947 19948 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19949 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19950 19951 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19952 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19953 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19954 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19955 19956 TEST_F(FormatTest, ParsesConfigurationBools) { 19957 FormatStyle Style = {}; 19958 Style.Language = FormatStyle::LK_Cpp; 19959 CHECK_PARSE_BOOL(AlignTrailingComments); 19960 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19961 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19962 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19963 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19964 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19965 CHECK_PARSE_BOOL(BinPackArguments); 19966 CHECK_PARSE_BOOL(BinPackParameters); 19967 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19968 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19969 CHECK_PARSE_BOOL(BreakStringLiterals); 19970 CHECK_PARSE_BOOL(CompactNamespaces); 19971 CHECK_PARSE_BOOL(DeriveLineEnding); 19972 CHECK_PARSE_BOOL(DerivePointerAlignment); 19973 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19974 CHECK_PARSE_BOOL(DisableFormat); 19975 CHECK_PARSE_BOOL(IndentAccessModifiers); 19976 CHECK_PARSE_BOOL(IndentCaseLabels); 19977 CHECK_PARSE_BOOL(IndentCaseBlocks); 19978 CHECK_PARSE_BOOL(IndentGotoLabels); 19979 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19980 CHECK_PARSE_BOOL(IndentRequiresClause); 19981 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19982 CHECK_PARSE_BOOL(InsertBraces); 19983 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19984 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19985 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19986 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19987 CHECK_PARSE_BOOL(ReflowComments); 19988 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19989 CHECK_PARSE_BOOL(SortUsingDeclarations); 19990 CHECK_PARSE_BOOL(SpacesInParentheses); 19991 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19992 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19993 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19994 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19995 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19996 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19997 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19998 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19999 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 20000 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 20001 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 20002 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 20003 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 20004 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 20005 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 20006 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 20007 CHECK_PARSE_BOOL(UseCRLF); 20008 20009 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 20010 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 20011 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 20012 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 20013 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 20014 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 20015 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 20016 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 20017 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 20018 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 20019 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 20020 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 20021 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 20022 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 20023 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 20024 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 20025 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 20026 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 20027 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 20028 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 20029 AfterFunctionDeclarationName); 20030 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 20031 AfterFunctionDefinitionName); 20032 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 20033 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 20034 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 20035 } 20036 20037 #undef CHECK_PARSE_BOOL 20038 20039 TEST_F(FormatTest, ParsesConfiguration) { 20040 FormatStyle Style = {}; 20041 Style.Language = FormatStyle::LK_Cpp; 20042 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 20043 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 20044 ConstructorInitializerIndentWidth, 1234u); 20045 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 20046 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 20047 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 20048 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 20049 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 20050 PenaltyBreakBeforeFirstCallParameter, 1234u); 20051 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 20052 PenaltyBreakTemplateDeclaration, 1234u); 20053 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 20054 1234u); 20055 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 20056 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 20057 PenaltyReturnTypeOnItsOwnLine, 1234u); 20058 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 20059 SpacesBeforeTrailingComments, 1234u); 20060 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 20061 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 20062 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 20063 20064 Style.QualifierAlignment = FormatStyle::QAS_Right; 20065 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 20066 FormatStyle::QAS_Leave); 20067 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 20068 FormatStyle::QAS_Right); 20069 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 20070 FormatStyle::QAS_Left); 20071 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 20072 FormatStyle::QAS_Custom); 20073 20074 Style.QualifierOrder.clear(); 20075 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 20076 std::vector<std::string>({"const", "volatile", "type"})); 20077 Style.QualifierOrder.clear(); 20078 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 20079 std::vector<std::string>({"const", "type"})); 20080 Style.QualifierOrder.clear(); 20081 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 20082 std::vector<std::string>({"volatile", "type"})); 20083 20084 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 20085 do { \ 20086 Style.FIELD.Enabled = true; \ 20087 CHECK_PARSE(#FIELD ": None", FIELD, \ 20088 FormatStyle::AlignConsecutiveStyle( \ 20089 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20090 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20091 /*PadOperators=*/true})); \ 20092 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 20093 FormatStyle::AlignConsecutiveStyle( \ 20094 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20095 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20096 /*PadOperators=*/true})); \ 20097 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 20098 FormatStyle::AlignConsecutiveStyle( \ 20099 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20100 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20101 /*PadOperators=*/true})); \ 20102 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 20103 FormatStyle::AlignConsecutiveStyle( \ 20104 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20105 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 20106 /*PadOperators=*/true})); \ 20107 /* For backwards compability, false / true should still parse */ \ 20108 CHECK_PARSE(#FIELD ": false", FIELD, \ 20109 FormatStyle::AlignConsecutiveStyle( \ 20110 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20111 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20112 /*PadOperators=*/true})); \ 20113 CHECK_PARSE(#FIELD ": true", FIELD, \ 20114 FormatStyle::AlignConsecutiveStyle( \ 20115 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20116 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20117 /*PadOperators=*/true})); \ 20118 \ 20119 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 20120 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 20121 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 20122 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 20123 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 20124 } while (false) 20125 20126 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 20127 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 20128 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 20129 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 20130 20131 #undef CHECK_ALIGN_CONSECUTIVE 20132 20133 Style.PointerAlignment = FormatStyle::PAS_Middle; 20134 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 20135 FormatStyle::PAS_Left); 20136 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 20137 FormatStyle::PAS_Right); 20138 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 20139 FormatStyle::PAS_Middle); 20140 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 20141 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 20142 FormatStyle::RAS_Pointer); 20143 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 20144 FormatStyle::RAS_Left); 20145 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 20146 FormatStyle::RAS_Right); 20147 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 20148 FormatStyle::RAS_Middle); 20149 // For backward compatibility: 20150 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 20151 FormatStyle::PAS_Left); 20152 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 20153 FormatStyle::PAS_Right); 20154 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 20155 FormatStyle::PAS_Middle); 20156 20157 Style.Standard = FormatStyle::LS_Auto; 20158 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 20159 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 20160 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 20161 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 20162 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 20163 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 20164 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 20165 // Legacy aliases: 20166 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 20167 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 20168 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 20169 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 20170 20171 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 20172 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 20173 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 20174 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 20175 FormatStyle::BOS_None); 20176 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 20177 FormatStyle::BOS_All); 20178 // For backward compatibility: 20179 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 20180 FormatStyle::BOS_None); 20181 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 20182 FormatStyle::BOS_All); 20183 20184 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20185 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20186 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20187 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20188 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20189 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20190 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20191 // For backward compatibility: 20192 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20193 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20194 20195 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20196 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20197 FormatStyle::BILS_AfterComma); 20198 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20199 FormatStyle::BILS_BeforeComma); 20200 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20201 FormatStyle::BILS_AfterColon); 20202 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20203 FormatStyle::BILS_BeforeColon); 20204 // For backward compatibility: 20205 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20206 FormatStyle::BILS_BeforeComma); 20207 20208 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20209 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20210 FormatStyle::PCIS_Never); 20211 CHECK_PARSE("PackConstructorInitializers: BinPack", 20212 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20213 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20214 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20215 CHECK_PARSE("PackConstructorInitializers: NextLine", 20216 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20217 // For backward compatibility: 20218 CHECK_PARSE("BasedOnStyle: Google\n" 20219 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20220 "AllowAllConstructorInitializersOnNextLine: false", 20221 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20222 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20223 CHECK_PARSE("BasedOnStyle: Google\n" 20224 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20225 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20226 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20227 "AllowAllConstructorInitializersOnNextLine: true", 20228 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20229 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20230 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20231 "AllowAllConstructorInitializersOnNextLine: false", 20232 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20233 20234 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20235 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20236 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20237 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20238 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20239 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20240 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20241 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20242 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20243 20244 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20245 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20246 FormatStyle::BAS_Align); 20247 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20248 FormatStyle::BAS_DontAlign); 20249 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20250 FormatStyle::BAS_AlwaysBreak); 20251 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20252 FormatStyle::BAS_BlockIndent); 20253 // For backward compatibility: 20254 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20255 FormatStyle::BAS_DontAlign); 20256 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20257 FormatStyle::BAS_Align); 20258 20259 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20260 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20261 FormatStyle::ENAS_DontAlign); 20262 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20263 FormatStyle::ENAS_Left); 20264 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20265 FormatStyle::ENAS_Right); 20266 // For backward compatibility: 20267 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20268 FormatStyle::ENAS_Left); 20269 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20270 FormatStyle::ENAS_Right); 20271 20272 Style.AlignOperands = FormatStyle::OAS_Align; 20273 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20274 FormatStyle::OAS_DontAlign); 20275 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20276 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20277 FormatStyle::OAS_AlignAfterOperator); 20278 // For backward compatibility: 20279 CHECK_PARSE("AlignOperands: false", AlignOperands, 20280 FormatStyle::OAS_DontAlign); 20281 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20282 20283 Style.UseTab = FormatStyle::UT_ForIndentation; 20284 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20285 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20286 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20287 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20288 FormatStyle::UT_ForContinuationAndIndentation); 20289 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20290 FormatStyle::UT_AlignWithSpaces); 20291 // For backward compatibility: 20292 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20293 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20294 20295 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20296 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20297 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20298 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20299 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20300 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20301 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20302 // For backward compatibility: 20303 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20304 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20305 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20306 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20307 20308 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20309 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20310 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20311 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20312 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20313 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20314 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20315 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20316 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20317 // For backward compatibility: 20318 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20319 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20320 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20321 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20322 20323 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20324 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20325 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20326 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20327 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20328 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20329 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20330 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20331 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20332 20333 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20334 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20335 FormatStyle::SBPO_Never); 20336 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20337 FormatStyle::SBPO_Always); 20338 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20339 FormatStyle::SBPO_ControlStatements); 20340 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20341 SpaceBeforeParens, 20342 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20343 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20344 FormatStyle::SBPO_NonEmptyParentheses); 20345 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20346 FormatStyle::SBPO_Custom); 20347 // For backward compatibility: 20348 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20349 FormatStyle::SBPO_Never); 20350 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20351 FormatStyle::SBPO_ControlStatements); 20352 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20353 SpaceBeforeParens, 20354 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20355 20356 Style.ColumnLimit = 123; 20357 FormatStyle BaseStyle = getLLVMStyle(); 20358 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20359 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20360 20361 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20362 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20363 FormatStyle::BS_Attach); 20364 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20365 FormatStyle::BS_Linux); 20366 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20367 FormatStyle::BS_Mozilla); 20368 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20369 FormatStyle::BS_Stroustrup); 20370 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20371 FormatStyle::BS_Allman); 20372 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20373 FormatStyle::BS_Whitesmiths); 20374 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20375 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20376 FormatStyle::BS_WebKit); 20377 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20378 FormatStyle::BS_Custom); 20379 20380 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20381 CHECK_PARSE("BraceWrapping:\n" 20382 " AfterControlStatement: MultiLine", 20383 BraceWrapping.AfterControlStatement, 20384 FormatStyle::BWACS_MultiLine); 20385 CHECK_PARSE("BraceWrapping:\n" 20386 " AfterControlStatement: Always", 20387 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20388 CHECK_PARSE("BraceWrapping:\n" 20389 " AfterControlStatement: Never", 20390 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20391 // For backward compatibility: 20392 CHECK_PARSE("BraceWrapping:\n" 20393 " AfterControlStatement: true", 20394 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20395 CHECK_PARSE("BraceWrapping:\n" 20396 " AfterControlStatement: false", 20397 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20398 20399 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20400 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20401 FormatStyle::RTBS_None); 20402 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20403 FormatStyle::RTBS_All); 20404 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20405 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20406 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20407 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20408 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20409 AlwaysBreakAfterReturnType, 20410 FormatStyle::RTBS_TopLevelDefinitions); 20411 20412 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20413 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20414 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20415 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20416 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20417 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20418 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20419 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20420 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20421 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20422 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20423 20424 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20425 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20426 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20427 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20428 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20429 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20430 AlwaysBreakAfterDefinitionReturnType, 20431 FormatStyle::DRTBS_TopLevel); 20432 20433 Style.NamespaceIndentation = FormatStyle::NI_All; 20434 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20435 FormatStyle::NI_None); 20436 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20437 FormatStyle::NI_Inner); 20438 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20439 FormatStyle::NI_All); 20440 20441 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20442 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20443 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20444 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20445 AllowShortIfStatementsOnASingleLine, 20446 FormatStyle::SIS_WithoutElse); 20447 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20448 AllowShortIfStatementsOnASingleLine, 20449 FormatStyle::SIS_OnlyFirstIf); 20450 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20451 AllowShortIfStatementsOnASingleLine, 20452 FormatStyle::SIS_AllIfsAndElse); 20453 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20454 AllowShortIfStatementsOnASingleLine, 20455 FormatStyle::SIS_OnlyFirstIf); 20456 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20457 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20458 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20459 AllowShortIfStatementsOnASingleLine, 20460 FormatStyle::SIS_WithoutElse); 20461 20462 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20463 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20464 FormatStyle::IEBS_AfterExternBlock); 20465 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20466 FormatStyle::IEBS_Indent); 20467 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20468 FormatStyle::IEBS_NoIndent); 20469 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20470 FormatStyle::IEBS_Indent); 20471 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20472 FormatStyle::IEBS_NoIndent); 20473 20474 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20475 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20476 FormatStyle::BFCS_Both); 20477 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20478 FormatStyle::BFCS_None); 20479 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20480 FormatStyle::BFCS_Before); 20481 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20482 FormatStyle::BFCS_After); 20483 20484 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20485 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20486 FormatStyle::SJSIO_After); 20487 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20488 FormatStyle::SJSIO_Before); 20489 20490 // FIXME: This is required because parsing a configuration simply overwrites 20491 // the first N elements of the list instead of resetting it. 20492 Style.ForEachMacros.clear(); 20493 std::vector<std::string> BoostForeach; 20494 BoostForeach.push_back("BOOST_FOREACH"); 20495 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20496 std::vector<std::string> BoostAndQForeach; 20497 BoostAndQForeach.push_back("BOOST_FOREACH"); 20498 BoostAndQForeach.push_back("Q_FOREACH"); 20499 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20500 BoostAndQForeach); 20501 20502 Style.IfMacros.clear(); 20503 std::vector<std::string> CustomIfs; 20504 CustomIfs.push_back("MYIF"); 20505 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20506 20507 Style.AttributeMacros.clear(); 20508 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20509 std::vector<std::string>{"__capability"}); 20510 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20511 std::vector<std::string>({"attr1", "attr2"})); 20512 20513 Style.StatementAttributeLikeMacros.clear(); 20514 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20515 StatementAttributeLikeMacros, 20516 std::vector<std::string>({"emit", "Q_EMIT"})); 20517 20518 Style.StatementMacros.clear(); 20519 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20520 std::vector<std::string>{"QUNUSED"}); 20521 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20522 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20523 20524 Style.NamespaceMacros.clear(); 20525 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20526 std::vector<std::string>{"TESTSUITE"}); 20527 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20528 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20529 20530 Style.WhitespaceSensitiveMacros.clear(); 20531 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20532 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20533 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20534 WhitespaceSensitiveMacros, 20535 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20536 Style.WhitespaceSensitiveMacros.clear(); 20537 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20538 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20539 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20540 WhitespaceSensitiveMacros, 20541 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20542 20543 Style.IncludeStyle.IncludeCategories.clear(); 20544 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20545 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20546 CHECK_PARSE("IncludeCategories:\n" 20547 " - Regex: abc/.*\n" 20548 " Priority: 2\n" 20549 " - Regex: .*\n" 20550 " Priority: 1\n" 20551 " CaseSensitive: true\n", 20552 IncludeStyle.IncludeCategories, ExpectedCategories); 20553 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20554 "abc$"); 20555 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20556 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20557 20558 Style.SortIncludes = FormatStyle::SI_Never; 20559 CHECK_PARSE("SortIncludes: true", SortIncludes, 20560 FormatStyle::SI_CaseSensitive); 20561 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20562 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20563 FormatStyle::SI_CaseInsensitive); 20564 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20565 FormatStyle::SI_CaseSensitive); 20566 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20567 20568 Style.RawStringFormats.clear(); 20569 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20570 { 20571 FormatStyle::LK_TextProto, 20572 {"pb", "proto"}, 20573 {"PARSE_TEXT_PROTO"}, 20574 /*CanonicalDelimiter=*/"", 20575 "llvm", 20576 }, 20577 { 20578 FormatStyle::LK_Cpp, 20579 {"cc", "cpp"}, 20580 {"C_CODEBLOCK", "CPPEVAL"}, 20581 /*CanonicalDelimiter=*/"cc", 20582 /*BasedOnStyle=*/"", 20583 }, 20584 }; 20585 20586 CHECK_PARSE("RawStringFormats:\n" 20587 " - Language: TextProto\n" 20588 " Delimiters:\n" 20589 " - 'pb'\n" 20590 " - 'proto'\n" 20591 " EnclosingFunctions:\n" 20592 " - 'PARSE_TEXT_PROTO'\n" 20593 " BasedOnStyle: llvm\n" 20594 " - Language: Cpp\n" 20595 " Delimiters:\n" 20596 " - 'cc'\n" 20597 " - 'cpp'\n" 20598 " EnclosingFunctions:\n" 20599 " - 'C_CODEBLOCK'\n" 20600 " - 'CPPEVAL'\n" 20601 " CanonicalDelimiter: 'cc'", 20602 RawStringFormats, ExpectedRawStringFormats); 20603 20604 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20605 " Minimum: 0\n" 20606 " Maximum: 0", 20607 SpacesInLineCommentPrefix.Minimum, 0u); 20608 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20609 Style.SpacesInLineCommentPrefix.Minimum = 1; 20610 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20611 " Minimum: 2", 20612 SpacesInLineCommentPrefix.Minimum, 0u); 20613 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20614 " Maximum: -1", 20615 SpacesInLineCommentPrefix.Maximum, -1u); 20616 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20617 " Minimum: 2", 20618 SpacesInLineCommentPrefix.Minimum, 2u); 20619 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20620 " Maximum: 1", 20621 SpacesInLineCommentPrefix.Maximum, 1u); 20622 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20623 20624 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20625 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20626 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20627 FormatStyle::SIAS_Always); 20628 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20629 // For backward compatibility: 20630 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20631 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20632 20633 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20634 FormatStyle::RCPS_WithPreceding); 20635 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20636 FormatStyle::RCPS_WithFollowing); 20637 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20638 FormatStyle::RCPS_SingleLine); 20639 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20640 FormatStyle::RCPS_OwnLine); 20641 20642 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20643 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20644 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20645 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20646 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20647 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20648 // For backward compatibility: 20649 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20650 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20651 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20652 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20653 } 20654 20655 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20656 FormatStyle Style = {}; 20657 Style.Language = FormatStyle::LK_Cpp; 20658 CHECK_PARSE("Language: Cpp\n" 20659 "IndentWidth: 12", 20660 IndentWidth, 12u); 20661 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20662 "IndentWidth: 34", 20663 &Style), 20664 ParseError::Unsuitable); 20665 FormatStyle BinPackedTCS = {}; 20666 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20667 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20668 "InsertTrailingCommas: Wrapped", 20669 &BinPackedTCS), 20670 ParseError::BinPackTrailingCommaConflict); 20671 EXPECT_EQ(12u, Style.IndentWidth); 20672 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20673 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20674 20675 Style.Language = FormatStyle::LK_JavaScript; 20676 CHECK_PARSE("Language: JavaScript\n" 20677 "IndentWidth: 12", 20678 IndentWidth, 12u); 20679 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20680 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20681 "IndentWidth: 34", 20682 &Style), 20683 ParseError::Unsuitable); 20684 EXPECT_EQ(23u, Style.IndentWidth); 20685 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20686 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20687 20688 CHECK_PARSE("BasedOnStyle: LLVM\n" 20689 "IndentWidth: 67", 20690 IndentWidth, 67u); 20691 20692 CHECK_PARSE("---\n" 20693 "Language: JavaScript\n" 20694 "IndentWidth: 12\n" 20695 "---\n" 20696 "Language: Cpp\n" 20697 "IndentWidth: 34\n" 20698 "...\n", 20699 IndentWidth, 12u); 20700 20701 Style.Language = FormatStyle::LK_Cpp; 20702 CHECK_PARSE("---\n" 20703 "Language: JavaScript\n" 20704 "IndentWidth: 12\n" 20705 "---\n" 20706 "Language: Cpp\n" 20707 "IndentWidth: 34\n" 20708 "...\n", 20709 IndentWidth, 34u); 20710 CHECK_PARSE("---\n" 20711 "IndentWidth: 78\n" 20712 "---\n" 20713 "Language: JavaScript\n" 20714 "IndentWidth: 56\n" 20715 "...\n", 20716 IndentWidth, 78u); 20717 20718 Style.ColumnLimit = 123; 20719 Style.IndentWidth = 234; 20720 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20721 Style.TabWidth = 345; 20722 EXPECT_FALSE(parseConfiguration("---\n" 20723 "IndentWidth: 456\n" 20724 "BreakBeforeBraces: Allman\n" 20725 "---\n" 20726 "Language: JavaScript\n" 20727 "IndentWidth: 111\n" 20728 "TabWidth: 111\n" 20729 "---\n" 20730 "Language: Cpp\n" 20731 "BreakBeforeBraces: Stroustrup\n" 20732 "TabWidth: 789\n" 20733 "...\n", 20734 &Style)); 20735 EXPECT_EQ(123u, Style.ColumnLimit); 20736 EXPECT_EQ(456u, Style.IndentWidth); 20737 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20738 EXPECT_EQ(789u, Style.TabWidth); 20739 20740 EXPECT_EQ(parseConfiguration("---\n" 20741 "Language: JavaScript\n" 20742 "IndentWidth: 56\n" 20743 "---\n" 20744 "IndentWidth: 78\n" 20745 "...\n", 20746 &Style), 20747 ParseError::Error); 20748 EXPECT_EQ(parseConfiguration("---\n" 20749 "Language: JavaScript\n" 20750 "IndentWidth: 56\n" 20751 "---\n" 20752 "Language: JavaScript\n" 20753 "IndentWidth: 78\n" 20754 "...\n", 20755 &Style), 20756 ParseError::Error); 20757 20758 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20759 } 20760 20761 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20762 FormatStyle Style = {}; 20763 Style.Language = FormatStyle::LK_JavaScript; 20764 Style.BreakBeforeTernaryOperators = true; 20765 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20766 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20767 20768 Style.BreakBeforeTernaryOperators = true; 20769 EXPECT_EQ(0, parseConfiguration("---\n" 20770 "BasedOnStyle: Google\n" 20771 "---\n" 20772 "Language: JavaScript\n" 20773 "IndentWidth: 76\n" 20774 "...\n", 20775 &Style) 20776 .value()); 20777 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20778 EXPECT_EQ(76u, Style.IndentWidth); 20779 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20780 } 20781 20782 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20783 FormatStyle Style = getLLVMStyle(); 20784 std::string YAML = configurationAsText(Style); 20785 FormatStyle ParsedStyle = {}; 20786 ParsedStyle.Language = FormatStyle::LK_Cpp; 20787 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20788 EXPECT_EQ(Style, ParsedStyle); 20789 } 20790 20791 TEST_F(FormatTest, WorksFor8bitEncodings) { 20792 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20793 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20794 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20795 "\"\xef\xee\xf0\xf3...\"", 20796 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20797 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20798 "\xef\xee\xf0\xf3...\"", 20799 getLLVMStyleWithColumns(12))); 20800 } 20801 20802 TEST_F(FormatTest, HandlesUTF8BOM) { 20803 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20804 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20805 format("\xef\xbb\xbf#include <iostream>")); 20806 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20807 format("\xef\xbb\xbf\n#include <iostream>")); 20808 } 20809 20810 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20811 #if !defined(_MSC_VER) 20812 20813 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20814 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20815 getLLVMStyleWithColumns(35)); 20816 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20817 getLLVMStyleWithColumns(31)); 20818 verifyFormat("// Однажды в студёную зимнюю пору...", 20819 getLLVMStyleWithColumns(36)); 20820 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20821 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20822 getLLVMStyleWithColumns(39)); 20823 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20824 getLLVMStyleWithColumns(35)); 20825 } 20826 20827 TEST_F(FormatTest, SplitsUTF8Strings) { 20828 // Non-printable characters' width is currently considered to be the length in 20829 // bytes in UTF8. The characters can be displayed in very different manner 20830 // (zero-width, single width with a substitution glyph, expanded to their code 20831 // (e.g. "<8d>"), so there's no single correct way to handle them. 20832 EXPECT_EQ("\"aaaaÄ\"\n" 20833 "\"\xc2\x8d\";", 20834 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20835 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20836 "\"\xc2\x8d\";", 20837 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20838 EXPECT_EQ("\"Однажды, в \"\n" 20839 "\"студёную \"\n" 20840 "\"зимнюю \"\n" 20841 "\"пору,\"", 20842 format("\"Однажды, в студёную зимнюю пору,\"", 20843 getLLVMStyleWithColumns(13))); 20844 EXPECT_EQ( 20845 "\"一 二 三 \"\n" 20846 "\"四 五六 \"\n" 20847 "\"七 八 九 \"\n" 20848 "\"十\"", 20849 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20850 EXPECT_EQ("\"一\t\"\n" 20851 "\"二 \t\"\n" 20852 "\"三 四 \"\n" 20853 "\"五\t\"\n" 20854 "\"六 \t\"\n" 20855 "\"七 \"\n" 20856 "\"八九十\tqq\"", 20857 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20858 getLLVMStyleWithColumns(11))); 20859 20860 // UTF8 character in an escape sequence. 20861 EXPECT_EQ("\"aaaaaa\"\n" 20862 "\"\\\xC2\x8D\"", 20863 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20864 } 20865 20866 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20867 EXPECT_EQ("const char *sssss =\n" 20868 " \"一二三四五六七八\\\n" 20869 " 九 十\";", 20870 format("const char *sssss = \"一二三四五六七八\\\n" 20871 " 九 十\";", 20872 getLLVMStyleWithColumns(30))); 20873 } 20874 20875 TEST_F(FormatTest, SplitsUTF8LineComments) { 20876 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20877 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20878 EXPECT_EQ("// Я из лесу\n" 20879 "// вышел; был\n" 20880 "// сильный\n" 20881 "// мороз.", 20882 format("// Я из лесу вышел; был сильный мороз.", 20883 getLLVMStyleWithColumns(13))); 20884 EXPECT_EQ("// 一二三\n" 20885 "// 四五六七\n" 20886 "// 八 九\n" 20887 "// 十", 20888 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20889 } 20890 20891 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20892 EXPECT_EQ("/* Гляжу,\n" 20893 " * поднимается\n" 20894 " * медленно в\n" 20895 " * гору\n" 20896 " * Лошадка,\n" 20897 " * везущая\n" 20898 " * хворосту\n" 20899 " * воз. */", 20900 format("/* Гляжу, поднимается медленно в гору\n" 20901 " * Лошадка, везущая хворосту воз. */", 20902 getLLVMStyleWithColumns(13))); 20903 EXPECT_EQ( 20904 "/* 一二三\n" 20905 " * 四五六七\n" 20906 " * 八 九\n" 20907 " * 十 */", 20908 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20909 EXPECT_EQ("/* \n" 20910 " * \n" 20911 " * - */", 20912 format("/* - */", getLLVMStyleWithColumns(12))); 20913 } 20914 20915 #endif // _MSC_VER 20916 20917 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20918 FormatStyle Style = getLLVMStyle(); 20919 20920 Style.ConstructorInitializerIndentWidth = 4; 20921 verifyFormat( 20922 "SomeClass::Constructor()\n" 20923 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20924 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20925 Style); 20926 20927 Style.ConstructorInitializerIndentWidth = 2; 20928 verifyFormat( 20929 "SomeClass::Constructor()\n" 20930 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20931 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20932 Style); 20933 20934 Style.ConstructorInitializerIndentWidth = 0; 20935 verifyFormat( 20936 "SomeClass::Constructor()\n" 20937 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20938 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20939 Style); 20940 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20941 verifyFormat( 20942 "SomeLongTemplateVariableName<\n" 20943 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20944 Style); 20945 verifyFormat("bool smaller = 1 < " 20946 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20947 " " 20948 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20949 Style); 20950 20951 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20952 verifyFormat("SomeClass::Constructor() :\n" 20953 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20954 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20955 Style); 20956 } 20957 20958 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20959 FormatStyle Style = getLLVMStyle(); 20960 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20961 Style.ConstructorInitializerIndentWidth = 4; 20962 verifyFormat("SomeClass::Constructor()\n" 20963 " : a(a)\n" 20964 " , b(b)\n" 20965 " , c(c) {}", 20966 Style); 20967 verifyFormat("SomeClass::Constructor()\n" 20968 " : a(a) {}", 20969 Style); 20970 20971 Style.ColumnLimit = 0; 20972 verifyFormat("SomeClass::Constructor()\n" 20973 " : a(a) {}", 20974 Style); 20975 verifyFormat("SomeClass::Constructor() noexcept\n" 20976 " : a(a) {}", 20977 Style); 20978 verifyFormat("SomeClass::Constructor()\n" 20979 " : a(a)\n" 20980 " , b(b)\n" 20981 " , c(c) {}", 20982 Style); 20983 verifyFormat("SomeClass::Constructor()\n" 20984 " : a(a) {\n" 20985 " foo();\n" 20986 " bar();\n" 20987 "}", 20988 Style); 20989 20990 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20991 verifyFormat("SomeClass::Constructor()\n" 20992 " : a(a)\n" 20993 " , b(b)\n" 20994 " , c(c) {\n}", 20995 Style); 20996 verifyFormat("SomeClass::Constructor()\n" 20997 " : a(a) {\n}", 20998 Style); 20999 21000 Style.ColumnLimit = 80; 21001 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 21002 Style.ConstructorInitializerIndentWidth = 2; 21003 verifyFormat("SomeClass::Constructor()\n" 21004 " : a(a)\n" 21005 " , b(b)\n" 21006 " , c(c) {}", 21007 Style); 21008 21009 Style.ConstructorInitializerIndentWidth = 0; 21010 verifyFormat("SomeClass::Constructor()\n" 21011 ": a(a)\n" 21012 ", b(b)\n" 21013 ", c(c) {}", 21014 Style); 21015 21016 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 21017 Style.ConstructorInitializerIndentWidth = 4; 21018 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 21019 verifyFormat( 21020 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 21021 Style); 21022 verifyFormat( 21023 "SomeClass::Constructor()\n" 21024 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 21025 Style); 21026 Style.ConstructorInitializerIndentWidth = 4; 21027 Style.ColumnLimit = 60; 21028 verifyFormat("SomeClass::Constructor()\n" 21029 " : aaaaaaaa(aaaaaaaa)\n" 21030 " , aaaaaaaa(aaaaaaaa)\n" 21031 " , aaaaaaaa(aaaaaaaa) {}", 21032 Style); 21033 } 21034 21035 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 21036 FormatStyle Style = getLLVMStyle(); 21037 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 21038 Style.ConstructorInitializerIndentWidth = 4; 21039 verifyFormat("SomeClass::Constructor()\n" 21040 " : a{a}\n" 21041 " , b{b} {}", 21042 Style); 21043 verifyFormat("SomeClass::Constructor()\n" 21044 " : a{a}\n" 21045 "#if CONDITION\n" 21046 " , b{b}\n" 21047 "#endif\n" 21048 "{\n}", 21049 Style); 21050 Style.ConstructorInitializerIndentWidth = 2; 21051 verifyFormat("SomeClass::Constructor()\n" 21052 "#if CONDITION\n" 21053 " : a{a}\n" 21054 "#endif\n" 21055 " , b{b}\n" 21056 " , c{c} {\n}", 21057 Style); 21058 Style.ConstructorInitializerIndentWidth = 0; 21059 verifyFormat("SomeClass::Constructor()\n" 21060 ": a{a}\n" 21061 "#ifdef CONDITION\n" 21062 ", b{b}\n" 21063 "#else\n" 21064 ", c{c}\n" 21065 "#endif\n" 21066 ", d{d} {\n}", 21067 Style); 21068 Style.ConstructorInitializerIndentWidth = 4; 21069 verifyFormat("SomeClass::Constructor()\n" 21070 " : a{a}\n" 21071 "#if WINDOWS\n" 21072 "#if DEBUG\n" 21073 " , b{0}\n" 21074 "#else\n" 21075 " , b{1}\n" 21076 "#endif\n" 21077 "#else\n" 21078 "#if DEBUG\n" 21079 " , b{2}\n" 21080 "#else\n" 21081 " , b{3}\n" 21082 "#endif\n" 21083 "#endif\n" 21084 "{\n}", 21085 Style); 21086 verifyFormat("SomeClass::Constructor()\n" 21087 " : a{a}\n" 21088 "#if WINDOWS\n" 21089 " , b{0}\n" 21090 "#if DEBUG\n" 21091 " , c{0}\n" 21092 "#else\n" 21093 " , c{1}\n" 21094 "#endif\n" 21095 "#else\n" 21096 "#if DEBUG\n" 21097 " , c{2}\n" 21098 "#else\n" 21099 " , c{3}\n" 21100 "#endif\n" 21101 " , b{1}\n" 21102 "#endif\n" 21103 "{\n}", 21104 Style); 21105 } 21106 21107 TEST_F(FormatTest, Destructors) { 21108 verifyFormat("void F(int &i) { i.~int(); }"); 21109 verifyFormat("void F(int &i) { i->~int(); }"); 21110 } 21111 21112 TEST_F(FormatTest, FormatsWithWebKitStyle) { 21113 FormatStyle Style = getWebKitStyle(); 21114 21115 // Don't indent in outer namespaces. 21116 verifyFormat("namespace outer {\n" 21117 "int i;\n" 21118 "namespace inner {\n" 21119 " int i;\n" 21120 "} // namespace inner\n" 21121 "} // namespace outer\n" 21122 "namespace other_outer {\n" 21123 "int i;\n" 21124 "}", 21125 Style); 21126 21127 // Don't indent case labels. 21128 verifyFormat("switch (variable) {\n" 21129 "case 1:\n" 21130 "case 2:\n" 21131 " doSomething();\n" 21132 " break;\n" 21133 "default:\n" 21134 " ++variable;\n" 21135 "}", 21136 Style); 21137 21138 // Wrap before binary operators. 21139 EXPECT_EQ("void f()\n" 21140 "{\n" 21141 " if (aaaaaaaaaaaaaaaa\n" 21142 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 21143 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21144 " return;\n" 21145 "}", 21146 format("void f() {\n" 21147 "if (aaaaaaaaaaaaaaaa\n" 21148 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 21149 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21150 "return;\n" 21151 "}", 21152 Style)); 21153 21154 // Allow functions on a single line. 21155 verifyFormat("void f() { return; }", Style); 21156 21157 // Allow empty blocks on a single line and insert a space in empty blocks. 21158 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 21159 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 21160 // However, don't merge non-empty short loops. 21161 EXPECT_EQ("while (true) {\n" 21162 " continue;\n" 21163 "}", 21164 format("while (true) { continue; }", Style)); 21165 21166 // Constructor initializers are formatted one per line with the "," on the 21167 // new line. 21168 verifyFormat("Constructor()\n" 21169 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 21170 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 21171 " aaaaaaaaaaaaaa)\n" 21172 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 21173 "{\n" 21174 "}", 21175 Style); 21176 verifyFormat("SomeClass::Constructor()\n" 21177 " : a(a)\n" 21178 "{\n" 21179 "}", 21180 Style); 21181 EXPECT_EQ("SomeClass::Constructor()\n" 21182 " : a(a)\n" 21183 "{\n" 21184 "}", 21185 format("SomeClass::Constructor():a(a){}", Style)); 21186 verifyFormat("SomeClass::Constructor()\n" 21187 " : a(a)\n" 21188 " , b(b)\n" 21189 " , c(c)\n" 21190 "{\n" 21191 "}", 21192 Style); 21193 verifyFormat("SomeClass::Constructor()\n" 21194 " : a(a)\n" 21195 "{\n" 21196 " foo();\n" 21197 " bar();\n" 21198 "}", 21199 Style); 21200 21201 // Access specifiers should be aligned left. 21202 verifyFormat("class C {\n" 21203 "public:\n" 21204 " int i;\n" 21205 "};", 21206 Style); 21207 21208 // Do not align comments. 21209 verifyFormat("int a; // Do not\n" 21210 "double b; // align comments.", 21211 Style); 21212 21213 // Do not align operands. 21214 EXPECT_EQ("ASSERT(aaaa\n" 21215 " || bbbb);", 21216 format("ASSERT ( aaaa\n||bbbb);", Style)); 21217 21218 // Accept input's line breaks. 21219 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21220 " || bbbbbbbbbbbbbbb) {\n" 21221 " i++;\n" 21222 "}", 21223 format("if (aaaaaaaaaaaaaaa\n" 21224 "|| bbbbbbbbbbbbbbb) { i++; }", 21225 Style)); 21226 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21227 " i++;\n" 21228 "}", 21229 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21230 21231 // Don't automatically break all macro definitions (llvm.org/PR17842). 21232 verifyFormat("#define aNumber 10", Style); 21233 // However, generally keep the line breaks that the user authored. 21234 EXPECT_EQ("#define aNumber \\\n" 21235 " 10", 21236 format("#define aNumber \\\n" 21237 " 10", 21238 Style)); 21239 21240 // Keep empty and one-element array literals on a single line. 21241 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21242 " copyItems:YES];", 21243 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21244 "copyItems:YES];", 21245 Style)); 21246 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21247 " copyItems:YES];", 21248 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21249 " copyItems:YES];", 21250 Style)); 21251 // FIXME: This does not seem right, there should be more indentation before 21252 // the array literal's entries. Nested blocks have the same problem. 21253 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21254 " @\"a\",\n" 21255 " @\"a\"\n" 21256 "]\n" 21257 " copyItems:YES];", 21258 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21259 " @\"a\",\n" 21260 " @\"a\"\n" 21261 " ]\n" 21262 " copyItems:YES];", 21263 Style)); 21264 EXPECT_EQ( 21265 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21266 " copyItems:YES];", 21267 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21268 " copyItems:YES];", 21269 Style)); 21270 21271 verifyFormat("[self.a b:c c:d];", Style); 21272 EXPECT_EQ("[self.a b:c\n" 21273 " c:d];", 21274 format("[self.a b:c\n" 21275 "c:d];", 21276 Style)); 21277 } 21278 21279 TEST_F(FormatTest, FormatsLambdas) { 21280 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21281 verifyFormat( 21282 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21283 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21284 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21285 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21286 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21287 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21288 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21289 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21290 verifyFormat("int x = f(*+[] {});"); 21291 verifyFormat("void f() {\n" 21292 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21293 "}\n"); 21294 verifyFormat("void f() {\n" 21295 " other(x.begin(), //\n" 21296 " x.end(), //\n" 21297 " [&](int, int) { return 1; });\n" 21298 "}\n"); 21299 verifyFormat("void f() {\n" 21300 " other.other.other.other.other(\n" 21301 " x.begin(), x.end(),\n" 21302 " [something, rather](int, int, int, int, int, int, int) { " 21303 "return 1; });\n" 21304 "}\n"); 21305 verifyFormat( 21306 "void f() {\n" 21307 " other.other.other.other.other(\n" 21308 " x.begin(), x.end(),\n" 21309 " [something, rather](int, int, int, int, int, int, int) {\n" 21310 " //\n" 21311 " });\n" 21312 "}\n"); 21313 verifyFormat("SomeFunction([]() { // A cool function...\n" 21314 " return 43;\n" 21315 "});"); 21316 EXPECT_EQ("SomeFunction([]() {\n" 21317 "#define A a\n" 21318 " return 43;\n" 21319 "});", 21320 format("SomeFunction([](){\n" 21321 "#define A a\n" 21322 "return 43;\n" 21323 "});")); 21324 verifyFormat("void f() {\n" 21325 " SomeFunction([](decltype(x), A *a) {});\n" 21326 " SomeFunction([](typeof(x), A *a) {});\n" 21327 " SomeFunction([](_Atomic(x), A *a) {});\n" 21328 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21329 "}"); 21330 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21331 " [](const aaaaaaaaaa &a) { return a; });"); 21332 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21333 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21334 "});"); 21335 verifyFormat("Constructor()\n" 21336 " : Field([] { // comment\n" 21337 " int i;\n" 21338 " }) {}"); 21339 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21340 " return some_parameter.size();\n" 21341 "};"); 21342 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21343 " [](const string &s) { return s; };"); 21344 verifyFormat("int i = aaaaaa ? 1 //\n" 21345 " : [] {\n" 21346 " return 2; //\n" 21347 " }();"); 21348 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21349 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21350 " return x == 2; // force break\n" 21351 " });"); 21352 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21353 " [=](int iiiiiiiiiiii) {\n" 21354 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21355 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21356 " });", 21357 getLLVMStyleWithColumns(60)); 21358 21359 verifyFormat("SomeFunction({[&] {\n" 21360 " // comment\n" 21361 " },\n" 21362 " [&] {\n" 21363 " // comment\n" 21364 " }});"); 21365 verifyFormat("SomeFunction({[&] {\n" 21366 " // comment\n" 21367 "}});"); 21368 verifyFormat( 21369 "virtual aaaaaaaaaaaaaaaa(\n" 21370 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21371 " aaaaa aaaaaaaaa);"); 21372 21373 // Lambdas with return types. 21374 verifyFormat("int c = []() -> int { return 2; }();\n"); 21375 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21376 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21377 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21378 verifyFormat("foo([]() noexcept -> int {});"); 21379 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21380 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21381 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21382 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21383 verifyFormat("[a, a]() -> a<1> {};"); 21384 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21385 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21386 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21387 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21388 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21389 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21390 verifyFormat("[]() -> foo<!5> { return {}; };"); 21391 verifyFormat("[]() -> foo<~5> { return {}; };"); 21392 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21393 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21394 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21395 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21396 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21397 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21398 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21399 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21400 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21401 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21402 verifyFormat("namespace bar {\n" 21403 "// broken:\n" 21404 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21405 "} // namespace bar"); 21406 verifyFormat("namespace bar {\n" 21407 "// broken:\n" 21408 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21409 "} // namespace bar"); 21410 verifyFormat("namespace bar {\n" 21411 "// broken:\n" 21412 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21413 "} // namespace bar"); 21414 verifyFormat("namespace bar {\n" 21415 "// broken:\n" 21416 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21417 "} // namespace bar"); 21418 verifyFormat("namespace bar {\n" 21419 "// broken:\n" 21420 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21421 "} // namespace bar"); 21422 verifyFormat("namespace bar {\n" 21423 "// broken:\n" 21424 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21425 "} // namespace bar"); 21426 verifyFormat("namespace bar {\n" 21427 "// broken:\n" 21428 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21429 "} // namespace bar"); 21430 verifyFormat("namespace bar {\n" 21431 "// broken:\n" 21432 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21433 "} // namespace bar"); 21434 verifyFormat("namespace bar {\n" 21435 "// broken:\n" 21436 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21437 "} // namespace bar"); 21438 verifyFormat("namespace bar {\n" 21439 "// broken:\n" 21440 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21441 "} // namespace bar"); 21442 verifyFormat("namespace bar {\n" 21443 "// broken:\n" 21444 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21445 "} // namespace bar"); 21446 verifyFormat("namespace bar {\n" 21447 "// broken:\n" 21448 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21449 "} // namespace bar"); 21450 verifyFormat("namespace bar {\n" 21451 "// broken:\n" 21452 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21453 "} // namespace bar"); 21454 verifyFormat("namespace bar {\n" 21455 "// broken:\n" 21456 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21457 "} // namespace bar"); 21458 verifyFormat("namespace bar {\n" 21459 "// broken:\n" 21460 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21461 "} // namespace bar"); 21462 verifyFormat("namespace bar {\n" 21463 "// broken:\n" 21464 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21465 "} // namespace bar"); 21466 verifyFormat("namespace bar {\n" 21467 "// broken:\n" 21468 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21469 "} // namespace bar"); 21470 verifyFormat("namespace bar {\n" 21471 "// broken:\n" 21472 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21473 "} // namespace bar"); 21474 verifyFormat("[]() -> a<1> {};"); 21475 verifyFormat("[]() -> a<1> { ; };"); 21476 verifyFormat("[]() -> a<1> { ; }();"); 21477 verifyFormat("[a, a]() -> a<true> {};"); 21478 verifyFormat("[]() -> a<true> {};"); 21479 verifyFormat("[]() -> a<true> { ; };"); 21480 verifyFormat("[]() -> a<true> { ; }();"); 21481 verifyFormat("[a, a]() -> a<false> {};"); 21482 verifyFormat("[]() -> a<false> {};"); 21483 verifyFormat("[]() -> a<false> { ; };"); 21484 verifyFormat("[]() -> a<false> { ; }();"); 21485 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21486 verifyFormat("namespace bar {\n" 21487 "auto foo{[]() -> foo<false> { ; }};\n" 21488 "} // namespace bar"); 21489 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21490 " int j) -> int {\n" 21491 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21492 "};"); 21493 verifyFormat( 21494 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21495 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21496 " return aaaaaaaaaaaaaaaaa;\n" 21497 " });", 21498 getLLVMStyleWithColumns(70)); 21499 verifyFormat("[]() //\n" 21500 " -> int {\n" 21501 " return 1; //\n" 21502 "};"); 21503 verifyFormat("[]() -> Void<T...> {};"); 21504 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21505 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21506 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21507 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21508 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21509 verifyFormat("return int{[x = x]() { return x; }()};"); 21510 21511 // Lambdas with explicit template argument lists. 21512 verifyFormat( 21513 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21514 verifyFormat("auto L = []<class T>(T) {\n" 21515 " {\n" 21516 " f();\n" 21517 " g();\n" 21518 " }\n" 21519 "};\n"); 21520 verifyFormat("auto L = []<class... T>(T...) {\n" 21521 " {\n" 21522 " f();\n" 21523 " g();\n" 21524 " }\n" 21525 "};\n"); 21526 verifyFormat("auto L = []<typename... T>(T...) {\n" 21527 " {\n" 21528 " f();\n" 21529 " g();\n" 21530 " }\n" 21531 "};\n"); 21532 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21533 " {\n" 21534 " f();\n" 21535 " g();\n" 21536 " }\n" 21537 "};\n"); 21538 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21539 " {\n" 21540 " f();\n" 21541 " g();\n" 21542 " }\n" 21543 "};\n"); 21544 21545 // Multiple lambdas in the same parentheses change indentation rules. These 21546 // lambdas are forced to start on new lines. 21547 verifyFormat("SomeFunction(\n" 21548 " []() {\n" 21549 " //\n" 21550 " },\n" 21551 " []() {\n" 21552 " //\n" 21553 " });"); 21554 21555 // A lambda passed as arg0 is always pushed to the next line. 21556 verifyFormat("SomeFunction(\n" 21557 " [this] {\n" 21558 " //\n" 21559 " },\n" 21560 " 1);\n"); 21561 21562 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21563 // the arg0 case above. 21564 auto Style = getGoogleStyle(); 21565 Style.BinPackArguments = false; 21566 verifyFormat("SomeFunction(\n" 21567 " a,\n" 21568 " [this] {\n" 21569 " //\n" 21570 " },\n" 21571 " b);\n", 21572 Style); 21573 verifyFormat("SomeFunction(\n" 21574 " a,\n" 21575 " [this] {\n" 21576 " //\n" 21577 " },\n" 21578 " b);\n"); 21579 21580 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21581 // the BinPackArguments value (as long as the code is wide enough). 21582 verifyFormat( 21583 "something->SomeFunction(\n" 21584 " a,\n" 21585 " [this] {\n" 21586 " " 21587 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21588 " },\n" 21589 " b);\n"); 21590 21591 // A multi-line lambda is pulled up as long as the introducer fits on the 21592 // previous line and there are no further args. 21593 verifyFormat("function(1, [this, that] {\n" 21594 " //\n" 21595 "});\n"); 21596 verifyFormat("function([this, that] {\n" 21597 " //\n" 21598 "});\n"); 21599 // FIXME: this format is not ideal and we should consider forcing the first 21600 // arg onto its own line. 21601 verifyFormat("function(a, b, c, //\n" 21602 " d, [this, that] {\n" 21603 " //\n" 21604 " });\n"); 21605 21606 // Multiple lambdas are treated correctly even when there is a short arg0. 21607 verifyFormat("SomeFunction(\n" 21608 " 1,\n" 21609 " [this] {\n" 21610 " //\n" 21611 " },\n" 21612 " [this] {\n" 21613 " //\n" 21614 " },\n" 21615 " 1);\n"); 21616 21617 // More complex introducers. 21618 verifyFormat("return [i, args...] {};"); 21619 21620 // Not lambdas. 21621 verifyFormat("constexpr char hello[]{\"hello\"};"); 21622 verifyFormat("double &operator[](int i) { return 0; }\n" 21623 "int i;"); 21624 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21625 verifyFormat("int i = a[a][a]->f();"); 21626 verifyFormat("int i = (*b)[a]->f();"); 21627 21628 // Other corner cases. 21629 verifyFormat("void f() {\n" 21630 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21631 " );\n" 21632 "}"); 21633 verifyFormat("auto k = *[](int *j) { return j; }(&i);"); 21634 21635 // Lambdas created through weird macros. 21636 verifyFormat("void f() {\n" 21637 " MACRO((const AA &a) { return 1; });\n" 21638 " MACRO((AA &a) { return 1; });\n" 21639 "}"); 21640 21641 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21642 " doo_dah();\n" 21643 " doo_dah();\n" 21644 " })) {\n" 21645 "}"); 21646 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21647 " doo_dah();\n" 21648 " doo_dah();\n" 21649 " })) {\n" 21650 "}"); 21651 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21652 " doo_dah();\n" 21653 " doo_dah();\n" 21654 " })) {\n" 21655 "}"); 21656 verifyFormat("auto lambda = []() {\n" 21657 " int a = 2\n" 21658 "#if A\n" 21659 " + 2\n" 21660 "#endif\n" 21661 " ;\n" 21662 "};"); 21663 21664 // Lambdas with complex multiline introducers. 21665 verifyFormat( 21666 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21667 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21668 " -> ::std::unordered_set<\n" 21669 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21670 " //\n" 21671 " });"); 21672 21673 FormatStyle DoNotMerge = getLLVMStyle(); 21674 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21675 verifyFormat("auto c = []() {\n" 21676 " return b;\n" 21677 "};", 21678 "auto c = []() { return b; };", DoNotMerge); 21679 verifyFormat("auto c = []() {\n" 21680 "};", 21681 " auto c = []() {};", DoNotMerge); 21682 21683 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21684 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21685 verifyFormat("auto c = []() {\n" 21686 " return b;\n" 21687 "};", 21688 "auto c = []() {\n" 21689 " return b;\n" 21690 " };", 21691 MergeEmptyOnly); 21692 verifyFormat("auto c = []() {};", 21693 "auto c = []() {\n" 21694 "};", 21695 MergeEmptyOnly); 21696 21697 FormatStyle MergeInline = getLLVMStyle(); 21698 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21699 verifyFormat("auto c = []() {\n" 21700 " return b;\n" 21701 "};", 21702 "auto c = []() { return b; };", MergeInline); 21703 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21704 MergeInline); 21705 verifyFormat("function([]() { return b; }, a)", 21706 "function([]() { return b; }, a)", MergeInline); 21707 verifyFormat("function(a, []() { return b; })", 21708 "function(a, []() { return b; })", MergeInline); 21709 21710 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21711 // AllowShortLambdasOnASingleLine 21712 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21713 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21714 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21715 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21716 FormatStyle::ShortLambdaStyle::SLS_None; 21717 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21718 " []()\n" 21719 " {\n" 21720 " return 17;\n" 21721 " });", 21722 LLVMWithBeforeLambdaBody); 21723 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21724 " []()\n" 21725 " {\n" 21726 " });", 21727 LLVMWithBeforeLambdaBody); 21728 verifyFormat("auto fct_SLS_None = []()\n" 21729 "{\n" 21730 " return 17;\n" 21731 "};", 21732 LLVMWithBeforeLambdaBody); 21733 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21734 " []()\n" 21735 " {\n" 21736 " return Call(\n" 21737 " []()\n" 21738 " {\n" 21739 " return 17;\n" 21740 " });\n" 21741 " });", 21742 LLVMWithBeforeLambdaBody); 21743 verifyFormat("void Fct() {\n" 21744 " return {[]()\n" 21745 " {\n" 21746 " return 17;\n" 21747 " }};\n" 21748 "}", 21749 LLVMWithBeforeLambdaBody); 21750 21751 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21752 FormatStyle::ShortLambdaStyle::SLS_Empty; 21753 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21754 " []()\n" 21755 " {\n" 21756 " return 17;\n" 21757 " });", 21758 LLVMWithBeforeLambdaBody); 21759 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21760 LLVMWithBeforeLambdaBody); 21761 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21762 "ongFunctionName_SLS_Empty(\n" 21763 " []() {});", 21764 LLVMWithBeforeLambdaBody); 21765 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21766 " []()\n" 21767 " {\n" 21768 " return 17;\n" 21769 " });", 21770 LLVMWithBeforeLambdaBody); 21771 verifyFormat("auto fct_SLS_Empty = []()\n" 21772 "{\n" 21773 " return 17;\n" 21774 "};", 21775 LLVMWithBeforeLambdaBody); 21776 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21777 " []()\n" 21778 " {\n" 21779 " return Call([]() {});\n" 21780 " });", 21781 LLVMWithBeforeLambdaBody); 21782 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21783 " []()\n" 21784 " {\n" 21785 " return Call([]() {});\n" 21786 " });", 21787 LLVMWithBeforeLambdaBody); 21788 verifyFormat( 21789 "FctWithLongLineInLambda_SLS_Empty(\n" 21790 " []()\n" 21791 " {\n" 21792 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21793 " AndShouldNotBeConsiderAsInline,\n" 21794 " LambdaBodyMustBeBreak);\n" 21795 " });", 21796 LLVMWithBeforeLambdaBody); 21797 21798 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21799 FormatStyle::ShortLambdaStyle::SLS_Inline; 21800 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21801 LLVMWithBeforeLambdaBody); 21802 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21803 LLVMWithBeforeLambdaBody); 21804 verifyFormat("auto fct_SLS_Inline = []()\n" 21805 "{\n" 21806 " return 17;\n" 21807 "};", 21808 LLVMWithBeforeLambdaBody); 21809 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21810 "17; }); });", 21811 LLVMWithBeforeLambdaBody); 21812 verifyFormat( 21813 "FctWithLongLineInLambda_SLS_Inline(\n" 21814 " []()\n" 21815 " {\n" 21816 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21817 " AndShouldNotBeConsiderAsInline,\n" 21818 " LambdaBodyMustBeBreak);\n" 21819 " });", 21820 LLVMWithBeforeLambdaBody); 21821 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21822 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21823 " []() { return 17; });", 21824 LLVMWithBeforeLambdaBody); 21825 verifyFormat( 21826 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21827 LLVMWithBeforeLambdaBody); 21828 21829 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21830 FormatStyle::ShortLambdaStyle::SLS_All; 21831 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21832 LLVMWithBeforeLambdaBody); 21833 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21834 LLVMWithBeforeLambdaBody); 21835 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21836 LLVMWithBeforeLambdaBody); 21837 verifyFormat("FctWithOneParam_SLS_All(\n" 21838 " []()\n" 21839 " {\n" 21840 " // A cool function...\n" 21841 " return 43;\n" 21842 " });", 21843 LLVMWithBeforeLambdaBody); 21844 verifyFormat("FctWithMultipleParams_SLS_All(" 21845 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21846 " []() { return 17; });", 21847 LLVMWithBeforeLambdaBody); 21848 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21849 LLVMWithBeforeLambdaBody); 21850 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21851 LLVMWithBeforeLambdaBody); 21852 verifyFormat( 21853 "FctWithLongLineInLambda_SLS_All(\n" 21854 " []()\n" 21855 " {\n" 21856 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21857 " AndShouldNotBeConsiderAsInline,\n" 21858 " LambdaBodyMustBeBreak);\n" 21859 " });", 21860 LLVMWithBeforeLambdaBody); 21861 verifyFormat( 21862 "auto fct_SLS_All = []()\n" 21863 "{\n" 21864 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21865 " AndShouldNotBeConsiderAsInline,\n" 21866 " LambdaBodyMustBeBreak);\n" 21867 "};", 21868 LLVMWithBeforeLambdaBody); 21869 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21870 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21871 LLVMWithBeforeLambdaBody); 21872 verifyFormat( 21873 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21874 " FirstParam,\n" 21875 " SecondParam,\n" 21876 " ThirdParam,\n" 21877 " FourthParam);", 21878 LLVMWithBeforeLambdaBody); 21879 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21880 " []() { return " 21881 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21882 " FirstParam,\n" 21883 " SecondParam,\n" 21884 " ThirdParam,\n" 21885 " FourthParam);", 21886 LLVMWithBeforeLambdaBody); 21887 verifyFormat( 21888 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21889 " SecondParam,\n" 21890 " ThirdParam,\n" 21891 " FourthParam,\n" 21892 " []() { return SomeValueNotSoLong; });", 21893 LLVMWithBeforeLambdaBody); 21894 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21895 " []()\n" 21896 " {\n" 21897 " return " 21898 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21899 "eConsiderAsInline;\n" 21900 " });", 21901 LLVMWithBeforeLambdaBody); 21902 verifyFormat( 21903 "FctWithLongLineInLambda_SLS_All(\n" 21904 " []()\n" 21905 " {\n" 21906 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21907 " AndShouldNotBeConsiderAsInline,\n" 21908 " LambdaBodyMustBeBreak);\n" 21909 " });", 21910 LLVMWithBeforeLambdaBody); 21911 verifyFormat("FctWithTwoParams_SLS_All(\n" 21912 " []()\n" 21913 " {\n" 21914 " // A cool function...\n" 21915 " return 43;\n" 21916 " },\n" 21917 " 87);", 21918 LLVMWithBeforeLambdaBody); 21919 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21920 LLVMWithBeforeLambdaBody); 21921 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21922 LLVMWithBeforeLambdaBody); 21923 verifyFormat( 21924 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21925 LLVMWithBeforeLambdaBody); 21926 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21927 "}); }, x);", 21928 LLVMWithBeforeLambdaBody); 21929 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21930 " []()\n" 21931 " {\n" 21932 " // A cool function...\n" 21933 " return Call([]() { return 17; });\n" 21934 " });", 21935 LLVMWithBeforeLambdaBody); 21936 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21937 " []()\n" 21938 " {\n" 21939 " return Call(\n" 21940 " []()\n" 21941 " {\n" 21942 " // A cool function...\n" 21943 " return 17;\n" 21944 " });\n" 21945 " });", 21946 LLVMWithBeforeLambdaBody); 21947 21948 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21949 FormatStyle::ShortLambdaStyle::SLS_None; 21950 21951 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21952 "{\n" 21953 " return MyAssignment::SelectFromList(this);\n" 21954 "};\n", 21955 LLVMWithBeforeLambdaBody); 21956 21957 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21958 "{\n" 21959 " return MyAssignment::SelectFromList(this);\n" 21960 "};\n", 21961 LLVMWithBeforeLambdaBody); 21962 21963 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21964 "{\n" 21965 " return MyAssignment::SelectFromList(this);\n" 21966 "};\n", 21967 LLVMWithBeforeLambdaBody); 21968 21969 verifyFormat("namespace test {\n" 21970 "class Test {\n" 21971 "public:\n" 21972 " Test() = default;\n" 21973 "};\n" 21974 "} // namespace test", 21975 LLVMWithBeforeLambdaBody); 21976 21977 // Lambdas with different indentation styles. 21978 Style = getLLVMStyleWithColumns(100); 21979 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21980 " return promise.then(\n" 21981 " [this, &someVariable, someObject = " 21982 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21983 " return someObject.startAsyncAction().then(\n" 21984 " [this, &someVariable](AsyncActionResult result) " 21985 "mutable { result.processMore(); });\n" 21986 " });\n" 21987 "}\n", 21988 format("SomeResult doSomething(SomeObject promise) {\n" 21989 " return promise.then([this, &someVariable, someObject = " 21990 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21991 " return someObject.startAsyncAction().then([this, " 21992 "&someVariable](AsyncActionResult result) mutable {\n" 21993 " result.processMore();\n" 21994 " });\n" 21995 " });\n" 21996 "}\n", 21997 Style)); 21998 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21999 verifyFormat("test() {\n" 22000 " ([]() -> {\n" 22001 " int b = 32;\n" 22002 " return 3;\n" 22003 " }).foo();\n" 22004 "}", 22005 Style); 22006 verifyFormat("test() {\n" 22007 " []() -> {\n" 22008 " int b = 32;\n" 22009 " return 3;\n" 22010 " }\n" 22011 "}", 22012 Style); 22013 verifyFormat("std::sort(v.begin(), v.end(),\n" 22014 " [](const auto &someLongArgumentName, const auto " 22015 "&someOtherLongArgumentName) {\n" 22016 " return someLongArgumentName.someMemberVariable < " 22017 "someOtherLongArgumentName.someMemberVariable;\n" 22018 "});", 22019 Style); 22020 verifyFormat("test() {\n" 22021 " (\n" 22022 " []() -> {\n" 22023 " int b = 32;\n" 22024 " return 3;\n" 22025 " },\n" 22026 " foo, bar)\n" 22027 " .foo();\n" 22028 "}", 22029 Style); 22030 verifyFormat("test() {\n" 22031 " ([]() -> {\n" 22032 " int b = 32;\n" 22033 " return 3;\n" 22034 " })\n" 22035 " .foo()\n" 22036 " .bar();\n" 22037 "}", 22038 Style); 22039 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22040 " return promise.then(\n" 22041 " [this, &someVariable, someObject = " 22042 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22043 " return someObject.startAsyncAction().then(\n" 22044 " [this, &someVariable](AsyncActionResult result) mutable { " 22045 "result.processMore(); });\n" 22046 " });\n" 22047 "}\n", 22048 format("SomeResult doSomething(SomeObject promise) {\n" 22049 " return promise.then([this, &someVariable, someObject = " 22050 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22051 " return someObject.startAsyncAction().then([this, " 22052 "&someVariable](AsyncActionResult result) mutable {\n" 22053 " result.processMore();\n" 22054 " });\n" 22055 " });\n" 22056 "}\n", 22057 Style)); 22058 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22059 " return promise.then([this, &someVariable] {\n" 22060 " return someObject.startAsyncAction().then(\n" 22061 " [this, &someVariable](AsyncActionResult result) mutable { " 22062 "result.processMore(); });\n" 22063 " });\n" 22064 "}\n", 22065 format("SomeResult doSomething(SomeObject promise) {\n" 22066 " return promise.then([this, &someVariable] {\n" 22067 " return someObject.startAsyncAction().then([this, " 22068 "&someVariable](AsyncActionResult result) mutable {\n" 22069 " result.processMore();\n" 22070 " });\n" 22071 " });\n" 22072 "}\n", 22073 Style)); 22074 Style = getGoogleStyle(); 22075 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 22076 EXPECT_EQ("#define A \\\n" 22077 " [] { \\\n" 22078 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 22079 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 22080 " }", 22081 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 22082 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 22083 Style)); 22084 // TODO: The current formatting has a minor issue that's not worth fixing 22085 // right now whereby the closing brace is indented relative to the signature 22086 // instead of being aligned. This only happens with macros. 22087 } 22088 22089 TEST_F(FormatTest, LambdaWithLineComments) { 22090 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 22091 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 22092 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 22093 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 22094 FormatStyle::ShortLambdaStyle::SLS_All; 22095 22096 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 22097 verifyFormat("auto k = []() // comment\n" 22098 "{ return; }", 22099 LLVMWithBeforeLambdaBody); 22100 verifyFormat("auto k = []() /* comment */ { return; }", 22101 LLVMWithBeforeLambdaBody); 22102 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 22103 LLVMWithBeforeLambdaBody); 22104 verifyFormat("auto k = []() // X\n" 22105 "{ return; }", 22106 LLVMWithBeforeLambdaBody); 22107 verifyFormat( 22108 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 22109 "{ return; }", 22110 LLVMWithBeforeLambdaBody); 22111 22112 LLVMWithBeforeLambdaBody.ColumnLimit = 0; 22113 22114 verifyFormat("foo([]()\n" 22115 " {\n" 22116 " bar(); //\n" 22117 " return 1; // comment\n" 22118 " }());", 22119 "foo([]() {\n" 22120 " bar(); //\n" 22121 " return 1; // comment\n" 22122 "}());", 22123 LLVMWithBeforeLambdaBody); 22124 verifyFormat("foo(\n" 22125 " 1, MACRO {\n" 22126 " baz();\n" 22127 " bar(); // comment\n" 22128 " },\n" 22129 " []() {});", 22130 "foo(\n" 22131 " 1, MACRO { baz(); bar(); // comment\n" 22132 " }, []() {}\n" 22133 ");", 22134 LLVMWithBeforeLambdaBody); 22135 } 22136 22137 TEST_F(FormatTest, EmptyLinesInLambdas) { 22138 verifyFormat("auto lambda = []() {\n" 22139 " x(); //\n" 22140 "};", 22141 "auto lambda = []() {\n" 22142 "\n" 22143 " x(); //\n" 22144 "\n" 22145 "};"); 22146 } 22147 22148 TEST_F(FormatTest, FormatsBlocks) { 22149 FormatStyle ShortBlocks = getLLVMStyle(); 22150 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22151 verifyFormat("int (^Block)(int, int);", ShortBlocks); 22152 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 22153 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 22154 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 22155 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 22156 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 22157 22158 verifyFormat("foo(^{ bar(); });", ShortBlocks); 22159 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 22160 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 22161 22162 verifyFormat("[operation setCompletionBlock:^{\n" 22163 " [self onOperationDone];\n" 22164 "}];"); 22165 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 22166 " [self onOperationDone];\n" 22167 "}]};"); 22168 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 22169 " f();\n" 22170 "}];"); 22171 verifyFormat("int a = [operation block:^int(int *i) {\n" 22172 " return 1;\n" 22173 "}];"); 22174 verifyFormat("[myObject doSomethingWith:arg1\n" 22175 " aaa:^int(int *a) {\n" 22176 " return 1;\n" 22177 " }\n" 22178 " bbb:f(a * bbbbbbbb)];"); 22179 22180 verifyFormat("[operation setCompletionBlock:^{\n" 22181 " [self.delegate newDataAvailable];\n" 22182 "}];", 22183 getLLVMStyleWithColumns(60)); 22184 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 22185 " NSString *path = [self sessionFilePath];\n" 22186 " if (path) {\n" 22187 " // ...\n" 22188 " }\n" 22189 "});"); 22190 verifyFormat("[[SessionService sharedService]\n" 22191 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22192 " if (window) {\n" 22193 " [self windowDidLoad:window];\n" 22194 " } else {\n" 22195 " [self errorLoadingWindow];\n" 22196 " }\n" 22197 " }];"); 22198 verifyFormat("void (^largeBlock)(void) = ^{\n" 22199 " // ...\n" 22200 "};\n", 22201 getLLVMStyleWithColumns(40)); 22202 verifyFormat("[[SessionService sharedService]\n" 22203 " loadWindowWithCompletionBlock: //\n" 22204 " ^(SessionWindow *window) {\n" 22205 " if (window) {\n" 22206 " [self windowDidLoad:window];\n" 22207 " } else {\n" 22208 " [self errorLoadingWindow];\n" 22209 " }\n" 22210 " }];", 22211 getLLVMStyleWithColumns(60)); 22212 verifyFormat("[myObject doSomethingWith:arg1\n" 22213 " firstBlock:^(Foo *a) {\n" 22214 " // ...\n" 22215 " int i;\n" 22216 " }\n" 22217 " secondBlock:^(Bar *b) {\n" 22218 " // ...\n" 22219 " int i;\n" 22220 " }\n" 22221 " thirdBlock:^Foo(Bar *b) {\n" 22222 " // ...\n" 22223 " int i;\n" 22224 " }];"); 22225 verifyFormat("[myObject doSomethingWith:arg1\n" 22226 " firstBlock:-1\n" 22227 " secondBlock:^(Bar *b) {\n" 22228 " // ...\n" 22229 " int i;\n" 22230 " }];"); 22231 22232 verifyFormat("f(^{\n" 22233 " @autoreleasepool {\n" 22234 " if (a) {\n" 22235 " g();\n" 22236 " }\n" 22237 " }\n" 22238 "});"); 22239 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22240 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22241 "};"); 22242 22243 FormatStyle FourIndent = getLLVMStyle(); 22244 FourIndent.ObjCBlockIndentWidth = 4; 22245 verifyFormat("[operation setCompletionBlock:^{\n" 22246 " [self onOperationDone];\n" 22247 "}];", 22248 FourIndent); 22249 } 22250 22251 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22252 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22253 22254 verifyFormat("[[SessionService sharedService] " 22255 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22256 " if (window) {\n" 22257 " [self windowDidLoad:window];\n" 22258 " } else {\n" 22259 " [self errorLoadingWindow];\n" 22260 " }\n" 22261 "}];", 22262 ZeroColumn); 22263 EXPECT_EQ("[[SessionService sharedService]\n" 22264 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22265 " if (window) {\n" 22266 " [self windowDidLoad:window];\n" 22267 " } else {\n" 22268 " [self errorLoadingWindow];\n" 22269 " }\n" 22270 " }];", 22271 format("[[SessionService sharedService]\n" 22272 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22273 " if (window) {\n" 22274 " [self windowDidLoad:window];\n" 22275 " } else {\n" 22276 " [self errorLoadingWindow];\n" 22277 " }\n" 22278 "}];", 22279 ZeroColumn)); 22280 verifyFormat("[myObject doSomethingWith:arg1\n" 22281 " firstBlock:^(Foo *a) {\n" 22282 " // ...\n" 22283 " int i;\n" 22284 " }\n" 22285 " secondBlock:^(Bar *b) {\n" 22286 " // ...\n" 22287 " int i;\n" 22288 " }\n" 22289 " thirdBlock:^Foo(Bar *b) {\n" 22290 " // ...\n" 22291 " int i;\n" 22292 " }];", 22293 ZeroColumn); 22294 verifyFormat("f(^{\n" 22295 " @autoreleasepool {\n" 22296 " if (a) {\n" 22297 " g();\n" 22298 " }\n" 22299 " }\n" 22300 "});", 22301 ZeroColumn); 22302 verifyFormat("void (^largeBlock)(void) = ^{\n" 22303 " // ...\n" 22304 "};", 22305 ZeroColumn); 22306 22307 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22308 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22309 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22310 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22311 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22312 " int i;\n" 22313 "};", 22314 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22315 } 22316 22317 TEST_F(FormatTest, SupportsCRLF) { 22318 EXPECT_EQ("int a;\r\n" 22319 "int b;\r\n" 22320 "int c;\r\n", 22321 format("int a;\r\n" 22322 " int b;\r\n" 22323 " int c;\r\n", 22324 getLLVMStyle())); 22325 EXPECT_EQ("int a;\r\n" 22326 "int b;\r\n" 22327 "int c;\r\n", 22328 format("int a;\r\n" 22329 " int b;\n" 22330 " int c;\r\n", 22331 getLLVMStyle())); 22332 EXPECT_EQ("int a;\n" 22333 "int b;\n" 22334 "int c;\n", 22335 format("int a;\r\n" 22336 " int b;\n" 22337 " int c;\n", 22338 getLLVMStyle())); 22339 EXPECT_EQ("\"aaaaaaa \"\r\n" 22340 "\"bbbbbbb\";\r\n", 22341 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22342 EXPECT_EQ("#define A \\\r\n" 22343 " b; \\\r\n" 22344 " c; \\\r\n" 22345 " d;\r\n", 22346 format("#define A \\\r\n" 22347 " b; \\\r\n" 22348 " c; d; \r\n", 22349 getGoogleStyle())); 22350 22351 EXPECT_EQ("/*\r\n" 22352 "multi line block comments\r\n" 22353 "should not introduce\r\n" 22354 "an extra carriage return\r\n" 22355 "*/\r\n", 22356 format("/*\r\n" 22357 "multi line block comments\r\n" 22358 "should not introduce\r\n" 22359 "an extra carriage return\r\n" 22360 "*/\r\n")); 22361 EXPECT_EQ("/*\r\n" 22362 "\r\n" 22363 "*/", 22364 format("/*\r\n" 22365 " \r\r\r\n" 22366 "*/")); 22367 22368 FormatStyle style = getLLVMStyle(); 22369 22370 style.DeriveLineEnding = true; 22371 style.UseCRLF = false; 22372 EXPECT_EQ("union FooBarBazQux {\n" 22373 " int foo;\n" 22374 " int bar;\n" 22375 " int baz;\n" 22376 "};", 22377 format("union FooBarBazQux {\r\n" 22378 " int foo;\n" 22379 " int bar;\r\n" 22380 " int baz;\n" 22381 "};", 22382 style)); 22383 style.UseCRLF = true; 22384 EXPECT_EQ("union FooBarBazQux {\r\n" 22385 " int foo;\r\n" 22386 " int bar;\r\n" 22387 " int baz;\r\n" 22388 "};", 22389 format("union FooBarBazQux {\r\n" 22390 " int foo;\n" 22391 " int bar;\r\n" 22392 " int baz;\n" 22393 "};", 22394 style)); 22395 22396 style.DeriveLineEnding = false; 22397 style.UseCRLF = false; 22398 EXPECT_EQ("union FooBarBazQux {\n" 22399 " int foo;\n" 22400 " int bar;\n" 22401 " int baz;\n" 22402 " int qux;\n" 22403 "};", 22404 format("union FooBarBazQux {\r\n" 22405 " int foo;\n" 22406 " int bar;\r\n" 22407 " int baz;\n" 22408 " int qux;\r\n" 22409 "};", 22410 style)); 22411 style.UseCRLF = true; 22412 EXPECT_EQ("union FooBarBazQux {\r\n" 22413 " int foo;\r\n" 22414 " int bar;\r\n" 22415 " int baz;\r\n" 22416 " int qux;\r\n" 22417 "};", 22418 format("union FooBarBazQux {\r\n" 22419 " int foo;\n" 22420 " int bar;\r\n" 22421 " int baz;\n" 22422 " int qux;\n" 22423 "};", 22424 style)); 22425 22426 style.DeriveLineEnding = true; 22427 style.UseCRLF = false; 22428 EXPECT_EQ("union FooBarBazQux {\r\n" 22429 " int foo;\r\n" 22430 " int bar;\r\n" 22431 " int baz;\r\n" 22432 " int qux;\r\n" 22433 "};", 22434 format("union FooBarBazQux {\r\n" 22435 " int foo;\n" 22436 " int bar;\r\n" 22437 " int baz;\n" 22438 " int qux;\r\n" 22439 "};", 22440 style)); 22441 style.UseCRLF = true; 22442 EXPECT_EQ("union FooBarBazQux {\n" 22443 " int foo;\n" 22444 " int bar;\n" 22445 " int baz;\n" 22446 " int qux;\n" 22447 "};", 22448 format("union FooBarBazQux {\r\n" 22449 " int foo;\n" 22450 " int bar;\r\n" 22451 " int baz;\n" 22452 " int qux;\n" 22453 "};", 22454 style)); 22455 } 22456 22457 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22458 verifyFormat("MY_CLASS(C) {\n" 22459 " int i;\n" 22460 " int j;\n" 22461 "};"); 22462 } 22463 22464 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22465 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22466 TwoIndent.ContinuationIndentWidth = 2; 22467 22468 EXPECT_EQ("int i =\n" 22469 " longFunction(\n" 22470 " arg);", 22471 format("int i = longFunction(arg);", TwoIndent)); 22472 22473 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22474 SixIndent.ContinuationIndentWidth = 6; 22475 22476 EXPECT_EQ("int i =\n" 22477 " longFunction(\n" 22478 " arg);", 22479 format("int i = longFunction(arg);", SixIndent)); 22480 } 22481 22482 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22483 FormatStyle Style = getLLVMStyle(); 22484 verifyFormat("int Foo::getter(\n" 22485 " //\n" 22486 ") const {\n" 22487 " return foo;\n" 22488 "}", 22489 Style); 22490 verifyFormat("void Foo::setter(\n" 22491 " //\n" 22492 ") {\n" 22493 " foo = 1;\n" 22494 "}", 22495 Style); 22496 } 22497 22498 TEST_F(FormatTest, SpacesInAngles) { 22499 FormatStyle Spaces = getLLVMStyle(); 22500 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22501 22502 verifyFormat("vector< ::std::string > x1;", Spaces); 22503 verifyFormat("Foo< int, Bar > x2;", Spaces); 22504 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22505 22506 verifyFormat("static_cast< int >(arg);", Spaces); 22507 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22508 verifyFormat("f< int, float >();", Spaces); 22509 verifyFormat("template <> g() {}", Spaces); 22510 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22511 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22512 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22513 Spaces); 22514 22515 Spaces.Standard = FormatStyle::LS_Cpp03; 22516 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22517 verifyFormat("A< A< int > >();", Spaces); 22518 22519 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22520 verifyFormat("A<A<int> >();", Spaces); 22521 22522 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22523 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22524 Spaces); 22525 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22526 Spaces); 22527 22528 verifyFormat("A<A<int> >();", Spaces); 22529 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22530 verifyFormat("A< A< int > >();", Spaces); 22531 22532 Spaces.Standard = FormatStyle::LS_Cpp11; 22533 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22534 verifyFormat("A< A< int > >();", Spaces); 22535 22536 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22537 verifyFormat("vector<::std::string> x4;", Spaces); 22538 verifyFormat("vector<int> x5;", Spaces); 22539 verifyFormat("Foo<int, Bar> x6;", Spaces); 22540 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22541 22542 verifyFormat("A<A<int>>();", Spaces); 22543 22544 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22545 verifyFormat("vector<::std::string> x4;", Spaces); 22546 verifyFormat("vector< ::std::string > x4;", Spaces); 22547 verifyFormat("vector<int> x5;", Spaces); 22548 verifyFormat("vector< int > x5;", Spaces); 22549 verifyFormat("Foo<int, Bar> x6;", Spaces); 22550 verifyFormat("Foo< int, Bar > x6;", Spaces); 22551 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22552 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22553 22554 verifyFormat("A<A<int>>();", Spaces); 22555 verifyFormat("A< A< int > >();", Spaces); 22556 verifyFormat("A<A<int > >();", Spaces); 22557 verifyFormat("A< A< int>>();", Spaces); 22558 22559 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22560 verifyFormat("// clang-format off\n" 22561 "foo<<<1, 1>>>();\n" 22562 "// clang-format on\n", 22563 Spaces); 22564 verifyFormat("// clang-format off\n" 22565 "foo< < <1, 1> > >();\n" 22566 "// clang-format on\n", 22567 Spaces); 22568 } 22569 22570 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22571 FormatStyle Style = getLLVMStyle(); 22572 Style.SpaceAfterTemplateKeyword = false; 22573 verifyFormat("template<int> void foo();", Style); 22574 } 22575 22576 TEST_F(FormatTest, TripleAngleBrackets) { 22577 verifyFormat("f<<<1, 1>>>();"); 22578 verifyFormat("f<<<1, 1, 1, s>>>();"); 22579 verifyFormat("f<<<a, b, c, d>>>();"); 22580 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22581 verifyFormat("f<param><<<1, 1>>>();"); 22582 verifyFormat("f<1><<<1, 1>>>();"); 22583 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22584 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22585 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22586 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22587 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22588 } 22589 22590 TEST_F(FormatTest, MergeLessLessAtEnd) { 22591 verifyFormat("<<"); 22592 EXPECT_EQ("< < <", format("\\\n<<<")); 22593 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22594 "aaallvm::outs() <<"); 22595 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22596 "aaaallvm::outs()\n <<"); 22597 } 22598 22599 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22600 std::string code = "#if A\n" 22601 "#if B\n" 22602 "a.\n" 22603 "#endif\n" 22604 " a = 1;\n" 22605 "#else\n" 22606 "#endif\n" 22607 "#if C\n" 22608 "#else\n" 22609 "#endif\n"; 22610 EXPECT_EQ(code, format(code)); 22611 } 22612 22613 TEST_F(FormatTest, HandleConflictMarkers) { 22614 // Git/SVN conflict markers. 22615 EXPECT_EQ("int a;\n" 22616 "void f() {\n" 22617 " callme(some(parameter1,\n" 22618 "<<<<<<< text by the vcs\n" 22619 " parameter2),\n" 22620 "||||||| text by the vcs\n" 22621 " parameter2),\n" 22622 " parameter3,\n" 22623 "======= text by the vcs\n" 22624 " parameter2, parameter3),\n" 22625 ">>>>>>> text by the vcs\n" 22626 " otherparameter);\n", 22627 format("int a;\n" 22628 "void f() {\n" 22629 " callme(some(parameter1,\n" 22630 "<<<<<<< text by the vcs\n" 22631 " parameter2),\n" 22632 "||||||| text by the vcs\n" 22633 " parameter2),\n" 22634 " parameter3,\n" 22635 "======= text by the vcs\n" 22636 " parameter2,\n" 22637 " parameter3),\n" 22638 ">>>>>>> text by the vcs\n" 22639 " otherparameter);\n")); 22640 22641 // Perforce markers. 22642 EXPECT_EQ("void f() {\n" 22643 " function(\n" 22644 ">>>> text by the vcs\n" 22645 " parameter,\n" 22646 "==== text by the vcs\n" 22647 " parameter,\n" 22648 "==== text by the vcs\n" 22649 " parameter,\n" 22650 "<<<< text by the vcs\n" 22651 " parameter);\n", 22652 format("void f() {\n" 22653 " function(\n" 22654 ">>>> text by the vcs\n" 22655 " parameter,\n" 22656 "==== text by the vcs\n" 22657 " parameter,\n" 22658 "==== text by the vcs\n" 22659 " parameter,\n" 22660 "<<<< text by the vcs\n" 22661 " parameter);\n")); 22662 22663 EXPECT_EQ("<<<<<<<\n" 22664 "|||||||\n" 22665 "=======\n" 22666 ">>>>>>>", 22667 format("<<<<<<<\n" 22668 "|||||||\n" 22669 "=======\n" 22670 ">>>>>>>")); 22671 22672 EXPECT_EQ("<<<<<<<\n" 22673 "|||||||\n" 22674 "int i;\n" 22675 "=======\n" 22676 ">>>>>>>", 22677 format("<<<<<<<\n" 22678 "|||||||\n" 22679 "int i;\n" 22680 "=======\n" 22681 ">>>>>>>")); 22682 22683 // FIXME: Handle parsing of macros around conflict markers correctly: 22684 EXPECT_EQ("#define Macro \\\n" 22685 "<<<<<<<\n" 22686 "Something \\\n" 22687 "|||||||\n" 22688 "Else \\\n" 22689 "=======\n" 22690 "Other \\\n" 22691 ">>>>>>>\n" 22692 " End int i;\n", 22693 format("#define Macro \\\n" 22694 "<<<<<<<\n" 22695 " Something \\\n" 22696 "|||||||\n" 22697 " Else \\\n" 22698 "=======\n" 22699 " Other \\\n" 22700 ">>>>>>>\n" 22701 " End\n" 22702 "int i;\n")); 22703 22704 verifyFormat(R"(==== 22705 #ifdef A 22706 a 22707 #else 22708 b 22709 #endif 22710 )"); 22711 } 22712 22713 TEST_F(FormatTest, DisableRegions) { 22714 EXPECT_EQ("int i;\n" 22715 "// clang-format off\n" 22716 " int j;\n" 22717 "// clang-format on\n" 22718 "int k;", 22719 format(" int i;\n" 22720 " // clang-format off\n" 22721 " int j;\n" 22722 " // clang-format on\n" 22723 " int k;")); 22724 EXPECT_EQ("int i;\n" 22725 "/* clang-format off */\n" 22726 " int j;\n" 22727 "/* clang-format on */\n" 22728 "int k;", 22729 format(" int i;\n" 22730 " /* clang-format off */\n" 22731 " int j;\n" 22732 " /* clang-format on */\n" 22733 " int k;")); 22734 22735 // Don't reflow comments within disabled regions. 22736 EXPECT_EQ("// clang-format off\n" 22737 "// long long long long long long line\n" 22738 "/* clang-format on */\n" 22739 "/* long long long\n" 22740 " * long long long\n" 22741 " * line */\n" 22742 "int i;\n" 22743 "/* clang-format off */\n" 22744 "/* long long long long long long line */\n", 22745 format("// clang-format off\n" 22746 "// long long long long long long line\n" 22747 "/* clang-format on */\n" 22748 "/* long long long long long long line */\n" 22749 "int i;\n" 22750 "/* clang-format off */\n" 22751 "/* long long long long long long line */\n", 22752 getLLVMStyleWithColumns(20))); 22753 } 22754 22755 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22756 format("? ) ="); 22757 verifyNoCrash("#define a\\\n /**/}"); 22758 } 22759 22760 TEST_F(FormatTest, FormatsTableGenCode) { 22761 FormatStyle Style = getLLVMStyle(); 22762 Style.Language = FormatStyle::LK_TableGen; 22763 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22764 } 22765 22766 TEST_F(FormatTest, ArrayOfTemplates) { 22767 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22768 format("auto a = new unique_ptr<int > [ 10];")); 22769 22770 FormatStyle Spaces = getLLVMStyle(); 22771 Spaces.SpacesInSquareBrackets = true; 22772 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22773 format("auto a = new unique_ptr<int > [10];", Spaces)); 22774 } 22775 22776 TEST_F(FormatTest, ArrayAsTemplateType) { 22777 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22778 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22779 22780 FormatStyle Spaces = getLLVMStyle(); 22781 Spaces.SpacesInSquareBrackets = true; 22782 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22783 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22784 } 22785 22786 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22787 22788 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22789 llvm::vfs::InMemoryFileSystem FS; 22790 auto Style1 = getStyle("file", "", "Google", "", &FS); 22791 ASSERT_TRUE((bool)Style1); 22792 ASSERT_EQ(*Style1, getGoogleStyle()); 22793 } 22794 22795 TEST(FormatStyle, GetStyleOfFile) { 22796 llvm::vfs::InMemoryFileSystem FS; 22797 // Test 1: format file in the same directory. 22798 ASSERT_TRUE( 22799 FS.addFile("/a/.clang-format", 0, 22800 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22801 ASSERT_TRUE( 22802 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22803 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22804 ASSERT_TRUE((bool)Style1); 22805 ASSERT_EQ(*Style1, getLLVMStyle()); 22806 22807 // Test 2.1: fallback to default. 22808 ASSERT_TRUE( 22809 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22810 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22811 ASSERT_TRUE((bool)Style2); 22812 ASSERT_EQ(*Style2, getMozillaStyle()); 22813 22814 // Test 2.2: no format on 'none' fallback style. 22815 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22816 ASSERT_TRUE((bool)Style2); 22817 ASSERT_EQ(*Style2, getNoStyle()); 22818 22819 // Test 2.3: format if config is found with no based style while fallback is 22820 // 'none'. 22821 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22822 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22823 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22824 ASSERT_TRUE((bool)Style2); 22825 ASSERT_EQ(*Style2, getLLVMStyle()); 22826 22827 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22828 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22829 ASSERT_TRUE((bool)Style2); 22830 ASSERT_EQ(*Style2, getLLVMStyle()); 22831 22832 // Test 3: format file in parent directory. 22833 ASSERT_TRUE( 22834 FS.addFile("/c/.clang-format", 0, 22835 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22836 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22837 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22838 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22839 ASSERT_TRUE((bool)Style3); 22840 ASSERT_EQ(*Style3, getGoogleStyle()); 22841 22842 // Test 4: error on invalid fallback style 22843 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22844 ASSERT_FALSE((bool)Style4); 22845 llvm::consumeError(Style4.takeError()); 22846 22847 // Test 5: error on invalid yaml on command line 22848 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22849 ASSERT_FALSE((bool)Style5); 22850 llvm::consumeError(Style5.takeError()); 22851 22852 // Test 6: error on invalid style 22853 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22854 ASSERT_FALSE((bool)Style6); 22855 llvm::consumeError(Style6.takeError()); 22856 22857 // Test 7: found config file, error on parsing it 22858 ASSERT_TRUE( 22859 FS.addFile("/d/.clang-format", 0, 22860 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22861 "InvalidKey: InvalidValue"))); 22862 ASSERT_TRUE( 22863 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22864 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22865 ASSERT_FALSE((bool)Style7a); 22866 llvm::consumeError(Style7a.takeError()); 22867 22868 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22869 ASSERT_TRUE((bool)Style7b); 22870 22871 // Test 8: inferred per-language defaults apply. 22872 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22873 ASSERT_TRUE((bool)StyleTd); 22874 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22875 22876 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22877 // fallback style. 22878 ASSERT_TRUE(FS.addFile( 22879 "/e/sub/.clang-format", 0, 22880 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22881 "ColumnLimit: 20"))); 22882 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22883 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22884 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22885 ASSERT_TRUE(static_cast<bool>(Style9)); 22886 ASSERT_EQ(*Style9, [] { 22887 auto Style = getNoStyle(); 22888 Style.ColumnLimit = 20; 22889 return Style; 22890 }()); 22891 22892 // Test 9.1.2: propagate more than one level with no parent file. 22893 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22894 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22895 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22896 llvm::MemoryBuffer::getMemBuffer( 22897 "BasedOnStyle: InheritParentConfig\n" 22898 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22899 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22900 22901 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22902 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22903 ASSERT_TRUE(static_cast<bool>(Style9)); 22904 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22905 auto Style = getNoStyle(); 22906 Style.ColumnLimit = 20; 22907 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22908 return Style; 22909 }()); 22910 22911 // Test 9.2: with LLVM fallback style 22912 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22913 ASSERT_TRUE(static_cast<bool>(Style9)); 22914 ASSERT_EQ(*Style9, [] { 22915 auto Style = getLLVMStyle(); 22916 Style.ColumnLimit = 20; 22917 return Style; 22918 }()); 22919 22920 // Test 9.3: with a parent file 22921 ASSERT_TRUE( 22922 FS.addFile("/e/.clang-format", 0, 22923 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22924 "UseTab: Always"))); 22925 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22926 ASSERT_TRUE(static_cast<bool>(Style9)); 22927 ASSERT_EQ(*Style9, [] { 22928 auto Style = getGoogleStyle(); 22929 Style.ColumnLimit = 20; 22930 Style.UseTab = FormatStyle::UT_Always; 22931 return Style; 22932 }()); 22933 22934 // Test 9.4: propagate more than one level with a parent file. 22935 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22936 auto Style = getGoogleStyle(); 22937 Style.ColumnLimit = 20; 22938 Style.UseTab = FormatStyle::UT_Always; 22939 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22940 return Style; 22941 }(); 22942 22943 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22944 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22945 ASSERT_TRUE(static_cast<bool>(Style9)); 22946 ASSERT_EQ(*Style9, SubSubStyle); 22947 22948 // Test 9.5: use InheritParentConfig as style name 22949 Style9 = 22950 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22951 ASSERT_TRUE(static_cast<bool>(Style9)); 22952 ASSERT_EQ(*Style9, SubSubStyle); 22953 22954 // Test 9.6: use command line style with inheritance 22955 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22956 "none", "", &FS); 22957 ASSERT_TRUE(static_cast<bool>(Style9)); 22958 ASSERT_EQ(*Style9, SubSubStyle); 22959 22960 // Test 9.7: use command line style with inheritance and own config 22961 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22962 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22963 "/e/sub/code.cpp", "none", "", &FS); 22964 ASSERT_TRUE(static_cast<bool>(Style9)); 22965 ASSERT_EQ(*Style9, SubSubStyle); 22966 22967 // Test 9.8: use inheritance from a file without BasedOnStyle 22968 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22969 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22970 ASSERT_TRUE( 22971 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22972 llvm::MemoryBuffer::getMemBuffer( 22973 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22974 // Make sure we do not use the fallback style 22975 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22976 ASSERT_TRUE(static_cast<bool>(Style9)); 22977 ASSERT_EQ(*Style9, [] { 22978 auto Style = getLLVMStyle(); 22979 Style.ColumnLimit = 123; 22980 return Style; 22981 }()); 22982 22983 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22984 ASSERT_TRUE(static_cast<bool>(Style9)); 22985 ASSERT_EQ(*Style9, [] { 22986 auto Style = getLLVMStyle(); 22987 Style.ColumnLimit = 123; 22988 Style.IndentWidth = 7; 22989 return Style; 22990 }()); 22991 22992 // Test 9.9: use inheritance from a specific config file. 22993 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22994 "none", "", &FS); 22995 ASSERT_TRUE(static_cast<bool>(Style9)); 22996 ASSERT_EQ(*Style9, SubSubStyle); 22997 } 22998 22999 TEST(FormatStyle, GetStyleOfSpecificFile) { 23000 llvm::vfs::InMemoryFileSystem FS; 23001 // Specify absolute path to a format file in a parent directory. 23002 ASSERT_TRUE( 23003 FS.addFile("/e/.clang-format", 0, 23004 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 23005 ASSERT_TRUE( 23006 FS.addFile("/e/explicit.clang-format", 0, 23007 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 23008 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 23009 llvm::MemoryBuffer::getMemBuffer("int i;"))); 23010 auto Style = getStyle("file:/e/explicit.clang-format", 23011 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 23012 ASSERT_TRUE(static_cast<bool>(Style)); 23013 ASSERT_EQ(*Style, getGoogleStyle()); 23014 23015 // Specify relative path to a format file. 23016 ASSERT_TRUE( 23017 FS.addFile("../../e/explicit.clang-format", 0, 23018 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 23019 Style = getStyle("file:../../e/explicit.clang-format", 23020 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 23021 ASSERT_TRUE(static_cast<bool>(Style)); 23022 ASSERT_EQ(*Style, getGoogleStyle()); 23023 23024 // Specify path to a format file that does not exist. 23025 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 23026 "LLVM", "", &FS); 23027 ASSERT_FALSE(static_cast<bool>(Style)); 23028 llvm::consumeError(Style.takeError()); 23029 23030 // Specify path to a file on the filesystem. 23031 SmallString<128> FormatFilePath; 23032 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 23033 "FormatFileTest", "tpl", FormatFilePath); 23034 EXPECT_FALSE((bool)ECF); 23035 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 23036 EXPECT_FALSE((bool)ECF); 23037 FormatFileTest << "BasedOnStyle: Google\n"; 23038 FormatFileTest.close(); 23039 23040 SmallString<128> TestFilePath; 23041 std::error_code ECT = 23042 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 23043 EXPECT_FALSE((bool)ECT); 23044 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 23045 CodeFileTest << "int i;\n"; 23046 CodeFileTest.close(); 23047 23048 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 23049 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 23050 23051 llvm::sys::fs::remove(FormatFilePath.c_str()); 23052 llvm::sys::fs::remove(TestFilePath.c_str()); 23053 ASSERT_TRUE(static_cast<bool>(Style)); 23054 ASSERT_EQ(*Style, getGoogleStyle()); 23055 } 23056 23057 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 23058 // Column limit is 20. 23059 std::string Code = "Type *a =\n" 23060 " new Type();\n" 23061 "g(iiiii, 0, jjjjj,\n" 23062 " 0, kkkkk, 0, mm);\n" 23063 "int bad = format ;"; 23064 std::string Expected = "auto a = new Type();\n" 23065 "g(iiiii, nullptr,\n" 23066 " jjjjj, nullptr,\n" 23067 " kkkkk, nullptr,\n" 23068 " mm);\n" 23069 "int bad = format ;"; 23070 FileID ID = Context.createInMemoryFile("format.cpp", Code); 23071 tooling::Replacements Replaces = toReplacements( 23072 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 23073 "auto "), 23074 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 23075 "nullptr"), 23076 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 23077 "nullptr"), 23078 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 23079 "nullptr")}); 23080 23081 FormatStyle Style = getLLVMStyle(); 23082 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 23083 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23084 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23085 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23086 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23087 EXPECT_TRUE(static_cast<bool>(Result)); 23088 EXPECT_EQ(Expected, *Result); 23089 } 23090 23091 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 23092 std::string Code = "#include \"a.h\"\n" 23093 "#include \"c.h\"\n" 23094 "\n" 23095 "int main() {\n" 23096 " return 0;\n" 23097 "}"; 23098 std::string Expected = "#include \"a.h\"\n" 23099 "#include \"b.h\"\n" 23100 "#include \"c.h\"\n" 23101 "\n" 23102 "int main() {\n" 23103 " return 0;\n" 23104 "}"; 23105 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 23106 tooling::Replacements Replaces = toReplacements( 23107 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 23108 "#include \"b.h\"\n")}); 23109 23110 FormatStyle Style = getLLVMStyle(); 23111 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 23112 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23113 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23114 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23115 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23116 EXPECT_TRUE(static_cast<bool>(Result)); 23117 EXPECT_EQ(Expected, *Result); 23118 } 23119 23120 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 23121 EXPECT_EQ("using std::cin;\n" 23122 "using std::cout;", 23123 format("using std::cout;\n" 23124 "using std::cin;", 23125 getGoogleStyle())); 23126 } 23127 23128 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 23129 FormatStyle Style = getLLVMStyle(); 23130 Style.Standard = FormatStyle::LS_Cpp03; 23131 // cpp03 recognize this string as identifier u8 and literal character 'a' 23132 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 23133 } 23134 23135 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 23136 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 23137 // all modes, including C++11, C++14 and C++17 23138 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 23139 } 23140 23141 TEST_F(FormatTest, DoNotFormatLikelyXml) { 23142 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 23143 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 23144 } 23145 23146 TEST_F(FormatTest, StructuredBindings) { 23147 // Structured bindings is a C++17 feature. 23148 // all modes, including C++11, C++14 and C++17 23149 verifyFormat("auto [a, b] = f();"); 23150 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 23151 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 23152 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 23153 EXPECT_EQ("auto const volatile [a, b] = f();", 23154 format("auto const volatile[a, b] = f();")); 23155 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 23156 EXPECT_EQ("auto &[a, b, c] = f();", 23157 format("auto &[ a , b,c ] = f();")); 23158 EXPECT_EQ("auto &&[a, b, c] = f();", 23159 format("auto &&[ a , b,c ] = f();")); 23160 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 23161 EXPECT_EQ("auto const volatile &&[a, b] = f();", 23162 format("auto const volatile &&[a, b] = f();")); 23163 EXPECT_EQ("auto const &&[a, b] = f();", 23164 format("auto const && [a, b] = f();")); 23165 EXPECT_EQ("const auto &[a, b] = f();", 23166 format("const auto & [a, b] = f();")); 23167 EXPECT_EQ("const auto volatile &&[a, b] = f();", 23168 format("const auto volatile &&[a, b] = f();")); 23169 EXPECT_EQ("volatile const auto &&[a, b] = f();", 23170 format("volatile const auto &&[a, b] = f();")); 23171 EXPECT_EQ("const auto &&[a, b] = f();", 23172 format("const auto && [a, b] = f();")); 23173 23174 // Make sure we don't mistake structured bindings for lambdas. 23175 FormatStyle PointerMiddle = getLLVMStyle(); 23176 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 23177 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 23178 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 23179 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 23180 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 23181 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 23182 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 23183 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 23184 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 23185 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 23186 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 23187 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 23188 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 23189 23190 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 23191 format("for (const auto && [a, b] : some_range) {\n}")); 23192 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 23193 format("for (const auto & [a, b] : some_range) {\n}")); 23194 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 23195 format("for (const auto[a, b] : some_range) {\n}")); 23196 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 23197 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 23198 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 23199 EXPECT_EQ("auto const &[x, y](expr);", 23200 format("auto const & [x,y] (expr);")); 23201 EXPECT_EQ("auto const &&[x, y](expr);", 23202 format("auto const && [x,y] (expr);")); 23203 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 23204 EXPECT_EQ("auto const &[x, y]{expr};", 23205 format("auto const & [x,y] {expr};")); 23206 EXPECT_EQ("auto const &&[x, y]{expr};", 23207 format("auto const && [x,y] {expr};")); 23208 23209 FormatStyle Spaces = getLLVMStyle(); 23210 Spaces.SpacesInSquareBrackets = true; 23211 verifyFormat("auto [ a, b ] = f();", Spaces); 23212 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23213 verifyFormat("auto &[ a, b ] = f();", Spaces); 23214 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23215 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23216 } 23217 23218 TEST_F(FormatTest, FileAndCode) { 23219 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23220 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23221 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23222 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23223 EXPECT_EQ(FormatStyle::LK_ObjC, 23224 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23225 EXPECT_EQ( 23226 FormatStyle::LK_ObjC, 23227 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23228 EXPECT_EQ(FormatStyle::LK_ObjC, 23229 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23230 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23231 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23232 EXPECT_EQ(FormatStyle::LK_ObjC, 23233 guessLanguage("foo", "@interface Foo\n@end\n")); 23234 EXPECT_EQ(FormatStyle::LK_ObjC, 23235 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23236 EXPECT_EQ( 23237 FormatStyle::LK_ObjC, 23238 guessLanguage("foo.h", 23239 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23240 EXPECT_EQ( 23241 FormatStyle::LK_Cpp, 23242 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23243 // Only one of the two preprocessor regions has ObjC-like code. 23244 EXPECT_EQ(FormatStyle::LK_ObjC, 23245 guessLanguage("foo.h", "#if A\n" 23246 "#define B() C\n" 23247 "#else\n" 23248 "#define B() [NSString a:@\"\"]\n" 23249 "#endif\n")); 23250 } 23251 23252 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23253 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23254 EXPECT_EQ(FormatStyle::LK_ObjC, 23255 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23256 EXPECT_EQ(FormatStyle::LK_Cpp, 23257 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23258 EXPECT_EQ( 23259 FormatStyle::LK_Cpp, 23260 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23261 EXPECT_EQ(FormatStyle::LK_ObjC, 23262 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23263 EXPECT_EQ(FormatStyle::LK_Cpp, 23264 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23265 EXPECT_EQ(FormatStyle::LK_ObjC, 23266 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23267 EXPECT_EQ(FormatStyle::LK_Cpp, 23268 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23269 EXPECT_EQ(FormatStyle::LK_Cpp, 23270 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23271 EXPECT_EQ(FormatStyle::LK_ObjC, 23272 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23273 EXPECT_EQ(FormatStyle::LK_Cpp, 23274 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23275 EXPECT_EQ( 23276 FormatStyle::LK_Cpp, 23277 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23278 EXPECT_EQ( 23279 FormatStyle::LK_Cpp, 23280 guessLanguage("foo.h", 23281 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23282 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23283 } 23284 23285 TEST_F(FormatTest, GuessLanguageWithCaret) { 23286 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23287 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23288 EXPECT_EQ(FormatStyle::LK_ObjC, 23289 guessLanguage("foo.h", "int(^)(char, float);")); 23290 EXPECT_EQ(FormatStyle::LK_ObjC, 23291 guessLanguage("foo.h", "int(^foo)(char, float);")); 23292 EXPECT_EQ(FormatStyle::LK_ObjC, 23293 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23294 EXPECT_EQ(FormatStyle::LK_ObjC, 23295 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23296 EXPECT_EQ( 23297 FormatStyle::LK_ObjC, 23298 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23299 } 23300 23301 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23302 EXPECT_EQ(FormatStyle::LK_Cpp, 23303 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23304 EXPECT_EQ(FormatStyle::LK_Cpp, 23305 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23306 EXPECT_EQ(FormatStyle::LK_Cpp, 23307 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23308 } 23309 23310 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23311 // ASM symbolic names are identifiers that must be surrounded by [] without 23312 // space in between: 23313 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23314 23315 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23316 verifyFormat(R"(// 23317 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23318 )"); 23319 23320 // A list of several ASM symbolic names. 23321 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23322 23323 // ASM symbolic names in inline ASM with inputs and outputs. 23324 verifyFormat(R"(// 23325 asm("cmoveq %1, %2, %[result]" 23326 : [result] "=r"(result) 23327 : "r"(test), "r"(new), "[result]"(old)); 23328 )"); 23329 23330 // ASM symbolic names in inline ASM with no outputs. 23331 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23332 } 23333 23334 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23335 EXPECT_EQ(FormatStyle::LK_Cpp, 23336 guessLanguage("foo.h", "void f() {\n" 23337 " asm (\"mov %[e], %[d]\"\n" 23338 " : [d] \"=rm\" (d)\n" 23339 " [e] \"rm\" (*e));\n" 23340 "}")); 23341 EXPECT_EQ(FormatStyle::LK_Cpp, 23342 guessLanguage("foo.h", "void f() {\n" 23343 " _asm (\"mov %[e], %[d]\"\n" 23344 " : [d] \"=rm\" (d)\n" 23345 " [e] \"rm\" (*e));\n" 23346 "}")); 23347 EXPECT_EQ(FormatStyle::LK_Cpp, 23348 guessLanguage("foo.h", "void f() {\n" 23349 " __asm (\"mov %[e], %[d]\"\n" 23350 " : [d] \"=rm\" (d)\n" 23351 " [e] \"rm\" (*e));\n" 23352 "}")); 23353 EXPECT_EQ(FormatStyle::LK_Cpp, 23354 guessLanguage("foo.h", "void f() {\n" 23355 " __asm__ (\"mov %[e], %[d]\"\n" 23356 " : [d] \"=rm\" (d)\n" 23357 " [e] \"rm\" (*e));\n" 23358 "}")); 23359 EXPECT_EQ(FormatStyle::LK_Cpp, 23360 guessLanguage("foo.h", "void f() {\n" 23361 " asm (\"mov %[e], %[d]\"\n" 23362 " : [d] \"=rm\" (d),\n" 23363 " [e] \"rm\" (*e));\n" 23364 "}")); 23365 EXPECT_EQ(FormatStyle::LK_Cpp, 23366 guessLanguage("foo.h", "void f() {\n" 23367 " asm volatile (\"mov %[e], %[d]\"\n" 23368 " : [d] \"=rm\" (d)\n" 23369 " [e] \"rm\" (*e));\n" 23370 "}")); 23371 } 23372 23373 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23374 EXPECT_EQ(FormatStyle::LK_Cpp, 23375 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23376 EXPECT_EQ(FormatStyle::LK_ObjC, 23377 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23378 EXPECT_EQ( 23379 FormatStyle::LK_Cpp, 23380 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23381 EXPECT_EQ( 23382 FormatStyle::LK_ObjC, 23383 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23384 } 23385 23386 TEST_F(FormatTest, TypenameMacros) { 23387 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23388 23389 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23390 FormatStyle Google = getGoogleStyleWithColumns(0); 23391 Google.TypenameMacros = TypenameMacros; 23392 verifyFormat("struct foo {\n" 23393 " int bar;\n" 23394 " TAILQ_ENTRY(a) bleh;\n" 23395 "};", 23396 Google); 23397 23398 FormatStyle Macros = getLLVMStyle(); 23399 Macros.TypenameMacros = TypenameMacros; 23400 23401 verifyFormat("STACK_OF(int) a;", Macros); 23402 verifyFormat("STACK_OF(int) *a;", Macros); 23403 verifyFormat("STACK_OF(int const *) *a;", Macros); 23404 verifyFormat("STACK_OF(int *const) *a;", Macros); 23405 verifyFormat("STACK_OF(int, string) a;", Macros); 23406 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23407 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23408 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23409 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23410 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23411 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23412 23413 Macros.PointerAlignment = FormatStyle::PAS_Left; 23414 verifyFormat("STACK_OF(int)* a;", Macros); 23415 verifyFormat("STACK_OF(int*)* a;", Macros); 23416 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23417 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23418 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23419 } 23420 23421 TEST_F(FormatTest, AtomicQualifier) { 23422 // Check that we treate _Atomic as a type and not a function call 23423 FormatStyle Google = getGoogleStyleWithColumns(0); 23424 verifyFormat("struct foo {\n" 23425 " int a1;\n" 23426 " _Atomic(a) a2;\n" 23427 " _Atomic(_Atomic(int) *const) a3;\n" 23428 "};", 23429 Google); 23430 verifyFormat("_Atomic(uint64_t) a;"); 23431 verifyFormat("_Atomic(uint64_t) *a;"); 23432 verifyFormat("_Atomic(uint64_t const *) *a;"); 23433 verifyFormat("_Atomic(uint64_t *const) *a;"); 23434 verifyFormat("_Atomic(const uint64_t *) *a;"); 23435 verifyFormat("_Atomic(uint64_t) a;"); 23436 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23437 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23438 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23439 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23440 23441 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23442 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23443 FormatStyle Style = getLLVMStyle(); 23444 Style.PointerAlignment = FormatStyle::PAS_Left; 23445 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23446 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23447 verifyFormat("_Atomic(int)* a;", Style); 23448 verifyFormat("_Atomic(int*)* a;", Style); 23449 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23450 23451 Style.SpacesInCStyleCastParentheses = true; 23452 Style.SpacesInParentheses = false; 23453 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23454 Style.SpacesInCStyleCastParentheses = false; 23455 Style.SpacesInParentheses = true; 23456 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23457 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23458 } 23459 23460 TEST_F(FormatTest, AmbersandInLamda) { 23461 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23462 FormatStyle AlignStyle = getLLVMStyle(); 23463 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23464 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23465 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23466 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23467 } 23468 23469 TEST_F(FormatTest, SpacesInConditionalStatement) { 23470 FormatStyle Spaces = getLLVMStyle(); 23471 Spaces.IfMacros.clear(); 23472 Spaces.IfMacros.push_back("MYIF"); 23473 Spaces.SpacesInConditionalStatement = true; 23474 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23475 verifyFormat("if ( !a )\n return;", Spaces); 23476 verifyFormat("if ( a )\n return;", Spaces); 23477 verifyFormat("if constexpr ( a )\n return;", Spaces); 23478 verifyFormat("MYIF ( a )\n return;", Spaces); 23479 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23480 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23481 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23482 verifyFormat("while ( a )\n return;", Spaces); 23483 verifyFormat("while ( (a && b) )\n return;", Spaces); 23484 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23485 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23486 // Check that space on the left of "::" is inserted as expected at beginning 23487 // of condition. 23488 verifyFormat("while ( ::func() )\n return;", Spaces); 23489 23490 // Check impact of ControlStatementsExceptControlMacros is honored. 23491 Spaces.SpaceBeforeParens = 23492 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23493 verifyFormat("MYIF( a )\n return;", Spaces); 23494 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23495 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23496 } 23497 23498 TEST_F(FormatTest, AlternativeOperators) { 23499 // Test case for ensuring alternate operators are not 23500 // combined with their right most neighbour. 23501 verifyFormat("int a and b;"); 23502 verifyFormat("int a and_eq b;"); 23503 verifyFormat("int a bitand b;"); 23504 verifyFormat("int a bitor b;"); 23505 verifyFormat("int a compl b;"); 23506 verifyFormat("int a not b;"); 23507 verifyFormat("int a not_eq b;"); 23508 verifyFormat("int a or b;"); 23509 verifyFormat("int a xor b;"); 23510 verifyFormat("int a xor_eq b;"); 23511 verifyFormat("return this not_eq bitand other;"); 23512 verifyFormat("bool operator not_eq(const X bitand other)"); 23513 23514 verifyFormat("int a and 5;"); 23515 verifyFormat("int a and_eq 5;"); 23516 verifyFormat("int a bitand 5;"); 23517 verifyFormat("int a bitor 5;"); 23518 verifyFormat("int a compl 5;"); 23519 verifyFormat("int a not 5;"); 23520 verifyFormat("int a not_eq 5;"); 23521 verifyFormat("int a or 5;"); 23522 verifyFormat("int a xor 5;"); 23523 verifyFormat("int a xor_eq 5;"); 23524 23525 verifyFormat("int a compl(5);"); 23526 verifyFormat("int a not(5);"); 23527 23528 /* FIXME handle alternate tokens 23529 * https://en.cppreference.com/w/cpp/language/operator_alternative 23530 // alternative tokens 23531 verifyFormat("compl foo();"); // ~foo(); 23532 verifyFormat("foo() <%%>;"); // foo(); 23533 verifyFormat("void foo() <%%>;"); // void foo(){} 23534 verifyFormat("int a <:1:>;"); // int a[1];[ 23535 verifyFormat("%:define ABC abc"); // #define ABC abc 23536 verifyFormat("%:%:"); // ## 23537 */ 23538 } 23539 23540 TEST_F(FormatTest, STLWhileNotDefineChed) { 23541 verifyFormat("#if defined(while)\n" 23542 "#define while EMIT WARNING C4005\n" 23543 "#endif // while"); 23544 } 23545 23546 TEST_F(FormatTest, OperatorSpacing) { 23547 FormatStyle Style = getLLVMStyle(); 23548 Style.PointerAlignment = FormatStyle::PAS_Right; 23549 verifyFormat("Foo::operator*();", Style); 23550 verifyFormat("Foo::operator void *();", Style); 23551 verifyFormat("Foo::operator void **();", Style); 23552 verifyFormat("Foo::operator void *&();", Style); 23553 verifyFormat("Foo::operator void *&&();", Style); 23554 verifyFormat("Foo::operator void const *();", Style); 23555 verifyFormat("Foo::operator void const **();", Style); 23556 verifyFormat("Foo::operator void const *&();", Style); 23557 verifyFormat("Foo::operator void const *&&();", Style); 23558 verifyFormat("Foo::operator()(void *);", Style); 23559 verifyFormat("Foo::operator*(void *);", Style); 23560 verifyFormat("Foo::operator*();", Style); 23561 verifyFormat("Foo::operator**();", Style); 23562 verifyFormat("Foo::operator&();", Style); 23563 verifyFormat("Foo::operator<int> *();", Style); 23564 verifyFormat("Foo::operator<Foo> *();", Style); 23565 verifyFormat("Foo::operator<int> **();", Style); 23566 verifyFormat("Foo::operator<Foo> **();", Style); 23567 verifyFormat("Foo::operator<int> &();", Style); 23568 verifyFormat("Foo::operator<Foo> &();", Style); 23569 verifyFormat("Foo::operator<int> &&();", Style); 23570 verifyFormat("Foo::operator<Foo> &&();", Style); 23571 verifyFormat("Foo::operator<int> *&();", Style); 23572 verifyFormat("Foo::operator<Foo> *&();", Style); 23573 verifyFormat("Foo::operator<int> *&&();", Style); 23574 verifyFormat("Foo::operator<Foo> *&&();", Style); 23575 verifyFormat("operator*(int (*)(), class Foo);", Style); 23576 23577 verifyFormat("Foo::operator&();", Style); 23578 verifyFormat("Foo::operator void &();", Style); 23579 verifyFormat("Foo::operator void const &();", Style); 23580 verifyFormat("Foo::operator()(void &);", Style); 23581 verifyFormat("Foo::operator&(void &);", Style); 23582 verifyFormat("Foo::operator&();", Style); 23583 verifyFormat("operator&(int (&)(), class Foo);", Style); 23584 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23585 23586 verifyFormat("Foo::operator&&();", Style); 23587 verifyFormat("Foo::operator**();", Style); 23588 verifyFormat("Foo::operator void &&();", Style); 23589 verifyFormat("Foo::operator void const &&();", Style); 23590 verifyFormat("Foo::operator()(void &&);", Style); 23591 verifyFormat("Foo::operator&&(void &&);", Style); 23592 verifyFormat("Foo::operator&&();", Style); 23593 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23594 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23595 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23596 Style); 23597 verifyFormat("operator void **()", Style); 23598 verifyFormat("operator const FooRight<Object> &()", Style); 23599 verifyFormat("operator const FooRight<Object> *()", Style); 23600 verifyFormat("operator const FooRight<Object> **()", Style); 23601 verifyFormat("operator const FooRight<Object> *&()", Style); 23602 verifyFormat("operator const FooRight<Object> *&&()", Style); 23603 23604 Style.PointerAlignment = FormatStyle::PAS_Left; 23605 verifyFormat("Foo::operator*();", Style); 23606 verifyFormat("Foo::operator**();", Style); 23607 verifyFormat("Foo::operator void*();", Style); 23608 verifyFormat("Foo::operator void**();", Style); 23609 verifyFormat("Foo::operator void*&();", Style); 23610 verifyFormat("Foo::operator void*&&();", Style); 23611 verifyFormat("Foo::operator void const*();", Style); 23612 verifyFormat("Foo::operator void const**();", Style); 23613 verifyFormat("Foo::operator void const*&();", Style); 23614 verifyFormat("Foo::operator void const*&&();", Style); 23615 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23616 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23617 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23618 verifyFormat("Foo::operator()(void*);", Style); 23619 verifyFormat("Foo::operator*(void*);", Style); 23620 verifyFormat("Foo::operator*();", Style); 23621 verifyFormat("Foo::operator<int>*();", Style); 23622 verifyFormat("Foo::operator<Foo>*();", Style); 23623 verifyFormat("Foo::operator<int>**();", Style); 23624 verifyFormat("Foo::operator<Foo>**();", Style); 23625 verifyFormat("Foo::operator<Foo>*&();", Style); 23626 verifyFormat("Foo::operator<int>&();", Style); 23627 verifyFormat("Foo::operator<Foo>&();", Style); 23628 verifyFormat("Foo::operator<int>&&();", Style); 23629 verifyFormat("Foo::operator<Foo>&&();", Style); 23630 verifyFormat("Foo::operator<int>*&();", Style); 23631 verifyFormat("Foo::operator<Foo>*&();", Style); 23632 verifyFormat("operator*(int (*)(), class Foo);", Style); 23633 23634 verifyFormat("Foo::operator&();", Style); 23635 verifyFormat("Foo::operator void&();", Style); 23636 verifyFormat("Foo::operator void const&();", Style); 23637 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23638 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23639 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23640 verifyFormat("Foo::operator()(void&);", Style); 23641 verifyFormat("Foo::operator&(void&);", Style); 23642 verifyFormat("Foo::operator&();", Style); 23643 verifyFormat("operator&(int (&)(), class Foo);", Style); 23644 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23645 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23646 23647 verifyFormat("Foo::operator&&();", Style); 23648 verifyFormat("Foo::operator void&&();", Style); 23649 verifyFormat("Foo::operator void const&&();", Style); 23650 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23651 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23652 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23653 verifyFormat("Foo::operator()(void&&);", Style); 23654 verifyFormat("Foo::operator&&(void&&);", Style); 23655 verifyFormat("Foo::operator&&();", Style); 23656 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23657 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23658 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23659 Style); 23660 verifyFormat("operator void**()", Style); 23661 verifyFormat("operator const FooLeft<Object>&()", Style); 23662 verifyFormat("operator const FooLeft<Object>*()", Style); 23663 verifyFormat("operator const FooLeft<Object>**()", Style); 23664 verifyFormat("operator const FooLeft<Object>*&()", Style); 23665 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23666 23667 // PR45107 23668 verifyFormat("operator Vector<String>&();", Style); 23669 verifyFormat("operator const Vector<String>&();", Style); 23670 verifyFormat("operator foo::Bar*();", Style); 23671 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23672 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23673 Style); 23674 23675 Style.PointerAlignment = FormatStyle::PAS_Middle; 23676 verifyFormat("Foo::operator*();", Style); 23677 verifyFormat("Foo::operator void *();", Style); 23678 verifyFormat("Foo::operator()(void *);", Style); 23679 verifyFormat("Foo::operator*(void *);", Style); 23680 verifyFormat("Foo::operator*();", Style); 23681 verifyFormat("operator*(int (*)(), class Foo);", Style); 23682 23683 verifyFormat("Foo::operator&();", Style); 23684 verifyFormat("Foo::operator void &();", Style); 23685 verifyFormat("Foo::operator void const &();", Style); 23686 verifyFormat("Foo::operator()(void &);", Style); 23687 verifyFormat("Foo::operator&(void &);", Style); 23688 verifyFormat("Foo::operator&();", Style); 23689 verifyFormat("operator&(int (&)(), class Foo);", Style); 23690 23691 verifyFormat("Foo::operator&&();", Style); 23692 verifyFormat("Foo::operator void &&();", Style); 23693 verifyFormat("Foo::operator void const &&();", Style); 23694 verifyFormat("Foo::operator()(void &&);", Style); 23695 verifyFormat("Foo::operator&&(void &&);", Style); 23696 verifyFormat("Foo::operator&&();", Style); 23697 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23698 } 23699 23700 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23701 FormatStyle Style = getLLVMStyle(); 23702 // PR46157 23703 verifyFormat("foo(operator+, -42);", Style); 23704 verifyFormat("foo(operator++, -42);", Style); 23705 verifyFormat("foo(operator--, -42);", Style); 23706 verifyFormat("foo(-42, operator--);", Style); 23707 verifyFormat("foo(-42, operator, );", Style); 23708 verifyFormat("foo(operator, , -42);", Style); 23709 } 23710 23711 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23712 FormatStyle Style = getLLVMStyle(); 23713 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23714 23715 // Don't use the helpers here, since 'mess up' will change the whitespace 23716 // and these are all whitespace sensitive by definition 23717 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23718 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23719 EXPECT_EQ( 23720 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23721 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23722 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23723 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23724 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23725 " Still=Intentional);", 23726 format("FOO(String-ized&Messy+But,: :\n" 23727 " Still=Intentional);", 23728 Style)); 23729 Style.AlignConsecutiveAssignments.Enabled = true; 23730 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23731 " Still=Intentional);", 23732 format("FOO(String-ized=&Messy+But,: :\n" 23733 " Still=Intentional);", 23734 Style)); 23735 23736 Style.ColumnLimit = 21; 23737 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23738 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23739 } 23740 23741 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23742 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23743 // test its interaction with line wrapping 23744 FormatStyle Style = getLLVMStyleWithColumns(80); 23745 verifyFormat("namespace {\n" 23746 "int i;\n" 23747 "int j;\n" 23748 "} // namespace", 23749 Style); 23750 23751 verifyFormat("namespace AAA {\n" 23752 "int i;\n" 23753 "int j;\n" 23754 "} // namespace AAA", 23755 Style); 23756 23757 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23758 "int i;\n" 23759 "int j;\n" 23760 "} // namespace Averyveryveryverylongnamespace", 23761 format("namespace Averyveryveryverylongnamespace {\n" 23762 "int i;\n" 23763 "int j;\n" 23764 "}", 23765 Style)); 23766 23767 EXPECT_EQ( 23768 "namespace " 23769 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23770 " went::mad::now {\n" 23771 "int i;\n" 23772 "int j;\n" 23773 "} // namespace\n" 23774 " // " 23775 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23776 "went::mad::now", 23777 format("namespace " 23778 "would::it::save::you::a::lot::of::time::if_::i::" 23779 "just::gave::up::and_::went::mad::now {\n" 23780 "int i;\n" 23781 "int j;\n" 23782 "}", 23783 Style)); 23784 23785 // This used to duplicate the comment again and again on subsequent runs 23786 EXPECT_EQ( 23787 "namespace " 23788 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23789 " went::mad::now {\n" 23790 "int i;\n" 23791 "int j;\n" 23792 "} // namespace\n" 23793 " // " 23794 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23795 "went::mad::now", 23796 format("namespace " 23797 "would::it::save::you::a::lot::of::time::if_::i::" 23798 "just::gave::up::and_::went::mad::now {\n" 23799 "int i;\n" 23800 "int j;\n" 23801 "} // namespace\n" 23802 " // " 23803 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23804 "and_::went::mad::now", 23805 Style)); 23806 } 23807 23808 TEST_F(FormatTest, LikelyUnlikely) { 23809 FormatStyle Style = getLLVMStyle(); 23810 23811 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23812 " return 29;\n" 23813 "}", 23814 Style); 23815 23816 verifyFormat("if (argc > 5) [[likely]] {\n" 23817 " return 29;\n" 23818 "}", 23819 Style); 23820 23821 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23822 " return 29;\n" 23823 "} else [[likely]] {\n" 23824 " return 42;\n" 23825 "}\n", 23826 Style); 23827 23828 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23829 " return 29;\n" 23830 "} else if (argc > 10) [[likely]] {\n" 23831 " return 99;\n" 23832 "} else {\n" 23833 " return 42;\n" 23834 "}\n", 23835 Style); 23836 23837 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23838 " return 29;\n" 23839 "}", 23840 Style); 23841 23842 verifyFormat("if (argc > 5) [[unlikely]]\n" 23843 " return 29;\n", 23844 Style); 23845 verifyFormat("if (argc > 5) [[likely]]\n" 23846 " return 29;\n", 23847 Style); 23848 23849 verifyFormat("while (limit > 0) [[unlikely]] {\n" 23850 " --limit;\n" 23851 "}", 23852 Style); 23853 verifyFormat("for (auto &limit : limits) [[likely]] {\n" 23854 " --limit;\n" 23855 "}", 23856 Style); 23857 23858 verifyFormat("for (auto &limit : limits) [[unlikely]]\n" 23859 " --limit;", 23860 Style); 23861 verifyFormat("while (limit > 0) [[likely]]\n" 23862 " --limit;", 23863 Style); 23864 23865 Style.AttributeMacros.push_back("UNLIKELY"); 23866 Style.AttributeMacros.push_back("LIKELY"); 23867 verifyFormat("if (argc > 5) UNLIKELY\n" 23868 " return 29;\n", 23869 Style); 23870 23871 verifyFormat("if (argc > 5) UNLIKELY {\n" 23872 " return 29;\n" 23873 "}", 23874 Style); 23875 verifyFormat("if (argc > 5) UNLIKELY {\n" 23876 " return 29;\n" 23877 "} else [[likely]] {\n" 23878 " return 42;\n" 23879 "}\n", 23880 Style); 23881 verifyFormat("if (argc > 5) UNLIKELY {\n" 23882 " return 29;\n" 23883 "} else LIKELY {\n" 23884 " return 42;\n" 23885 "}\n", 23886 Style); 23887 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23888 " return 29;\n" 23889 "} else LIKELY {\n" 23890 " return 42;\n" 23891 "}\n", 23892 Style); 23893 23894 verifyFormat("for (auto &limit : limits) UNLIKELY {\n" 23895 " --limit;\n" 23896 "}", 23897 Style); 23898 verifyFormat("while (limit > 0) LIKELY {\n" 23899 " --limit;\n" 23900 "}", 23901 Style); 23902 23903 verifyFormat("while (limit > 0) UNLIKELY\n" 23904 " --limit;", 23905 Style); 23906 verifyFormat("for (auto &limit : limits) LIKELY\n" 23907 " --limit;", 23908 Style); 23909 } 23910 23911 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23912 verifyFormat("Constructor()\n" 23913 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23914 " aaaa(aaaaaaaaaaaaaaaaaa, " 23915 "aaaaaaaaaaaaaaaaaat))"); 23916 verifyFormat("Constructor()\n" 23917 " : aaaaaaaaaaaaa(aaaaaa), " 23918 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23919 23920 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23921 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23922 verifyFormat("Constructor()\n" 23923 " : aaaaaa(aaaaaa),\n" 23924 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23925 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23926 StyleWithWhitespacePenalty); 23927 verifyFormat("Constructor()\n" 23928 " : aaaaaaaaaaaaa(aaaaaa), " 23929 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23930 StyleWithWhitespacePenalty); 23931 } 23932 23933 TEST_F(FormatTest, LLVMDefaultStyle) { 23934 FormatStyle Style = getLLVMStyle(); 23935 verifyFormat("extern \"C\" {\n" 23936 "int foo();\n" 23937 "}", 23938 Style); 23939 } 23940 TEST_F(FormatTest, GNUDefaultStyle) { 23941 FormatStyle Style = getGNUStyle(); 23942 verifyFormat("extern \"C\"\n" 23943 "{\n" 23944 " int foo ();\n" 23945 "}", 23946 Style); 23947 } 23948 TEST_F(FormatTest, MozillaDefaultStyle) { 23949 FormatStyle Style = getMozillaStyle(); 23950 verifyFormat("extern \"C\"\n" 23951 "{\n" 23952 " int foo();\n" 23953 "}", 23954 Style); 23955 } 23956 TEST_F(FormatTest, GoogleDefaultStyle) { 23957 FormatStyle Style = getGoogleStyle(); 23958 verifyFormat("extern \"C\" {\n" 23959 "int foo();\n" 23960 "}", 23961 Style); 23962 } 23963 TEST_F(FormatTest, ChromiumDefaultStyle) { 23964 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23965 verifyFormat("extern \"C\" {\n" 23966 "int foo();\n" 23967 "}", 23968 Style); 23969 } 23970 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23971 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23972 verifyFormat("extern \"C\"\n" 23973 "{\n" 23974 " int foo();\n" 23975 "}", 23976 Style); 23977 } 23978 TEST_F(FormatTest, WebKitDefaultStyle) { 23979 FormatStyle Style = getWebKitStyle(); 23980 verifyFormat("extern \"C\" {\n" 23981 "int foo();\n" 23982 "}", 23983 Style); 23984 } 23985 23986 TEST_F(FormatTest, Concepts) { 23987 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23988 FormatStyle::BBCDS_Always); 23989 verifyFormat("template <typename T>\n" 23990 "concept True = true;"); 23991 23992 verifyFormat("template <typename T>\n" 23993 "concept C = ((false || foo()) && C2<T>) ||\n" 23994 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23995 getLLVMStyleWithColumns(60)); 23996 23997 verifyFormat("template <typename T>\n" 23998 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23999 "sizeof(T) <= 8;"); 24000 24001 verifyFormat("template <typename T>\n" 24002 "concept DelayedCheck = true && requires(T t) {\n" 24003 " t.bar();\n" 24004 " t.baz();\n" 24005 " } && sizeof(T) <= 8;"); 24006 24007 verifyFormat("template <typename T>\n" 24008 "concept DelayedCheck = true && requires(T t) { // Comment\n" 24009 " t.bar();\n" 24010 " t.baz();\n" 24011 " } && sizeof(T) <= 8;"); 24012 24013 verifyFormat("template <typename T>\n" 24014 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 24015 "sizeof(T) <= 8;"); 24016 24017 verifyFormat("template <typename T>\n" 24018 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 24019 "&& sizeof(T) <= 8;"); 24020 24021 verifyFormat( 24022 "template <typename T>\n" 24023 "concept DelayedCheck = static_cast<bool>(0) ||\n" 24024 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24025 24026 verifyFormat("template <typename T>\n" 24027 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 24028 "&& sizeof(T) <= 8;"); 24029 24030 verifyFormat( 24031 "template <typename T>\n" 24032 "concept DelayedCheck = (bool)(0) ||\n" 24033 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24034 24035 verifyFormat("template <typename T>\n" 24036 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 24037 "&& sizeof(T) <= 8;"); 24038 24039 verifyFormat("template <typename T>\n" 24040 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 24041 "sizeof(T) <= 8;"); 24042 24043 verifyFormat("template <typename T>\n" 24044 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 24045 " requires(T t) {\n" 24046 " t.bar();\n" 24047 " t.baz();\n" 24048 " } && sizeof(T) <= 8 && !(4 < 3);", 24049 getLLVMStyleWithColumns(60)); 24050 24051 verifyFormat("template <typename T>\n" 24052 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 24053 24054 verifyFormat("template <typename T>\n" 24055 "concept C = foo();"); 24056 24057 verifyFormat("template <typename T>\n" 24058 "concept C = foo(T());"); 24059 24060 verifyFormat("template <typename T>\n" 24061 "concept C = foo(T{});"); 24062 24063 verifyFormat("template <typename T>\n" 24064 "concept Size = V<sizeof(T)>::Value > 5;"); 24065 24066 verifyFormat("template <typename T>\n" 24067 "concept True = S<T>::Value;"); 24068 24069 verifyFormat( 24070 "template <typename T>\n" 24071 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 24072 " sizeof(T) <= 8;"); 24073 24074 // FIXME: This is misformatted because the fake l paren starts at bool, not at 24075 // the lambda l square. 24076 verifyFormat("template <typename T>\n" 24077 "concept C = [] -> bool { return true; }() && requires(T t) { " 24078 "t.bar(); } &&\n" 24079 " sizeof(T) <= 8;"); 24080 24081 verifyFormat( 24082 "template <typename T>\n" 24083 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 24084 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24085 24086 verifyFormat("template <typename T>\n" 24087 "concept C = decltype([]() { return std::true_type{}; " 24088 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24089 getLLVMStyleWithColumns(120)); 24090 24091 verifyFormat("template <typename T>\n" 24092 "concept C = decltype([]() -> std::true_type { return {}; " 24093 "}())::value &&\n" 24094 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24095 24096 verifyFormat("template <typename T>\n" 24097 "concept C = true;\n" 24098 "Foo Bar;"); 24099 24100 verifyFormat("template <typename T>\n" 24101 "concept Hashable = requires(T a) {\n" 24102 " { std::hash<T>{}(a) } -> " 24103 "std::convertible_to<std::size_t>;\n" 24104 " };"); 24105 24106 verifyFormat( 24107 "template <typename T>\n" 24108 "concept EqualityComparable = requires(T a, T b) {\n" 24109 " { a == b } -> std::same_as<bool>;\n" 24110 " };"); 24111 24112 verifyFormat( 24113 "template <typename T>\n" 24114 "concept EqualityComparable = requires(T a, T b) {\n" 24115 " { a == b } -> std::same_as<bool>;\n" 24116 " { a != b } -> std::same_as<bool>;\n" 24117 " };"); 24118 24119 verifyFormat("template <typename T>\n" 24120 "concept WeakEqualityComparable = requires(T a, T b) {\n" 24121 " { a == b };\n" 24122 " { a != b };\n" 24123 " };"); 24124 24125 verifyFormat("template <typename T>\n" 24126 "concept HasSizeT = requires { typename T::size_t; };"); 24127 24128 verifyFormat("template <typename T>\n" 24129 "concept Semiregular =\n" 24130 " DefaultConstructible<T> && CopyConstructible<T> && " 24131 "CopyAssignable<T> &&\n" 24132 " requires(T a, std::size_t n) {\n" 24133 " requires Same<T *, decltype(&a)>;\n" 24134 " { a.~T() } noexcept;\n" 24135 " requires Same<T *, decltype(new T)>;\n" 24136 " requires Same<T *, decltype(new T[n])>;\n" 24137 " { delete new T; };\n" 24138 " { delete new T[n]; };\n" 24139 " };"); 24140 24141 verifyFormat("template <typename T>\n" 24142 "concept Semiregular =\n" 24143 " requires(T a, std::size_t n) {\n" 24144 " requires Same<T *, decltype(&a)>;\n" 24145 " { a.~T() } noexcept;\n" 24146 " requires Same<T *, decltype(new T)>;\n" 24147 " requires Same<T *, decltype(new T[n])>;\n" 24148 " { delete new T; };\n" 24149 " { delete new T[n]; };\n" 24150 " { new T } -> std::same_as<T *>;\n" 24151 " } && DefaultConstructible<T> && CopyConstructible<T> && " 24152 "CopyAssignable<T>;"); 24153 24154 verifyFormat( 24155 "template <typename T>\n" 24156 "concept Semiregular =\n" 24157 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 24158 " requires Same<T *, decltype(&a)>;\n" 24159 " { a.~T() } noexcept;\n" 24160 " requires Same<T *, decltype(new T)>;\n" 24161 " requires Same<T *, decltype(new " 24162 "T[n])>;\n" 24163 " { delete new T; };\n" 24164 " { delete new T[n]; };\n" 24165 " } && CopyConstructible<T> && " 24166 "CopyAssignable<T>;"); 24167 24168 verifyFormat("template <typename T>\n" 24169 "concept Two = requires(T t) {\n" 24170 " { t.foo() } -> std::same_as<Bar>;\n" 24171 " } && requires(T &&t) {\n" 24172 " { t.foo() } -> std::same_as<Bar &&>;\n" 24173 " };"); 24174 24175 verifyFormat( 24176 "template <typename T>\n" 24177 "concept C = requires(T x) {\n" 24178 " { *x } -> std::convertible_to<typename T::inner>;\n" 24179 " { x + 1 } noexcept -> std::same_as<int>;\n" 24180 " { x * 1 } -> std::convertible_to<T>;\n" 24181 " };"); 24182 24183 verifyFormat( 24184 "template <typename T, typename U = T>\n" 24185 "concept Swappable = requires(T &&t, U &&u) {\n" 24186 " swap(std::forward<T>(t), std::forward<U>(u));\n" 24187 " swap(std::forward<U>(u), std::forward<T>(t));\n" 24188 " };"); 24189 24190 verifyFormat("template <typename T, typename U>\n" 24191 "concept Common = requires(T &&t, U &&u) {\n" 24192 " typename CommonType<T, U>;\n" 24193 " { CommonType<T, U>(std::forward<T>(t)) };\n" 24194 " };"); 24195 24196 verifyFormat("template <typename T, typename U>\n" 24197 "concept Common = requires(T &&t, U &&u) {\n" 24198 " typename CommonType<T, U>;\n" 24199 " { CommonType<T, U>{std::forward<T>(t)} };\n" 24200 " };"); 24201 24202 verifyFormat( 24203 "template <typename T>\n" 24204 "concept C = requires(T t) {\n" 24205 " requires Bar<T> && Foo<T>;\n" 24206 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24207 " };"); 24208 24209 verifyFormat("template <typename T>\n" 24210 "concept HasFoo = requires(T t) {\n" 24211 " { t.foo() };\n" 24212 " t.foo();\n" 24213 " };\n" 24214 "template <typename T>\n" 24215 "concept HasBar = requires(T t) {\n" 24216 " { t.bar() };\n" 24217 " t.bar();\n" 24218 " };"); 24219 24220 verifyFormat("template <typename T>\n" 24221 "concept Large = sizeof(T) > 10;"); 24222 24223 verifyFormat("template <typename T, typename U>\n" 24224 "concept FooableWith = requires(T t, U u) {\n" 24225 " typename T::foo_type;\n" 24226 " { t.foo(u) } -> typename T::foo_type;\n" 24227 " t++;\n" 24228 " };\n" 24229 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 24230 24231 verifyFormat("template <typename T>\n" 24232 "concept Context = is_specialization_of_v<context, T>;"); 24233 24234 verifyFormat("template <typename T>\n" 24235 "concept Node = std::is_object_v<T>;"); 24236 24237 verifyFormat("template <class T>\n" 24238 "concept integral = __is_integral(T);"); 24239 24240 verifyFormat("template <class T>\n" 24241 "concept is2D = __array_extent(T, 1) == 2;"); 24242 24243 verifyFormat("template <class T>\n" 24244 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24245 24246 verifyFormat("template <class T, class T2>\n" 24247 "concept Same = __is_same_as<T, T2>;"); 24248 24249 verifyFormat( 24250 "template <class _InIt, class _OutIt>\n" 24251 "concept _Can_reread_dest =\n" 24252 " std::forward_iterator<_OutIt> &&\n" 24253 " std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;"); 24254 24255 auto Style = getLLVMStyle(); 24256 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24257 24258 verifyFormat( 24259 "template <typename T>\n" 24260 "concept C = requires(T t) {\n" 24261 " requires Bar<T> && Foo<T>;\n" 24262 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24263 " };", 24264 Style); 24265 24266 verifyFormat("template <typename T>\n" 24267 "concept HasFoo = requires(T t) {\n" 24268 " { t.foo() };\n" 24269 " t.foo();\n" 24270 " };\n" 24271 "template <typename T>\n" 24272 "concept HasBar = requires(T t) {\n" 24273 " { t.bar() };\n" 24274 " t.bar();\n" 24275 " };", 24276 Style); 24277 24278 verifyFormat("template <typename T> concept True = true;", Style); 24279 24280 verifyFormat("template <typename T>\n" 24281 "concept C = decltype([]() -> std::true_type { return {}; " 24282 "}())::value &&\n" 24283 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24284 Style); 24285 24286 verifyFormat("template <typename T>\n" 24287 "concept Semiregular =\n" 24288 " DefaultConstructible<T> && CopyConstructible<T> && " 24289 "CopyAssignable<T> &&\n" 24290 " requires(T a, std::size_t n) {\n" 24291 " requires Same<T *, decltype(&a)>;\n" 24292 " { a.~T() } noexcept;\n" 24293 " requires Same<T *, decltype(new T)>;\n" 24294 " requires Same<T *, decltype(new T[n])>;\n" 24295 " { delete new T; };\n" 24296 " { delete new T[n]; };\n" 24297 " };", 24298 Style); 24299 24300 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24301 24302 verifyFormat("template <typename T> concept C =\n" 24303 " requires(T t) {\n" 24304 " requires Bar<T> && Foo<T>;\n" 24305 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24306 " };", 24307 Style); 24308 24309 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24310 " { t.foo() };\n" 24311 " t.foo();\n" 24312 " };\n" 24313 "template <typename T> concept HasBar = requires(T t) {\n" 24314 " { t.bar() };\n" 24315 " t.bar();\n" 24316 " };", 24317 Style); 24318 24319 verifyFormat("template <typename T> concept True = true;", Style); 24320 24321 verifyFormat( 24322 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24323 " return {};\n" 24324 " }())::value &&\n" 24325 " requires(T t) { t.bar(); } && " 24326 "sizeof(T) <= 8;", 24327 Style); 24328 24329 verifyFormat("template <typename T> concept Semiregular =\n" 24330 " DefaultConstructible<T> && CopyConstructible<T> && " 24331 "CopyAssignable<T> &&\n" 24332 " requires(T a, std::size_t n) {\n" 24333 " requires Same<T *, decltype(&a)>;\n" 24334 " { a.~T() } noexcept;\n" 24335 " requires Same<T *, decltype(new T)>;\n" 24336 " requires Same<T *, decltype(new T[n])>;\n" 24337 " { delete new T; };\n" 24338 " { delete new T[n]; };\n" 24339 " };", 24340 Style); 24341 24342 // The following tests are invalid C++, we just want to make sure we don't 24343 // assert. 24344 verifyFormat("template <typename T>\n" 24345 "concept C = requires C2<T>;"); 24346 24347 verifyFormat("template <typename T>\n" 24348 "concept C = 5 + 4;"); 24349 24350 verifyFormat("template <typename T>\n" 24351 "concept C =\n" 24352 "class X;"); 24353 24354 verifyFormat("template <typename T>\n" 24355 "concept C = [] && true;"); 24356 24357 verifyFormat("template <typename T>\n" 24358 "concept C = [] && requires(T t) { typename T::size_type; };"); 24359 } 24360 24361 TEST_F(FormatTest, RequiresClausesPositions) { 24362 auto Style = getLLVMStyle(); 24363 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24364 EXPECT_EQ(Style.IndentRequiresClause, true); 24365 24366 verifyFormat("template <typename T>\n" 24367 " requires(Foo<T> && std::trait<T>)\n" 24368 "struct Bar;", 24369 Style); 24370 24371 verifyFormat("template <typename T>\n" 24372 " requires(Foo<T> && std::trait<T>)\n" 24373 "class Bar {\n" 24374 "public:\n" 24375 " Bar(T t);\n" 24376 " bool baz();\n" 24377 "};", 24378 Style); 24379 24380 verifyFormat( 24381 "template <typename T>\n" 24382 " requires requires(T &&t) {\n" 24383 " typename T::I;\n" 24384 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24385 " }\n" 24386 "Bar(T) -> Bar<typename T::I>;", 24387 Style); 24388 24389 verifyFormat("template <typename T>\n" 24390 " requires(Foo<T> && std::trait<T>)\n" 24391 "constexpr T MyGlobal;", 24392 Style); 24393 24394 verifyFormat("template <typename T>\n" 24395 " requires Foo<T> && requires(T t) {\n" 24396 " { t.baz() } -> std::same_as<bool>;\n" 24397 " requires std::same_as<T::Factor, int>;\n" 24398 " }\n" 24399 "inline int bar(T t) {\n" 24400 " return t.baz() ? T::Factor : 5;\n" 24401 "}", 24402 Style); 24403 24404 verifyFormat("template <typename T>\n" 24405 "inline int bar(T t)\n" 24406 " requires Foo<T> && requires(T t) {\n" 24407 " { t.baz() } -> std::same_as<bool>;\n" 24408 " requires std::same_as<T::Factor, int>;\n" 24409 " }\n" 24410 "{\n" 24411 " return t.baz() ? T::Factor : 5;\n" 24412 "}", 24413 Style); 24414 24415 verifyFormat("template <typename T>\n" 24416 " requires F<T>\n" 24417 "int bar(T t) {\n" 24418 " return 5;\n" 24419 "}", 24420 Style); 24421 24422 verifyFormat("template <typename T>\n" 24423 "int bar(T t)\n" 24424 " requires F<T>\n" 24425 "{\n" 24426 " return 5;\n" 24427 "}", 24428 Style); 24429 24430 verifyFormat("template <typename T>\n" 24431 "int bar(T t)\n" 24432 " requires F<T>;", 24433 Style); 24434 24435 Style.IndentRequiresClause = false; 24436 verifyFormat("template <typename T>\n" 24437 "requires F<T>\n" 24438 "int bar(T t) {\n" 24439 " return 5;\n" 24440 "}", 24441 Style); 24442 24443 verifyFormat("template <typename T>\n" 24444 "int bar(T t)\n" 24445 "requires F<T>\n" 24446 "{\n" 24447 " return 5;\n" 24448 "}", 24449 Style); 24450 24451 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24452 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24453 "template <typename T> requires Foo<T> void bar() {}\n" 24454 "template <typename T> void bar() requires Foo<T> {}\n" 24455 "template <typename T> void bar() requires Foo<T>;\n" 24456 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24457 Style); 24458 24459 auto ColumnStyle = Style; 24460 ColumnStyle.ColumnLimit = 40; 24461 verifyFormat("template <typename AAAAAAA>\n" 24462 "requires Foo<T> struct Bar {};\n" 24463 "template <typename AAAAAAA>\n" 24464 "requires Foo<T> void bar() {}\n" 24465 "template <typename AAAAAAA>\n" 24466 "void bar() requires Foo<T> {}\n" 24467 "template <typename AAAAAAA>\n" 24468 "requires Foo<T> Baz(T) -> Baz<T>;", 24469 ColumnStyle); 24470 24471 verifyFormat("template <typename T>\n" 24472 "requires Foo<AAAAAAA> struct Bar {};\n" 24473 "template <typename T>\n" 24474 "requires Foo<AAAAAAA> void bar() {}\n" 24475 "template <typename T>\n" 24476 "void bar() requires Foo<AAAAAAA> {}\n" 24477 "template <typename T>\n" 24478 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24479 ColumnStyle); 24480 24481 verifyFormat("template <typename AAAAAAA>\n" 24482 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24483 "struct Bar {};\n" 24484 "template <typename AAAAAAA>\n" 24485 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24486 "void bar() {}\n" 24487 "template <typename AAAAAAA>\n" 24488 "void bar()\n" 24489 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24490 "template <typename AAAAAAA>\n" 24491 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24492 "template <typename AAAAAAA>\n" 24493 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24494 "Bar(T) -> Bar<T>;", 24495 ColumnStyle); 24496 24497 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24498 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24499 24500 verifyFormat("template <typename T>\n" 24501 "requires Foo<T> struct Bar {};\n" 24502 "template <typename T>\n" 24503 "requires Foo<T> void bar() {}\n" 24504 "template <typename T>\n" 24505 "void bar()\n" 24506 "requires Foo<T> {}\n" 24507 "template <typename T>\n" 24508 "void bar()\n" 24509 "requires Foo<T>;\n" 24510 "template <typename T>\n" 24511 "requires Foo<T> Bar(T) -> Bar<T>;", 24512 Style); 24513 24514 verifyFormat("template <typename AAAAAAA>\n" 24515 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24516 "struct Bar {};\n" 24517 "template <typename AAAAAAA>\n" 24518 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24519 "void bar() {}\n" 24520 "template <typename AAAAAAA>\n" 24521 "void bar()\n" 24522 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24523 "template <typename AAAAAAA>\n" 24524 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24525 "template <typename AAAAAAA>\n" 24526 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24527 "Bar(T) -> Bar<T>;", 24528 ColumnStyle); 24529 24530 Style.IndentRequiresClause = true; 24531 ColumnStyle.IndentRequiresClause = true; 24532 24533 verifyFormat("template <typename T>\n" 24534 " requires Foo<T> struct Bar {};\n" 24535 "template <typename T>\n" 24536 " requires Foo<T> void bar() {}\n" 24537 "template <typename T>\n" 24538 "void bar()\n" 24539 " requires Foo<T> {}\n" 24540 "template <typename T>\n" 24541 " requires Foo<T> Bar(T) -> Bar<T>;", 24542 Style); 24543 24544 verifyFormat("template <typename AAAAAAA>\n" 24545 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24546 "struct Bar {};\n" 24547 "template <typename AAAAAAA>\n" 24548 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24549 "void bar() {}\n" 24550 "template <typename AAAAAAA>\n" 24551 "void bar()\n" 24552 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24553 "template <typename AAAAAAA>\n" 24554 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24555 "template <typename AAAAAAA>\n" 24556 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24557 "Bar(T) -> Bar<T>;", 24558 ColumnStyle); 24559 24560 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24561 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24562 24563 verifyFormat("template <typename T> requires Foo<T>\n" 24564 "struct Bar {};\n" 24565 "template <typename T> requires Foo<T>\n" 24566 "void bar() {}\n" 24567 "template <typename T>\n" 24568 "void bar() requires Foo<T>\n" 24569 "{}\n" 24570 "template <typename T> void bar() requires Foo<T>;\n" 24571 "template <typename T> requires Foo<T>\n" 24572 "Bar(T) -> Bar<T>;", 24573 Style); 24574 24575 verifyFormat("template <typename AAAAAAA>\n" 24576 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24577 "struct Bar {};\n" 24578 "template <typename AAAAAAA>\n" 24579 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24580 "void bar() {}\n" 24581 "template <typename AAAAAAA>\n" 24582 "void bar()\n" 24583 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24584 "{}\n" 24585 "template <typename AAAAAAA>\n" 24586 "requires Foo<AAAAAAAA>\n" 24587 "Bar(T) -> Bar<T>;\n" 24588 "template <typename AAAAAAA>\n" 24589 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24590 "Bar(T) -> Bar<T>;", 24591 ColumnStyle); 24592 } 24593 24594 TEST_F(FormatTest, RequiresClauses) { 24595 verifyFormat("struct [[nodiscard]] zero_t {\n" 24596 " template <class T>\n" 24597 " requires requires { number_zero_v<T>; }\n" 24598 " [[nodiscard]] constexpr operator T() const {\n" 24599 " return number_zero_v<T>;\n" 24600 " }\n" 24601 "};"); 24602 24603 auto Style = getLLVMStyle(); 24604 24605 verifyFormat( 24606 "template <typename T>\n" 24607 " requires is_default_constructible_v<hash<T>> and\n" 24608 " is_copy_constructible_v<hash<T>> and\n" 24609 " is_move_constructible_v<hash<T>> and\n" 24610 " is_copy_assignable_v<hash<T>> and " 24611 "is_move_assignable_v<hash<T>> and\n" 24612 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24613 " is_callable_v<hash<T>(T)> and\n" 24614 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24615 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24616 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24617 "struct S {};", 24618 Style); 24619 24620 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24621 verifyFormat( 24622 "template <typename T>\n" 24623 " requires is_default_constructible_v<hash<T>>\n" 24624 " and is_copy_constructible_v<hash<T>>\n" 24625 " and is_move_constructible_v<hash<T>>\n" 24626 " and is_copy_assignable_v<hash<T>> and " 24627 "is_move_assignable_v<hash<T>>\n" 24628 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24629 " and is_callable_v<hash<T>(T)>\n" 24630 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24631 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24632 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24633 "&>()))>\n" 24634 "struct S {};", 24635 Style); 24636 24637 // Not a clause, but we once hit an assert. 24638 verifyFormat("#if 0\n" 24639 "#else\n" 24640 "foo();\n" 24641 "#endif\n" 24642 "bar(requires);"); 24643 } 24644 24645 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24646 FormatStyle Style = getLLVMStyle(); 24647 StringRef Source = "void Foo::slot() {\n" 24648 " unsigned char MyChar = 'x';\n" 24649 " emit signal(MyChar);\n" 24650 " Q_EMIT signal(MyChar);\n" 24651 "}"; 24652 24653 EXPECT_EQ(Source, format(Source, Style)); 24654 24655 Style.AlignConsecutiveDeclarations.Enabled = true; 24656 EXPECT_EQ("void Foo::slot() {\n" 24657 " unsigned char MyChar = 'x';\n" 24658 " emit signal(MyChar);\n" 24659 " Q_EMIT signal(MyChar);\n" 24660 "}", 24661 format(Source, Style)); 24662 24663 Style.StatementAttributeLikeMacros.push_back("emit"); 24664 EXPECT_EQ(Source, format(Source, Style)); 24665 24666 Style.StatementAttributeLikeMacros = {}; 24667 EXPECT_EQ("void Foo::slot() {\n" 24668 " unsigned char MyChar = 'x';\n" 24669 " emit signal(MyChar);\n" 24670 " Q_EMIT signal(MyChar);\n" 24671 "}", 24672 format(Source, Style)); 24673 } 24674 24675 TEST_F(FormatTest, IndentAccessModifiers) { 24676 FormatStyle Style = getLLVMStyle(); 24677 Style.IndentAccessModifiers = true; 24678 // Members are *two* levels below the record; 24679 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24680 verifyFormat("class C {\n" 24681 " int i;\n" 24682 "};\n", 24683 Style); 24684 verifyFormat("union C {\n" 24685 " int i;\n" 24686 " unsigned u;\n" 24687 "};\n", 24688 Style); 24689 // Access modifiers should be indented one level below the record. 24690 verifyFormat("class C {\n" 24691 " public:\n" 24692 " int i;\n" 24693 "};\n", 24694 Style); 24695 verifyFormat("struct S {\n" 24696 " private:\n" 24697 " class C {\n" 24698 " int j;\n" 24699 "\n" 24700 " public:\n" 24701 " C();\n" 24702 " };\n" 24703 "\n" 24704 " public:\n" 24705 " int i;\n" 24706 "};\n", 24707 Style); 24708 // Enumerations are not records and should be unaffected. 24709 Style.AllowShortEnumsOnASingleLine = false; 24710 verifyFormat("enum class E {\n" 24711 " A,\n" 24712 " B\n" 24713 "};\n", 24714 Style); 24715 // Test with a different indentation width; 24716 // also proves that the result is Style.AccessModifierOffset agnostic. 24717 Style.IndentWidth = 3; 24718 verifyFormat("class C {\n" 24719 " public:\n" 24720 " int i;\n" 24721 "};\n", 24722 Style); 24723 } 24724 24725 TEST_F(FormatTest, LimitlessStringsAndComments) { 24726 auto Style = getLLVMStyleWithColumns(0); 24727 constexpr StringRef Code = 24728 "/**\n" 24729 " * This is a multiline comment with quite some long lines, at least for " 24730 "the LLVM Style.\n" 24731 " * We will redo this with strings and line comments. Just to check if " 24732 "everything is working.\n" 24733 " */\n" 24734 "bool foo() {\n" 24735 " /* Single line multi line comment. */\n" 24736 " const std::string String = \"This is a multiline string with quite " 24737 "some long lines, at least for the LLVM Style.\"\n" 24738 " \"We already did it with multi line " 24739 "comments, and we will do it with line comments. Just to check if " 24740 "everything is working.\";\n" 24741 " // This is a line comment (block) with quite some long lines, at " 24742 "least for the LLVM Style.\n" 24743 " // We already did this with multi line comments and strings. Just to " 24744 "check if everything is working.\n" 24745 " const std::string SmallString = \"Hello World\";\n" 24746 " // Small line comment\n" 24747 " return String.size() > SmallString.size();\n" 24748 "}"; 24749 EXPECT_EQ(Code, format(Code, Style)); 24750 } 24751 24752 TEST_F(FormatTest, FormatDecayCopy) { 24753 // error cases from unit tests 24754 verifyFormat("foo(auto())"); 24755 verifyFormat("foo(auto{})"); 24756 verifyFormat("foo(auto({}))"); 24757 verifyFormat("foo(auto{{}})"); 24758 24759 verifyFormat("foo(auto(1))"); 24760 verifyFormat("foo(auto{1})"); 24761 verifyFormat("foo(new auto(1))"); 24762 verifyFormat("foo(new auto{1})"); 24763 verifyFormat("decltype(auto(1)) x;"); 24764 verifyFormat("decltype(auto{1}) x;"); 24765 verifyFormat("auto(x);"); 24766 verifyFormat("auto{x};"); 24767 verifyFormat("new auto{x};"); 24768 verifyFormat("auto{x} = y;"); 24769 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24770 // the user's own fault 24771 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24772 // clearly the user's own fault 24773 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24774 } 24775 24776 TEST_F(FormatTest, Cpp20ModulesSupport) { 24777 FormatStyle Style = getLLVMStyle(); 24778 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24779 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24780 24781 verifyFormat("export import foo;", Style); 24782 verifyFormat("export import foo:bar;", Style); 24783 verifyFormat("export import foo.bar;", Style); 24784 verifyFormat("export import foo.bar:baz;", Style); 24785 verifyFormat("export import :bar;", Style); 24786 verifyFormat("export module foo:bar;", Style); 24787 verifyFormat("export module foo;", Style); 24788 verifyFormat("export module foo.bar;", Style); 24789 verifyFormat("export module foo.bar:baz;", Style); 24790 verifyFormat("export import <string_view>;", Style); 24791 24792 verifyFormat("export type_name var;", Style); 24793 verifyFormat("template <class T> export using A = B<T>;", Style); 24794 verifyFormat("export using A = B;", Style); 24795 verifyFormat("export int func() {\n" 24796 " foo();\n" 24797 "}", 24798 Style); 24799 verifyFormat("export struct {\n" 24800 " int foo;\n" 24801 "};", 24802 Style); 24803 verifyFormat("export {\n" 24804 " int foo;\n" 24805 "};", 24806 Style); 24807 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24808 24809 verifyFormat("import bar;", Style); 24810 verifyFormat("import foo.bar;", Style); 24811 verifyFormat("import foo:bar;", Style); 24812 verifyFormat("import :bar;", Style); 24813 verifyFormat("import <ctime>;", Style); 24814 verifyFormat("import \"header\";", Style); 24815 24816 verifyFormat("module foo;", Style); 24817 verifyFormat("module foo:bar;", Style); 24818 verifyFormat("module foo.bar;", Style); 24819 verifyFormat("module;", Style); 24820 24821 verifyFormat("export namespace hi {\n" 24822 "const char *sayhi();\n" 24823 "}", 24824 Style); 24825 24826 verifyFormat("module :private;", Style); 24827 verifyFormat("import <foo/bar.h>;", Style); 24828 verifyFormat("import foo...bar;", Style); 24829 verifyFormat("import ..........;", Style); 24830 verifyFormat("module foo:private;", Style); 24831 verifyFormat("import a", Style); 24832 verifyFormat("module a", Style); 24833 verifyFormat("export import a", Style); 24834 verifyFormat("export module a", Style); 24835 24836 verifyFormat("import", Style); 24837 verifyFormat("module", Style); 24838 verifyFormat("export", Style); 24839 } 24840 24841 TEST_F(FormatTest, CoroutineForCoawait) { 24842 FormatStyle Style = getLLVMStyle(); 24843 verifyFormat("for co_await (auto x : range())\n ;"); 24844 verifyFormat("for (auto i : arr) {\n" 24845 "}", 24846 Style); 24847 verifyFormat("for co_await (auto i : arr) {\n" 24848 "}", 24849 Style); 24850 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24851 "}", 24852 Style); 24853 } 24854 24855 TEST_F(FormatTest, CoroutineCoAwait) { 24856 verifyFormat("int x = co_await foo();"); 24857 verifyFormat("int x = (co_await foo());"); 24858 verifyFormat("co_await (42);"); 24859 verifyFormat("void operator co_await(int);"); 24860 verifyFormat("void operator co_await(a);"); 24861 verifyFormat("co_await a;"); 24862 verifyFormat("co_await missing_await_resume{};"); 24863 verifyFormat("co_await a; // comment"); 24864 verifyFormat("void test0() { co_await a; }"); 24865 verifyFormat("co_await co_await co_await foo();"); 24866 verifyFormat("co_await foo().bar();"); 24867 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24868 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24869 "foo(); }(x, y);"); 24870 24871 FormatStyle Style = getLLVMStyleWithColumns(40); 24872 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24873 " co_return co_await foo();\n" 24874 "}(x, y);", 24875 Style); 24876 verifyFormat("co_await;"); 24877 } 24878 24879 TEST_F(FormatTest, CoroutineCoYield) { 24880 verifyFormat("int x = co_yield foo();"); 24881 verifyFormat("int x = (co_yield foo());"); 24882 verifyFormat("co_yield (42);"); 24883 verifyFormat("co_yield {42};"); 24884 verifyFormat("co_yield 42;"); 24885 verifyFormat("co_yield n++;"); 24886 verifyFormat("co_yield ++n;"); 24887 verifyFormat("co_yield;"); 24888 } 24889 24890 TEST_F(FormatTest, CoroutineCoReturn) { 24891 verifyFormat("co_return (42);"); 24892 verifyFormat("co_return;"); 24893 verifyFormat("co_return {};"); 24894 verifyFormat("co_return x;"); 24895 verifyFormat("co_return co_await foo();"); 24896 verifyFormat("co_return co_yield foo();"); 24897 } 24898 24899 TEST_F(FormatTest, EmptyShortBlock) { 24900 auto Style = getLLVMStyle(); 24901 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24902 24903 verifyFormat("try {\n" 24904 " doA();\n" 24905 "} catch (Exception &e) {\n" 24906 " e.printStackTrace();\n" 24907 "}\n", 24908 Style); 24909 24910 verifyFormat("try {\n" 24911 " doA();\n" 24912 "} catch (Exception &e) {}\n", 24913 Style); 24914 } 24915 24916 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24917 auto Style = getLLVMStyle(); 24918 24919 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24920 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24921 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24922 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24923 24924 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24925 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24926 } 24927 24928 TEST_F(FormatTest, InsertBraces) { 24929 FormatStyle Style = getLLVMStyle(); 24930 Style.InsertBraces = true; 24931 24932 verifyFormat("// clang-format off\n" 24933 "// comment\n" 24934 "if (a) f();\n" 24935 "// clang-format on\n" 24936 "if (b) {\n" 24937 " g();\n" 24938 "}", 24939 "// clang-format off\n" 24940 "// comment\n" 24941 "if (a) f();\n" 24942 "// clang-format on\n" 24943 "if (b) g();", 24944 Style); 24945 24946 verifyFormat("if (a) {\n" 24947 " switch (b) {\n" 24948 " case 1:\n" 24949 " c = 0;\n" 24950 " break;\n" 24951 " default:\n" 24952 " c = 1;\n" 24953 " }\n" 24954 "}", 24955 "if (a)\n" 24956 " switch (b) {\n" 24957 " case 1:\n" 24958 " c = 0;\n" 24959 " break;\n" 24960 " default:\n" 24961 " c = 1;\n" 24962 " }", 24963 Style); 24964 24965 verifyFormat("for (auto node : nodes) {\n" 24966 " if (node) {\n" 24967 " break;\n" 24968 " }\n" 24969 "}", 24970 "for (auto node : nodes)\n" 24971 " if (node)\n" 24972 " break;", 24973 Style); 24974 24975 verifyFormat("for (auto node : nodes) {\n" 24976 " if (node)\n" 24977 "}", 24978 "for (auto node : nodes)\n" 24979 " if (node)", 24980 Style); 24981 24982 verifyFormat("do {\n" 24983 " --a;\n" 24984 "} while (a);", 24985 "do\n" 24986 " --a;\n" 24987 "while (a);", 24988 Style); 24989 24990 verifyFormat("if (i) {\n" 24991 " ++i;\n" 24992 "} else {\n" 24993 " --i;\n" 24994 "}", 24995 "if (i)\n" 24996 " ++i;\n" 24997 "else {\n" 24998 " --i;\n" 24999 "}", 25000 Style); 25001 25002 verifyFormat("void f() {\n" 25003 " while (j--) {\n" 25004 " while (i) {\n" 25005 " --i;\n" 25006 " }\n" 25007 " }\n" 25008 "}", 25009 "void f() {\n" 25010 " while (j--)\n" 25011 " while (i)\n" 25012 " --i;\n" 25013 "}", 25014 Style); 25015 25016 verifyFormat("f({\n" 25017 " if (a) {\n" 25018 " g();\n" 25019 " }\n" 25020 "});", 25021 "f({\n" 25022 " if (a)\n" 25023 " g();\n" 25024 "});", 25025 Style); 25026 25027 verifyFormat("if (a) {\n" 25028 " f();\n" 25029 "} else if (b) {\n" 25030 " g();\n" 25031 "} else {\n" 25032 " h();\n" 25033 "}", 25034 "if (a)\n" 25035 " f();\n" 25036 "else if (b)\n" 25037 " g();\n" 25038 "else\n" 25039 " h();", 25040 Style); 25041 25042 verifyFormat("if (a) {\n" 25043 " f();\n" 25044 "}\n" 25045 "// comment\n" 25046 "/* comment */", 25047 "if (a)\n" 25048 " f();\n" 25049 "// comment\n" 25050 "/* comment */", 25051 Style); 25052 25053 verifyFormat("if (a) {\n" 25054 " // foo\n" 25055 " // bar\n" 25056 " f();\n" 25057 "}", 25058 "if (a)\n" 25059 " // foo\n" 25060 " // bar\n" 25061 " f();", 25062 Style); 25063 25064 verifyFormat("if (a) { // comment\n" 25065 " // comment\n" 25066 " f();\n" 25067 "}", 25068 "if (a) // comment\n" 25069 " // comment\n" 25070 " f();", 25071 Style); 25072 25073 verifyFormat("if (a) {\n" 25074 " f(); // comment\n" 25075 "}", 25076 "if (a)\n" 25077 " f(); // comment", 25078 Style); 25079 25080 verifyFormat("if (a) {\n" 25081 " f();\n" 25082 "}\n" 25083 "#undef A\n" 25084 "#undef B", 25085 "if (a)\n" 25086 " f();\n" 25087 "#undef A\n" 25088 "#undef B", 25089 Style); 25090 25091 verifyFormat("if (a)\n" 25092 "#ifdef A\n" 25093 " f();\n" 25094 "#else\n" 25095 " g();\n" 25096 "#endif", 25097 Style); 25098 25099 verifyFormat("#if 0\n" 25100 "#elif 1\n" 25101 "#endif\n" 25102 "void f() {\n" 25103 " if (a) {\n" 25104 " g();\n" 25105 " }\n" 25106 "}", 25107 "#if 0\n" 25108 "#elif 1\n" 25109 "#endif\n" 25110 "void f() {\n" 25111 " if (a) g();\n" 25112 "}", 25113 Style); 25114 25115 Style.ColumnLimit = 15; 25116 25117 verifyFormat("#define A \\\n" 25118 " if (a) \\\n" 25119 " f();", 25120 Style); 25121 25122 verifyFormat("if (a + b >\n" 25123 " c) {\n" 25124 " f();\n" 25125 "}", 25126 "if (a + b > c)\n" 25127 " f();", 25128 Style); 25129 } 25130 25131 TEST_F(FormatTest, RemoveBraces) { 25132 FormatStyle Style = getLLVMStyle(); 25133 Style.RemoveBracesLLVM = true; 25134 25135 // The following test cases are fully-braced versions of the examples at 25136 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 25137 // statement-bodies-of-if-else-loop-statements". 25138 25139 // Omit the braces since the body is simple and clearly associated with the 25140 // `if`. 25141 verifyFormat("if (isa<FunctionDecl>(D))\n" 25142 " handleFunctionDecl(D);\n" 25143 "else if (isa<VarDecl>(D))\n" 25144 " handleVarDecl(D);", 25145 "if (isa<FunctionDecl>(D)) {\n" 25146 " handleFunctionDecl(D);\n" 25147 "} else if (isa<VarDecl>(D)) {\n" 25148 " handleVarDecl(D);\n" 25149 "}", 25150 Style); 25151 25152 // Here we document the condition itself and not the body. 25153 verifyFormat("if (isa<VarDecl>(D)) {\n" 25154 " // It is necessary that we explain the situation with this\n" 25155 " // surprisingly long comment, so it would be unclear\n" 25156 " // without the braces whether the following statement is in\n" 25157 " // the scope of the `if`.\n" 25158 " // Because the condition is documented, we can't really\n" 25159 " // hoist this comment that applies to the body above the\n" 25160 " // `if`.\n" 25161 " handleOtherDecl(D);\n" 25162 "}", 25163 Style); 25164 25165 // Use braces on the outer `if` to avoid a potential dangling `else` 25166 // situation. 25167 verifyFormat("if (isa<VarDecl>(D)) {\n" 25168 " if (shouldProcessAttr(A))\n" 25169 " handleAttr(A);\n" 25170 "}", 25171 "if (isa<VarDecl>(D)) {\n" 25172 " if (shouldProcessAttr(A)) {\n" 25173 " handleAttr(A);\n" 25174 " }\n" 25175 "}", 25176 Style); 25177 25178 // Use braces for the `if` block to keep it uniform with the `else` block. 25179 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25180 " handleFunctionDecl(D);\n" 25181 "} else {\n" 25182 " // In this `else` case, it is necessary that we explain the\n" 25183 " // situation with this surprisingly long comment, so it\n" 25184 " // would be unclear without the braces whether the\n" 25185 " // following statement is in the scope of the `if`.\n" 25186 " handleOtherDecl(D);\n" 25187 "}", 25188 Style); 25189 25190 // This should also omit braces. The `for` loop contains only a single 25191 // statement, so it shouldn't have braces. The `if` also only contains a 25192 // single simple statement (the `for` loop), so it also should omit braces. 25193 verifyFormat("if (isa<FunctionDecl>(D))\n" 25194 " for (auto *A : D.attrs())\n" 25195 " handleAttr(A);", 25196 "if (isa<FunctionDecl>(D)) {\n" 25197 " for (auto *A : D.attrs()) {\n" 25198 " handleAttr(A);\n" 25199 " }\n" 25200 "}", 25201 Style); 25202 25203 // Use braces for a `do-while` loop and its enclosing statement. 25204 verifyFormat("if (Tok->is(tok::l_brace)) {\n" 25205 " do {\n" 25206 " Tok = Tok->Next;\n" 25207 " } while (Tok);\n" 25208 "}", 25209 Style); 25210 25211 // Use braces for the outer `if` since the nested `for` is braced. 25212 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25213 " for (auto *A : D.attrs()) {\n" 25214 " // In this `for` loop body, it is necessary that we\n" 25215 " // explain the situation with this surprisingly long\n" 25216 " // comment, forcing braces on the `for` block.\n" 25217 " handleAttr(A);\n" 25218 " }\n" 25219 "}", 25220 Style); 25221 25222 // Use braces on the outer block because there are more than two levels of 25223 // nesting. 25224 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25225 " for (auto *A : D.attrs())\n" 25226 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 25227 " handleAttrOnDecl(D, A, i);\n" 25228 "}", 25229 "if (isa<FunctionDecl>(D)) {\n" 25230 " for (auto *A : D.attrs()) {\n" 25231 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 25232 " handleAttrOnDecl(D, A, i);\n" 25233 " }\n" 25234 " }\n" 25235 "}", 25236 Style); 25237 25238 // Use braces on the outer block because of a nested `if`; otherwise the 25239 // compiler would warn: `add explicit braces to avoid dangling else` 25240 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25241 " if (shouldProcess(D))\n" 25242 " handleVarDecl(D);\n" 25243 " else\n" 25244 " markAsIgnored(D);\n" 25245 "}", 25246 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25247 " if (shouldProcess(D)) {\n" 25248 " handleVarDecl(D);\n" 25249 " } else {\n" 25250 " markAsIgnored(D);\n" 25251 " }\n" 25252 "}", 25253 Style); 25254 25255 verifyFormat("// clang-format off\n" 25256 "// comment\n" 25257 "while (i > 0) { --i; }\n" 25258 "// clang-format on\n" 25259 "while (j < 0)\n" 25260 " ++j;", 25261 "// clang-format off\n" 25262 "// comment\n" 25263 "while (i > 0) { --i; }\n" 25264 "// clang-format on\n" 25265 "while (j < 0) { ++j; }", 25266 Style); 25267 25268 verifyFormat("if (a)\n" 25269 " b; // comment\n" 25270 "else if (c)\n" 25271 " d; /* comment */\n" 25272 "else\n" 25273 " e;", 25274 "if (a) {\n" 25275 " b; // comment\n" 25276 "} else if (c) {\n" 25277 " d; /* comment */\n" 25278 "} else {\n" 25279 " e;\n" 25280 "}", 25281 Style); 25282 25283 verifyFormat("if (a) {\n" 25284 " b;\n" 25285 " c;\n" 25286 "} else if (d) {\n" 25287 " e;\n" 25288 "}", 25289 Style); 25290 25291 verifyFormat("if (a) {\n" 25292 "#undef NDEBUG\n" 25293 " b;\n" 25294 "} else {\n" 25295 " c;\n" 25296 "}", 25297 Style); 25298 25299 verifyFormat("if (a) {\n" 25300 " // comment\n" 25301 "} else if (b) {\n" 25302 " c;\n" 25303 "}", 25304 Style); 25305 25306 verifyFormat("if (a) {\n" 25307 " b;\n" 25308 "} else {\n" 25309 " { c; }\n" 25310 "}", 25311 Style); 25312 25313 verifyFormat("if (a) {\n" 25314 " if (b) // comment\n" 25315 " c;\n" 25316 "} else if (d) {\n" 25317 " e;\n" 25318 "}", 25319 "if (a) {\n" 25320 " if (b) { // comment\n" 25321 " c;\n" 25322 " }\n" 25323 "} else if (d) {\n" 25324 " e;\n" 25325 "}", 25326 Style); 25327 25328 verifyFormat("if (a) {\n" 25329 " if (b) {\n" 25330 " c;\n" 25331 " // comment\n" 25332 " } else if (d) {\n" 25333 " e;\n" 25334 " }\n" 25335 "}", 25336 Style); 25337 25338 verifyFormat("if (a) {\n" 25339 " if (b)\n" 25340 " c;\n" 25341 "}", 25342 "if (a) {\n" 25343 " if (b) {\n" 25344 " c;\n" 25345 " }\n" 25346 "}", 25347 Style); 25348 25349 verifyFormat("if (a)\n" 25350 " if (b)\n" 25351 " c;\n" 25352 " else\n" 25353 " d;\n" 25354 "else\n" 25355 " e;", 25356 "if (a) {\n" 25357 " if (b) {\n" 25358 " c;\n" 25359 " } else {\n" 25360 " d;\n" 25361 " }\n" 25362 "} else {\n" 25363 " e;\n" 25364 "}", 25365 Style); 25366 25367 verifyFormat("if (a) {\n" 25368 " // comment\n" 25369 " if (b)\n" 25370 " c;\n" 25371 " else if (d)\n" 25372 " e;\n" 25373 "} else {\n" 25374 " g;\n" 25375 "}", 25376 "if (a) {\n" 25377 " // comment\n" 25378 " if (b) {\n" 25379 " c;\n" 25380 " } else if (d) {\n" 25381 " e;\n" 25382 " }\n" 25383 "} else {\n" 25384 " g;\n" 25385 "}", 25386 Style); 25387 25388 verifyFormat("if (a)\n" 25389 " b;\n" 25390 "else if (c)\n" 25391 " d;\n" 25392 "else\n" 25393 " e;", 25394 "if (a) {\n" 25395 " b;\n" 25396 "} else {\n" 25397 " if (c) {\n" 25398 " d;\n" 25399 " } else {\n" 25400 " e;\n" 25401 " }\n" 25402 "}", 25403 Style); 25404 25405 verifyFormat("if (a) {\n" 25406 " if (b)\n" 25407 " c;\n" 25408 " else if (d)\n" 25409 " e;\n" 25410 "} else {\n" 25411 " g;\n" 25412 "}", 25413 "if (a) {\n" 25414 " if (b)\n" 25415 " c;\n" 25416 " else {\n" 25417 " if (d)\n" 25418 " e;\n" 25419 " }\n" 25420 "} else {\n" 25421 " g;\n" 25422 "}", 25423 Style); 25424 25425 verifyFormat("if (isa<VarDecl>(D)) {\n" 25426 " for (auto *A : D.attrs())\n" 25427 " if (shouldProcessAttr(A))\n" 25428 " handleAttr(A);\n" 25429 "}", 25430 "if (isa<VarDecl>(D)) {\n" 25431 " for (auto *A : D.attrs()) {\n" 25432 " if (shouldProcessAttr(A)) {\n" 25433 " handleAttr(A);\n" 25434 " }\n" 25435 " }\n" 25436 "}", 25437 Style); 25438 25439 verifyFormat("do {\n" 25440 " ++I;\n" 25441 "} while (hasMore() && Filter(*I));", 25442 "do { ++I; } while (hasMore() && Filter(*I));", Style); 25443 25444 verifyFormat("if (a)\n" 25445 " if (b)\n" 25446 " c;\n" 25447 " else {\n" 25448 " if (d)\n" 25449 " e;\n" 25450 " }\n" 25451 "else\n" 25452 " f;", 25453 Style); 25454 25455 verifyFormat("if (a)\n" 25456 " if (b)\n" 25457 " c;\n" 25458 " else {\n" 25459 " if (d)\n" 25460 " e;\n" 25461 " else if (f)\n" 25462 " g;\n" 25463 " }\n" 25464 "else\n" 25465 " h;", 25466 Style); 25467 25468 verifyFormat("if (a) {\n" 25469 " b;\n" 25470 "} else if (c) {\n" 25471 " d;\n" 25472 " e;\n" 25473 "}", 25474 "if (a) {\n" 25475 " b;\n" 25476 "} else {\n" 25477 " if (c) {\n" 25478 " d;\n" 25479 " e;\n" 25480 " }\n" 25481 "}", 25482 Style); 25483 25484 verifyFormat("if (a) {\n" 25485 " b;\n" 25486 " c;\n" 25487 "} else if (d) {\n" 25488 " e;\n" 25489 " f;\n" 25490 "}", 25491 "if (a) {\n" 25492 " b;\n" 25493 " c;\n" 25494 "} else {\n" 25495 " if (d) {\n" 25496 " e;\n" 25497 " f;\n" 25498 " }\n" 25499 "}", 25500 Style); 25501 25502 verifyFormat("if (a) {\n" 25503 " b;\n" 25504 "} else if (c) {\n" 25505 " d;\n" 25506 "} else {\n" 25507 " e;\n" 25508 " f;\n" 25509 "}", 25510 "if (a) {\n" 25511 " b;\n" 25512 "} else {\n" 25513 " if (c) {\n" 25514 " d;\n" 25515 " } else {\n" 25516 " e;\n" 25517 " f;\n" 25518 " }\n" 25519 "}", 25520 Style); 25521 25522 verifyFormat("if (a) {\n" 25523 " b;\n" 25524 "} else if (c) {\n" 25525 " d;\n" 25526 "} else if (e) {\n" 25527 " f;\n" 25528 " g;\n" 25529 "}", 25530 "if (a) {\n" 25531 " b;\n" 25532 "} else {\n" 25533 " if (c) {\n" 25534 " d;\n" 25535 " } else if (e) {\n" 25536 " f;\n" 25537 " g;\n" 25538 " }\n" 25539 "}", 25540 Style); 25541 25542 verifyFormat("if (a) {\n" 25543 " if (b)\n" 25544 " c;\n" 25545 " else if (d) {\n" 25546 " e;\n" 25547 " f;\n" 25548 " }\n" 25549 "} else {\n" 25550 " g;\n" 25551 "}", 25552 "if (a) {\n" 25553 " if (b)\n" 25554 " c;\n" 25555 " else {\n" 25556 " if (d) {\n" 25557 " e;\n" 25558 " f;\n" 25559 " }\n" 25560 " }\n" 25561 "} else {\n" 25562 " g;\n" 25563 "}", 25564 Style); 25565 25566 verifyFormat("if (a)\n" 25567 " if (b)\n" 25568 " c;\n" 25569 " else {\n" 25570 " if (d) {\n" 25571 " e;\n" 25572 " f;\n" 25573 " }\n" 25574 " }\n" 25575 "else\n" 25576 " g;", 25577 Style); 25578 25579 verifyFormat("if (a) {\n" 25580 " b;\n" 25581 " c;\n" 25582 "} else { // comment\n" 25583 " if (d) {\n" 25584 " e;\n" 25585 " f;\n" 25586 " }\n" 25587 "}", 25588 Style); 25589 25590 verifyFormat("if (a)\n" 25591 " b;\n" 25592 "else if (c)\n" 25593 " while (d)\n" 25594 " e;\n" 25595 "// comment", 25596 "if (a)\n" 25597 "{\n" 25598 " b;\n" 25599 "} else if (c) {\n" 25600 " while (d) {\n" 25601 " e;\n" 25602 " }\n" 25603 "}\n" 25604 "// comment", 25605 Style); 25606 25607 verifyFormat("if (a) {\n" 25608 " b;\n" 25609 "} else if (c) {\n" 25610 " d;\n" 25611 "} else {\n" 25612 " e;\n" 25613 " g;\n" 25614 "}", 25615 Style); 25616 25617 verifyFormat("if (a) {\n" 25618 " b;\n" 25619 "} else if (c) {\n" 25620 " d;\n" 25621 "} else {\n" 25622 " e;\n" 25623 "} // comment", 25624 Style); 25625 25626 verifyFormat("int abs = [](int i) {\n" 25627 " if (i >= 0)\n" 25628 " return i;\n" 25629 " return -i;\n" 25630 "};", 25631 "int abs = [](int i) {\n" 25632 " if (i >= 0) {\n" 25633 " return i;\n" 25634 " }\n" 25635 " return -i;\n" 25636 "};", 25637 Style); 25638 25639 verifyFormat("if (a)\n" 25640 " foo();\n" 25641 "else\n" 25642 " bar();", 25643 "if (a)\n" 25644 "{\n" 25645 " foo();\n" 25646 "}\n" 25647 "else\n" 25648 "{\n" 25649 " bar();\n" 25650 "}", 25651 Style); 25652 25653 verifyFormat("if (a)\n" 25654 " foo();\n" 25655 "// comment\n" 25656 "else\n" 25657 " bar();", 25658 "if (a) {\n" 25659 " foo();\n" 25660 "}\n" 25661 "// comment\n" 25662 "else {\n" 25663 " bar();\n" 25664 "}", 25665 Style); 25666 25667 verifyFormat("if (a) {\n" 25668 "Label:\n" 25669 "}", 25670 Style); 25671 25672 verifyFormat("if (a) {\n" 25673 "Label:\n" 25674 " f();\n" 25675 "}", 25676 Style); 25677 25678 verifyFormat("if (a) {\n" 25679 " f();\n" 25680 "Label:\n" 25681 "}", 25682 Style); 25683 25684 verifyFormat("if consteval {\n" 25685 " f();\n" 25686 "} else {\n" 25687 " g();\n" 25688 "}", 25689 Style); 25690 25691 verifyFormat("if not consteval {\n" 25692 " f();\n" 25693 "} else if (a) {\n" 25694 " g();\n" 25695 "}", 25696 Style); 25697 25698 verifyFormat("if !consteval {\n" 25699 " g();\n" 25700 "}", 25701 Style); 25702 25703 Style.ColumnLimit = 65; 25704 verifyFormat("if (condition) {\n" 25705 " ff(Indices,\n" 25706 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25707 "} else {\n" 25708 " ff(Indices,\n" 25709 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25710 "}", 25711 Style); 25712 25713 Style.ColumnLimit = 20; 25714 25715 verifyFormat("int ab = [](int i) {\n" 25716 " if (i > 0) {\n" 25717 " i = 12345678 -\n" 25718 " i;\n" 25719 " }\n" 25720 " return i;\n" 25721 "};", 25722 Style); 25723 25724 verifyFormat("if (a) {\n" 25725 " b = c + // 1 -\n" 25726 " d;\n" 25727 "}", 25728 Style); 25729 25730 verifyFormat("if (a) {\n" 25731 " b = c >= 0 ? d\n" 25732 " : e;\n" 25733 "}", 25734 "if (a) {\n" 25735 " b = c >= 0 ? d : e;\n" 25736 "}", 25737 Style); 25738 25739 verifyFormat("if (a)\n" 25740 " b = c > 0 ? d : e;", 25741 "if (a) {\n" 25742 " b = c > 0 ? d : e;\n" 25743 "}", 25744 Style); 25745 25746 verifyFormat("if (-b >=\n" 25747 " c) { // Keep.\n" 25748 " foo();\n" 25749 "} else {\n" 25750 " bar();\n" 25751 "}", 25752 "if (-b >= c) { // Keep.\n" 25753 " foo();\n" 25754 "} else {\n" 25755 " bar();\n" 25756 "}", 25757 Style); 25758 25759 verifyFormat("if (a) /* Remove. */\n" 25760 " f();\n" 25761 "else\n" 25762 " g();", 25763 "if (a) <% /* Remove. */\n" 25764 " f();\n" 25765 "%> else <%\n" 25766 " g();\n" 25767 "%>", 25768 Style); 25769 25770 verifyFormat("while (\n" 25771 " !i--) <% // Keep.\n" 25772 " foo();\n" 25773 "%>", 25774 "while (!i--) <% // Keep.\n" 25775 " foo();\n" 25776 "%>", 25777 Style); 25778 25779 verifyFormat("for (int &i : chars)\n" 25780 " ++i;", 25781 "for (int &i :\n" 25782 " chars) {\n" 25783 " ++i;\n" 25784 "}", 25785 Style); 25786 25787 verifyFormat("if (a)\n" 25788 " b;\n" 25789 "else if (c) {\n" 25790 " d;\n" 25791 " e;\n" 25792 "} else\n" 25793 " f = g(foo, bar,\n" 25794 " baz);", 25795 "if (a)\n" 25796 " b;\n" 25797 "else {\n" 25798 " if (c) {\n" 25799 " d;\n" 25800 " e;\n" 25801 " } else\n" 25802 " f = g(foo, bar, baz);\n" 25803 "}", 25804 Style); 25805 25806 Style.ColumnLimit = 0; 25807 verifyFormat("if (a)\n" 25808 " b234567890223456789032345678904234567890 = " 25809 "c234567890223456789032345678904234567890;", 25810 "if (a) {\n" 25811 " b234567890223456789032345678904234567890 = " 25812 "c234567890223456789032345678904234567890;\n" 25813 "}", 25814 Style); 25815 25816 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 25817 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 25818 Style.BraceWrapping.BeforeElse = true; 25819 25820 Style.ColumnLimit = 65; 25821 25822 verifyFormat("if (condition)\n" 25823 "{\n" 25824 " ff(Indices,\n" 25825 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25826 "}\n" 25827 "else\n" 25828 "{\n" 25829 " ff(Indices,\n" 25830 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25831 "}", 25832 "if (condition) {\n" 25833 " ff(Indices,\n" 25834 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25835 "} else {\n" 25836 " ff(Indices,\n" 25837 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25838 "}", 25839 Style); 25840 25841 verifyFormat("if (a)\n" 25842 "{ //\n" 25843 " foo();\n" 25844 "}", 25845 "if (a) { //\n" 25846 " foo();\n" 25847 "}", 25848 Style); 25849 25850 Style.ColumnLimit = 20; 25851 25852 verifyFormat("int ab = [](int i) {\n" 25853 " if (i > 0)\n" 25854 " {\n" 25855 " i = 12345678 -\n" 25856 " i;\n" 25857 " }\n" 25858 " return i;\n" 25859 "};", 25860 "int ab = [](int i) {\n" 25861 " if (i > 0) {\n" 25862 " i = 12345678 -\n" 25863 " i;\n" 25864 " }\n" 25865 " return i;\n" 25866 "};", 25867 Style); 25868 25869 verifyFormat("if (a)\n" 25870 "{\n" 25871 " b = c + // 1 -\n" 25872 " d;\n" 25873 "}", 25874 "if (a) {\n" 25875 " b = c + // 1 -\n" 25876 " d;\n" 25877 "}", 25878 Style); 25879 25880 verifyFormat("if (a)\n" 25881 "{\n" 25882 " b = c >= 0 ? d\n" 25883 " : e;\n" 25884 "}", 25885 "if (a) {\n" 25886 " b = c >= 0 ? d : e;\n" 25887 "}", 25888 Style); 25889 25890 verifyFormat("if (a)\n" 25891 " b = c > 0 ? d : e;", 25892 "if (a)\n" 25893 "{\n" 25894 " b = c > 0 ? d : e;\n" 25895 "}", 25896 Style); 25897 25898 verifyFormat("if (foo + bar <=\n" 25899 " baz)\n" 25900 "{\n" 25901 " func(arg1, arg2);\n" 25902 "}", 25903 "if (foo + bar <= baz) {\n" 25904 " func(arg1, arg2);\n" 25905 "}", 25906 Style); 25907 25908 verifyFormat("if (foo + bar < baz)\n" 25909 " func(arg1, arg2);\n" 25910 "else\n" 25911 " func();", 25912 "if (foo + bar < baz)\n" 25913 "<%\n" 25914 " func(arg1, arg2);\n" 25915 "%>\n" 25916 "else\n" 25917 "<%\n" 25918 " func();\n" 25919 "%>", 25920 Style); 25921 25922 verifyFormat("while (i--)\n" 25923 "<% // Keep.\n" 25924 " foo();\n" 25925 "%>", 25926 "while (i--) <% // Keep.\n" 25927 " foo();\n" 25928 "%>", 25929 Style); 25930 25931 verifyFormat("for (int &i : chars)\n" 25932 " ++i;", 25933 "for (int &i : chars)\n" 25934 "{\n" 25935 " ++i;\n" 25936 "}", 25937 Style); 25938 } 25939 25940 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25941 auto Style = getLLVMStyle(); 25942 25943 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25944 "void functionDecl(int a, int b, int c);"; 25945 25946 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25947 "paramF, paramG, paramH, paramI);\n" 25948 "void functionDecl(int argumentA, int argumentB, int " 25949 "argumentC, int argumentD, int argumentE);"; 25950 25951 verifyFormat(Short, Style); 25952 25953 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25954 "paramF, paramG, paramH,\n" 25955 " paramI);\n" 25956 "void functionDecl(int argumentA, int argumentB, int " 25957 "argumentC, int argumentD,\n" 25958 " int argumentE);"; 25959 25960 verifyFormat(NoBreak, Medium, Style); 25961 verifyFormat(NoBreak, 25962 "functionCall(\n" 25963 " paramA,\n" 25964 " paramB,\n" 25965 " paramC,\n" 25966 " paramD,\n" 25967 " paramE,\n" 25968 " paramF,\n" 25969 " paramG,\n" 25970 " paramH,\n" 25971 " paramI\n" 25972 ");\n" 25973 "void functionDecl(\n" 25974 " int argumentA,\n" 25975 " int argumentB,\n" 25976 " int argumentC,\n" 25977 " int argumentD,\n" 25978 " int argumentE\n" 25979 ");", 25980 Style); 25981 25982 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25983 " nestedLongFunctionCall(argument1, " 25984 "argument2, argument3,\n" 25985 " argument4, " 25986 "argument5));", 25987 Style); 25988 25989 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25990 25991 verifyFormat(Short, Style); 25992 verifyFormat( 25993 "functionCall(\n" 25994 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25995 "paramI\n" 25996 ");\n" 25997 "void functionDecl(\n" 25998 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25999 "argumentE\n" 26000 ");", 26001 Medium, Style); 26002 26003 Style.AllowAllArgumentsOnNextLine = false; 26004 Style.AllowAllParametersOfDeclarationOnNextLine = false; 26005 26006 verifyFormat(Short, Style); 26007 verifyFormat( 26008 "functionCall(\n" 26009 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 26010 "paramI\n" 26011 ");\n" 26012 "void functionDecl(\n" 26013 " int argumentA, int argumentB, int argumentC, int argumentD, int " 26014 "argumentE\n" 26015 ");", 26016 Medium, Style); 26017 26018 Style.BinPackArguments = false; 26019 Style.BinPackParameters = false; 26020 26021 verifyFormat(Short, Style); 26022 26023 verifyFormat("functionCall(\n" 26024 " paramA,\n" 26025 " paramB,\n" 26026 " paramC,\n" 26027 " paramD,\n" 26028 " paramE,\n" 26029 " paramF,\n" 26030 " paramG,\n" 26031 " paramH,\n" 26032 " paramI\n" 26033 ");\n" 26034 "void functionDecl(\n" 26035 " int argumentA,\n" 26036 " int argumentB,\n" 26037 " int argumentC,\n" 26038 " int argumentD,\n" 26039 " int argumentE\n" 26040 ");", 26041 Medium, Style); 26042 26043 verifyFormat("outerFunctionCall(\n" 26044 " nestedFunctionCall(argument1),\n" 26045 " nestedLongFunctionCall(\n" 26046 " argument1,\n" 26047 " argument2,\n" 26048 " argument3,\n" 26049 " argument4,\n" 26050 " argument5\n" 26051 " )\n" 26052 ");", 26053 Style); 26054 26055 verifyFormat("int a = (int)b;", Style); 26056 verifyFormat("int a = (int)b;", 26057 "int a = (\n" 26058 " int\n" 26059 ") b;", 26060 Style); 26061 26062 verifyFormat("return (true);", Style); 26063 verifyFormat("return (true);", 26064 "return (\n" 26065 " true\n" 26066 ");", 26067 Style); 26068 26069 verifyFormat("void foo();", Style); 26070 verifyFormat("void foo();", 26071 "void foo(\n" 26072 ");", 26073 Style); 26074 26075 verifyFormat("void foo() {}", Style); 26076 verifyFormat("void foo() {}", 26077 "void foo(\n" 26078 ") {\n" 26079 "}", 26080 Style); 26081 26082 verifyFormat("auto string = std::string();", Style); 26083 verifyFormat("auto string = std::string();", 26084 "auto string = std::string(\n" 26085 ");", 26086 Style); 26087 26088 verifyFormat("void (*functionPointer)() = nullptr;", Style); 26089 verifyFormat("void (*functionPointer)() = nullptr;", 26090 "void (\n" 26091 " *functionPointer\n" 26092 ")\n" 26093 "(\n" 26094 ") = nullptr;", 26095 Style); 26096 } 26097 26098 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 26099 auto Style = getLLVMStyle(); 26100 26101 verifyFormat("if (foo()) {\n" 26102 " return;\n" 26103 "}", 26104 Style); 26105 26106 verifyFormat("if (quitelongarg !=\n" 26107 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 26108 "comment\n" 26109 " return;\n" 26110 "}", 26111 Style); 26112 26113 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26114 26115 verifyFormat("if (foo()) {\n" 26116 " return;\n" 26117 "}", 26118 Style); 26119 26120 verifyFormat("if (quitelongarg !=\n" 26121 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 26122 "comment\n" 26123 " return;\n" 26124 "}", 26125 Style); 26126 } 26127 26128 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 26129 auto Style = getLLVMStyle(); 26130 26131 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 26132 " doSomething();\n" 26133 "}", 26134 Style); 26135 26136 verifyFormat("for (int myReallyLongCountVariable = 0; " 26137 "myReallyLongCountVariable < count;\n" 26138 " myReallyLongCountVariable++) {\n" 26139 " doSomething();\n" 26140 "}", 26141 Style); 26142 26143 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26144 26145 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 26146 " doSomething();\n" 26147 "}", 26148 Style); 26149 26150 verifyFormat("for (int myReallyLongCountVariable = 0; " 26151 "myReallyLongCountVariable < count;\n" 26152 " myReallyLongCountVariable++) {\n" 26153 " doSomething();\n" 26154 "}", 26155 Style); 26156 } 26157 26158 TEST_F(FormatTest, UnderstandsDigraphs) { 26159 verifyFormat("int arr<:5:> = {};"); 26160 verifyFormat("int arr[5] = <%%>;"); 26161 verifyFormat("int arr<:::qualified_variable:> = {};"); 26162 verifyFormat("int arr[::qualified_variable] = <%%>;"); 26163 verifyFormat("%:include <header>"); 26164 verifyFormat("%:define A x##y"); 26165 verifyFormat("#define A x%:%:y"); 26166 } 26167 26168 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 26169 auto Style = getLLVMStyle(); 26170 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 26171 Style.AlignConsecutiveAssignments.Enabled = true; 26172 Style.AlignConsecutiveDeclarations.Enabled = true; 26173 26174 // The AlignArray code is incorrect for non square Arrays and can cause 26175 // crashes, these tests assert that the array is not changed but will 26176 // also act as regression tests for when it is properly fixed 26177 verifyFormat("struct test demo[] = {\n" 26178 " {1, 2},\n" 26179 " {3, 4, 5},\n" 26180 " {6, 7, 8}\n" 26181 "};", 26182 Style); 26183 verifyFormat("struct test demo[] = {\n" 26184 " {1, 2, 3, 4, 5},\n" 26185 " {3, 4, 5},\n" 26186 " {6, 7, 8}\n" 26187 "};", 26188 Style); 26189 verifyFormat("struct test demo[] = {\n" 26190 " {1, 2, 3, 4, 5},\n" 26191 " {3, 4, 5},\n" 26192 " {6, 7, 8, 9, 10, 11, 12}\n" 26193 "};", 26194 Style); 26195 verifyFormat("struct test demo[] = {\n" 26196 " {1, 2, 3},\n" 26197 " {3, 4, 5},\n" 26198 " {6, 7, 8, 9, 10, 11, 12}\n" 26199 "};", 26200 Style); 26201 26202 verifyFormat("S{\n" 26203 " {},\n" 26204 " {},\n" 26205 " {a, b}\n" 26206 "};", 26207 Style); 26208 verifyFormat("S{\n" 26209 " {},\n" 26210 " {},\n" 26211 " {a, b},\n" 26212 "};", 26213 Style); 26214 verifyFormat("void foo() {\n" 26215 " auto thing = test{\n" 26216 " {\n" 26217 " {13}, {something}, // A\n" 26218 " }\n" 26219 " };\n" 26220 "}", 26221 "void foo() {\n" 26222 " auto thing = test{\n" 26223 " {\n" 26224 " {13},\n" 26225 " {something}, // A\n" 26226 " }\n" 26227 " };\n" 26228 "}", 26229 Style); 26230 } 26231 26232 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 26233 auto Style = getLLVMStyle(); 26234 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 26235 Style.AlignConsecutiveAssignments.Enabled = true; 26236 Style.AlignConsecutiveDeclarations.Enabled = true; 26237 26238 // The AlignArray code is incorrect for non square Arrays and can cause 26239 // crashes, these tests assert that the array is not changed but will 26240 // also act as regression tests for when it is properly fixed 26241 verifyFormat("struct test demo[] = {\n" 26242 " {1, 2},\n" 26243 " {3, 4, 5},\n" 26244 " {6, 7, 8}\n" 26245 "};", 26246 Style); 26247 verifyFormat("struct test demo[] = {\n" 26248 " {1, 2, 3, 4, 5},\n" 26249 " {3, 4, 5},\n" 26250 " {6, 7, 8}\n" 26251 "};", 26252 Style); 26253 verifyFormat("struct test demo[] = {\n" 26254 " {1, 2, 3, 4, 5},\n" 26255 " {3, 4, 5},\n" 26256 " {6, 7, 8, 9, 10, 11, 12}\n" 26257 "};", 26258 Style); 26259 verifyFormat("struct test demo[] = {\n" 26260 " {1, 2, 3},\n" 26261 " {3, 4, 5},\n" 26262 " {6, 7, 8, 9, 10, 11, 12}\n" 26263 "};", 26264 Style); 26265 26266 verifyFormat("S{\n" 26267 " {},\n" 26268 " {},\n" 26269 " {a, b}\n" 26270 "};", 26271 Style); 26272 verifyFormat("S{\n" 26273 " {},\n" 26274 " {},\n" 26275 " {a, b},\n" 26276 "};", 26277 Style); 26278 verifyFormat("void foo() {\n" 26279 " auto thing = test{\n" 26280 " {\n" 26281 " {13}, {something}, // A\n" 26282 " }\n" 26283 " };\n" 26284 "}", 26285 "void foo() {\n" 26286 " auto thing = test{\n" 26287 " {\n" 26288 " {13},\n" 26289 " {something}, // A\n" 26290 " }\n" 26291 " };\n" 26292 "}", 26293 Style); 26294 } 26295 26296 TEST_F(FormatTest, FormatsVariableTemplates) { 26297 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 26298 verifyFormat("template <typename T> " 26299 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 26300 } 26301 26302 } // namespace 26303 } // namespace format 26304 } // namespace clang 26305